* [PATCH v3 14/20] landlock: Add tracepoints for ptrace and scope denials
From: Mickaël Salaün @ 2026-07-22 17:11 UTC (permalink / raw)
To: Günther Noack, Steven Rostedt
Cc: Mickaël Salaün, Christian Brauner, Jann Horn, Jeff Xu,
Justin Suess, Kees Cook, Masami Hiramatsu, Mathieu Desnoyers,
Matthieu Buffet, Mikhail Ivanov, Tingmao Wang, kernel-team,
linux-security-module, linux-trace-kernel
In-Reply-To: <20260722171159.2776765-1-mic@digikod.net>
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 <gnoack@google.com>
Cc: Justin Suess <utilityemal77@gmail.com>
Cc: Masami Hiramatsu <mhiramat@kernel.org>
Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: Steven Rostedt <rostedt@goodmis.org>
Cc: Tingmao Wang <m@maowtm.org>
Signed-off-by: Mickaël Salaün <mic@digikod.net>
---
Changes since v2:
https://patch.msgid.link/20260406143717.1815792-13-mic@digikod.net
- 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(-)
diff --git a/include/trace/events/landlock.h b/include/trace/events/landlock.h
index e70dcc9a94b9..94de20fbe908 100644
--- a/include/trace/events/landlock.h
+++ b/include/trace/events/landlock.h
@@ -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 */
diff --git a/security/landlock/log.h b/security/landlock/log.h
index 25afc17cf055..e0a6e44f3ddd 100644
--- a/security/landlock/log.h
+++ b/security/landlock/log.h
@@ -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
diff --git a/security/landlock/task.c b/security/landlock/task.c
index c0da22736ea0..cbc7c1ef33cb 100644
--- a/security/landlock/task.c
+++ b/security/landlock/task.c
@@ -88,6 +88,7 @@ static int hook_ptrace_access_check(struct task_struct *const child,
const unsigned int mode)
{
const struct landlock_cred_security *parent_subject;
+ u64 tracee_domain_id = 0;
int err;
/* Quick return for non-landlocked tasks. */
@@ -99,6 +100,10 @@ static int hook_ptrace_access_check(struct task_struct *const child,
const struct landlock_domain *const child_dom =
landlock_get_task_domain(child);
err = domain_ptrace(parent_subject->domain, child_dom);
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
+ if (child_dom)
+ tracee_domain_id = child_dom->hierarchy->id;
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
}
if (!err)
@@ -116,6 +121,7 @@ static int hook_ptrace_access_check(struct task_struct *const child,
.u.tsk = child,
},
.layer_plus_one = parent_subject->domain->num_layers,
+ .other_domain_id = tracee_domain_id,
});
return err;
@@ -136,6 +142,7 @@ static int hook_ptrace_traceme(struct task_struct *const parent)
{
const struct landlock_cred_security *parent_subject;
const struct landlock_domain *child_dom;
+ u64 tracee_domain_id = 0;
int err;
child_dom = landlock_get_current_domain();
@@ -147,6 +154,12 @@ static int hook_ptrace_traceme(struct task_struct *const parent)
if (!err)
return 0;
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
+ /* The tracee is the current task; its domain is stable here. */
+ if (child_dom)
+ tracee_domain_id = child_dom->hierarchy->id;
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
+
/*
* For the ptrace_traceme case, we log the domain which is the cause of
* the denial, which means the parent domain instead of the current
@@ -161,6 +174,7 @@ static int hook_ptrace_traceme(struct task_struct *const parent)
.u.tsk = current,
},
.layer_plus_one = parent_subject->domain->num_layers,
+ .other_domain_id = tracee_domain_id,
});
return err;
}
@@ -236,13 +250,17 @@ static bool domain_is_scoped(const struct landlock_domain *const client,
}
static bool sock_is_scoped(struct sock *const other,
- const struct landlock_domain *const domain)
+ const struct landlock_domain *const domain,
+ u64 *const peer_domain_id)
{
const struct landlock_domain *dom_other;
/* The credentials will not change. */
lockdep_assert_held(&unix_sk(other)->lock);
dom_other = landlock_cred(other->sk_socket->file->f_cred)->domain;
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
+ *peer_domain_id = dom_other ? dom_other->hierarchy->id : 0;
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
return domain_is_scoped(domain, dom_other,
LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET);
}
@@ -270,6 +288,7 @@ static int hook_unix_stream_connect(struct sock *const sock,
struct sock *const newsk)
{
size_t handle_layer;
+ u64 peer_domain_id = 0;
const struct landlock_cred_security *const subject =
landlock_get_applicable_subject(current_cred(), unix_scope,
&handle_layer);
@@ -281,7 +300,7 @@ static int hook_unix_stream_connect(struct sock *const sock,
if (!is_abstract_socket(other))
return 0;
- if (!sock_is_scoped(other, subject->domain))
+ if (!sock_is_scoped(other, subject->domain, &peer_domain_id))
return 0;
landlock_log_denial(subject, &(struct landlock_request) {
@@ -293,6 +312,7 @@ static int hook_unix_stream_connect(struct sock *const sock,
},
},
.layer_plus_one = handle_layer + 1,
+ .other_domain_id = peer_domain_id,
});
return -EPERM;
}
@@ -301,6 +321,7 @@ static int hook_unix_may_send(struct socket *const sock,
struct socket *const other)
{
size_t handle_layer;
+ u64 peer_domain_id = 0;
const struct landlock_cred_security *const subject =
landlock_get_applicable_subject(current_cred(), unix_scope,
&handle_layer);
@@ -318,7 +339,7 @@ static int hook_unix_may_send(struct socket *const sock,
if (!is_abstract_socket(other->sk))
return 0;
- if (!sock_is_scoped(other->sk, subject->domain))
+ if (!sock_is_scoped(other->sk, subject->domain, &peer_domain_id))
return 0;
landlock_log_denial(subject, &(struct landlock_request) {
@@ -330,6 +351,7 @@ static int hook_unix_may_send(struct socket *const sock,
},
},
.layer_plus_one = handle_layer + 1,
+ .other_domain_id = peer_domain_id,
});
return -EPERM;
}
@@ -344,6 +366,7 @@ static int hook_task_kill(struct task_struct *const p,
{
bool is_scoped;
size_t handle_layer;
+ u64 target_domain_id = 0;
const struct landlock_cred_security *subject;
if (!cred) {
@@ -370,9 +393,15 @@ static int hook_task_kill(struct task_struct *const p,
return 0;
scoped_guard(rcu) {
- is_scoped = domain_is_scoped(subject->domain,
- landlock_get_task_domain(p),
+ const struct landlock_domain *const other =
+ landlock_get_task_domain(p);
+
+ is_scoped = domain_is_scoped(subject->domain, other,
signal_scope.scope);
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
+ if (other)
+ target_domain_id = other->hierarchy->id;
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
}
if (!is_scoped)
@@ -385,6 +414,7 @@ static int hook_task_kill(struct task_struct *const p,
.u.tsk = p,
},
.layer_plus_one = handle_layer + 1,
+ .other_domain_id = target_domain_id,
});
return -EPERM;
}
@@ -394,6 +424,7 @@ static int hook_file_send_sigiotask(struct task_struct *tsk,
{
const struct landlock_cred_security *subject;
bool is_scoped = false;
+ u64 target_domain_id = 0;
/* Lock already held by send_sigio() and send_sigurg(). */
lockdep_assert_held(&fown->lock);
@@ -421,9 +452,15 @@ static int hook_file_send_sigiotask(struct task_struct *tsk,
return 0;
scoped_guard(rcu) {
- is_scoped = domain_is_scoped(subject->domain,
- landlock_get_task_domain(tsk),
+ const struct landlock_domain *const other =
+ landlock_get_task_domain(tsk);
+
+ is_scoped = domain_is_scoped(subject->domain, other,
signal_scope.scope);
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
+ if (other)
+ target_domain_id = other->hierarchy->id;
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
}
if (!is_scoped)
@@ -438,6 +475,7 @@ static int hook_file_send_sigiotask(struct task_struct *tsk,
#ifdef CONFIG_SECURITY_LANDLOCK_LOG
.layer_plus_one = landlock_file(fown->file)->fown_layer + 1,
#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
+ .other_domain_id = target_domain_id,
});
return -EPERM;
}
diff --git a/security/landlock/trace.c b/security/landlock/trace.c
index 4c4229d4ffdf..2ea7aac8d75d 100644
--- a/security/landlock/trace.c
+++ b/security/landlock/trace.c
@@ -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;
}
}
--
2.54.0
^ permalink raw reply related
* [PATCH v3 12/20] landlock: Add tracepoints for rule checking
From: Mickaël Salaün @ 2026-07-22 17:11 UTC (permalink / raw)
To: Günther Noack, Steven Rostedt
Cc: Mickaël Salaün, Christian Brauner, Jann Horn, Jeff Xu,
Justin Suess, Kees Cook, Masami Hiramatsu, Mathieu Desnoyers,
Matthieu Buffet, Mikhail Ivanov, Tingmao Wang, kernel-team,
linux-security-module, linux-trace-kernel
In-Reply-To: <20260722171159.2776765-1-mic@digikod.net>
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 <gnoack@google.com>
Cc: Justin Suess <utilityemal77@gmail.com>
Cc: Masami Hiramatsu <mhiramat@kernel.org>
Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: Steven Rostedt <rostedt@goodmis.org>
Cc: Tingmao Wang <m@maowtm.org>
Signed-off-by: Mickaël Salaün <mic@digikod.net>
---
Changes since v2:
https://patch.msgid.link/20260406143717.1815792-10-mic@digikod.net
- 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/20250523165741.693976-6-mic@digikod.net
- 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(-)
diff --git a/include/trace/events/landlock.h b/include/trace/events/landlock.h
index 7f221d8fff38..c693248afe23 100644
--- a/include/trace/events/landlock.h
+++ b/include/trace/events/landlock.h
@@ -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 */
diff --git a/security/landlock/domain.c b/security/landlock/domain.c
index 082c4da68536..c20020024de4 100644
--- a/security/landlock/domain.c
+++ b/security/landlock/domain.c
@@ -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
diff --git a/security/landlock/domain.h b/security/landlock/domain.h
index 8351e22016fe..5baa4a73b446 100644
--- a/security/landlock/domain.h
+++ b/security/landlock/domain.h
@@ -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,
diff --git a/security/landlock/fs.c b/security/landlock/fs.c
index 48744a21d0a3..fe028aac26ae 100644
--- a/security/landlock/fs.c
+++ b/security/landlock/fs.c
@@ -376,31 +376,55 @@ int landlock_append_fs_rule(struct landlock_ruleset *const ruleset,
/* Access-control management */
-/*
- * The lifetime of the returned rule is tied to @domain.
+/**
+ * get_inode_id - Look up the Landlock object for a dentry
+ * @dentry: The dentry to look up.
+ * @id: Filled with the inode's Landlock object pointer on success.
+ *
+ * Extracts the Landlock object pointer from @dentry's inode security blob and
+ * stores it in @id for use as a rule-tree lookup key.
*
- * Returns NULL if no rule is found or if @dentry is negative.
+ * When this returns false (negative dentry or no Landlock object), no rule can
+ * match this inode, so landlock_unmask_layers() need not be called. Callers
+ * that gate landlock_unmask_layers() on this function must handle the NULL
+ * masks case independently, since the !masks-returns-true early-return in
+ * landlock_unmask_layers() will not be reached. See the allowed_parent2
+ * initialization in is_access_to_paths_allowed().
+ *
+ * Return: True if a Landlock object exists for @dentry, false otherwise.
*/
-static const struct landlock_rule *
-find_rule(const struct landlock_domain *const domain,
- const struct dentry *const dentry)
+static bool get_inode_id(const struct dentry *const dentry,
+ struct landlock_id *id)
{
- const struct landlock_rule *rule;
- const struct inode *inode;
- struct landlock_id id = {
- .type = LANDLOCK_KEY_INODE,
- };
-
/* Ignores nonexistent leafs. */
if (d_is_negative(dentry))
- return NULL;
+ return false;
- inode = d_backing_inode(dentry);
- rcu_read_lock();
- id.key.object = rcu_dereference(landlock_inode(inode)->object);
- rule = landlock_find_rule(domain, id);
- rcu_read_unlock();
- return rule;
+ /*
+ * rcu_access_pointer() is sufficient: the pointer is used only as a
+ * numeric comparison key for rule lookup, not dereferenced. The object
+ * cannot be freed while the domain exists because the domain's rule
+ * tree holds its own reference to it.
+ */
+ id->key.object = rcu_access_pointer(
+ landlock_inode(d_backing_inode(dentry))->object);
+ return !!id->key.object;
+}
+
+static bool unmask_layers_fs(const struct landlock_domain *const domain,
+ const struct landlock_id id,
+ const access_mask_t access_request,
+ struct layer_masks *masks,
+ const struct dentry *const dentry)
+{
+ const struct landlock_rule *rule = NULL;
+ bool ret;
+
+ ret = landlock_unmask_layers(domain, id, masks, &rule);
+ if (rule)
+ trace_landlock_check_rule_fs(domain, rule, access_request,
+ dentry);
+ return ret;
}
/*
@@ -781,6 +805,9 @@ is_access_to_paths_allowed(const struct landlock_domain *const domain,
bool allowed_parent1 = false, allowed_parent2 = false, is_dom_check,
child1_is_directory = true, child2_is_directory = true;
struct path walker_path;
+ struct landlock_id id = {
+ .type = LANDLOCK_KEY_INODE,
+ };
access_mask_t access_masked_parent1, access_masked_parent2;
struct layer_masks _layer_masks_child1, _layer_masks_child2;
struct layer_masks *layer_masks_child1 = NULL,
@@ -820,28 +847,46 @@ is_access_to_paths_allowed(const struct landlock_domain *const domain,
/* For a simple request, only check for requested accesses. */
access_masked_parent1 = access_request_parent1;
access_masked_parent2 = access_request_parent2;
+ /*
+ * Simple requests have no parent2 to check, so parent2 is
+ * trivially allowed. This must be set explicitly because the
+ * get_inode_id() gate in the pathwalk loop may prevent
+ * landlock_unmask_layers() from being called (which would
+ * otherwise return true for NULL masks as a side effect).
+ */
+ allowed_parent2 = true;
is_dom_check = false;
}
if (unlikely(dentry_child1)) {
- /*
- * Get the layer masks for the child dentries for use by domain
- * check later.
- */
- if (landlock_init_layer_masks(domain, LANDLOCK_MASK_ACCESS_FS,
- &_layer_masks_child1,
- LANDLOCK_KEY_INODE))
- landlock_unmask_layers(find_rule(domain, dentry_child1),
- &_layer_masks_child1);
+ struct landlock_id id = {
+ .type = LANDLOCK_KEY_INODE,
+ };
+ access_mask_t handled;
+
+ handled = landlock_init_layer_masks(domain,
+ LANDLOCK_MASK_ACCESS_FS,
+ &_layer_masks_child1,
+ LANDLOCK_KEY_INODE);
+ if (handled && get_inode_id(dentry_child1, &id))
+ unmask_layers_fs(domain, id, handled,
+ &_layer_masks_child1, dentry_child1);
layer_masks_child1 = &_layer_masks_child1;
child1_is_directory = d_is_dir(dentry_child1);
}
if (unlikely(dentry_child2)) {
- if (landlock_init_layer_masks(domain, LANDLOCK_MASK_ACCESS_FS,
- &_layer_masks_child2,
- LANDLOCK_KEY_INODE))
- landlock_unmask_layers(find_rule(domain, dentry_child2),
- &_layer_masks_child2);
+ struct landlock_id id = {
+ .type = LANDLOCK_KEY_INODE,
+ };
+ access_mask_t handled;
+
+ handled = landlock_init_layer_masks(domain,
+ LANDLOCK_MASK_ACCESS_FS,
+ &_layer_masks_child2,
+ LANDLOCK_KEY_INODE);
+ if (handled && get_inode_id(dentry_child2, &id))
+ unmask_layers_fs(domain, id, handled,
+ &_layer_masks_child2, dentry_child2);
layer_masks_child2 = &_layer_masks_child2;
child2_is_directory = d_is_dir(dentry_child2);
}
@@ -853,8 +898,6 @@ is_access_to_paths_allowed(const struct landlock_domain *const domain,
* restriction.
*/
while (true) {
- const struct landlock_rule *rule;
-
/*
* If at least all accesses allowed on the destination are
* already allowed on the source, respectively if there is at
@@ -895,13 +938,20 @@ is_access_to_paths_allowed(const struct landlock_domain *const domain,
break;
}
- rule = find_rule(domain, walker_path.dentry);
- allowed_parent1 =
- allowed_parent1 ||
- landlock_unmask_layers(rule, layer_masks_parent1);
- allowed_parent2 =
- allowed_parent2 ||
- landlock_unmask_layers(rule, layer_masks_parent2);
+ if (get_inode_id(walker_path.dentry, &id)) {
+ allowed_parent1 =
+ allowed_parent1 ||
+ unmask_layers_fs(domain, id,
+ access_masked_parent1,
+ layer_masks_parent1,
+ walker_path.dentry);
+ allowed_parent2 =
+ allowed_parent2 ||
+ unmask_layers_fs(domain, id,
+ access_masked_parent2,
+ layer_masks_parent2,
+ walker_path.dentry);
+ }
/* Stops when a rule from each layer grants access. */
if (allowed_parent1 && allowed_parent2)
@@ -1064,23 +1114,30 @@ static bool collect_domain_accesses(const struct landlock_domain *const domain,
struct layer_masks *layer_masks_dom)
{
bool ret = false;
+ access_mask_t access_masked_dom;
if (WARN_ON_ONCE(!domain || !mnt_root || !dir || !layer_masks_dom))
return true;
if (is_nouser_or_private(dir))
return true;
- if (!landlock_init_layer_masks(domain, LANDLOCK_MASK_ACCESS_FS,
- layer_masks_dom, LANDLOCK_KEY_INODE))
+ access_masked_dom =
+ landlock_init_layer_masks(domain, LANDLOCK_MASK_ACCESS_FS,
+ layer_masks_dom, LANDLOCK_KEY_INODE);
+ if (!access_masked_dom)
return true;
dget(dir);
while (true) {
struct dentry *parent_dentry;
+ struct landlock_id id = {
+ .type = LANDLOCK_KEY_INODE,
+ };
/* Gets all layers allowing all domain accesses. */
- if (landlock_unmask_layers(find_rule(domain, dir),
- layer_masks_dom)) {
+ if (get_inode_id(dir, &id) &&
+ unmask_layers_fs(domain, id, access_masked_dom,
+ layer_masks_dom, dir)) {
/*
* Stops when all handled accesses are allowed by at
* least one rule in each layer.
diff --git a/security/landlock/net.c b/security/landlock/net.c
index ead97fcfdcff..8f2aaac54b33 100644
--- a/security/landlock/net.c
+++ b/security/landlock/net.c
@@ -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;
--
2.54.0
^ permalink raw reply related
* [PATCH v3 15/20] selftests/landlock: Add trace event test infrastructure and tests
From: Mickaël Salaün @ 2026-07-22 17:11 UTC (permalink / raw)
To: Günther Noack, Steven Rostedt
Cc: Mickaël Salaün, Christian Brauner, Jann Horn, Jeff Xu,
Justin Suess, Kees Cook, Masami Hiramatsu, Mathieu Desnoyers,
Matthieu Buffet, Mikhail Ivanov, Tingmao Wang, kernel-team,
linux-security-module, linux-trace-kernel
In-Reply-To: <20260722171159.2776765-1-mic@digikod.net>
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 <gnoack@google.com>
Cc: Tingmao Wang <m@maowtm.org>
Signed-off-by: Mickaël Salaün <mic@digikod.net>
---
Changes since v2:
https://patch.msgid.link/20260406143717.1815792-14-mic@digikod.net
- 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
diff --git a/tools/testing/selftests/landlock/audit.h b/tools/testing/selftests/landlock/audit.h
index f45fdef35681..d428ce802f49 100644
--- a/tools/testing/selftests/landlock/audit.h
+++ b/tools/testing/selftests/landlock/audit.h
@@ -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
diff --git a/tools/testing/selftests/landlock/common.h b/tools/testing/selftests/landlock/common.h
index 7206d5105d66..c5124de68a51 100644
--- a/tools/testing/selftests/landlock/common.h
+++ b/tools/testing/selftests/landlock/common.h
@@ -253,3 +253,50 @@ static void __maybe_unused set_unix_address(struct service_fixture *const srv,
srv->unix_addr_len = SUN_LEN(&srv->unix_addr);
srv->unix_addr.sun_path[0] = '\0';
}
+
+/**
+ * regex_escape - Escape BRE metacharacters in a string
+ *
+ * @src: Source string to escape.
+ * @dst: Destination buffer for the escaped string.
+ * @dst_size: Size of the destination buffer.
+ *
+ * Escapes characters that have special meaning in POSIX Basic Regular
+ * Expressions: $ * . [ \ ] ^
+ *
+ * Returns a pointer to the NUL terminator in @dst (cursor-style API for
+ * chaining), or (char *)-ENOMEM if the buffer is too small.
+ */
+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;
+}
diff --git a/tools/testing/selftests/landlock/config b/tools/testing/selftests/landlock/config
index 8fe9b461b1fd..d86321936fd8 100644
--- a/tools/testing/selftests/landlock/config
+++ b/tools/testing/selftests/landlock/config
@@ -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
diff --git a/tools/testing/selftests/landlock/trace.h b/tools/testing/selftests/landlock/trace.h
new file mode 100644
index 000000000000..31f17b43e9f4
--- /dev/null
+++ b/tools/testing/selftests/landlock/trace.h
@@ -0,0 +1,634 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/*
+ * Landlock trace test helpers
+ *
+ * Copyright © 2026 Cloudflare, Inc.
+ */
+
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <regex.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include "kselftest_harness.h"
+
+#define TRACEFS_ROOT "/sys/kernel/tracing"
+#define TRACEFS_LANDLOCK_DIR TRACEFS_ROOT "/events/landlock"
+#define TRACEFS_CREATE_RULESET_ENABLE \
+ TRACEFS_LANDLOCK_DIR "/landlock_create_ruleset/enable"
+#define TRACEFS_CREATE_DOMAIN_ENABLE \
+ TRACEFS_LANDLOCK_DIR "/landlock_create_domain/enable"
+#define TRACEFS_ADD_RULE_FS_ENABLE \
+ TRACEFS_LANDLOCK_DIR "/landlock_add_rule_fs/enable"
+#define TRACEFS_ADD_RULE_NET_ENABLE \
+ TRACEFS_LANDLOCK_DIR "/landlock_add_rule_net/enable"
+#define TRACEFS_CHECK_RULE_FS_ENABLE \
+ TRACEFS_LANDLOCK_DIR "/landlock_check_rule_fs/enable"
+#define TRACEFS_CHECK_RULE_NET_ENABLE \
+ TRACEFS_LANDLOCK_DIR "/landlock_check_rule_net/enable"
+#define TRACEFS_DENY_ACCESS_FS_ENABLE \
+ TRACEFS_LANDLOCK_DIR "/landlock_deny_access_fs/enable"
+#define TRACEFS_DENY_ACCESS_NET_ENABLE \
+ TRACEFS_LANDLOCK_DIR "/landlock_deny_access_net/enable"
+#define TRACEFS_DENY_PTRACE_ENABLE \
+ TRACEFS_LANDLOCK_DIR "/landlock_deny_ptrace/enable"
+#define TRACEFS_DENY_SCOPE_SIGNAL_ENABLE \
+ TRACEFS_LANDLOCK_DIR "/landlock_deny_scope_signal/enable"
+#define TRACEFS_DENY_SCOPE_ABSTRACT_UNIX_SOCKET_ENABLE \
+ TRACEFS_LANDLOCK_DIR \
+ "/landlock_deny_scope_abstract_unix_socket/enable"
+#define TRACEFS_FREE_DOMAIN_ENABLE \
+ TRACEFS_LANDLOCK_DIR "/landlock_free_domain/enable"
+#define TRACEFS_FREE_RULESET_ENABLE \
+ TRACEFS_LANDLOCK_DIR "/landlock_free_ruleset/enable"
+#define TRACEFS_TRACE TRACEFS_ROOT "/trace"
+#define TRACEFS_SET_EVENT_PID TRACEFS_ROOT "/set_event_pid"
+#define TRACEFS_OPTIONS_EVENT_FORK TRACEFS_ROOT "/options/event-fork"
+
+#define TRACE_BUFFER_SIZE (64 * 1024)
+
+/*
+ * Trace line prefix: matches the ftrace "trace" file format. Format: "
+ * <task>-<pid> [<cpu>] <flags> <timestamp>: "
+ *
+ * The task parameter must be a string literal truncated to 15 chars
+ * (TASK_COMM_LEN - 1), matching what the kernel stores in task->comm. The
+ * pattern accepts either the expected task name or "<...>" because the ftrace
+ * comm cache may evict short-lived processes (e.g., forked children that exit
+ * before the trace buffer is read).
+ *
+ * No unescaped '.' in any REGEX macro; literal dots use '\\.'.
+ */
+#define TRACE_PREFIX(task) \
+ "^ *\\(<\\.\\.\\.>" \
+ "\\|" task "\\)" \
+ "-[0-9]\\+ *\\[[0-9]\\+\\] [^ ]\\+ \\+[0-9]\\+\\.[0-9]\\+: "
+
+/*
+ * Task name for events emitted by kworker threads (e.g., free_domain fires from
+ * a work queue, not from the test process).
+ */
+#define KWORKER_TASK "kworker/[0-9]\\+:[0-9]\\+"
+
+#define REGEX_ADD_RULE_FS(task) \
+ TRACE_PREFIX(task) \
+ "landlock_add_rule_fs: " \
+ "ruleset=[0-9a-f]\\+\\.[0-9]\\+ " \
+ "access_rights=[a-z_|]* " \
+ "dev=[0-9]\\+:[0-9]\\+ " \
+ "ino=[0-9]\\+ " \
+ "path=[^ ]\\+$"
+
+#define REGEX_ADD_RULE_NET(task) \
+ TRACE_PREFIX(task) \
+ "landlock_add_rule_net: " \
+ "ruleset=[0-9a-f]\\+\\.[0-9]\\+ " \
+ "access_rights=[a-z_|]* " \
+ "port=[0-9]\\+$"
+
+#define REGEX_CREATE_RULESET(task) \
+ TRACE_PREFIX(task) \
+ "landlock_create_ruleset: " \
+ "ruleset=[0-9a-f]\\+\\.[0-9]\\+ " \
+ "handled_fs=[a-z_|]* " \
+ "handled_net=[a-z_|]* " \
+ "scoped=[a-z_|]*$"
+
+#define REGEX_CREATE_DOMAIN(task) \
+ TRACE_PREFIX(task) \
+ "landlock_create_domain: " \
+ "domain=[0-9a-f]\\+ " \
+ "parent=[0-9a-f]\\+ " \
+ "ruleset=[0-9a-f]\\+\\.[0-9]\\+$"
+
+#define REGEX_CHECK_RULE_FS(task) \
+ TRACE_PREFIX(task) \
+ "landlock_check_rule_fs: " \
+ "domain=[0-9a-f]\\+ " \
+ "access_request=[a-z_|]* " \
+ "dev=[0-9]\\+:[0-9]\\+ " \
+ "ino=[0-9]\\+ " \
+ "grants={[a-z_|,]*}$"
+
+#define REGEX_CHECK_RULE_NET(task) \
+ TRACE_PREFIX(task) \
+ "landlock_check_rule_net: " \
+ "domain=[0-9a-f]\\+ " \
+ "access_request=[a-z_|]* " \
+ "port=[0-9]\\+ " \
+ "grants={[a-z_|,]*}$"
+
+#define REGEX_DENY_ACCESS_FS(task) \
+ TRACE_PREFIX(task) \
+ "landlock_deny_access_fs: " \
+ "domain=[0-9a-f]\\+ " \
+ "same_exec=[01] " \
+ "logged=[01] " \
+ "blockers=[a-z_|]* " \
+ "dev=[0-9]\\+:[0-9]\\+ " \
+ "ino=[0-9]\\+ " \
+ "path=[^ ]*$"
+
+#define REGEX_DENY_ACCESS_NET(task) \
+ TRACE_PREFIX(task) \
+ "landlock_deny_access_net: " \
+ "domain=[0-9a-f]\\+ " \
+ "same_exec=[01] " \
+ "logged=[01] " \
+ "blockers=[a-z_|]* " \
+ "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]\\+ " \
+ "tracee_comm=[^ ]*$"
+
+#define REGEX_DENY_SCOPE_SIGNAL(task) \
+ TRACE_PREFIX(task) \
+ "landlock_deny_scope_signal: " \
+ "domain=[0-9a-f]\\+ " \
+ "same_exec=[01] " \
+ "logged=[01] " \
+ "target_pid=[0-9]\\+ " \
+ "target_comm=[^ ]*$"
+
+#define REGEX_DENY_SCOPE_ABSTRACT_UNIX_SOCKET(task) \
+ TRACE_PREFIX(task) \
+ "landlock_deny_scope_abstract_unix_socket: " \
+ "domain=[0-9a-f]\\+ " \
+ "same_exec=[01] " \
+ "logged=[01] " \
+ "peer_pid=[0-9]\\+ " \
+ "sun_path=[^ ]*$"
+
+#define REGEX_FREE_DOMAIN(task) \
+ TRACE_PREFIX(task) \
+ "landlock_free_domain: " \
+ "domain=[0-9a-f]\\+ " \
+ "denials=[0-9]\\+$"
+
+#define REGEX_FREE_RULESET(task) \
+ TRACE_PREFIX(task) \
+ "landlock_free_ruleset: " \
+ "ruleset=[0-9a-f]\\+\\.[0-9]\\+$"
+
+static int __maybe_unused tracefs_write(const char *path, const char *value)
+{
+ int fd;
+ ssize_t ret;
+ size_t len = strlen(value);
+
+ fd = open(path, O_WRONLY | O_TRUNC | O_CLOEXEC);
+ if (fd < 0)
+ return -errno;
+
+ ret = write(fd, value, len);
+ close(fd);
+ if (ret < 0)
+ return -errno;
+ if ((size_t)ret != len)
+ return -EIO;
+
+ return 0;
+}
+
+static int __maybe_unused tracefs_write_int(const char *path, int value)
+{
+ char buf[32];
+
+ snprintf(buf, sizeof(buf), "%d", value);
+ return tracefs_write(path, buf);
+}
+
+static int __maybe_unused tracefs_setup(void)
+{
+ struct stat st;
+
+ /* Mount tracefs if not already mounted. */
+ if (stat(TRACEFS_ROOT, &st) != 0) {
+ int ret = mount("tracefs", TRACEFS_ROOT, "tracefs", 0, NULL);
+
+ if (ret)
+ return -errno;
+ }
+
+ /* Verify landlock events are available. */
+ if (stat(TRACEFS_LANDLOCK_DIR, &st) != 0)
+ return -ENOENT;
+
+ return 0;
+}
+
+/*
+ * Set up PID-based event filtering so only events from the current process and
+ * its children are recorded. This is analogous to audit's AUDIT_EXE filter: it
+ * prevents events from unrelated processes from polluting the trace buffer.
+ */
+static int __maybe_unused tracefs_set_pid_filter(pid_t pid)
+{
+ int ret;
+
+ /* Enable event-fork so children inherit the PID filter. */
+ ret = tracefs_write(TRACEFS_OPTIONS_EVENT_FORK, "1");
+ if (ret)
+ return ret;
+
+ return tracefs_write_int(TRACEFS_SET_EVENT_PID, pid);
+}
+
+/* Clear the PID filter to stop filtering by PID. */
+static int __maybe_unused tracefs_clear_pid_filter(void)
+{
+ return tracefs_write(TRACEFS_SET_EVENT_PID, "");
+}
+
+static int __maybe_unused tracefs_enable_event(const char *enable_path,
+ bool enable)
+{
+ return tracefs_write(enable_path, enable ? "1" : "0");
+}
+
+static int __maybe_unused tracefs_clear(void)
+{
+ return tracefs_write(TRACEFS_TRACE, "");
+}
+
+/*
+ * Reads the trace buffer content into a newly allocated buffer. The caller is
+ * responsible for freeing the returned buffer. Returns NULL on error.
+ */
+static char __maybe_unused *tracefs_read_trace(void)
+{
+ char *buf;
+ int fd;
+ ssize_t total = 0, ret;
+
+ buf = malloc(TRACE_BUFFER_SIZE);
+ if (!buf)
+ return NULL;
+
+ fd = open(TRACEFS_TRACE, O_RDONLY | O_CLOEXEC);
+ if (fd < 0) {
+ free(buf);
+ return NULL;
+ }
+
+ while (total < TRACE_BUFFER_SIZE - 1) {
+ ret = read(fd, buf + total, TRACE_BUFFER_SIZE - 1 - total);
+ if (ret <= 0)
+ break;
+ total += ret;
+ }
+ close(fd);
+ buf[total] = '\0';
+ return buf;
+}
+
+/* Counts the number of lines in @buf matching the basic regex @pattern. */
+static int __maybe_unused tracefs_count_matches(const char *buf,
+ const char *pattern)
+{
+ regex_t regex;
+ int count = 0;
+ const char *line, *end;
+
+ if (regcomp(®ex, pattern, 0) != 0)
+ return -EINVAL;
+
+ line = buf;
+ while (*line) {
+ end = strchr(line, '\n');
+ if (!end)
+ end = line + strlen(line);
+
+ /* Create a temporary null-terminated line. */
+ size_t len = end - line;
+ char *tmp = malloc(len + 1);
+
+ if (tmp) {
+ memcpy(tmp, line, len);
+ tmp[len] = '\0';
+ if (regexec(®ex, tmp, 0, NULL, 0) == 0)
+ count++;
+ free(tmp);
+ }
+
+ if (*end == '\n')
+ line = end + 1;
+ else
+ break;
+ }
+
+ regfree(®ex);
+ return count;
+}
+
+/*
+ * Extracts the value of a named field from a trace line in @buf. Searches for
+ * the first line matching @line_pattern, then extracts the value after
+ * "@field_name=" into @out. Stops at space or newline.
+ *
+ * Returns 0 on success, -ENOENT if no match.
+ */
+static int __maybe_unused tracefs_extract_field(const char *buf,
+ const char *line_pattern,
+ const char *field_name,
+ char *out, size_t out_size)
+{
+ regex_t regex;
+ const char *line, *end;
+
+ if (regcomp(®ex, line_pattern, 0) != 0)
+ return -EINVAL;
+
+ line = buf;
+ while (*line) {
+ end = strchr(line, '\n');
+ if (!end)
+ end = line + strlen(line);
+
+ size_t len = end - line;
+ char *tmp = malloc(len + 1);
+
+ if (tmp) {
+ const char *field, *val_start;
+ size_t field_len, val_len;
+
+ memcpy(tmp, line, len);
+ tmp[len] = '\0';
+
+ if (regexec(®ex, tmp, 0, NULL, 0) != 0) {
+ free(tmp);
+ goto next;
+ }
+
+ /*
+ * Find "field_name=" in the line, ensuring a word
+ * boundary before the field name to avoid substring
+ * matches (e.g., "port" in "sport").
+ */
+ field_len = strlen(field_name);
+ field = tmp;
+ while ((field = strstr(field, field_name))) {
+ if (field[field_len] == '=' &&
+ (field == tmp || field[-1] == ' '))
+ break;
+ field++;
+ }
+ if (!field) {
+ free(tmp);
+ regfree(®ex);
+ return -ENOENT;
+ }
+
+ val_start = field + field_len + 1;
+ val_len = 0;
+ while (val_start[val_len] &&
+ val_start[val_len] != ' ' &&
+ val_start[val_len] != '\n')
+ val_len++;
+
+ if (val_len >= out_size)
+ val_len = out_size - 1;
+ memcpy(out, val_start, val_len);
+ out[val_len] = '\0';
+
+ free(tmp);
+ regfree(®ex);
+ return 0;
+ }
+next:
+ if (*end == '\n')
+ line = end + 1;
+ else
+ break;
+ }
+
+ regfree(®ex);
+ return -ENOENT;
+}
+
+/*
+ * Common fixture setup for trace tests. Mounts tracefs if needed and sets a
+ * PID filter. The caller must create a mount namespace first
+ * (unshare(CLONE_NEWNS) + mount(MS_REC | MS_PRIVATE)) to isolate the tracefs
+ * mount; the trace buffer, per-event enable flags, and PID filter are global
+ * kernel state, scoped to the test by the PID filter.
+ *
+ * Returns 0 on success, -errno on failure (caller should SKIP).
+ */
+static int __maybe_unused tracefs_fixture_setup(void)
+{
+ int ret;
+
+ ret = tracefs_setup();
+ if (ret)
+ return ret;
+
+ return tracefs_set_pid_filter(getpid());
+}
+
+static void __maybe_unused tracefs_fixture_teardown(void)
+{
+ tracefs_clear_pid_filter();
+}
+
+/*
+ * Temporarily raises CAP_SYS_ADMIN effective capability, calls @func, then
+ * drops the capability. Returns the value from @func, or -EPERM if the
+ * capability manipulation fails.
+ */
+static int __maybe_unused tracefs_priv_call(int (*func)(void))
+{
+ const cap_value_t admin = CAP_SYS_ADMIN;
+ cap_t cap_p;
+ int ret;
+
+ cap_p = cap_get_proc();
+ if (!cap_p)
+ return -EPERM;
+
+ if (cap_set_flag(cap_p, CAP_EFFECTIVE, 1, &admin, CAP_SET) ||
+ cap_set_proc(cap_p)) {
+ cap_free(cap_p);
+ return -EPERM;
+ }
+
+ ret = func();
+
+ cap_set_flag(cap_p, CAP_EFFECTIVE, 1, &admin, CAP_CLEAR);
+ cap_set_proc(cap_p);
+ cap_free(cap_p);
+ return ret;
+}
+
+/* Read the trace buffer with elevated privileges. Returns NULL on failure. */
+static char __maybe_unused *tracefs_read_buf(void)
+{
+ /* Cannot use tracefs_priv_call() because the return type is char *. */
+ cap_t cap_p;
+ char *buf;
+ const cap_value_t admin = CAP_SYS_ADMIN;
+
+ cap_p = cap_get_proc();
+ if (!cap_p)
+ return NULL;
+
+ if (cap_set_flag(cap_p, CAP_EFFECTIVE, 1, &admin, CAP_SET) ||
+ cap_set_proc(cap_p)) {
+ cap_free(cap_p);
+ return NULL;
+ }
+
+ buf = tracefs_read_trace();
+
+ cap_set_flag(cap_p, CAP_EFFECTIVE, 1, &admin, CAP_CLEAR);
+ cap_set_proc(cap_p);
+ cap_free(cap_p);
+ return buf;
+}
+
+/* Clear the trace buffer with elevated privileges. Returns 0 on success. */
+static int __maybe_unused tracefs_clear_buf(void)
+{
+ return tracefs_priv_call(tracefs_clear);
+}
+
+/*
+ * Forks a child that creates a Landlock sandbox and performs an FS access. The
+ * parent waits for the child, then reads the trace buffer.
+ *
+ * Requires common.h and wrappers.h to be included before trace.h.
+ */
+static void __maybe_unused sandbox_child_fs_access(
+ struct __test_metadata *const _metadata, const char *rule_path,
+ __u64 handled_access, __u64 allowed_access, const char *access_path)
+{
+ pid_t pid;
+ int status;
+
+ pid = fork();
+ ASSERT_LE(0, pid);
+
+ if (pid == 0) {
+ struct landlock_ruleset_attr ruleset_attr = {
+ .handled_access_fs = handled_access,
+ };
+ struct landlock_path_beneath_attr path_beneath = {
+ .allowed_access = allowed_access,
+ };
+ int ruleset_fd, fd;
+
+ ruleset_fd = landlock_create_ruleset(&ruleset_attr,
+ sizeof(ruleset_attr), 0);
+ if (ruleset_fd < 0)
+ _exit(1);
+
+ path_beneath.parent_fd =
+ open(rule_path, O_PATH | O_DIRECTORY | O_CLOEXEC);
+ if (path_beneath.parent_fd < 0) {
+ close(ruleset_fd);
+ _exit(1);
+ }
+
+ if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
+ &path_beneath, 0)) {
+ close(path_beneath.parent_fd);
+ close(ruleset_fd);
+ _exit(1);
+ }
+ close(path_beneath.parent_fd);
+
+ 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);
+
+ fd = open(access_path, 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));
+}
+
+/*
+ * Forks a child that creates a Landlock sandbox allowing execute+read_dir for
+ * /usr and execute-only for ".", then execs ./true. The true binary opens "."
+ * on startup, triggering a read_dir denial with same_exec=0. The parent waits
+ * for the child to exit.
+ */
+static void __maybe_unused sandbox_child_exec_true(
+ struct __test_metadata *const _metadata, __u32 restrict_flags)
+{
+ pid_t pid;
+ int status;
+
+ 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 = {
+ .allowed_access = LANDLOCK_ACCESS_FS_EXECUTE |
+ LANDLOCK_ACCESS_FS_READ_DIR,
+ };
+ int ruleset_fd;
+
+ ruleset_fd = landlock_create_ruleset(&attr, sizeof(attr), 0);
+ if (ruleset_fd < 0)
+ _exit(1);
+
+ path_beneath.parent_fd =
+ open("/usr", O_PATH | O_DIRECTORY | O_CLOEXEC);
+ if (path_beneath.parent_fd >= 0) {
+ landlock_add_rule(ruleset_fd,
+ LANDLOCK_RULE_PATH_BENEATH,
+ &path_beneath, 0);
+ close(path_beneath.parent_fd);
+ }
+
+ path_beneath.allowed_access = LANDLOCK_ACCESS_FS_EXECUTE;
+ path_beneath.parent_fd =
+ open(".", O_PATH | O_DIRECTORY | O_CLOEXEC);
+ if (path_beneath.parent_fd >= 0) {
+ landlock_add_rule(ruleset_fd,
+ LANDLOCK_RULE_PATH_BENEATH,
+ &path_beneath, 0);
+ close(path_beneath.parent_fd);
+ }
+
+ prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+ if (landlock_restrict_self(ruleset_fd, restrict_flags))
+ _exit(1);
+ close(ruleset_fd);
+
+ execl("./true", "./true", NULL);
+ _exit(1);
+ }
+
+ ASSERT_EQ(pid, waitpid(pid, &status, 0));
+ ASSERT_TRUE(WIFEXITED(status));
+ EXPECT_EQ(0, WEXITSTATUS(status));
+}
diff --git a/tools/testing/selftests/landlock/trace_test.c b/tools/testing/selftests/landlock/trace_test.c
new file mode 100644
index 000000000000..a141f22ad98f
--- /dev/null
+++ b/tools/testing/selftests/landlock/trace_test.c
@@ -0,0 +1,1101 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Landlock tests - Tracepoints
+ *
+ * Copyright © 2026 Cloudflare, Inc.
+ */
+
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/landlock.h>
+#include <sched.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include "common.h"
+#include "trace.h"
+
+#define TRACE_TASK "trace_test"
+
+/* clang-format off */
+FIXTURE(trace) {
+ /* clang-format on */
+ int tracefs_ok;
+};
+
+FIXTURE_SETUP(trace)
+{
+ 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_CREATE_RULESET_ENABLE, true));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_CREATE_DOMAIN_ENABLE, true));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_ADD_RULE_FS_ENABLE, true));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_ADD_RULE_NET_ENABLE, true));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_CHECK_RULE_FS_ENABLE, true));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_CHECK_RULE_NET_ENABLE, true));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_DENY_ACCESS_FS_ENABLE, true));
+ ASSERT_EQ(0,
+ tracefs_enable_event(TRACEFS_DENY_ACCESS_NET_ENABLE, true));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_FREE_DOMAIN_ENABLE, true));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_FREE_RULESET_ENABLE, true));
+ ASSERT_EQ(0, tracefs_clear());
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+FIXTURE_TEARDOWN(trace)
+{
+ if (!self->tracefs_ok)
+ return;
+
+ /* Disables landlock events and clears PID filter. */
+ set_cap(_metadata, CAP_SYS_ADMIN);
+ tracefs_enable_event(TRACEFS_CREATE_RULESET_ENABLE, false);
+ tracefs_enable_event(TRACEFS_CREATE_DOMAIN_ENABLE, false);
+ tracefs_enable_event(TRACEFS_ADD_RULE_FS_ENABLE, false);
+ tracefs_enable_event(TRACEFS_ADD_RULE_NET_ENABLE, false);
+ tracefs_enable_event(TRACEFS_CHECK_RULE_FS_ENABLE, false);
+ tracefs_enable_event(TRACEFS_CHECK_RULE_NET_ENABLE, false);
+ tracefs_enable_event(TRACEFS_DENY_ACCESS_FS_ENABLE, false);
+ tracefs_enable_event(TRACEFS_DENY_ACCESS_NET_ENABLE, false);
+ tracefs_enable_event(TRACEFS_FREE_DOMAIN_ENABLE, false);
+ tracefs_enable_event(TRACEFS_FREE_RULESET_ENABLE, false);
+ tracefs_clear_pid_filter();
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+
+ /*
+ * The mount namespace is cleaned up automatically when the test process
+ * (harness child) exits.
+ */
+}
+
+/*
+ * Verifies that no trace events are emitted when the tracepoints are disabled.
+ */
+TEST_F(trace, no_trace_when_disabled)
+{
+ char *buf;
+
+ /* Disable all landlock events. */
+ set_cap(_metadata, CAP_SYS_ADMIN);
+ ASSERT_EQ(0,
+ tracefs_enable_event(TRACEFS_CREATE_RULESET_ENABLE, false));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_CREATE_DOMAIN_ENABLE, false));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_ADD_RULE_FS_ENABLE, false));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_ADD_RULE_NET_ENABLE, false));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_CHECK_RULE_FS_ENABLE, false));
+ ASSERT_EQ(0,
+ tracefs_enable_event(TRACEFS_CHECK_RULE_NET_ENABLE, false));
+ ASSERT_EQ(0,
+ tracefs_enable_event(TRACEFS_DENY_ACCESS_FS_ENABLE, false));
+ ASSERT_EQ(0,
+ tracefs_enable_event(TRACEFS_DENY_ACCESS_NET_ENABLE, false));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_DENY_PTRACE_ENABLE, false));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_DENY_SCOPE_SIGNAL_ENABLE,
+ false));
+ ASSERT_EQ(0, tracefs_enable_event(
+ TRACEFS_DENY_SCOPE_ABSTRACT_UNIX_SOCKET_ENABLE,
+ false));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_FREE_DOMAIN_ENABLE, false));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_FREE_RULESET_ENABLE, false));
+ ASSERT_EQ(0, tracefs_clear());
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+
+ /*
+ * Trigger both allowed and denied accesses to verify neither check_rule
+ * nor check_access events fire when disabled.
+ */
+ sandbox_child_fs_access(_metadata, "/usr", LANDLOCK_ACCESS_FS_READ_DIR,
+ LANDLOCK_ACCESS_FS_READ_DIR, "/tmp");
+
+ /* Read trace buffer and verify no landlock events at all. */
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ EXPECT_EQ(0, tracefs_count_matches(buf, "landlock_"))
+ {
+ TH_LOG("Expected 0 landlock events when disabled\n%s", buf);
+ }
+
+ free(buf);
+}
+
+/*
+ * Verifies that landlock_create_ruleset emits a trace event with the correct
+ * handled access masks.
+ */
+TEST_F(trace, create_ruleset)
+{
+ struct landlock_ruleset_attr ruleset_attr = {
+ .handled_access_fs = LANDLOCK_ACCESS_FS_READ_FILE,
+ .handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP,
+ };
+ int ruleset_fd;
+ char *buf, *dot;
+ char field[64];
+
+ ruleset_fd =
+ landlock_create_ruleset(&ruleset_attr, sizeof(ruleset_attr), 0);
+ ASSERT_LE(0, ruleset_fd);
+ ASSERT_EQ(0, close(ruleset_fd));
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ EXPECT_EQ(1,
+ tracefs_count_matches(buf, REGEX_CREATE_RULESET(TRACE_TASK)))
+ {
+ TH_LOG("Expected 1 create_ruleset event\n%s", buf);
+ }
+
+ /* Verify handled_fs matches what we requested. */
+ EXPECT_EQ(0,
+ tracefs_extract_field(buf, REGEX_CREATE_RULESET(TRACE_TASK),
+ "handled_fs", field, sizeof(field)));
+ EXPECT_STREQ("read_file", field);
+
+ /* Verify handled_net matches. */
+ EXPECT_EQ(0,
+ tracefs_extract_field(buf, REGEX_CREATE_RULESET(TRACE_TASK),
+ "handled_net", field, sizeof(field)));
+ EXPECT_STREQ("bind_tcp", field);
+
+ /* Verify version is 0 at creation (no rules added yet). */
+ EXPECT_EQ(0,
+ tracefs_extract_field(buf, REGEX_CREATE_RULESET(TRACE_TASK),
+ "ruleset", field, sizeof(field)));
+ /* Format is <hex>.<dec>; version is after the dot. */
+ dot = strchr(field, '.');
+ ASSERT_NE(0, !!dot);
+ EXPECT_STREQ("0", dot + 1);
+
+ free(buf);
+}
+
+/*
+ * Verifies that the ruleset version increments with each add_rule call and that
+ * create_domain records the correct version.
+ */
+TEST_F(trace, ruleset_version)
+{
+ pid_t pid;
+ int status;
+ char *buf;
+ const char *dot;
+ char field[64];
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ pid = fork();
+ ASSERT_LE(0, pid);
+
+ if (pid == 0) {
+ struct landlock_ruleset_attr ruleset_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;
+
+ ruleset_fd = landlock_create_ruleset(&ruleset_attr,
+ sizeof(ruleset_attr), 0);
+ if (ruleset_fd < 0)
+ _exit(1);
+
+ /* First rule: version becomes 1. */
+ path_beneath.parent_fd =
+ open("/usr", O_PATH | O_DIRECTORY | O_CLOEXEC);
+ if (path_beneath.parent_fd < 0)
+ _exit(1);
+ landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
+ &path_beneath, 0);
+ close(path_beneath.parent_fd);
+
+ /* Second rule: version becomes 2. */
+ path_beneath.parent_fd =
+ open("/tmp", O_PATH | O_DIRECTORY | O_CLOEXEC);
+ if (path_beneath.parent_fd < 0)
+ _exit(1);
+ landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
+ &path_beneath, 0);
+ 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);
+ _exit(0);
+ }
+
+ ASSERT_EQ(pid, waitpid(pid, &status, 0));
+ ASSERT_TRUE(WIFEXITED(status));
+ EXPECT_EQ(0, WEXITSTATUS(status));
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ /* Verify create_ruleset has version=0. */
+ ASSERT_EQ(0,
+ tracefs_extract_field(buf, REGEX_CREATE_RULESET(TRACE_TASK),
+ "ruleset", field, sizeof(field)));
+ dot = strchr(field, '.');
+ ASSERT_NE(0, !!dot);
+ EXPECT_STREQ("0", dot + 1);
+
+ /* Verify 2 add_rule_fs events were emitted. */
+ EXPECT_EQ(2, tracefs_count_matches(buf, REGEX_ADD_RULE_FS(TRACE_TASK)))
+ {
+ TH_LOG("Expected 2 add_rule_fs events\n%s", buf);
+ }
+
+ /*
+ * Verify create_domain records version=2 (after 2 add_rule calls). The
+ * ruleset field format is <hex_id>.<dec_version>.
+ */
+ ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_CREATE_DOMAIN(TRACE_TASK),
+ "ruleset", field, sizeof(field)));
+ dot = strchr(field, '.');
+ ASSERT_NE(0, !!dot);
+ EXPECT_STREQ("2", dot + 1);
+
+ free(buf);
+}
+
+/*
+ * Verifies that landlock_create_domain emits a trace event linking the ruleset
+ * ID to the new domain ID.
+ */
+TEST_F(trace, create_domain)
+{
+ pid_t pid;
+ int status, check_count;
+ char *buf;
+ char parent_id[64], domain_id[64], check_domain[64];
+
+ /* Clear before the sandboxed child. */
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ pid = fork();
+ ASSERT_LE(0, pid);
+
+ if (pid == 0) {
+ struct landlock_ruleset_attr ruleset_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(&ruleset_attr,
+ sizeof(ruleset_attr), 0);
+ if (ruleset_fd < 0)
+ _exit(1);
+
+ path_beneath.parent_fd =
+ open("/usr", O_PATH | O_DIRECTORY | O_CLOEXEC);
+ if (path_beneath.parent_fd < 0)
+ _exit(1);
+
+ landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
+ &path_beneath, 0);
+ 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);
+
+ /* Trigger a check_rule to verify domain_id correlation. */
+ fd = open("/usr", 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));
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ /* Verify create_domain event exists. */
+ EXPECT_EQ(1,
+ tracefs_count_matches(buf, REGEX_CREATE_DOMAIN(TRACE_TASK)))
+ {
+ TH_LOG("Expected 1 create_domain event\n%s", buf);
+ }
+
+ /* Extract the domain ID from create_domain. */
+ EXPECT_EQ(0, tracefs_extract_field(buf, REGEX_CREATE_DOMAIN(TRACE_TASK),
+ "domain", domain_id,
+ sizeof(domain_id)));
+
+ /* Verify domain ID is non-zero. */
+ EXPECT_NE(0, strcmp(domain_id, "0"));
+
+ /* Verify parent=0 (first restriction, no prior domain). */
+ EXPECT_EQ(0, tracefs_extract_field(buf, REGEX_CREATE_DOMAIN(TRACE_TASK),
+ "parent", parent_id,
+ sizeof(parent_id)));
+ EXPECT_STREQ("0", parent_id);
+
+ /*
+ * Verify the same domain ID appears in the check_rule event, confirming
+ * end-to-end correlation.
+ */
+ check_count =
+ tracefs_count_matches(buf, REGEX_CHECK_RULE_FS(TRACE_TASK));
+ ASSERT_LE(1, check_count)
+ {
+ TH_LOG("Expected check_rule_fs events\n%s", buf);
+ }
+
+ EXPECT_EQ(0, tracefs_extract_field(buf, REGEX_CHECK_RULE_FS(TRACE_TASK),
+ "domain", check_domain,
+ sizeof(check_domain)));
+ EXPECT_STREQ(domain_id, check_domain);
+
+ free(buf);
+}
+
+/* Builds a rule-less scope-based ruleset; returns the fd or -1. */
+static int build_enforce_ruleset(void)
+{
+ const struct landlock_ruleset_attr attr = {
+ .scoped = LANDLOCK_SCOPE_SIGNAL,
+ };
+
+ return landlock_create_ruleset(&attr, sizeof(attr), 0);
+}
+
+/*
+ * Verifies that nested landlock_restrict_self calls produce trace events with
+ * correct parent domain IDs: the second create_domain's parent should be the
+ * first domain's ID.
+ */
+TEST_F(trace, create_domain_nested)
+{
+ pid_t pid;
+ int status;
+ char *buf;
+ const char *after_first;
+ char first_domain[64], first_parent[64], second_parent[64];
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ pid = fork();
+ ASSERT_LE(0, pid);
+
+ if (pid == 0) {
+ int ruleset_fd;
+
+ /* First restriction. */
+ ruleset_fd = build_enforce_ruleset();
+ if (ruleset_fd < 0)
+ _exit(1);
+ prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+ if (landlock_restrict_self(ruleset_fd, 0))
+ _exit(1);
+ close(ruleset_fd);
+
+ /* Second restriction (nested). */
+ ruleset_fd = build_enforce_ruleset();
+ if (ruleset_fd < 0)
+ _exit(1);
+ if (landlock_restrict_self(ruleset_fd, 0))
+ _exit(1);
+ close(ruleset_fd);
+
+ _exit(0);
+ }
+
+ ASSERT_EQ(pid, waitpid(pid, &status, 0));
+ ASSERT_TRUE(WIFEXITED(status));
+ EXPECT_EQ(0, WEXITSTATUS(status));
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ /* Should have 2 create_domain events. */
+ EXPECT_EQ(2,
+ tracefs_count_matches(buf, REGEX_CREATE_DOMAIN(TRACE_TASK)))
+ {
+ TH_LOG("Expected 2 create_domain events\n%s", buf);
+ }
+
+ /*
+ * Extract domain and parent from each create_domain event. The first
+ * event (parent=0) is the outer domain; the second (parent!=0) is the
+ * nested domain whose parent should match the first domain's ID.
+ */
+ ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_CREATE_DOMAIN(TRACE_TASK),
+ "domain", first_domain,
+ sizeof(first_domain)));
+ ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_CREATE_DOMAIN(TRACE_TASK),
+ "parent", first_parent,
+ sizeof(first_parent)));
+ EXPECT_STREQ("0", first_parent);
+
+ /*
+ * Find the second create_domain by scanning past the first.
+ * tracefs_extract_field returns the first match, so search in the
+ * buffer after the first event.
+ *
+ * Skip past the first create_domain line. tracefs_extract_field matches
+ * the first line that matches the regex, so passing the buffer after
+ * the first matching line gives us the second event.
+ */
+ after_first = strstr(buf, "landlock_create_domain:");
+ ASSERT_NE(NULL, after_first);
+ after_first = strchr(after_first, '\n');
+ ASSERT_NE(NULL, after_first);
+
+ ASSERT_EQ(0, tracefs_extract_field(
+ after_first + 1, REGEX_CREATE_DOMAIN(TRACE_TASK),
+ "parent", second_parent, sizeof(second_parent)));
+
+ /* The second domain's parent should be the first domain's ID. */
+ EXPECT_STREQ(first_domain, second_parent);
+
+ free(buf);
+}
+
+/*
+ * Verifies that landlock_add_rule does not emit a trace event when the syscall
+ * fails (e.g., invalid ruleset fd).
+ */
+TEST_F(trace, add_rule_invalid_fd)
+{
+ struct landlock_path_beneath_attr path_beneath = {
+ .allowed_access = LANDLOCK_ACCESS_FS_READ_FILE,
+ };
+ char *buf;
+
+ path_beneath.parent_fd = open("/usr", O_PATH | O_DIRECTORY | O_CLOEXEC);
+ ASSERT_LE(0, path_beneath.parent_fd);
+
+ /* Invalid ruleset fd (-1). */
+ ASSERT_EQ(-1, landlock_add_rule(-1, LANDLOCK_RULE_PATH_BENEATH,
+ &path_beneath, 0));
+ ASSERT_EQ(0, close(path_beneath.parent_fd));
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ EXPECT_EQ(0, tracefs_count_matches(buf, REGEX_ADD_RULE_FS(TRACE_TASK)))
+ {
+ TH_LOG("No add_rule_fs event expected on invalid fd\n%s", buf);
+ }
+
+ free(buf);
+}
+
+/*
+ * Verifies that landlock_create_domain does not emit a trace event when the
+ * syscall fails (e.g., invalid ruleset fd or unknown flags).
+ */
+TEST_F(trace, create_domain_invalid)
+{
+ int ruleset_fd;
+ char *buf;
+
+ ruleset_fd = build_enforce_ruleset();
+ ASSERT_LE(0, ruleset_fd);
+
+ /* Clear the trace buffer after create_ruleset event. */
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ /* Invalid fd. */
+ ASSERT_EQ(-1, landlock_restrict_self(-1, 0));
+
+ /* Unknown flags. */
+ ASSERT_EQ(-1, landlock_restrict_self(ruleset_fd, -1));
+
+ ASSERT_EQ(0, close(ruleset_fd));
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ EXPECT_EQ(0,
+ tracefs_count_matches(buf, REGEX_CREATE_DOMAIN(TRACE_TASK)))
+ {
+ TH_LOG("No create_domain event expected on error\n%s", buf);
+ }
+
+ free(buf);
+}
+
+/*
+ * Verifies that trace_landlock_free_domain fires when a domain is deallocated,
+ * with the correct denials count.
+ */
+TEST_F(trace, free_domain)
+{
+ char *buf;
+ int count;
+ char denials_field[32];
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ /*
+ * The domain is freed via a work queue (kworker), so the free_domain
+ * trace event is emitted from a different PID. Clear the PID filter
+ * BEFORE the child exits, so the kworker event passes the filter when
+ * it fires.
+ */
+ set_cap(_metadata, CAP_SYS_ADMIN);
+ tracefs_clear_pid_filter();
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+
+ sandbox_child_fs_access(_metadata, "/usr", LANDLOCK_ACCESS_FS_READ_DIR,
+ LANDLOCK_ACCESS_FS_READ_DIR, "/tmp");
+
+ /*
+ * Wait for the deferred deallocation work to run. The domain is freed
+ * asynchronously from a kworker; poll until the event appears or a
+ * timeout is reached.
+ */
+ for (int retry = 0; retry < 10; retry++) {
+ usleep(100000);
+
+ set_cap(_metadata, CAP_SYS_ADMIN);
+ buf = tracefs_read_trace();
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+ ASSERT_NE(NULL, buf);
+
+ count = tracefs_count_matches(buf,
+ REGEX_FREE_DOMAIN(KWORKER_TASK));
+ if (count >= 1)
+ break;
+ free(buf);
+ buf = NULL;
+ }
+
+ set_cap(_metadata, CAP_SYS_ADMIN);
+ ASSERT_EQ(0, tracefs_set_pid_filter(getpid()));
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+
+ ASSERT_NE(NULL, buf);
+ EXPECT_LE(1, count)
+ {
+ TH_LOG("Expected free_domain event, got %d\n%s", count, buf);
+ }
+
+ /* Verify denials count matches the single denial we triggered. */
+ EXPECT_EQ(0, tracefs_extract_field(buf, REGEX_FREE_DOMAIN(KWORKER_TASK),
+ "denials", denials_field,
+ sizeof(denials_field)));
+ EXPECT_STREQ("1", denials_field);
+
+ free(buf);
+}
+
+/*
+ * Verifies that deny_access_fs includes the enriched fields: same_exec and
+ * logged.
+ */
+TEST_F(trace, deny_access_fs_fields)
+{
+ char *buf;
+ char field_buf[64];
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ /* Trigger a denial: rule for /usr, access /tmp. */
+ sandbox_child_fs_access(_metadata, "/usr", LANDLOCK_ACCESS_FS_READ_DIR,
+ LANDLOCK_ACCESS_FS_READ_DIR, "/tmp");
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ /* Verify the enriched fields are present and have valid values. */
+ ASSERT_EQ(0, tracefs_extract_field(
+ buf, REGEX_DENY_ACCESS_FS(TRACE_TASK), "same_exec",
+ field_buf, sizeof(field_buf)));
+ /* Child is the same exec that restricted itself. */
+ EXPECT_STREQ("1", field_buf);
+
+ /* Same exec with default flags: audit would log this denial. */
+ ASSERT_EQ(0, tracefs_extract_field(
+ buf, REGEX_DENY_ACCESS_FS(TRACE_TASK), "logged",
+ field_buf, sizeof(field_buf)));
+ EXPECT_STREQ("1", field_buf);
+
+ free(buf);
+}
+
+/*
+ * Verifies that same_exec is 1 (true) for denials from the same executable that
+ * called landlock_restrict_self().
+ */
+TEST_F(trace, same_exec_before_exec)
+{
+ pid_t pid;
+ int status;
+ char *buf;
+ char field[64];
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ pid = fork();
+ ASSERT_LE(0, pid);
+
+ if (pid == 0) {
+ struct landlock_ruleset_attr attr = {
+ .handled_access_fs = LANDLOCK_ACCESS_FS_READ_DIR,
+ };
+ int ruleset_fd, dir_fd;
+
+ ruleset_fd = landlock_create_ruleset(&attr, sizeof(attr), 0);
+ if (ruleset_fd < 0)
+ _exit(1);
+
+ /* No rules: all read_dir access is denied. */
+ prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+ if (landlock_restrict_self(ruleset_fd, 0))
+ _exit(1);
+ close(ruleset_fd);
+
+ /* Trigger denial without exec (same executable). */
+ dir_fd = open(".", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
+ if (dir_fd >= 0)
+ close(dir_fd);
+ _exit(0);
+ }
+
+ ASSERT_EQ(pid, waitpid(pid, &status, 0));
+ ASSERT_TRUE(WIFEXITED(status));
+ EXPECT_EQ(0, WEXITSTATUS(status));
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ /* Should have at least one deny_access_fs denial. */
+ EXPECT_LE(1,
+ tracefs_count_matches(buf, REGEX_DENY_ACCESS_FS(TRACE_TASK)));
+
+ /* Verify same_exec=1 (same executable, no exec). */
+ ASSERT_EQ(0,
+ tracefs_extract_field(buf, REGEX_DENY_ACCESS_FS(TRACE_TASK),
+ "same_exec", field, sizeof(field)));
+ EXPECT_STREQ("1", field);
+
+ /* Same exec with default flags: audit would log this denial. */
+ ASSERT_EQ(0,
+ tracefs_extract_field(buf, REGEX_DENY_ACCESS_FS(TRACE_TASK),
+ "logged", field, sizeof(field)));
+ EXPECT_STREQ("1", field);
+
+ free(buf);
+}
+
+/*
+ * Verifies that same_exec is 0 (false) for denials from a process that has
+ * exec'd a new binary after landlock_restrict_self(). The sandboxed child
+ * exec's true which opens "." and triggers a read_dir denial. Covers the
+ * "trace-only" visibility condition: with same_exec=0 and the default
+ * log_new_exec=0, audit suppresses the denial (logged=0) but the trace event
+ * still fires.
+ */
+TEST_F(trace, same_exec_after_exec)
+{
+ char *buf;
+ char field[64];
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ sandbox_child_exec_true(_metadata, 0);
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ EXPECT_LE(1, tracefs_count_matches(buf, REGEX_DENY_ACCESS_FS("true")));
+
+ /* Verify same_exec=0 (different executable after exec). */
+ ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_DENY_ACCESS_FS("true"),
+ "same_exec", field, sizeof(field)));
+ EXPECT_STREQ("0", field);
+
+ /*
+ * same_exec=0 with default log_new_exec=0: audit suppresses (logged=0).
+ */
+ ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_DENY_ACCESS_FS("true"),
+ "logged", field, sizeof(field)));
+ EXPECT_STREQ("0", field);
+
+ free(buf);
+}
+
+/*
+ * Verifies that LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF suppresses logging
+ * (logged=0) for a denial from the same executable.
+ */
+TEST_F(trace, log_flags_same_exec_off)
+{
+ pid_t pid;
+ int status;
+ char *buf;
+ char field[64];
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ pid = fork();
+ ASSERT_LE(0, pid);
+
+ if (pid == 0) {
+ struct landlock_ruleset_attr attr = {
+ .handled_access_fs = LANDLOCK_ACCESS_FS_READ_DIR,
+ };
+ int ruleset_fd, dir_fd;
+
+ ruleset_fd = landlock_create_ruleset(&attr, sizeof(attr), 0);
+ if (ruleset_fd < 0)
+ _exit(1);
+
+ prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+ if (landlock_restrict_self(
+ ruleset_fd,
+ LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF))
+ _exit(1);
+ close(ruleset_fd);
+
+ dir_fd = open(".", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
+ if (dir_fd >= 0)
+ close(dir_fd);
+ _exit(0);
+ }
+
+ ASSERT_EQ(pid, waitpid(pid, &status, 0));
+ ASSERT_TRUE(WIFEXITED(status));
+ EXPECT_EQ(0, WEXITSTATUS(status));
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ EXPECT_LE(1,
+ tracefs_count_matches(buf, REGEX_DENY_ACCESS_FS(TRACE_TASK)));
+
+ /* Same-exec denial with LOG_SAME_EXEC_OFF: audit suppresses it. */
+ ASSERT_EQ(0,
+ tracefs_extract_field(buf, REGEX_DENY_ACCESS_FS(TRACE_TASK),
+ "logged", field, sizeof(field)));
+ EXPECT_STREQ("0", field);
+
+ free(buf);
+}
+
+/*
+ * Verifies that LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON causes a post-exec
+ * denial to be logged (logged=1). The child exec's true so that the denial
+ * comes from a new executable (same_exec=0).
+ */
+TEST_F(trace, log_flags_new_exec_on)
+{
+ char *buf;
+ char field[64];
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ sandbox_child_exec_true(_metadata,
+ LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON);
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ EXPECT_LE(1, tracefs_count_matches(buf, REGEX_DENY_ACCESS_FS("true")));
+
+ ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_DENY_ACCESS_FS("true"),
+ "same_exec", field, sizeof(field)));
+ EXPECT_STREQ("0", field);
+
+ /* LOG_NEW_EXEC_ON: the post-exec denial (same_exec=0) is logged. */
+ ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_DENY_ACCESS_FS("true"),
+ "logged", field, sizeof(field)));
+ EXPECT_STREQ("1", field);
+
+ free(buf);
+}
+
+/*
+ * Verifies that denials suppressed by audit log flags are still counted in
+ * num_denials. The child restricts itself with default flags (log_same_exec=1,
+ * log_new_exec=0), then execs true which attempts to read a denied directory.
+ * After exec, same_exec=0 and log_new_exec=0, so audit suppresses the denial.
+ * But the trace event fires unconditionally and free_domain must report the
+ * correct denials count.
+ */
+TEST_F(trace, non_audit_visible_denial_counting)
+{
+ char *buf = NULL;
+ char denials_field[32];
+ int count;
+
+ set_cap(_metadata, CAP_SYS_ADMIN);
+ ASSERT_EQ(0, tracefs_clear());
+ tracefs_clear_pid_filter();
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+
+ sandbox_child_exec_true(_metadata, 0);
+
+ /* Wait for free_domain event with retry. */
+ for (int retry = 0; retry < 10; retry++) {
+ usleep(100000);
+
+ set_cap(_metadata, CAP_SYS_ADMIN);
+ buf = tracefs_read_trace();
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+ if (!buf)
+ break;
+
+ count = tracefs_count_matches(buf,
+ REGEX_FREE_DOMAIN(KWORKER_TASK));
+ if (count >= 1)
+ break;
+ free(buf);
+ buf = NULL;
+ }
+
+ set_cap(_metadata, CAP_SYS_ADMIN);
+ ASSERT_EQ(0, tracefs_set_pid_filter(getpid()));
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+
+ /*
+ * The denial happened after exec (same_exec=0), so audit would suppress
+ * it. But num_denials counts all denials regardless.
+ */
+ ASSERT_NE(NULL, buf)
+ {
+ TH_LOG("free_domain event not found after 10 retries");
+ }
+ EXPECT_EQ(0, tracefs_extract_field(buf, REGEX_FREE_DOMAIN(KWORKER_TASK),
+ "denials", denials_field,
+ sizeof(denials_field)));
+ EXPECT_STREQ("1", denials_field);
+
+ free(buf);
+}
+
+/*
+ * Verifies that landlock_add_rule_net emits a trace event with the correct port
+ * and allowed access mask fields.
+ */
+TEST_F(trace, add_rule_net_fields)
+{
+ struct landlock_ruleset_attr ruleset_attr = {
+ .handled_access_net = LANDLOCK_ACCESS_NET_BIND_TCP,
+ };
+ struct landlock_net_port_attr net_port = {
+ .allowed_access = LANDLOCK_ACCESS_NET_BIND_TCP,
+ .port = 8080,
+ };
+ int ruleset_fd;
+ char *buf;
+ char field[64];
+
+ ruleset_fd =
+ landlock_create_ruleset(&ruleset_attr, sizeof(ruleset_attr), 0);
+ ASSERT_LE(0, ruleset_fd);
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ ASSERT_EQ(0, landlock_add_rule(ruleset_fd, LANDLOCK_RULE_NET_PORT,
+ &net_port, 0));
+ close(ruleset_fd);
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ EXPECT_EQ(1, tracefs_count_matches(buf, REGEX_ADD_RULE_NET(TRACE_TASK)))
+ {
+ TH_LOG("Expected 1 add_rule_net event\n%s", buf);
+ }
+
+ /*
+ * Verify the port is in host endianness, matching the UAPI convention
+ * (landlock_net_port_attr.port). On little-endian, htons(8080) is
+ * 36895, so this comparison catches byte-order bugs.
+ */
+ EXPECT_EQ(0, tracefs_extract_field(buf, REGEX_ADD_RULE_NET(TRACE_TASK),
+ "port", field, sizeof(field)));
+ EXPECT_STREQ("8080", field);
+ /*
+ * The allowed mask is the absolute value after transformation: the
+ * user-requested BIND_TCP plus all unhandled access rights (the other
+ * net access bits are unhandled because the ruleset only handles
+ * BIND_TCP).
+ */
+ EXPECT_EQ(0,
+ tracefs_extract_field(buf, REGEX_ADD_RULE_NET(TRACE_TASK),
+ "access_rights", field, sizeof(field)));
+ EXPECT_STREQ("bind_tcp|connect_tcp|bind_udp|connect_send_udp", field);
+
+ free(buf);
+}
+
+/*
+ * Verifies that LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF suppresses audit
+ * logging for child domains (logged=0) even though the child's own
+ * per-execution flags are the defaults, while the trace event still fires
+ * (tracing is unconditional). The parent creates a domain with
+ * LOG_SUBDOMAINS_OFF, then the child creates a sub-domain and triggers a
+ * denial.
+ */
+TEST_F(trace, log_flags_subdomains_off)
+{
+ pid_t pid;
+ int status;
+ char *buf;
+ char field[64];
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ pid = fork();
+ ASSERT_LE(0, pid);
+
+ if (pid == 0) {
+ struct landlock_ruleset_attr attr = {
+ .handled_access_fs = LANDLOCK_ACCESS_FS_READ_DIR,
+ };
+ int parent_fd, child_fd, dir_fd;
+
+ /* Parent domain with LOG_SUBDOMAINS_OFF. */
+ parent_fd = landlock_create_ruleset(&attr, sizeof(attr), 0);
+ if (parent_fd < 0)
+ _exit(1);
+
+ prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+ if (landlock_restrict_self(
+ parent_fd,
+ LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF))
+ _exit(1);
+ close(parent_fd);
+
+ /* Child sub-domain with default flags. */
+ child_fd = landlock_create_ruleset(&attr, sizeof(attr), 0);
+ if (child_fd < 0)
+ _exit(1);
+
+ if (landlock_restrict_self(child_fd, 0))
+ _exit(1);
+ close(child_fd);
+
+ /* Trigger a denial from the child domain. */
+ dir_fd = open(".", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
+ if (dir_fd >= 0)
+ close(dir_fd);
+ _exit(0);
+ }
+
+ ASSERT_EQ(pid, waitpid(pid, &status, 0));
+ ASSERT_TRUE(WIFEXITED(status));
+ EXPECT_EQ(0, WEXITSTATUS(status));
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ /*
+ * Trace fires unconditionally even though audit is disabled for the
+ * child domain (parent had LOG_SUBDOMAINS_OFF).
+ */
+ EXPECT_LE(1,
+ tracefs_count_matches(buf, REGEX_DENY_ACCESS_FS(TRACE_TASK)))
+ {
+ TH_LOG("Expected deny_access_fs event despite "
+ "LOG_SUBDOMAINS_OFF\n%s",
+ buf);
+ }
+
+ /*
+ * The child's per-execution flags default to logging, but the
+ * ancestor's LOG_SUBDOMAINS_OFF disables it, so audit suppresses this
+ * denial (logged=0). This is exactly the case the single logged field
+ * captures and the raw per-execution flags could not.
+ */
+ ASSERT_EQ(0,
+ tracefs_extract_field(buf, REGEX_DENY_ACCESS_FS(TRACE_TASK),
+ "logged", field, sizeof(field)));
+ EXPECT_STREQ("0", field);
+
+ free(buf);
+}
+
+/* Verifies that landlock_free_ruleset fires when a ruleset FD is closed. */
+TEST_F(trace, free_ruleset_on_close)
+{
+ struct landlock_ruleset_attr ruleset_attr = {
+ .handled_access_fs = LANDLOCK_ACCESS_FS_READ_DIR,
+ };
+ int ruleset_fd;
+ char *buf;
+
+ ruleset_fd =
+ landlock_create_ruleset(&ruleset_attr, sizeof(ruleset_attr), 0);
+ ASSERT_LE(0, ruleset_fd);
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ /* Closing the FD should trigger free_ruleset. */
+ close(ruleset_fd);
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ EXPECT_EQ(1, tracefs_count_matches(buf, REGEX_FREE_RULESET(TRACE_TASK)))
+ {
+ TH_LOG("Expected 1 free_ruleset event\n%s", buf);
+ }
+
+ free(buf);
+}
+
+/*
+ * The following tests are intentionally elided because the underlying kernel
+ * mechanisms are already validated by audit tests:
+ *
+ * - Domain ID monotonicity: validated by audit_test.c:layers. The same
+ * landlock_get_id_range() function serves both audit and trace.
+ *
+ * - Domain deallocation order (LIFO): validated by audit_test.c:layers. Trace
+ * events fire from the same free_domain_work() code path.
+ *
+ * - Max-layer stacking (16 domains): validated by audit_test.c:layers.
+ *
+ * - IPv6 network tests: IPv6 hook dispatch uses the same
+ * current_check_access_socket() as IPv4, validated by net_test.c:audit tests.
+ *
+ * - Per-access-right full matrix (all 16 FS rights): hook dispatch is validated
+ * by fs_test.c:audit tests. Trace tests verify representative samples to
+ * ensure bitmask encoding is correct.
+ *
+ * - Combined log flag variants (e.g., LOG_SUBDOMAINS_OFF + LOG_NEW_EXEC_ON):
+ * individual flag tests above cover each flag's effect on trace fields. Flag
+ * combination logic is validated by audit_test.c:audit_flags tests.
+ *
+ * - fs.refer multi-record denials and fs.change_topology (mount):
+ * trace_denial() uses the same code path for all FS request types. The
+ * DENTRY union member is validated by the deny_access_fs_fields
+ * test. Audit tests in fs_test.c cover refer and mount denial specifics.
+ */
+
+TEST_HARNESS_MAIN
diff --git a/tools/testing/selftests/landlock/true.c b/tools/testing/selftests/landlock/true.c
index 3f9ccbf52783..1e39b664512d 100644
--- a/tools/testing/selftests/landlock/true.c
+++ b/tools/testing/selftests/landlock/true.c
@@ -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;
}
--
2.54.0
^ permalink raw reply related
* [PATCH v3 13/20] landlock: Add landlock_deny_access_fs and landlock_deny_access_net
From: Mickaël Salaün @ 2026-07-22 17:11 UTC (permalink / raw)
To: Günther Noack, Steven Rostedt
Cc: Mickaël Salaün, Christian Brauner, Jann Horn, Jeff Xu,
Justin Suess, Kees Cook, Masami Hiramatsu, Mathieu Desnoyers,
Matthieu Buffet, Mikhail Ivanov, Tingmao Wang, kernel-team,
linux-security-module, linux-trace-kernel
In-Reply-To: <20260722171159.2776765-1-mic@digikod.net>
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 <gnoack@google.com>
Cc: Justin Suess <utilityemal77@gmail.com>
Cc: Masami Hiramatsu <mhiramat@kernel.org>
Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: Steven Rostedt <rostedt@goodmis.org>
Cc: Tingmao Wang <m@maowtm.org>
Signed-off-by: Mickaël Salaün <mic@digikod.net>
---
Changes since v2:
https://patch.msgid.link/20260406143717.1815792-12-mic@digikod.net
- 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(-)
diff --git a/include/trace/events/landlock.h b/include/trace/events/landlock.h
index c693248afe23..e70dcc9a94b9 100644
--- a/include/trace/events/landlock.h
+++ b/include/trace/events/landlock.h
@@ -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 */
diff --git a/security/landlock/log.c b/security/landlock/log.c
index 13033808bdbd..931d8b4c2c06 100644
--- a/security/landlock/log.c
+++ b/security/landlock/log.c
@@ -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);
}
diff --git a/security/landlock/trace.c b/security/landlock/trace.c
index 5e6df313c7d2..4c4229d4ffdf 100644
--- a/security/landlock/trace.c
+++ b/security/landlock/trace.c
@@ -6,9 +6,19 @@
* Copyright © 2026 Cloudflare, Inc.
*/
-#include "trace.h"
+#include <linux/cleanup.h>
+#include <linux/dcache.h>
+#include <linux/err.h>
+#include <linux/fs.h>
+#include <linux/lsm_audit.h>
+#include <net/sock.h>
+
+#include "access.h"
#include "domain.h"
+#include "fs.h"
+#include "log.h"
#include "ruleset.h"
+#include "trace.h"
/*
* Generates the tracepoint definitions in this translation unit. The trace
@@ -44,3 +54,110 @@ void landlock_trace_free_domain(const struct landlock_hierarchy *const hierarchy
if (READ_ONCE(hierarchy->log_status) != LANDLOCK_LOG_UNCOMMITTED)
trace_landlock_free_domain(hierarchy);
}
+
+/**
+ * landlock_trace_denial - Emit a tracepoint for a denied access request
+ *
+ * @request: Detail of the user space request.
+ * @youngest_denied: The youngest hierarchy node that denied the access.
+ * @missing: The set of denied access rights.
+ * @same_exec: Whether the current task is the same executable that called
+ * landlock_restrict_self() for the denying domain, as computed
+ * by landlock_log_denial().
+ * @logged: Whether the domain's policy selects this denial for logging, as
+ * computed by landlock_log_denial().
+ *
+ * Emits the tracepoint matching @request->type when its event is enabled.
+ * Unlike audit, fires regardless of @logged; the value is recorded in the event
+ * so consumers can filter on it.
+ *
+ * Called from landlock_log_denial().
+ */
+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)
+{
+ switch (request->type) {
+ case LANDLOCK_REQUEST_FS_ACCESS:
+ case LANDLOCK_REQUEST_FS_CHANGE_TOPOLOGY:
+ if (trace_landlock_deny_access_fs_enabled()) {
+ char *buf __free(__putname) = __getname();
+ struct path dentry_path;
+ const char *pathname;
+ const struct path *path = NULL;
+
+ /*
+ * Selects the path from the audit data type, as
+ * dump_common_audit_data() does. A FS_ACCESS denial
+ * carries a file (hook_file_truncate) or an ioctl op
+ * (hook_file_ioctl) rather than a path;
+ * FS_CHANGE_TOPOLOGY carries a path or a bare dentry.
+ * Reading the wrong union member would dereference
+ * garbage, so every reachable type is handled here.
+ */
+ switch (request->audit.type) {
+ case LSM_AUDIT_DATA_FILE:
+ path = &request->audit.u.file->f_path;
+ break;
+ case LSM_AUDIT_DATA_IOCTL_OP:
+ path = &request->audit.u.op->path;
+ break;
+ case LSM_AUDIT_DATA_DENTRY:
+ /*
+ * Build a path on the stack with the real
+ * dentry so TP_fast_assign can extract dev and
+ * ino; the mnt field is unused there.
+ */
+ dentry_path = (struct path){
+ .dentry = request->audit.u.dentry,
+ };
+ path = &dentry_path;
+ break;
+ case LSM_AUDIT_DATA_PATH:
+ path = &request->audit.u.path;
+ break;
+ default:
+ WARN_ONCE(1,
+ "Unhandled Landlock FS audit type %d",
+ request->audit.type);
+ break;
+ }
+
+ if (!path)
+ break;
+
+ if (!buf) {
+ pathname = "<no_mem>";
+ } else if (request->audit.type ==
+ LSM_AUDIT_DATA_DENTRY) {
+ /* No vfsmount: render the dentry path alone. */
+ pathname = dentry_path_raw(
+ request->audit.u.dentry, buf, PATH_MAX);
+ if (IS_ERR(pathname))
+ pathname =
+ PTR_ERR(pathname) ==
+ -ENAMETOOLONG ?
+ "<too_long>" :
+ "<unreachable>";
+ } else {
+ pathname = resolve_path_for_trace(path, buf);
+ }
+
+ trace_landlock_deny_access_fs(youngest_denied,
+ same_exec, logged,
+ missing, path, pathname);
+ }
+ break;
+ case LANDLOCK_REQUEST_NET_ACCESS:
+ if (trace_landlock_deny_access_net_enabled())
+ trace_landlock_deny_access_net(
+ youngest_denied, same_exec, logged, missing,
+ request->audit.u.net->sk,
+ ntohs(request->audit.u.net->sport),
+ ntohs(request->audit.u.net->dport));
+ break;
+ default:
+ break;
+ }
+}
diff --git a/security/landlock/trace.h b/security/landlock/trace.h
index 59c8ea348625..7be98e748855 100644
--- a/security/landlock/trace.h
+++ b/security/landlock/trace.h
@@ -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 */
--
2.54.0
^ permalink raw reply related
* [PATCH v3 16/20] selftests/landlock: Add filesystem tracepoint tests
From: Mickaël Salaün @ 2026-07-22 17:11 UTC (permalink / raw)
To: Günther Noack, Steven Rostedt
Cc: Mickaël Salaün, Christian Brauner, Jann Horn, Jeff Xu,
Justin Suess, Kees Cook, Masami Hiramatsu, Mathieu Desnoyers,
Matthieu Buffet, Mikhail Ivanov, Tingmao Wang, kernel-team,
linux-security-module, linux-trace-kernel
In-Reply-To: <20260722171159.2776765-1-mic@digikod.net>
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 <gnoack@google.com>
Cc: Tingmao Wang <m@maowtm.org>
Signed-off-by: Mickaël Salaün <mic@digikod.net>
---
Changes since v2:
https://patch.msgid.link/20260406143717.1815792-15-mic@digikod.net
- 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
diff --git a/tools/testing/selftests/landlock/fs_test.c b/tools/testing/selftests/landlock/fs_test.c
index 86e08aa6e0a7..b22df68a2923 100644
--- a/tools/testing/selftests/landlock/fs_test.c
+++ b/tools/testing/selftests/landlock/fs_test.c
@@ -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
diff --git a/tools/testing/selftests/landlock/trace_fs_test.c b/tools/testing/selftests/landlock/trace_fs_test.c
new file mode 100644
index 000000000000..5220f6a4bee1
--- /dev/null
+++ b/tools/testing/selftests/landlock/trace_fs_test.c
@@ -0,0 +1,496 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Landlock tests - Filesystem tracepoints
+ *
+ * Copyright © 2026 Cloudflare, Inc.
+ */
+
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/landlock.h>
+#include <sched.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include "common.h"
+#include "trace.h"
+
+#define TRACE_TASK "trace_fs_test"
+
+/*
+ * Like REGEX_DENY_ACCESS_FS(), but pins the logged field to a specific value
+ * ("0" or "1") so a test can tell a suppressed (quiet) denial from a logged
+ * one. The tracepoint fires for every denial; logged carries the audit
+ * verdict.
+ */
+#define REGEX_DENY_ACCESS_FS_LOGGED(task, log) \
+ TRACE_PREFIX(task) \
+ "landlock_deny_access_fs: " \
+ "domain=[0-9a-f]\\+ " \
+ "same_exec=[01] " \
+ "logged=" log " " \
+ "blockers=[a-z_|]* " \
+ "dev=[0-9]\\+:[0-9]\\+ " \
+ "ino=[0-9]\\+ " \
+ "path=[^ ]*$"
+
+/* clang-format off */
+FIXTURE(trace_fs) {
+ /* clang-format on */
+ int tracefs_ok;
+};
+
+FIXTURE_SETUP(trace_fs)
+{
+ 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_ADD_RULE_FS_ENABLE, true));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_CHECK_RULE_FS_ENABLE, true));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_DENY_ACCESS_FS_ENABLE, true));
+ ASSERT_EQ(0, tracefs_clear());
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+FIXTURE_TEARDOWN(trace_fs)
+{
+ if (!self->tracefs_ok)
+ return;
+
+ set_cap(_metadata, CAP_SYS_ADMIN);
+ tracefs_enable_event(TRACEFS_ADD_RULE_FS_ENABLE, false);
+ tracefs_enable_event(TRACEFS_CHECK_RULE_FS_ENABLE, false);
+ tracefs_enable_event(TRACEFS_DENY_ACCESS_FS_ENABLE, false);
+ tracefs_fixture_teardown();
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+/*
+ * Baseline: verifies that without Landlock, the operation succeeds and no
+ * check_rule or deny_access trace events fire.
+ */
+TEST_F(trace_fs, unsandboxed)
+{
+ char *buf;
+ int count, status, fd;
+ pid_t pid;
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ pid = fork();
+ ASSERT_LE(0, pid);
+
+ if (pid == 0) {
+ /*
+ * No sandbox: verify that a normal FS access does not produce
+ * Landlock trace events.
+ */
+ fd = open("/usr", 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));
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ count = tracefs_count_matches(buf, REGEX_CHECK_RULE_FS(TRACE_TASK));
+ EXPECT_EQ(0, count);
+ count = tracefs_count_matches(buf, REGEX_DENY_ACCESS_FS(TRACE_TASK));
+ EXPECT_EQ(0, count);
+
+ free(buf);
+}
+
+/*
+ * Verifies that adding a filesystem rule emits a landlock_add_rule_fs trace
+ * event with the expected path and field values: ruleset ID is non-zero,
+ * access_rights is non-zero, and path matches.
+ */
+TEST_F(trace_fs, add_rule_fs)
+{
+ struct landlock_ruleset_attr ruleset_attr = {
+ .handled_access_fs = LANDLOCK_ACCESS_FS_READ_FILE |
+ LANDLOCK_ACCESS_FS_WRITE_FILE |
+ LANDLOCK_ACCESS_FS_READ_DIR,
+ };
+ struct landlock_path_beneath_attr path_beneath = {
+ .allowed_access = LANDLOCK_ACCESS_FS_READ_FILE,
+ };
+ char *buf, field_buf[64];
+ int ruleset_fd, count;
+
+ ruleset_fd =
+ landlock_create_ruleset(&ruleset_attr, sizeof(ruleset_attr), 0);
+ ASSERT_LE(0, ruleset_fd);
+
+ path_beneath.parent_fd = open("/usr", O_PATH | O_DIRECTORY | O_CLOEXEC);
+ ASSERT_LE(0, path_beneath.parent_fd);
+
+ ASSERT_EQ(0, landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
+ &path_beneath, 0));
+ ASSERT_EQ(0, close(path_beneath.parent_fd));
+ ASSERT_EQ(0, close(ruleset_fd));
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ count = tracefs_count_matches(buf, REGEX_ADD_RULE_FS(TRACE_TASK));
+ EXPECT_EQ(1, count)
+ {
+ TH_LOG("Expected 1 add_rule_fs event, got %d\n%s", count, buf);
+ }
+
+ /* Ruleset ID should be non-zero. */
+ ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_ADD_RULE_FS(TRACE_TASK),
+ "ruleset", field_buf,
+ sizeof(field_buf)));
+ EXPECT_STRNE("0", field_buf);
+
+ /* Access rights should be non-zero. */
+ ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_ADD_RULE_FS(TRACE_TASK),
+ "access_rights", field_buf,
+ sizeof(field_buf)));
+ EXPECT_STRNE("", field_buf);
+
+ /* Path should be /usr. */
+ ASSERT_EQ(0,
+ tracefs_extract_field(buf, REGEX_ADD_RULE_FS(TRACE_TASK),
+ "path", field_buf, sizeof(field_buf)));
+ EXPECT_STREQ("/usr", field_buf);
+
+ free(buf);
+}
+
+/*
+ * Verifies that an allowed access emits check_rule events (rule matched during
+ * pathwalk) but does NOT emit deny_access events (no denial).
+ */
+TEST_F(trace_fs, allowed_access)
+{
+ char *buf, field_buf[64];
+ int count;
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ /* Rule allows READ_DIR for /usr, access /usr which is allowed. */
+ sandbox_child_fs_access(_metadata, "/usr", LANDLOCK_ACCESS_FS_READ_DIR,
+ LANDLOCK_ACCESS_FS_READ_DIR, "/usr");
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ count = tracefs_count_matches(buf, REGEX_CHECK_RULE_FS(TRACE_TASK));
+ EXPECT_LE(1, count);
+
+ /* Single-layer grants array, intersected with the request. */
+ ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_CHECK_RULE_FS(TRACE_TASK),
+ "grants", field_buf,
+ sizeof(field_buf)));
+ EXPECT_STREQ("{read_dir}", field_buf);
+
+ count = tracefs_count_matches(buf, REGEX_DENY_ACCESS_FS(TRACE_TASK));
+ EXPECT_EQ(0, count);
+
+ free(buf);
+}
+
+/*
+ * Verifies that accessing a path whose access type is not in the handled set
+ * does not emit landlock_check_rule events. The ruleset handles READ_FILE, but
+ * the directory open checks READ_DIR which is unhandled; Landlock has no
+ * opinion and no rule evaluation occurs.
+ */
+TEST_F(trace_fs, check_rule_unhandled)
+{
+ char *buf;
+ int count;
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ /* Handles READ_FILE only; READ_DIR is unhandled. */
+ sandbox_child_fs_access(_metadata, "/usr", LANDLOCK_ACCESS_FS_READ_FILE,
+ LANDLOCK_ACCESS_FS_READ_FILE, "/tmp");
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ /* No check_rule events because READ_DIR is not in the handled set. */
+ count = tracefs_count_matches(buf, REGEX_CHECK_RULE_FS(TRACE_TASK));
+ EXPECT_EQ(0, count);
+
+ free(buf);
+}
+
+/*
+ * Verifies that nested domains (child sandboxed under a parent domain) emit
+ * check_rule events from both layers and produce a deny_access event when the
+ * inner domain's rule does not cover the access.
+ */
+TEST_F(trace_fs, check_rule_nested)
+{
+ char *buf, field_buf[64], *comma;
+ size_t first_len, second_len;
+ int count_rule, count_access, status;
+ pid_t pid;
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ pid = fork();
+ ASSERT_LE(0, pid);
+
+ if (pid == 0) {
+ struct landlock_ruleset_attr ruleset_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;
+
+ /* First layer: allow /usr. */
+ ruleset_fd = landlock_create_ruleset(&ruleset_attr,
+ sizeof(ruleset_attr), 0);
+ if (ruleset_fd < 0)
+ _exit(1);
+
+ path_beneath.parent_fd =
+ open("/usr", O_PATH | O_DIRECTORY | O_CLOEXEC);
+ if (path_beneath.parent_fd < 0) {
+ close(ruleset_fd);
+ _exit(1);
+ }
+
+ if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
+ &path_beneath, 0)) {
+ close(path_beneath.parent_fd);
+ close(ruleset_fd);
+ _exit(1);
+ }
+ close(path_beneath.parent_fd);
+
+ 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);
+
+ /* Second layer: also allow /usr. */
+ ruleset_fd = landlock_create_ruleset(&ruleset_attr,
+ sizeof(ruleset_attr), 0);
+ if (ruleset_fd < 0)
+ _exit(1);
+
+ path_beneath.parent_fd =
+ open("/usr", O_PATH | O_DIRECTORY | O_CLOEXEC);
+ if (path_beneath.parent_fd < 0) {
+ close(ruleset_fd);
+ _exit(1);
+ }
+
+ if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
+ &path_beneath, 0)) {
+ close(path_beneath.parent_fd);
+ close(ruleset_fd);
+ _exit(1);
+ }
+ close(path_beneath.parent_fd);
+
+ if (landlock_restrict_self(ruleset_fd, 0)) {
+ close(ruleset_fd);
+ _exit(1);
+ }
+ close(ruleset_fd);
+
+ /* Access /usr which is allowed by both layers. */
+ fd = open("/usr", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
+ if (fd >= 0)
+ close(fd);
+
+ /* Access /tmp which has no rule in either layer. */
+ fd = open("/tmp", 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));
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ count_rule =
+ tracefs_count_matches(buf, REGEX_CHECK_RULE_FS(TRACE_TASK));
+ EXPECT_LE(1, count_rule);
+
+ /*
+ * Both layers have the same rule, so the grants array must have two
+ * identical symbolic entries, e.g. {read_dir,read_dir}.
+ */
+ ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_CHECK_RULE_FS(TRACE_TASK),
+ "grants", field_buf,
+ sizeof(field_buf)));
+ comma = strchr(field_buf, ',');
+ EXPECT_NE(0, !!comma);
+ if (comma) {
+ /*
+ * Verify both entries are identical: compare the substring
+ * before the comma with the substring after it (stripping the
+ * braces).
+ */
+ first_len = comma - field_buf - 1;
+ second_len = strlen(comma + 1) - 1;
+ EXPECT_EQ(first_len, second_len);
+ EXPECT_EQ(0, strncmp(field_buf + 1, comma + 1, first_len));
+ }
+
+ count_access =
+ tracefs_count_matches(buf, REGEX_DENY_ACCESS_FS(TRACE_TASK));
+ EXPECT_LE(1, count_access);
+
+ free(buf);
+}
+
+/*
+ * Verifies that a denied FS access emits a landlock_deny_access_fs trace event
+ * with the blocked access and path.
+ */
+TEST_F(trace_fs, deny_access_fs_denied)
+{
+ char *buf;
+ int count;
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ /*
+ * Rule allows READ_DIR for /usr, but access /tmp which has no rule.
+ * READ_DIR access to /tmp is denied by absence and should emit a
+ * deny_access_fs event.
+ */
+ sandbox_child_fs_access(_metadata, "/usr", LANDLOCK_ACCESS_FS_READ_DIR,
+ LANDLOCK_ACCESS_FS_READ_DIR, "/tmp");
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ count = tracefs_count_matches(buf, REGEX_DENY_ACCESS_FS(TRACE_TASK));
+ EXPECT_LE(1, count);
+
+ free(buf);
+}
+
+/*
+ * A denied FS access covered by a quiet rule (LANDLOCK_ADD_RULE_QUIET with the
+ * access listed in quiet_access_fs) still emits a landlock_deny_access_fs
+ * event, but with logged=0, the same audit-logging verdict audit would apply to
+ * suppress the record.
+ */
+TEST_F(trace_fs, deny_access_fs_quiet)
+{
+ char *buf, field[64];
+ pid_t pid;
+ int status;
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ pid = fork();
+ ASSERT_LE(0, pid);
+ if (pid == 0) {
+ struct landlock_ruleset_attr ruleset_attr = {
+ .handled_access_fs = LANDLOCK_ACCESS_FS_READ_DIR,
+ .quiet_access_fs = LANDLOCK_ACCESS_FS_READ_DIR,
+ };
+ struct landlock_path_beneath_attr path_beneath = {
+ .allowed_access = 0,
+ };
+ int ruleset_fd, fd;
+
+ ruleset_fd = landlock_create_ruleset(&ruleset_attr,
+ sizeof(ruleset_attr), 0);
+ if (ruleset_fd < 0)
+ _exit(1);
+
+ /* Marks /tmp quiet without granting any access. */
+ path_beneath.parent_fd =
+ open("/tmp", O_PATH | O_DIRECTORY | O_CLOEXEC);
+ if (path_beneath.parent_fd < 0) {
+ close(ruleset_fd);
+ _exit(1);
+ }
+ if (landlock_add_rule(ruleset_fd, LANDLOCK_RULE_PATH_BENEATH,
+ &path_beneath, LANDLOCK_ADD_RULE_QUIET)) {
+ close(path_beneath.parent_fd);
+ close(ruleset_fd);
+ _exit(1);
+ }
+ close(path_beneath.parent_fd);
+
+ 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);
+
+ /* Denied READ_DIR on the quiet /tmp: suppressed, logged=0. */
+ fd = open("/tmp", 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));
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ /* The event fires with the suppressed verdict. */
+ EXPECT_LE(1, tracefs_count_matches(buf, REGEX_DENY_ACCESS_FS_LOGGED(
+ TRACE_TASK, "0")));
+ /* The quiet rule must not leave the denial logged. */
+ EXPECT_EQ(0, tracefs_count_matches(buf, REGEX_DENY_ACCESS_FS_LOGGED(
+ TRACE_TASK, "1")));
+
+ /*
+ * Quiet suppresses only the logged verdict: the rest of the denial
+ * event stays populated (non-zero domain, non-empty blockers).
+ */
+ ASSERT_EQ(0, tracefs_extract_field(
+ buf, REGEX_DENY_ACCESS_FS_LOGGED(TRACE_TASK, "0"),
+ "domain", field, sizeof(field)));
+ EXPECT_STRNE("0", field);
+ ASSERT_EQ(0, tracefs_extract_field(
+ buf, REGEX_DENY_ACCESS_FS_LOGGED(TRACE_TASK, "0"),
+ "blockers", field, sizeof(field)));
+ EXPECT_STRNE("", field);
+
+ free(buf);
+}
+
+TEST_HARNESS_MAIN
--
2.54.0
^ permalink raw reply related
* [PATCH v3 17/20] selftests/landlock: Add network tracepoint tests
From: Mickaël Salaün @ 2026-07-22 17:11 UTC (permalink / raw)
To: Günther Noack, Steven Rostedt
Cc: Mickaël Salaün, Christian Brauner, Jann Horn, Jeff Xu,
Justin Suess, Kees Cook, Masami Hiramatsu, Mathieu Desnoyers,
Matthieu Buffet, Mikhail Ivanov, Tingmao Wang, kernel-team,
linux-security-module, linux-trace-kernel
In-Reply-To: <20260722171159.2776765-1-mic@digikod.net>
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 <gnoack@google.com>
Cc: Tingmao Wang <m@maowtm.org>
Signed-off-by: Mickaël Salaün <mic@digikod.net>
---
Changes since v2:
https://patch.msgid.link/20260406143717.1815792-16-mic@digikod.net
- 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(-)
diff --git a/tools/testing/selftests/landlock/net_test.c b/tools/testing/selftests/landlock/net_test.c
index be2eb88092fb..578bb0a64f11 100644
--- a/tools/testing/selftests/landlock/net_test.c
+++ b/tools/testing/selftests/landlock/net_test.c
@@ -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
--
2.54.0
^ permalink raw reply related
* [PATCH v3 18/20] selftests/landlock: Add scope and ptrace tracepoint tests
From: Mickaël Salaün @ 2026-07-22 17:11 UTC (permalink / raw)
To: Günther Noack, Steven Rostedt
Cc: Mickaël Salaün, Christian Brauner, Jann Horn, Jeff Xu,
Justin Suess, Kees Cook, Masami Hiramatsu, Mathieu Desnoyers,
Matthieu Buffet, Mikhail Ivanov, Tingmao Wang, kernel-team,
linux-security-module, linux-trace-kernel
In-Reply-To: <20260722171159.2776765-1-mic@digikod.net>
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 <gnoack@google.com>
Cc: Tingmao Wang <m@maowtm.org>
Signed-off-by: Mickaël Salaün <mic@digikod.net>
---
Changes since v2:
https://patch.msgid.link/20260406143717.1815792-17-mic@digikod.net
- 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(-)
diff --git a/tools/testing/selftests/landlock/ptrace_test.c b/tools/testing/selftests/landlock/ptrace_test.c
index 4f64c90583cd..2644445a9d02 100644
--- a/tools/testing/selftests/landlock/ptrace_test.c
+++ b/tools/testing/selftests/landlock/ptrace_test.c
@@ -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
diff --git a/tools/testing/selftests/landlock/scoped_abstract_unix_test.c b/tools/testing/selftests/landlock/scoped_abstract_unix_test.c
index 40fc82fbf01d..6c945d319d32 100644
--- a/tools/testing/selftests/landlock/scoped_abstract_unix_test.c
+++ b/tools/testing/selftests/landlock/scoped_abstract_unix_test.c
@@ -12,6 +12,7 @@
#include <sched.h>
#include <signal.h>
#include <stddef.h>
+#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/stat.h>
@@ -23,6 +24,9 @@
#include "audit.h"
#include "common.h"
#include "scoped_common.h"
+#include "trace.h"
+
+#define TRACE_TASK "scoped_abstract"
/* Number of pending connections queue to be hold. */
const short backlog = 10;
@@ -1205,4 +1209,463 @@ TEST(self_connect)
_metadata->exit_code = KSFT_FAIL;
}
+/* Trace tests */
+
+/* clang-format off */
+FIXTURE(trace_unix) {
+ /* clang-format on */
+ int tracefs_ok;
+};
+
+FIXTURE_SETUP(trace_unix)
+{
+ 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_SCOPE_ABSTRACT_UNIX_SOCKET_ENABLE,
+ true));
+ ASSERT_EQ(0, tracefs_clear());
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+FIXTURE_TEARDOWN(trace_unix)
+{
+ if (!self->tracefs_ok)
+ return;
+
+ set_cap(_metadata, CAP_SYS_ADMIN);
+ tracefs_enable_event(TRACEFS_DENY_SCOPE_ABSTRACT_UNIX_SOCKET_ENABLE,
+ false);
+ tracefs_fixture_teardown();
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+/* clang-format off */
+FIXTURE_VARIANT(trace_unix)
+{
+ /* clang-format on */
+ bool sandbox;
+ bool sandbox_target;
+ int expect_denied;
+};
+
+/* Denied: sandboxed child connects to unsandboxed peer (peer_domain=0). */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_unix, denied) {
+ /* clang-format on */
+ .sandbox = true,
+ .sandbox_target = false,
+ .expect_denied = 1,
+};
+
+/*
+ * Denied: sandboxed child connects to a peer socket owned by a sandboxed
+ * process, so the peer is in a domain and peer_domain= is non-zero.
+ */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_unix, denied_scoped_peer) {
+ /* clang-format on */
+ .sandbox = true,
+ .sandbox_target = true,
+ .expect_denied = 1,
+};
+
+/* Allowed: unsandboxed child connects. */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_unix, allowed) {
+ /* clang-format on */
+ .sandbox = false,
+ .sandbox_target = false,
+ .expect_denied = 0,
+};
+
+TEST_F(trace_unix, deny_scope_unix)
+{
+ struct sockaddr_un addr = {
+ .sun_family = AF_UNIX,
+ };
+ char *buf, field[128], expected_path[64], expected_pid[16];
+ int server_fd, client_fd, count, status;
+ pid_t child;
+
+ if (!self->tracefs_ok)
+ SKIP(return, "tracefs not available");
+
+ /*
+ * For the non-zero peer_domain case, sandbox the parent before it
+ * creates the server socket. The peer domain is read from the server
+ * socket file's credentials, so the socket carries the parent's domain
+ * and peer_domain= is non-zero.
+ */
+ if (variant->sandbox_target)
+ create_scoped_domain(_metadata,
+ LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET);
+
+ /* Create an abstract unix socket server in the parent. */
+ server_fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+ ASSERT_LE(0, server_fd);
+
+ addr.sun_path[0] = '\0';
+ snprintf(addr.sun_path + 1, sizeof(addr.sun_path) - 1,
+ "landlock_trace_test_%d", getpid());
+
+ ASSERT_EQ(0, bind(server_fd, (struct sockaddr *)&addr,
+ offsetof(struct sockaddr_un, sun_path) + 1 +
+ strlen(addr.sun_path + 1)));
+ ASSERT_EQ(0, listen(server_fd, 1));
+
+ child = fork();
+ ASSERT_LE(0, child);
+
+ if (child == 0) {
+ if (variant->sandbox) {
+ struct landlock_ruleset_attr ruleset_attr = {
+ .scoped = LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET,
+ };
+ int ruleset_fd;
+
+ 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);
+ }
+
+ client_fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
+ if (client_fd < 0)
+ _exit(1);
+
+ if (variant->sandbox) {
+ /* Connect should be denied. */
+ if (connect(client_fd, (struct sockaddr *)&addr,
+ offsetof(struct sockaddr_un, sun_path) + 1 +
+ strlen(addr.sun_path + 1)) == 0) {
+ close(client_fd);
+ _exit(2);
+ }
+ if (errno != EPERM) {
+ close(client_fd);
+ _exit(3);
+ }
+ } else {
+ /* No sandbox: connect should succeed. */
+ if (connect(client_fd, (struct sockaddr *)&addr,
+ offsetof(struct sockaddr_un, sun_path) + 1 +
+ strlen(addr.sun_path + 1)) != 0) {
+ close(client_fd);
+ _exit(2);
+ }
+ }
+ close(client_fd);
+ _exit(0);
+ }
+
+ ASSERT_EQ(child, waitpid(child, &status, 0));
+ ASSERT_TRUE(WIFEXITED(status));
+ EXPECT_EQ(0, WEXITSTATUS(status));
+ close(server_fd);
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ count = tracefs_count_matches(
+ buf, REGEX_DENY_SCOPE_ABSTRACT_UNIX_SOCKET(TRACE_TASK));
+ if (variant->expect_denied) {
+ EXPECT_EQ(variant->expect_denied, count)
+ {
+ TH_LOG("Expected deny_scope_abstract_unix_socket "
+ "event, got %d\n%s",
+ count, buf);
+ }
+
+ /* Verify sun_path (trace skips the leading NUL). */
+ snprintf(expected_path, sizeof(expected_path),
+ "landlock_trace_test_%d", getpid());
+ ASSERT_EQ(0, tracefs_extract_field(
+ buf,
+ REGEX_DENY_SCOPE_ABSTRACT_UNIX_SOCKET(
+ TRACE_TASK),
+ "sun_path", field, sizeof(field)));
+ EXPECT_STREQ(expected_path, field);
+
+ /* Verify peer_pid is the parent's PID. */
+ snprintf(expected_pid, sizeof(expected_pid), "%d", getpid());
+ ASSERT_EQ(0, tracefs_extract_field(
+ buf,
+ REGEX_DENY_SCOPE_ABSTRACT_UNIX_SOCKET(
+ TRACE_TASK),
+ "peer_pid", field, sizeof(field)));
+ EXPECT_STREQ(expected_pid, field);
+
+ /*
+ * Verify peer_domain: 0 when the peer is unsandboxed, non-zero
+ * when the peer socket is owned by a domain.
+ */
+ ASSERT_EQ(0, tracefs_extract_field(
+ buf,
+ REGEX_DENY_SCOPE_ABSTRACT_UNIX_SOCKET(
+ TRACE_TASK),
+ "peer_domain", field, sizeof(field)));
+ EXPECT_EQ(variant->sandbox_target, strcmp("0", field) != 0)
+ {
+ TH_LOG("Unexpected peer_domain=%s", field);
+ }
+ } else {
+ EXPECT_EQ(0, count)
+ {
+ TH_LOG("Expected 0 deny_scope events, got %d\n%s",
+ count, buf);
+ }
+ }
+
+ free(buf);
+}
+
+/*
+ * Trace test for the datagram send path (hook_unix_may_send), which reaches the
+ * same landlock_deny_scope_abstract_unix_socket tracepoint as a stream
+ * connect(2) but through sendto(2) on an unconnected datagram socket.
+ */
+
+/* clang-format off */
+FIXTURE(trace_unix_dgram) {
+ /* clang-format on */
+ int tracefs_ok;
+};
+
+FIXTURE_SETUP(trace_unix_dgram)
+{
+ 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_SCOPE_ABSTRACT_UNIX_SOCKET_ENABLE,
+ true));
+ ASSERT_EQ(0, tracefs_clear());
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+FIXTURE_TEARDOWN(trace_unix_dgram)
+{
+ if (!self->tracefs_ok)
+ return;
+
+ set_cap(_metadata, CAP_SYS_ADMIN);
+ tracefs_enable_event(TRACEFS_DENY_SCOPE_ABSTRACT_UNIX_SOCKET_ENABLE,
+ false);
+ tracefs_fixture_teardown();
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+/* clang-format off */
+FIXTURE_VARIANT(trace_unix_dgram)
+{
+ /* clang-format on */
+ bool sandbox;
+ bool sandbox_target;
+ int expect_denied;
+};
+
+/*
+ * Denied: sandboxed child sends a datagram to an unsandboxed peer
+ * (peer_domain=0).
+ */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_unix_dgram, denied) {
+ /* clang-format on */
+ .sandbox = true,
+ .sandbox_target = false,
+ .expect_denied = 1,
+};
+
+/*
+ * Denied: sandboxed child sends a datagram to a peer socket owned by a
+ * sandboxed process, so the peer is in a domain and peer_domain= is non-zero.
+ */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_unix_dgram, denied_scoped_peer) {
+ /* clang-format on */
+ .sandbox = true,
+ .sandbox_target = true,
+ .expect_denied = 1,
+};
+
+/* Allowed: unsandboxed child sends a datagram. */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_unix_dgram, allowed) {
+ /* clang-format on */
+ .sandbox = false,
+ .sandbox_target = false,
+ .expect_denied = 0,
+};
+
+TEST_F(trace_unix_dgram, deny_scope_unix)
+{
+ struct sockaddr_un addr = {
+ .sun_family = AF_UNIX,
+ };
+ socklen_t addr_len;
+ char *buf, field[128], expected_path[64];
+ int server_fd, client_fd, count, status;
+ pid_t child;
+
+ if (!self->tracefs_ok)
+ SKIP(return, "tracefs not available");
+
+ /*
+ * For the non-zero peer_domain case, sandbox the parent before it
+ * creates the server socket. The peer domain is read from the server
+ * socket file's credentials, so the socket carries the parent's domain
+ * and peer_domain= is non-zero.
+ */
+ if (variant->sandbox_target)
+ create_scoped_domain(_metadata,
+ LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET);
+
+ /* Create an abstract unix datagram server in the parent. */
+ server_fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0);
+ ASSERT_LE(0, server_fd);
+
+ addr.sun_path[0] = '\0';
+ snprintf(addr.sun_path + 1, sizeof(addr.sun_path) - 1,
+ "landlock_trace_test_%d", getpid());
+ addr_len = offsetof(struct sockaddr_un, sun_path) + 1 +
+ strlen(addr.sun_path + 1);
+
+ ASSERT_EQ(0, bind(server_fd, (struct sockaddr *)&addr, addr_len));
+
+ child = fork();
+ ASSERT_LE(0, child);
+
+ if (child == 0) {
+ if (variant->sandbox) {
+ struct landlock_ruleset_attr ruleset_attr = {
+ .scoped = LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET,
+ };
+ int ruleset_fd;
+
+ 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);
+ }
+
+ client_fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0);
+ if (client_fd < 0)
+ _exit(1);
+
+ if (variant->sandbox) {
+ /* Sending to the abstract peer should be denied. */
+ if (sendto(client_fd, ".", 1, 0,
+ (struct sockaddr *)&addr, addr_len) == 0) {
+ close(client_fd);
+ _exit(2);
+ }
+ if (errno != EPERM) {
+ close(client_fd);
+ _exit(3);
+ }
+ } else {
+ /* No sandbox: sending should succeed. */
+ if (sendto(client_fd, ".", 1, 0,
+ (struct sockaddr *)&addr, addr_len) != 1) {
+ close(client_fd);
+ _exit(2);
+ }
+ }
+ close(client_fd);
+ _exit(0);
+ }
+
+ ASSERT_EQ(child, waitpid(child, &status, 0));
+ ASSERT_TRUE(WIFEXITED(status));
+ EXPECT_EQ(0, WEXITSTATUS(status));
+ close(server_fd);
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ count = tracefs_count_matches(
+ buf, REGEX_DENY_SCOPE_ABSTRACT_UNIX_SOCKET(TRACE_TASK));
+ if (variant->expect_denied) {
+ EXPECT_EQ(variant->expect_denied, count)
+ {
+ TH_LOG("Expected deny_scope_abstract_unix_socket "
+ "event, got %d\n%s",
+ count, buf);
+ }
+
+ /* Verify sun_path (trace skips the leading NUL). */
+ snprintf(expected_path, sizeof(expected_path),
+ "landlock_trace_test_%d", getpid());
+ ASSERT_EQ(0, tracefs_extract_field(
+ buf,
+ REGEX_DENY_SCOPE_ABSTRACT_UNIX_SOCKET(
+ TRACE_TASK),
+ "sun_path", field, sizeof(field)));
+ EXPECT_STREQ(expected_path, field);
+
+ /*
+ * peer_pid is 0 for a datagram peer (no SO_PEERCRED), so it is
+ * not asserted here; sun_path is the reliable peer identifier.
+ *
+ * Verify peer_domain: 0 when the peer is unsandboxed, non-zero
+ * when the peer socket is owned by a domain.
+ */
+ ASSERT_EQ(0, tracefs_extract_field(
+ buf,
+ REGEX_DENY_SCOPE_ABSTRACT_UNIX_SOCKET(
+ TRACE_TASK),
+ "peer_domain", field, sizeof(field)));
+ EXPECT_EQ(variant->sandbox_target, strcmp("0", field) != 0)
+ {
+ TH_LOG("Unexpected peer_domain=%s", field);
+ }
+ } else {
+ EXPECT_EQ(0, count)
+ {
+ TH_LOG("Expected 0 deny_scope events, got %d\n%s",
+ count, buf);
+ }
+ }
+
+ free(buf);
+}
+
TEST_HARNESS_MAIN
diff --git a/tools/testing/selftests/landlock/scoped_signal_test.c b/tools/testing/selftests/landlock/scoped_signal_test.c
index 2d37d0c06c06..259cdcc8aa5c 100644
--- a/tools/testing/selftests/landlock/scoped_signal_test.c
+++ b/tools/testing/selftests/landlock/scoped_signal_test.c
@@ -10,7 +10,9 @@
#include <fcntl.h>
#include <linux/landlock.h>
#include <pthread.h>
+#include <sched.h>
#include <signal.h>
+#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/types.h>
#include <sys/wait.h>
@@ -18,6 +20,9 @@
#include "common.h"
#include "scoped_common.h"
+#include "trace.h"
+
+#define TRACE_TASK "scoped_signal_t"
/* This variable is used for handling several signals. */
static volatile sig_atomic_t is_signaled;
@@ -762,4 +767,403 @@ TEST(sigio_to_pgid_self)
EXPECT_EQ(0, close(trigger[1]));
}
+/* Trace tests */
+
+/* clang-format off */
+FIXTURE(trace_signal) {
+ /* clang-format on */
+ int tracefs_ok;
+};
+
+FIXTURE_SETUP(trace_signal)
+{
+ 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_SCOPE_SIGNAL_ENABLE, true));
+ ASSERT_EQ(0, tracefs_clear());
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+FIXTURE_TEARDOWN(trace_signal)
+{
+ if (!self->tracefs_ok)
+ return;
+
+ set_cap(_metadata, CAP_SYS_ADMIN);
+ tracefs_enable_event(TRACEFS_DENY_SCOPE_SIGNAL_ENABLE, false);
+ tracefs_fixture_teardown();
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+/* clang-format off */
+FIXTURE_VARIANT(trace_signal)
+{
+ /* clang-format on */
+ bool sandbox;
+ bool sandbox_target;
+ int expect_denied;
+};
+
+/* Denied: sandboxed child signals unsandboxed parent (target_domain=0). */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_signal, denied) {
+ /* clang-format on */
+ .sandbox = true,
+ .sandbox_target = false,
+ .expect_denied = 1,
+};
+
+/*
+ * Denied: sandboxed child signals a sandboxed parent, so the target is in a
+ * domain and target_domain= is non-zero.
+ */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_signal, denied_scoped_target) {
+ /* clang-format on */
+ .sandbox = true,
+ .sandbox_target = true,
+ .expect_denied = 1,
+};
+
+/* Allowed: unsandboxed child signals unsandboxed parent. */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_signal, allowed) {
+ /* clang-format on */
+ .sandbox = false,
+ .sandbox_target = false,
+ .expect_denied = 0,
+};
+
+TEST_F(trace_signal, deny_scope_signal)
+{
+ char *buf, field[64], expected_pid[16];
+ int count, status;
+ pid_t child;
+
+ if (!self->tracefs_ok)
+ SKIP(return, "tracefs not available");
+
+ /*
+ * For the non-zero target_domain case, sandbox the parent (the signal
+ * target) before forking. The child inherits that domain and adds its
+ * own scoped layer, so the signal is still denied and target_domain=
+ * names the parent's domain.
+ */
+ if (variant->sandbox_target)
+ create_scoped_domain(_metadata, LANDLOCK_SCOPE_SIGNAL);
+
+ 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;
+
+ 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);
+ }
+
+ if (variant->sandbox) {
+ /* Signal to unsandboxed parent should be denied. */
+ if (kill(getppid(), 0) == 0)
+ _exit(2);
+ if (errno != EPERM)
+ _exit(3);
+ } else {
+ /* No sandbox: kill should succeed. */
+ if (kill(getppid(), 0) != 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_SCOPE_SIGNAL(TRACE_TASK));
+ if (variant->expect_denied) {
+ EXPECT_EQ(variant->expect_denied, count)
+ {
+ TH_LOG("Expected deny_scope_signal event, got %d\n%s",
+ count, buf);
+ }
+
+ /* Verify target_pid is the parent's PID. */
+ snprintf(expected_pid, sizeof(expected_pid), "%d", getpid());
+ ASSERT_EQ(0, tracefs_extract_field(
+ buf, REGEX_DENY_SCOPE_SIGNAL(TRACE_TASK),
+ "target_pid", field, sizeof(field)));
+ EXPECT_STREQ(expected_pid, field);
+
+ /*
+ * Verify target_domain: 0 when the target is unsandboxed,
+ * non-zero when the target is in a domain.
+ */
+ ASSERT_EQ(0, tracefs_extract_field(
+ buf, REGEX_DENY_SCOPE_SIGNAL(TRACE_TASK),
+ "target_domain", field, sizeof(field)));
+ EXPECT_EQ(variant->sandbox_target, strcmp("0", field) != 0)
+ {
+ TH_LOG("Unexpected target_domain=%s", field);
+ }
+ } else {
+ EXPECT_EQ(0, count)
+ {
+ TH_LOG("Expected 0 deny_scope_signal events, "
+ "got %d\n%s",
+ count, buf);
+ }
+ }
+
+ free(buf);
+}
+
+/*
+ * Trace test for the asynchronous SIGIO/SIGURG delivery path
+ * (hook_file_send_sigiotask), which reaches the same landlock_deny_scope_signal
+ * tracepoint as a synchronous kill(2) but through fcntl(F_SETOWN).
+ */
+
+/* clang-format off */
+FIXTURE(trace_fown) {
+ /* clang-format on */
+ int tracefs_ok;
+};
+
+FIXTURE_SETUP(trace_fown)
+{
+ 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_SCOPE_SIGNAL_ENABLE, true));
+ ASSERT_EQ(0, tracefs_clear());
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+FIXTURE_TEARDOWN(trace_fown)
+{
+ if (!self->tracefs_ok)
+ return;
+
+ set_cap(_metadata, CAP_SYS_ADMIN);
+ tracefs_enable_event(TRACEFS_DENY_SCOPE_SIGNAL_ENABLE, false);
+ tracefs_fixture_teardown();
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+}
+
+/* clang-format off */
+FIXTURE_VARIANT(trace_fown)
+{
+ /* clang-format on */
+ bool sandbox;
+ bool sandbox_target;
+ int expect_denied;
+};
+
+/*
+ * Denied: a sandboxed file owner's SIGURG is delivered to an unsandboxed target
+ * process (target_domain=0).
+ */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_fown, denied) {
+ /* clang-format on */
+ .sandbox = true,
+ .sandbox_target = false,
+ .expect_denied = 1,
+};
+
+/*
+ * Denied: the SIGURG target sandboxes itself in its own domain, so the target
+ * is in a domain and target_domain= is non-zero.
+ */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_fown, denied_scoped_target) {
+ /* clang-format on */
+ .sandbox = true,
+ .sandbox_target = true,
+ .expect_denied = 1,
+};
+
+/* Allowed: an unsandboxed file owner delivers SIGURG. */
+/* clang-format off */
+FIXTURE_VARIANT_ADD(trace_fown, allowed) {
+ /* clang-format on */
+ .sandbox = false,
+ .sandbox_target = false,
+ .expect_denied = 0,
+};
+
+TEST_F(trace_fown, deny_scope_fown)
+{
+ int server_socket, recv_socket;
+ struct service_fixture server_address;
+ char buffer_parent, field[64], *buf;
+ int status, count;
+ int pipe_parent[2], pipe_child[2];
+ pid_t child;
+
+ if (!self->tracefs_ok)
+ SKIP(return, "tracefs not available");
+
+ memset(&server_address, 0, sizeof(server_address));
+ set_unix_address(&server_address, 0);
+
+ ASSERT_EQ(0, pipe2(pipe_parent, O_CLOEXEC));
+ ASSERT_EQ(0, pipe2(pipe_child, O_CLOEXEC));
+
+ child = fork();
+ ASSERT_LE(0, child);
+ if (child == 0) {
+ int client_socket;
+ char buffer_child;
+
+ EXPECT_EQ(0, close(pipe_parent[1]));
+ EXPECT_EQ(0, close(pipe_child[0]));
+
+ ASSERT_EQ(0, setup_signal_handler(SIGURG));
+ client_socket = socket(AF_UNIX, SOCK_STREAM, 0);
+ ASSERT_LE(0, client_socket);
+
+ /*
+ * The SIGURG target is this child; for the non-zero
+ * target_domain case it sandboxes itself in its own domain,
+ * unrelated to the file owner's domain.
+ */
+ if (variant->sandbox_target)
+ create_scoped_domain(_metadata, LANDLOCK_SCOPE_SIGNAL);
+
+ /* Waits for the parent to listen. */
+ ASSERT_EQ(1, read(pipe_parent[0], &buffer_child, 1));
+ ASSERT_EQ(0, connect(client_socket, &server_address.unix_addr,
+ server_address.unix_addr_len));
+
+ /*
+ * Waits for the parent to accept the connection, sandbox
+ * itself, and call fcntl(F_SETOWN).
+ */
+ ASSERT_EQ(1, read(pipe_parent[0], &buffer_child, 1));
+ /* Triggers the asynchronous SIGURG to this file owner. */
+ ASSERT_EQ(1, send(client_socket, ".", 1, MSG_OOB));
+ EXPECT_EQ(0, close(client_socket));
+ ASSERT_EQ(1, write(pipe_child[1], ".", 1));
+ EXPECT_EQ(0, close(pipe_child[1]));
+
+ _exit(0);
+ return;
+ }
+ EXPECT_EQ(0, close(pipe_parent[0]));
+ EXPECT_EQ(0, close(pipe_child[1]));
+
+ server_socket = socket(AF_UNIX, SOCK_STREAM, 0);
+ ASSERT_LE(0, server_socket);
+ ASSERT_EQ(0, bind(server_socket, &server_address.unix_addr,
+ server_address.unix_addr_len));
+ ASSERT_EQ(0, listen(server_socket, backlog));
+ ASSERT_EQ(1, write(pipe_parent[1], ".", 1));
+
+ recv_socket = accept(server_socket, NULL, NULL);
+ ASSERT_LE(0, recv_socket);
+
+ /*
+ * The file owner is the denying subject; its domain is captured at
+ * fcntl(F_SETOWN) time, so sandbox it before setting the owner.
+ */
+ if (variant->sandbox)
+ create_scoped_domain(_metadata, LANDLOCK_SCOPE_SIGNAL);
+
+ /*
+ * Sets the child to receive SIGURG for MSG_OOB. This uncommon use is a
+ * valid attack scenario which also simplifies this test.
+ */
+ ASSERT_EQ(0, fcntl(recv_socket, F_SETOWN, child));
+
+ ASSERT_EQ(1, write(pipe_parent[1], ".", 1));
+
+ /* Waits for the child to send MSG_OOB. */
+ ASSERT_EQ(1, read(pipe_child[0], &buffer_parent, 1));
+ EXPECT_EQ(0, close(pipe_child[0]));
+ ASSERT_EQ(1, recv(recv_socket, &buffer_parent, 1, MSG_OOB));
+ EXPECT_EQ(0, close(recv_socket));
+ EXPECT_EQ(0, close(server_socket));
+
+ 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_SCOPE_SIGNAL(TRACE_TASK));
+ if (variant->expect_denied) {
+ EXPECT_EQ(variant->expect_denied, count)
+ {
+ TH_LOG("Expected deny_scope_signal event, got %d\n%s",
+ count, buf);
+ }
+
+ /*
+ * Verify target_domain: 0 when the target is unsandboxed,
+ * non-zero when the target is in a domain.
+ */
+ ASSERT_EQ(0, tracefs_extract_field(
+ buf, REGEX_DENY_SCOPE_SIGNAL(TRACE_TASK),
+ "target_domain", field, sizeof(field)));
+ EXPECT_EQ(variant->sandbox_target, strcmp("0", field) != 0)
+ {
+ TH_LOG("Unexpected target_domain=%s", field);
+ }
+ } else {
+ EXPECT_EQ(0, count)
+ {
+ TH_LOG("Expected 0 deny_scope_signal events, "
+ "got %d\n%s",
+ count, buf);
+ }
+ }
+
+ free(buf);
+}
+
TEST_HARNESS_MAIN
diff --git a/tools/testing/selftests/landlock/trace.h b/tools/testing/selftests/landlock/trace.h
index 31f17b43e9f4..e03c689ef398 100644
--- a/tools/testing/selftests/landlock/trace.h
+++ b/tools/testing/selftests/landlock/trace.h
@@ -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=[^ ]*$"
--
2.54.0
^ permalink raw reply related
* [PATCH v3 20/20] landlock: Document tracepoints
From: Mickaël Salaün @ 2026-07-22 17:11 UTC (permalink / raw)
To: Günther Noack, Steven Rostedt
Cc: Mickaël Salaün, Christian Brauner, Jann Horn, Jeff Xu,
Justin Suess, Kees Cook, Masami Hiramatsu, Mathieu Desnoyers,
Matthieu Buffet, Mikhail Ivanov, Tingmao Wang, kernel-team,
linux-security-module, linux-trace-kernel
In-Reply-To: <20260722171159.2776765-1-mic@digikod.net>
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 <gnoack@google.com>
Cc: Tingmao Wang <m@maowtm.org>
Signed-off-by: Mickaël Salaün <mic@digikod.net>
---
Changes since v2:
https://patch.msgid.link/20260406143717.1815792-18-mic@digikod.net
- 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
diff --git a/Documentation/admin-guide/LSM/landlock.rst b/Documentation/admin-guide/LSM/landlock.rst
index 314052bbeb0a..1e4bc9fdc0a0 100644
--- a/Documentation/admin-guide/LSM/landlock.rst
+++ b/Documentation/admin-guide/LSM/landlock.rst
@@ -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
diff --git a/Documentation/security/landlock.rst b/Documentation/security/landlock.rst
index c5186526e76f..6b5075f4d501 100644
--- a/Documentation/security/landlock.rst
+++ b/Documentation/security/landlock.rst
@@ -1,13 +1,14 @@
.. SPDX-License-Identifier: GPL-2.0
.. Copyright © 2017-2020 Mickaël Salaün <mic@digikod.net>
.. 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
diff --git a/Documentation/trace/events-landlock.rst b/Documentation/trace/events-landlock.rst
new file mode 100644
index 000000000000..da713157b685
--- /dev/null
+++ b/Documentation/trace/events-landlock.rst
@@ -0,0 +1,313 @@
+.. SPDX-License-Identifier: GPL-2.0
+.. Copyright © 2026 Cloudflare, Inc.
+
+=====================
+Landlock Trace Events
+=====================
+
+:Author: Mickaël Salaün
+:Date: July 2026
+
+Landlock emits trace events for sandbox lifecycle operations and access
+denials. These events can be consumed by ftrace (for human-readable
+trace output and filtering) and by eBPF programs (for programmatic
+introspection via BTF).
+
+User space documentation can be found here:
+Documentation/userspace-api/landlock.rst
+
+.. warning::
+
+ Landlock trace events, like audit records, expose sensitive
+ information about all sandboxed processes on the system. See
+ :ref:`landlock_observability_security` for security considerations
+ and privilege requirements.
+
+Event overview
+==============
+
+Landlock trace events are organized in four categories:
+
+**Syscall events** are emitted during Landlock system calls:
+
+- ``landlock_create_ruleset``: a new ruleset is created
+- ``landlock_add_rule_fs``: a filesystem rule is added to a ruleset
+- ``landlock_add_rule_net``: a network port rule is added to a ruleset
+- ``landlock_create_domain``: a new domain is created from a ruleset
+- ``landlock_enforce_domain``: a domain is enforced on a thread
+
+**Denial events** are emitted when an access is denied:
+
+- ``landlock_deny_access_fs``: filesystem access denied
+- ``landlock_deny_access_net``: network access denied
+- ``landlock_deny_ptrace``: ptrace access denied
+- ``landlock_deny_scope_signal``: signal delivery denied
+- ``landlock_deny_scope_abstract_unix_socket``: abstract unix socket
+ access denied
+
+**Rule evaluation events** are emitted during rule matching:
+
+- ``landlock_check_rule_fs``: a filesystem rule is evaluated
+- ``landlock_check_rule_net``: a network port rule is evaluated
+
+**Lifecycle events**:
+
+- ``landlock_free_domain``: a domain is freed
+- ``landlock_free_ruleset``: a ruleset is freed
+
+Enabling events
+===============
+
+Enable all Landlock events::
+
+ echo 1 > /sys/kernel/tracing/events/landlock/enable
+
+Enable a specific event::
+
+ echo 1 > /sys/kernel/tracing/events/landlock/landlock_deny_access_fs/enable
+
+Read the trace output::
+
+ cat /sys/kernel/tracing/trace_pipe
+
+Event samples
+=============
+
+A fully unprivileged program is sandboxed so that it can still run (its
+binary and shared libraries stay readable) and write only ``/tmp``, then
+it is denied reading ``/etc/passwd``, which lies outside its read-only
+set. ``/etc/passwd`` is world-readable, so the denial comes solely from
+Landlock, not from regular file permissions::
+
+ $ cd /sys/kernel/tracing/events/landlock/
+ $ echo 1 | tee landlock_{create_ruleset,create_domain,enforce_domain,deny_access_fs,free_domain}/enable >/dev/null
+ $ LC_ALL=C LL_FS_RO=/usr:/lib:/lib64:/bin:/etc/ld.so.cache LL_FS_RW=/tmp \
+ ./sandboxer cat /etc/passwd
+ $ cat /sys/kernel/tracing/trace_pipe
+ cat-127 [...] landlock_create_ruleset: ruleset=195cc6b76.0 handled_fs=execute|write_file|read_file|read_dir|remove_dir|remove_file|make_char|make_dir|make_reg|make_sock|make_fifo|make_block|make_sym|refer|truncate|ioctl_dev|resolve_unix handled_net= scoped=
+ cat-127 [...] landlock_create_domain: domain=195cc6b7c parent=0 ruleset=195cc6b76.6
+ cat-127 [...] landlock_enforce_domain: domain=195cc6b7c complete=1 process_wide=1
+ cat-127 [...] landlock_deny_access_fs: domain=195cc6b7c same_exec=0 logged=0 blockers=read_file dev=0:17 ino=5901179 path=/etc/passwd
+ kworker/0:1-11 [...] landlock_free_domain: domain=195cc6b7c denials=1
+
+The ``[...]`` replaces the ftrace CPU, flags, and timestamp columns. The
+first four events share the ``cat`` command name and PID because the
+sandboxer replaces itself with ``cat`` via ``execve()`` before the
+denial, and ftrace resolves a recorded PID to its latest command name.
+``landlock_free_domain`` fires later from a kworker thread, so it carries
+that thread's name instead.
+
+Here ``logged=0`` shows that audit would not record this cross-execution
+denial under the default flags, yet the ``deny_access_fs`` event still
+appears.
+
+Differences from audit records
+==============================
+
+Tracepoints and audit records both log Landlock denials, but differ
+in some field formats:
+
+- **Paths**: Most filesystem tracepoints resolve the path with
+ ``d_absolute_path()`` (namespace-independent absolute paths), while
+ mount-topology denials that carry only a dentry use ``dentry_path_raw()``.
+ Audit uses ``d_path()`` (relative to the process's chroot). A resolution
+ failure is reported as ``<no_mem>``, ``<too_long>``, or ``<unreachable>``.
+ Path-based tracepoint output is deterministic regardless of the tracer's
+ mount namespace.
+
+- **Device names**: Tracepoints use numeric ``dev=<major>:<minor>``.
+ Audit uses string ``dev="<s_id>"``. Numeric format is more precise
+ for machine parsing.
+
+- **Denied access field**: The ``deny_access_fs`` and ``deny_access_net``
+ tracepoints use the ``blockers=`` field name (same as audit). Both
+ render the blocked access rights as names: audit prefixes the category
+ and separates with commas (e.g., ``blockers=fs.read_file``), while the
+ tracepoints omit the category (carried by the event name) and separate
+ with ``|`` (e.g., ``blockers=read_file``). Scope and ptrace
+ tracepoints omit ``blockers`` because the event name identifies the
+ denial type.
+
+- **Scope and ptrace target names**: Tracepoints use role-specific field
+ names (``tracee_pid``, ``target_pid``, ``peer_pid``) that reflect the
+ semantic of each event. Audit uses generic names (``opid``, ``ocomm``)
+ because the audit log format is not event-type-specific.
+
+- **Process name**: The ptrace and signal denial tracepoints include the
+ role-prefixed ``tracee_comm=`` and ``target_comm=`` labels in the
+ printk output for stateless consumers (each matches its sibling
+ ``tracee_pid=``/``target_pid=`` field). eBPF consumers can read
+ ``comm`` directly from the task_struct via BTF. The ``comm`` value is
+ treated as untrusted input (escaped via ``__print_untrusted_str``).
+
+- **Other party's domain**: A scope or ptrace denial compares the
+ subject's denying domain (``domain=``, always the enforcing domain and
+ never the current task) with the other party's domain, so these
+ tracepoints also report the other party's domain as a scalar ID:
+ ``tracee_domain=`` (ptrace), ``target_domain=`` (signal), and
+ ``peer_domain=`` (abstract unix socket). It is ``0`` when the other
+ party is unsandboxed, and otherwise a domain ID that a consumer resolves
+ against the ``landlock_create_ruleset`` and ``landlock_create_domain``
+ events it recorded. Because a scope or ptrace verdict is decided by
+ comparing the two domains, resolving both the subject ``domain=`` and
+ this other-party ID against those lifecycle events lets a consumer
+ verify or reproduce the verdict by redoing the same two-domain
+ comparison, rather than only noting which boundary was crossed. Audit
+ records do not carry the other party's domain.
+
+Ruleset versioning
+==================
+
+Syscall events include a ruleset version (``ruleset=<hex_id>.<version>``)
+that tracks the number of rules added to the ruleset. The version is
+incremented on each ``landlock_add_rule()`` call and frozen at
+``landlock_restrict_self()`` time. This enables trace consumers to
+correlate a domain with the exact set of rules it was created from.
+
+Domain enforcement
+==================
+
+The whole-process-enforced guarantee (``complete=1 && process_wide=1``)
+is the observable outcome of a successful
+``landlock_restrict_self(..., LANDLOCK_RESTRICT_SELF_TSYNC)``; see the
+thread synchronization section of
+Documentation/userspace-api/landlock.rst.
+
+Interpreting check_rule events
+==============================
+
+The ``check_rule_fs`` and ``check_rule_net`` events expose the per-layer
+rule evaluation, which is useful for understanding *why* a specific
+access is allowed or denied.
+
+.. warning::
+
+ These events fire on the access-check hot path, once per matching rule
+ per check. On a busy sandboxed workload this can be very high
+ frequency. Enable them only for targeted debugging, ideally combined
+ with an ftrace filter (for example on ``ino`` or ``domain_id``), and
+ expect tracing overhead while they are enabled.
+
+Two output fields carry the evaluation:
+
+- ``access_request=`` is the set of access rights being evaluated against the
+ rule, rendered as ``|``-separated names. For most checks this is the
+ access the operation requested. For filesystem ``rename`` and ``link``
+ double-checks it is the domain's full handled mask, because those
+ operations re-evaluate every handled right.
+
+- ``grants=`` is a per-layer breakdown of the requested rights that this
+ rule grants, in the form ``{<layer>,<layer>,...}``:
+
+ - The braces wrap one comma-separated group per domain layer, ordered
+ from the outermost (least nested) sandbox layer to the innermost.
+ - Each group lists the requested rights the rule grants at that layer,
+ joined by ``|``.
+ - An empty group (for example the middle layer in
+ ``{read_file,,read_file}``) means the rule grants none of the
+ requested rights at that layer.
+
+A Landlock domain allows an access only when, for every requested right,
+every layer that handles that right has at least one matching rule
+granting it. A single ``check_rule`` event therefore shows one rule's
+contribution, not the final decision:
+
+- If a right appears in every layer's group, this rule alone is
+ sufficient to allow that right.
+- If a right is missing from some layer's group, that layer must grant it
+ through another matching rule, or the right is denied and appears in the
+ ``blockers=`` field of the corresponding ``deny_access`` event.
+
+To reconstruct the decision for an object, aggregate the ``grants=``
+groups of all ``check_rule`` events emitted for that object during the
+check.
+
+.. note::
+
+ Because a verdict requires aggregating ``grants=`` across all matching
+ rules of one access check, a stateless ftrace filter on a single
+ ``check_rule`` event cannot distinguish an allowed access from a
+ denied one.
+
+For example, a program sandboxed with read and execute access to the
+whole filesystem reads ``/etc/passwd``; both the ``execve()`` and the
+read match the rule covering ``/`` (inode 2), so ``check_rule_fs`` fires
+with the requested rights intersected against what that rule grants.
+The ``access_request=`` mask includes ``truncate`` because the file-open hook
+evaluates that optional right alongside the required access, but the
+rule does not grant it, so ``truncate`` never appears in ``grants=``::
+
+ cat-127 [...] landlock_check_rule_fs: domain=1e40cb56f access_request=execute|read_file|truncate dev=0:17 ino=2 grants={execute|read_file}
+ cat-127 [...] landlock_check_rule_fs: domain=1e40cb56f access_request=read_file|truncate dev=0:17 ino=2 grants={read_file}
+
+The ``[...]`` replaces the ftrace CPU, flags, and timestamp columns. A
+single ``grants=`` group means the enforcing domain has one layer. With
+two nested sandboxes that each grant the same rights, the rule spans both
+layers, so ``grants=`` has one group per layer::
+
+ cat-128 [...] landlock_check_rule_fs: domain=184788b52 access_request=execute|read_file|truncate dev=0:17 ino=2 grants={execute|read_file,execute|read_file}
+ cat-128 [...] landlock_check_rule_fs: domain=184788b52 access_request=read_file|truncate dev=0:17 ino=2 grants={read_file,read_file}
+
+eBPF access
+===========
+
+eBPF programs attached via ``BPF_RAW_TRACEPOINT`` can access the
+tracepoint arguments directly through BTF. The arguments include both
+standard kernel objects and Landlock-internal objects:
+
+- Standard kernel objects (``struct task_struct``, ``struct sock``,
+ ``struct path``, ``struct dentry``) can be used with existing BPF
+ helpers.
+- Landlock-internal objects (``struct landlock_domain``,
+ ``struct landlock_ruleset``, ``struct landlock_rule``,
+ ``struct landlock_hierarchy``) can be read via ``BPF_CORE_READ``.
+ Internal struct layouts may change between kernel versions; use CO-RE
+ for field relocation.
+
+A stateful eBPF program observes the full event stream and maintains
+per-domain state in BPF maps:
+
+1. On ``landlock_create_domain``: record the domain ID and parent (the
+ per-domain Landlock log flags are not event fields; read them from
+ ``struct landlock_hierarchy`` via BTF if needed).
+2. On ``landlock_enforce_domain``: record the sandboxed thread under the
+ ``domain=`` key (join to the ``create_domain`` recorded in step 1),
+ building the per-domain thread set; filter ``complete==1`` for a
+ one-event-per-operation summary.
+3. On ``landlock_deny_access_*``: look up the domain, decide whether
+ to count, alert, or ignore the denial based on custom policy.
+4. On ``landlock_free_domain``: clean up the per-domain state, log
+ final statistics.
+
+This approach requires no kernel modification and no Landlock-specific
+BPF helpers. The Landlock IDs serve as correlation keys across events.
+
+Audit filtering equivalence
+===========================
+
+The ``logged`` field reflects the domain's log policy but not the global
+``audit_enabled`` toggle, so it does not change when audit is turned on
+or off. When audit is enabled, ``logged==1`` selects the denials the
+domain submits to audit (audit-side rate-limiting and exclude rules may
+still drop some), so a stateless ftrace filter can select them::
+
+ # Show only denials that audit would also log:
+ echo 'logged==1' > \
+ /sys/kernel/tracing/events/landlock/landlock_deny_access_fs/filter
+
+Event reference
+===============
+
+.. kernel-doc:: include/trace/events/landlock.h
+ :doc: Landlock trace events
+
+.. kernel-doc:: include/trace/events/landlock.h
+ :internal:
+
+Additional documentation
+========================
+
+* Documentation/userspace-api/landlock.rst
+* Documentation/admin-guide/LSM/landlock.rst
+* Documentation/security/landlock.rst
+* https://landlock.io
diff --git a/Documentation/trace/index.rst b/Documentation/trace/index.rst
index 5d9bf4694d5d..f4058e8e92e3 100644
--- a/Documentation/trace/index.rst
+++ b/Documentation/trace/index.rst
@@ -54,6 +54,7 @@ applications.
events-power
events-nmi
events-msr
+ events-landlock
events-pci
events-pci-controller
boottime-trace
diff --git a/Documentation/userspace-api/landlock.rst b/Documentation/userspace-api/landlock.rst
index 5a63d4476c1c..af625b7becf9 100644
--- a/Documentation/userspace-api/landlock.rst
+++ b/Documentation/userspace-api/landlock.rst
@@ -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
diff --git a/MAINTAINERS b/MAINTAINERS
index ca41aec9993c..866763cab9b7 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -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
--
2.54.0
^ permalink raw reply related
* [PATCH v3 19/20] selftests/landlock: Add landlock_enforce_domain trace tests
From: Mickaël Salaün @ 2026-07-22 17:11 UTC (permalink / raw)
To: Günther Noack, Steven Rostedt
Cc: Mickaël Salaün, Christian Brauner, Jann Horn, Jeff Xu,
Justin Suess, Kees Cook, Masami Hiramatsu, Mathieu Desnoyers,
Matthieu Buffet, Mikhail Ivanov, Tingmao Wang, kernel-team,
linux-security-module, linux-trace-kernel
In-Reply-To: <20260722171159.2776765-1-mic@digikod.net>
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 <gnoack@google.com>
Cc: Tingmao Wang <m@maowtm.org>
Signed-off-by: Mickaël Salaün <mic@digikod.net>
---
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(+)
diff --git a/tools/testing/selftests/landlock/trace.h b/tools/testing/selftests/landlock/trace.h
index e03c689ef398..9e901823ddaf 100644
--- a/tools/testing/selftests/landlock/trace.h
+++ b/tools/testing/selftests/landlock/trace.h
@@ -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: " \
diff --git a/tools/testing/selftests/landlock/trace_test.c b/tools/testing/selftests/landlock/trace_test.c
index a141f22ad98f..e2415b98868d 100644
--- a/tools/testing/selftests/landlock/trace_test.c
+++ b/tools/testing/selftests/landlock/trace_test.c
@@ -9,6 +9,7 @@
#include <errno.h>
#include <fcntl.h>
#include <linux/landlock.h>
+#include <pthread.h>
#include <sched.h>
#include <stdio.h>
#include <string.h>
@@ -47,6 +48,7 @@ FIXTURE_SETUP(trace)
ASSERT_EQ(0, tracefs_enable_event(TRACEFS_CREATE_RULESET_ENABLE, true));
ASSERT_EQ(0, tracefs_enable_event(TRACEFS_CREATE_DOMAIN_ENABLE, true));
+ ASSERT_EQ(0, tracefs_enable_event(TRACEFS_ENFORCE_DOMAIN_ENABLE, true));
ASSERT_EQ(0, tracefs_enable_event(TRACEFS_ADD_RULE_FS_ENABLE, true));
ASSERT_EQ(0, tracefs_enable_event(TRACEFS_ADD_RULE_NET_ENABLE, true));
ASSERT_EQ(0, tracefs_enable_event(TRACEFS_CHECK_RULE_FS_ENABLE, true));
@@ -69,6 +71,7 @@ FIXTURE_TEARDOWN(trace)
set_cap(_metadata, CAP_SYS_ADMIN);
tracefs_enable_event(TRACEFS_CREATE_RULESET_ENABLE, false);
tracefs_enable_event(TRACEFS_CREATE_DOMAIN_ENABLE, false);
+ tracefs_enable_event(TRACEFS_ENFORCE_DOMAIN_ENABLE, false);
tracefs_enable_event(TRACEFS_ADD_RULE_FS_ENABLE, false);
tracefs_enable_event(TRACEFS_ADD_RULE_NET_ENABLE, false);
tracefs_enable_event(TRACEFS_CHECK_RULE_FS_ENABLE, false);
@@ -98,6 +101,8 @@ TEST_F(trace, no_trace_when_disabled)
ASSERT_EQ(0,
tracefs_enable_event(TRACEFS_CREATE_RULESET_ENABLE, false));
ASSERT_EQ(0, tracefs_enable_event(TRACEFS_CREATE_DOMAIN_ENABLE, false));
+ ASSERT_EQ(0,
+ tracefs_enable_event(TRACEFS_ENFORCE_DOMAIN_ENABLE, false));
ASSERT_EQ(0, tracefs_enable_event(TRACEFS_ADD_RULE_FS_ENABLE, false));
ASSERT_EQ(0, tracefs_enable_event(TRACEFS_ADD_RULE_NET_ENABLE, false));
ASSERT_EQ(0, tracefs_enable_event(TRACEFS_CHECK_RULE_FS_ENABLE, false));
@@ -1069,6 +1074,523 @@ TEST_F(trace, free_ruleset_on_close)
free(buf);
}
+/*
+ * Counts landlock_enforce_domain lines, filtered by @domain (NULL matches any),
+ * @complete and @process_wide (a negative value matches any). Builds the
+ * anchored regex dynamically so a single helper covers every field assertion.
+ */
+static int count_enforce_matches(const char *buf, const char *domain,
+ int complete, int process_wide)
+{
+ char pattern[512], dom[80], comp[8], pw[8];
+
+ if (domain)
+ snprintf(dom, sizeof(dom), "%s", domain);
+ else
+ snprintf(dom, sizeof(dom), "[0-9a-f]\\+");
+ if (complete < 0)
+ snprintf(comp, sizeof(comp), "[01]");
+ else
+ snprintf(comp, sizeof(comp), "%d", complete);
+ if (process_wide < 0)
+ snprintf(pw, sizeof(pw), "[01]");
+ else
+ snprintf(pw, sizeof(pw), "%d", process_wide);
+
+ snprintf(pattern, sizeof(pattern),
+ TRACE_PREFIX(TRACE_TASK) "landlock_enforce_domain: "
+ "domain=%s "
+ "complete=%s process_wide=%s$",
+ dom, comp, pw);
+ return tracefs_count_matches(buf, pattern);
+}
+
+/* Idle sibling: waits on the barrier so it is a live thread, then sleeps. */
+static void *enforce_idle(void *arg)
+{
+ pthread_barrier_t *barrier = arg;
+
+ pthread_barrier_wait(barrier);
+ while (true)
+ sleep(1);
+ return NULL;
+}
+
+/*
+ * Child body: spawns @nthreads idle siblings (barrier-synchronized so they are
+ * live when the syscall runs), then enforces a domain with @flags. Returns 0
+ * on success; the process exits afterwards, reaping the siblings.
+ */
+static int child_enforce(int nthreads, __u32 flags)
+{
+ pthread_t threads[8];
+ pthread_barrier_t barrier;
+ int ruleset_fd, i;
+
+ if (nthreads > 0) {
+ if (pthread_barrier_init(&barrier, NULL, nthreads + 1))
+ return 1;
+ for (i = 0; i < nthreads; i++)
+ if (pthread_create(&threads[i], NULL, enforce_idle,
+ &barrier))
+ return 1;
+ pthread_barrier_wait(&barrier);
+ }
+
+ ruleset_fd = build_enforce_ruleset();
+ if (ruleset_fd < 0)
+ return 1;
+
+ prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+ if (landlock_restrict_self(ruleset_fd, flags))
+ return 1;
+ close(ruleset_fd);
+ return 0;
+}
+
+/* Reads the group's live thread count from /proc/self/status (get_nr_threads). */
+static int read_thread_count(void)
+{
+ char line[128];
+ FILE *f;
+ int n = -1;
+
+ f = fopen("/proc/self/status", "re");
+ if (!f)
+ return -1;
+ while (fgets(line, sizeof(line), f))
+ if (sscanf(line, "Threads: %d", &n) == 1)
+ break;
+ fclose(f);
+ return n;
+}
+
+/* Exit code the non-leader child uses to signal "could not go single-threaded". */
+#define ENFORCE_SKIP_EXIT 2
+
+/*
+ * Runs in a spawned thread after the group leader called pthread_exit(). Waits
+ * until it is the only live thread (get_nr_threads() == 1 despite not being the
+ * leader), then enforces a domain.
+ */
+static void *enforce_nonleader(void *arg)
+{
+ int ruleset_fd, i;
+
+ for (i = 0; i < 200; i++) {
+ if (read_thread_count() == 1)
+ break;
+ usleep(10000);
+ }
+ if (read_thread_count() != 1)
+ _exit(ENFORCE_SKIP_EXIT);
+
+ ruleset_fd = build_enforce_ruleset();
+ if (ruleset_fd < 0)
+ _exit(1);
+ prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+ if (landlock_restrict_self(ruleset_fd, 0))
+ _exit(1);
+ _exit(0);
+}
+
+/*
+ * Verifies the single-threaded non-TSYNC case: one create_domain and exactly
+ * one enforce_domain, with complete=1 (the operation concludes) and
+ * process_wide=1 (get_nr_threads() == 1), sharing the created domain ID.
+ */
+TEST_F(trace, enforce_single)
+{
+ pid_t pid;
+ int status;
+ char *buf;
+ char domain[64];
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ pid = fork();
+ ASSERT_LE(0, pid);
+ if (pid == 0)
+ _exit(child_enforce(0, 0));
+
+ ASSERT_EQ(pid, waitpid(pid, &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_CREATE_DOMAIN(TRACE_TASK)));
+ EXPECT_EQ(1, count_enforce_matches(buf, NULL, -1, -1))
+ {
+ TH_LOG("Expected 1 enforce_domain event\n%s", buf);
+ }
+ EXPECT_EQ(1, count_enforce_matches(buf, NULL, 1, 1));
+
+ ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_CREATE_DOMAIN(TRACE_TASK),
+ "domain", domain, sizeof(domain)));
+ EXPECT_EQ(1, count_enforce_matches(buf, domain, 1, 1));
+
+ free(buf);
+}
+
+/*
+ * Verifies that TSYNC on a single-threaded process still concludes: one
+ * enforce_domain with complete=1 and process_wide=1.
+ */
+TEST_F(trace, enforce_tsync_single)
+{
+ pid_t pid;
+ int status;
+ char *buf;
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ pid = fork();
+ ASSERT_LE(0, pid);
+ if (pid == 0)
+ _exit(child_enforce(0, LANDLOCK_RESTRICT_SELF_TSYNC));
+
+ ASSERT_EQ(pid, waitpid(pid, &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_CREATE_DOMAIN(TRACE_TASK)));
+ EXPECT_EQ(1, count_enforce_matches(buf, NULL, -1, -1));
+ EXPECT_EQ(1, count_enforce_matches(buf, NULL, 1, 1));
+
+ free(buf);
+}
+
+/*
+ * Verifies TSYNC across a multi-threaded process: one create_domain and
+ * exactly N+1 enforce_domain events (caller plus N siblings), of which exactly
+ * one is complete=1, all are process_wide=1, and all carry the same domain ID.
+ * These are order-independent field counts, evaluated after the syscall
+ * returns (the caller has waited on all siblings by then).
+ */
+TEST_F(trace, enforce_tsync_multithread)
+{
+ const int nsiblings = 3;
+ pid_t pid;
+ int status;
+ char *buf;
+ char domain[64];
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ pid = fork();
+ ASSERT_LE(0, pid);
+ if (pid == 0)
+ _exit(child_enforce(nsiblings, LANDLOCK_RESTRICT_SELF_TSYNC));
+
+ ASSERT_EQ(pid, waitpid(pid, &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_CREATE_DOMAIN(TRACE_TASK)));
+ EXPECT_EQ(nsiblings + 1, count_enforce_matches(buf, NULL, -1, -1))
+ {
+ TH_LOG("Expected %d enforce_domain events\n%s", nsiblings + 1,
+ buf);
+ }
+ EXPECT_EQ(1, count_enforce_matches(buf, NULL, 1, -1));
+ EXPECT_EQ(nsiblings, count_enforce_matches(buf, NULL, 0, -1));
+ EXPECT_EQ(nsiblings + 1, count_enforce_matches(buf, NULL, -1, 1));
+
+ ASSERT_EQ(0, tracefs_extract_field(buf, REGEX_CREATE_DOMAIN(TRACE_TASK),
+ "domain", domain, sizeof(domain)));
+ EXPECT_EQ(nsiblings + 1, count_enforce_matches(buf, domain, -1, -1));
+
+ free(buf);
+}
+
+/*
+ * Verifies the disambiguation case: a non-TSYNC restrict_self on a
+ * multi-threaded process enforces only the caller, so the single enforce_domain
+ * has process_wide=0 (the siblings stay unconfined).
+ */
+TEST_F(trace, enforce_multithread_non_tsync)
+{
+ const int nsiblings = 3;
+ pid_t pid;
+ int status;
+ char *buf;
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ pid = fork();
+ ASSERT_LE(0, pid);
+ if (pid == 0)
+ _exit(child_enforce(nsiblings, 0));
+
+ ASSERT_EQ(pid, waitpid(pid, &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_CREATE_DOMAIN(TRACE_TASK)));
+ EXPECT_EQ(1, count_enforce_matches(buf, NULL, -1, -1));
+ EXPECT_EQ(1, count_enforce_matches(buf, NULL, 1, 0))
+ {
+ TH_LOG("Expected process_wide=0 enforce_domain event\n%s", buf);
+ }
+
+ free(buf);
+}
+
+/*
+ * Verifies that a single-threaded caller that is not the group leader (the
+ * leader called pthread_exit()) still reports process_wide=1, the case
+ * get_nr_threads() handles and the leader-relative thread_group_empty() would
+ * not. SKIPs if the group cannot be reduced to one live thread.
+ */
+TEST_F(trace, enforce_single_non_leader)
+{
+ pid_t pid;
+ int status;
+ char *buf;
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ pid = fork();
+ ASSERT_LE(0, pid);
+ if (pid == 0) {
+ pthread_t worker;
+
+ if (pthread_create(&worker, NULL, enforce_nonleader, NULL))
+ _exit(1);
+ /* Leader leaves; the worker becomes the only live thread. */
+ pthread_exit(NULL);
+ }
+
+ ASSERT_EQ(pid, waitpid(pid, &status, 0));
+ ASSERT_TRUE(WIFEXITED(status));
+ if (WEXITSTATUS(status) == ENFORCE_SKIP_EXIT)
+ SKIP(return, "could not reduce group to a single thread");
+ EXPECT_EQ(0, WEXITSTATUS(status));
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ EXPECT_EQ(1,
+ tracefs_count_matches(buf, REGEX_CREATE_DOMAIN(TRACE_TASK)));
+ EXPECT_EQ(1, count_enforce_matches(buf, NULL, 1, 1))
+ {
+ TH_LOG("Expected process_wide=1 for non-leader caller\n%s",
+ buf);
+ }
+
+ free(buf);
+}
+
+/*
+ * Verifies the flags-only path (ruleset_fd == -1) creates no domain and emits
+ * neither create_domain nor enforce_domain, with and without TSYNC.
+ */
+TEST_F(trace, enforce_flags_only)
+{
+ pid_t pid;
+ int status;
+ char *buf;
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ pid = fork();
+ ASSERT_LE(0, pid);
+ if (pid == 0) {
+ prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+ if (landlock_restrict_self(
+ -1, LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF))
+ _exit(1);
+ if (landlock_restrict_self(
+ -1, LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF |
+ LANDLOCK_RESTRICT_SELF_TSYNC))
+ _exit(1);
+ _exit(0);
+ }
+
+ ASSERT_EQ(pid, waitpid(pid, &status, 0));
+ ASSERT_TRUE(WIFEXITED(status));
+ EXPECT_EQ(0, WEXITSTATUS(status));
+
+ buf = tracefs_read_buf();
+ ASSERT_NE(NULL, buf);
+
+ EXPECT_EQ(0,
+ tracefs_count_matches(buf, REGEX_CREATE_DOMAIN(TRACE_TASK)));
+ EXPECT_EQ(0, count_enforce_matches(buf, NULL, -1, -1))
+ {
+ TH_LOG("No enforce_domain expected on flags-only path\n%s",
+ buf);
+ }
+
+ free(buf);
+}
+
+static void enforce_nop_handler(int sig)
+{
+}
+
+struct abort_signaler_data {
+ pthread_t target;
+ volatile bool stop;
+};
+
+/* Hammers the target thread with SIGUSR1 to interrupt the TSYNC prepare wait. */
+static void *abort_signaler(void *arg)
+{
+ struct abort_signaler_data *data = arg;
+
+ while (!data->stop)
+ pthread_kill(data->target, SIGUSR1);
+ return NULL;
+}
+
+/*
+ * Child body for the abort test: with idle siblings and a signaler interrupting
+ * it, repeatedly enforces under TSYNC. An interrupted attempt aborts its
+ * just-created domain (create_domain + free_domain, zero enforce_domain) while
+ * -ERESTARTNOINTR transparently restarts the syscall, so a successful retry may
+ * add its own full lifecycle.
+ */
+static int child_abort(int nsiblings, int attempts)
+{
+ pthread_t threads[16];
+ pthread_t signaler;
+ pthread_barrier_t barrier;
+ struct abort_signaler_data data = {};
+ struct sigaction sa = {};
+ int i;
+
+ sa.sa_handler = enforce_nop_handler;
+ if (sigaction(SIGUSR1, &sa, NULL))
+ return 1;
+
+ if (pthread_barrier_init(&barrier, NULL, nsiblings + 1))
+ return 1;
+ for (i = 0; i < nsiblings; i++)
+ if (pthread_create(&threads[i], NULL, enforce_idle, &barrier))
+ return 1;
+ pthread_barrier_wait(&barrier);
+
+ data.target = pthread_self();
+ if (pthread_create(&signaler, NULL, abort_signaler, &data))
+ return 1;
+
+ prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
+ for (i = 0; i < attempts; i++) {
+ int ruleset_fd = build_enforce_ruleset();
+
+ if (ruleset_fd < 0)
+ break;
+ /* Ignore the result: an abort returns an error, that is fine. */
+ landlock_restrict_self(ruleset_fd,
+ LANDLOCK_RESTRICT_SELF_TSYNC);
+ close(ruleset_fd);
+ }
+
+ data.stop = true;
+ pthread_join(signaler, NULL);
+ return 0;
+}
+
+/*
+ * Verifies the abort contract: a domain aborted by a thread-sync failure emits
+ * create_domain and free_domain but zero enforce_domain. The signal race is
+ * probabilistic and -ERESTARTNOINTR may add a successful retry's lifecycle, so
+ * events are grouped by domain ID and the test SKIPs if no abort occurred.
+ */
+TEST_F(trace, enforce_abort)
+{
+ pid_t pid;
+ int status, retry;
+ char *buf = NULL;
+ const char *cursor;
+ char domain[64];
+ bool abort_found = false;
+
+ ASSERT_EQ(0, tracefs_clear_buf());
+
+ /* free_domain fires from a kworker, so widen the filter first. */
+ set_cap(_metadata, CAP_SYS_ADMIN);
+ tracefs_clear_pid_filter();
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+
+ pid = fork();
+ ASSERT_LE(0, pid);
+ if (pid == 0)
+ _exit(child_abort(8, 8));
+
+ ASSERT_EQ(pid, waitpid(pid, &status, 0));
+ ASSERT_TRUE(WIFEXITED(status));
+ EXPECT_EQ(0, WEXITSTATUS(status));
+
+ /* Poll for the asynchronous free_domain events. */
+ for (retry = 0; retry < 10; retry++) {
+ usleep(100000);
+ set_cap(_metadata, CAP_SYS_ADMIN);
+ free(buf);
+ buf = tracefs_read_trace();
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+ ASSERT_NE(NULL, buf);
+ }
+
+ set_cap(_metadata, CAP_SYS_ADMIN);
+ ASSERT_EQ(0, tracefs_set_pid_filter(getpid()));
+ clear_cap(_metadata, CAP_SYS_ADMIN);
+
+ /*
+ * Walk every create_domain and look for one whose domain ID has zero
+ * enforce_domain events but a matching free_domain: that is an aborted
+ * domain (created, never enforced, freed).
+ */
+ cursor = buf;
+ while (tracefs_extract_field(cursor, REGEX_CREATE_DOMAIN(TRACE_TASK),
+ "domain", domain, sizeof(domain)) == 0) {
+ const char *cd, *nl;
+ char free_pattern[256];
+
+ if (count_enforce_matches(buf, domain, -1, -1) == 0) {
+ snprintf(
+ free_pattern, sizeof(free_pattern),
+ TRACE_PREFIX(
+ KWORKER_TASK) "landlock_free_domain: "
+ "domain=%s denials=[0-9]\\+$",
+ domain);
+ if (tracefs_count_matches(buf, free_pattern) >= 1)
+ abort_found = true;
+ }
+
+ cd = strstr(cursor, "landlock_create_domain:");
+ if (!cd)
+ break;
+ nl = strchr(cd, '\n');
+ if (!nl)
+ break;
+ cursor = nl + 1;
+ }
+
+ if (!abort_found) {
+ free(buf);
+ SKIP(return, "signal race did not produce a thread-sync abort");
+ }
+
+ free(buf);
+}
+
/*
* The following tests are intentionally elided because the underlying kernel
* mechanisms are already validated by audit tests:
--
2.54.0
^ permalink raw reply related
* [PATCH v3 04/20] landlock: Split denial logging from audit into common framework
From: Mickaël Salaün @ 2026-07-22 17:11 UTC (permalink / raw)
To: Günther Noack, Steven Rostedt
Cc: Mickaël Salaün, Christian Brauner, Jann Horn, Jeff Xu,
Justin Suess, Kees Cook, Masami Hiramatsu, Mathieu Desnoyers,
Matthieu Buffet, Mikhail Ivanov, Tingmao Wang, kernel-team,
linux-security-module, linux-trace-kernel
In-Reply-To: <20260722171159.2776765-1-mic@digikod.net>
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.
Cc: Günther Noack <gnoack@google.com>
Signed-off-by: Mickaël Salaün <mic@digikod.net>
---
Changes since v2:
https://patch.msgid.link/20260406143717.1815792-5-mic@digikod.net
- 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
diff --git a/security/landlock/Kconfig b/security/landlock/Kconfig
index 3f1493402052..b4e7f0e9ba9b 100644
--- a/security/landlock/Kconfig
+++ b/security/landlock/Kconfig
@@ -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
diff --git a/security/landlock/Makefile b/security/landlock/Makefile
index 23e13644916f..2462e6c5921e 100644
--- a/security/landlock/Makefile
+++ b/security/landlock/Makefile
@@ -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
diff --git a/security/landlock/access.h b/security/landlock/access.h
index 1a8227a709d9..bbbb41f41147 100644
--- a/security/landlock/access.h
+++ b/security/landlock/access.h
@@ -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));
/*
diff --git a/security/landlock/audit.c b/security/landlock/audit.c
index 7cb00619a741..dfa1e5a64aac 100644
--- a/security/landlock/audit.c
+++ b/security/landlock/audit.c
@@ -5,7 +5,6 @@
* Copyright © 2023-2025 Microsoft Corporation
*/
-#include <kunit/test.h>
#include <linux/audit.h>
#include <linux/bitops.h>
#include <linux/lsm_audit.h>
@@ -18,7 +17,7 @@
#include "cred.h"
#include "domain.h"
#include "limits.h"
-#include "ruleset.h"
+#include "log.h"
static const char *const fs_access_strings[] = {
[BIT_INDEX(LANDLOCK_ACCESS_FS_EXECUTE)] = "fs.execute",
@@ -137,393 +136,6 @@ static void log_domain(struct landlock_hierarchy *const hierarchy)
WRITE_ONCE(hierarchy->log_status, LANDLOCK_LOG_RECORDED);
}
-static struct landlock_hierarchy *
-get_hierarchy(const struct landlock_domain *const domain, const size_t layer)
-{
- struct landlock_hierarchy *hierarchy = domain->hierarchy;
- ssize_t i;
-
- if (WARN_ON_ONCE(layer >= domain->num_layers))
- return hierarchy;
-
- for (i = domain->num_layers - 1; i > layer; i--) {
- if (WARN_ON_ONCE(!hierarchy->parent))
- break;
-
- hierarchy = hierarchy->parent;
- }
-
- return hierarchy;
-}
-
-#ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
-
-static void test_get_hierarchy(struct kunit *const test)
-{
- struct landlock_hierarchy dom0_hierarchy = {
- .id = 10,
- };
- struct landlock_hierarchy dom1_hierarchy = {
- .parent = &dom0_hierarchy,
- .id = 20,
- };
- struct landlock_hierarchy dom2_hierarchy = {
- .parent = &dom1_hierarchy,
- .id = 30,
- };
- struct landlock_domain dom2 = {
- .hierarchy = &dom2_hierarchy,
- .num_layers = 3,
- };
-
- KUNIT_EXPECT_EQ(test, 10, get_hierarchy(&dom2, 0)->id);
- KUNIT_EXPECT_EQ(test, 20, get_hierarchy(&dom2, 1)->id);
- KUNIT_EXPECT_EQ(test, 30, get_hierarchy(&dom2, 2)->id);
- /* KUNIT_EXPECT_EQ(test, 30, get_hierarchy(&dom2, -1)->id); */
-}
-
-#endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
-
-/* Get the youngest layer that denied the access_request. */
-static size_t get_denied_layer(const struct landlock_domain *const domain,
- access_mask_t *const access_request,
- const struct layer_masks *masks)
-{
- for (ssize_t i = ARRAY_SIZE(masks->layers) - 1; i >= 0; i--) {
- if (masks->layers[i].access & *access_request) {
- *access_request &= masks->layers[i].access;
- return i;
- }
- }
-
- /* Not found - fall back to default values */
- *access_request = 0;
- return domain->num_layers - 1;
-}
-
-#ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
-
-static void test_get_denied_layer(struct kunit *const test)
-{
- const struct landlock_domain dom = {
- .num_layers = 5,
- };
- const struct layer_masks masks = {
- .layers[0].access = LANDLOCK_ACCESS_FS_EXECUTE |
- LANDLOCK_ACCESS_FS_READ_DIR,
- .layers[1].access = LANDLOCK_ACCESS_FS_READ_FILE |
- LANDLOCK_ACCESS_FS_READ_DIR,
- .layers[2].access = LANDLOCK_ACCESS_FS_REMOVE_DIR,
- };
- access_mask_t access;
-
- access = LANDLOCK_ACCESS_FS_EXECUTE;
- KUNIT_EXPECT_EQ(test, 0, get_denied_layer(&dom, &access, &masks));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_EXECUTE);
-
- access = LANDLOCK_ACCESS_FS_READ_FILE;
- KUNIT_EXPECT_EQ(test, 1, get_denied_layer(&dom, &access, &masks));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_READ_FILE);
-
- access = LANDLOCK_ACCESS_FS_READ_DIR;
- KUNIT_EXPECT_EQ(test, 1, get_denied_layer(&dom, &access, &masks));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_READ_DIR);
-
- access = LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_READ_DIR;
- KUNIT_EXPECT_EQ(test, 1, get_denied_layer(&dom, &access, &masks));
- KUNIT_EXPECT_EQ(test, access,
- LANDLOCK_ACCESS_FS_READ_FILE |
- LANDLOCK_ACCESS_FS_READ_DIR);
-
- access = LANDLOCK_ACCESS_FS_EXECUTE | LANDLOCK_ACCESS_FS_READ_DIR;
- KUNIT_EXPECT_EQ(test, 1, get_denied_layer(&dom, &access, &masks));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_READ_DIR);
-
- access = LANDLOCK_ACCESS_FS_WRITE_FILE;
- KUNIT_EXPECT_EQ(test, 4, get_denied_layer(&dom, &access, &masks));
- KUNIT_EXPECT_EQ(test, access, 0);
-}
-
-#endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
-
-static size_t
-get_layer_from_deny_masks(access_mask_t *const access_request,
- const access_mask_t all_existing_optional_access,
- const deny_masks_t deny_masks,
- optional_access_t quiet_optional_accesses,
- bool *quiet)
-{
- const unsigned long access_opt = all_existing_optional_access;
- const unsigned long access_req = *access_request;
- access_mask_t missing = 0;
- size_t youngest_layer = 0;
- size_t access_index = 0;
- unsigned long access_bit;
- bool should_quiet = false;
-
- /* This will require change with new object types. */
- WARN_ON_ONCE(access_opt != _LANDLOCK_ACCESS_FS_OPTIONAL);
-
- for_each_set_bit(access_bit, &access_opt,
- BITS_PER_TYPE(access_mask_t)) {
- if (access_req & BIT(access_bit)) {
- const size_t layer =
- (deny_masks >>
- (access_index *
- HWEIGHT(LANDLOCK_MAX_NUM_LAYERS - 1))) &
- (LANDLOCK_MAX_NUM_LAYERS - 1);
- const bool layer_has_quiet =
- !!(quiet_optional_accesses & BIT(access_index));
-
- if (layer > youngest_layer) {
- youngest_layer = layer;
- missing = BIT(access_bit);
- should_quiet = layer_has_quiet;
- } else if (layer == youngest_layer) {
- missing |= BIT(access_bit);
- /*
- * Whether the layer has rules with quiet flag
- * covering the file accessed does not depend on
- * the access, and so the following
- * WARN_ON_ONCE() should not fail.
- */
- WARN_ON_ONCE(should_quiet && !layer_has_quiet);
- should_quiet = layer_has_quiet;
- }
- }
- access_index++;
- }
-
- *access_request = missing;
- *quiet = should_quiet;
- return youngest_layer;
-}
-
-#ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
-
-static void test_get_layer_from_deny_masks(struct kunit *const test)
-{
- deny_masks_t deny_mask;
- access_mask_t access;
- optional_access_t quiet_optional_accesses;
- bool quiet;
-
- /* truncate:0 ioctl_dev:2 */
- deny_mask = 0x20;
- quiet_optional_accesses = 0;
-
- access = LANDLOCK_ACCESS_FS_TRUNCATE;
- KUNIT_EXPECT_EQ(test, 0,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
- KUNIT_EXPECT_EQ(test, quiet, false);
-
- access = LANDLOCK_ACCESS_FS_IOCTL_DEV;
- KUNIT_EXPECT_EQ(test, 2,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_IOCTL_DEV);
- KUNIT_EXPECT_EQ(test, quiet, false);
-
- access = LANDLOCK_ACCESS_FS_TRUNCATE | LANDLOCK_ACCESS_FS_IOCTL_DEV;
- KUNIT_EXPECT_EQ(test, 2,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_IOCTL_DEV);
- KUNIT_EXPECT_EQ(test, quiet, false);
-
- /* layer denying truncate: quiet, ioctl: not quiet */
- quiet_optional_accesses = 0b01;
-
- access = LANDLOCK_ACCESS_FS_TRUNCATE;
- KUNIT_EXPECT_EQ(test, 0,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
- KUNIT_EXPECT_EQ(test, quiet, true);
-
- access = LANDLOCK_ACCESS_FS_IOCTL_DEV;
- KUNIT_EXPECT_EQ(test, 2,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_IOCTL_DEV);
- KUNIT_EXPECT_EQ(test, quiet, false);
-
- access = LANDLOCK_ACCESS_FS_TRUNCATE | LANDLOCK_ACCESS_FS_IOCTL_DEV;
- KUNIT_EXPECT_EQ(test, 2,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_IOCTL_DEV);
- KUNIT_EXPECT_EQ(test, quiet, false);
-
- /* Reverse order - truncate:2 ioctl_dev:0 */
- deny_mask = 0x02;
- quiet_optional_accesses = 0;
-
- access = LANDLOCK_ACCESS_FS_TRUNCATE;
- KUNIT_EXPECT_EQ(test, 2,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
- KUNIT_EXPECT_EQ(test, quiet, false);
-
- access = LANDLOCK_ACCESS_FS_IOCTL_DEV;
- KUNIT_EXPECT_EQ(test, 0,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_IOCTL_DEV);
- KUNIT_EXPECT_EQ(test, quiet, false);
-
- access = LANDLOCK_ACCESS_FS_TRUNCATE | LANDLOCK_ACCESS_FS_IOCTL_DEV;
- KUNIT_EXPECT_EQ(test, 2,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
- KUNIT_EXPECT_EQ(test, quiet, false);
-
- /* layer denying truncate: quiet, ioctl: not quiet */
- quiet_optional_accesses = 0b01;
-
- access = LANDLOCK_ACCESS_FS_TRUNCATE;
- KUNIT_EXPECT_EQ(test, 2,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
- KUNIT_EXPECT_EQ(test, quiet, true);
-
- access = LANDLOCK_ACCESS_FS_IOCTL_DEV;
- KUNIT_EXPECT_EQ(test, 0,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_IOCTL_DEV);
- KUNIT_EXPECT_EQ(test, quiet, false);
-
- access = LANDLOCK_ACCESS_FS_TRUNCATE | LANDLOCK_ACCESS_FS_IOCTL_DEV;
- KUNIT_EXPECT_EQ(test, 2,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
- KUNIT_EXPECT_EQ(test, quiet, true);
-
- /* layer denying truncate: not quiet, ioctl: quiet */
- quiet_optional_accesses = 0b10;
-
- access = LANDLOCK_ACCESS_FS_TRUNCATE;
- KUNIT_EXPECT_EQ(test, 2,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
- KUNIT_EXPECT_EQ(test, quiet, false);
-
- access = LANDLOCK_ACCESS_FS_IOCTL_DEV;
- KUNIT_EXPECT_EQ(test, 0,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_IOCTL_DEV);
- KUNIT_EXPECT_EQ(test, quiet, true);
-
- access = LANDLOCK_ACCESS_FS_TRUNCATE | LANDLOCK_ACCESS_FS_IOCTL_DEV;
- KUNIT_EXPECT_EQ(test, 2,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
- KUNIT_EXPECT_EQ(test, quiet, false);
-
- /* truncate:15 ioctl_dev:15 */
- deny_mask = 0xff;
- quiet_optional_accesses = 0;
-
- access = LANDLOCK_ACCESS_FS_TRUNCATE;
- KUNIT_EXPECT_EQ(test, 15,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
- KUNIT_EXPECT_EQ(test, quiet, false);
-
- access = LANDLOCK_ACCESS_FS_TRUNCATE | LANDLOCK_ACCESS_FS_IOCTL_DEV;
- KUNIT_EXPECT_EQ(test, 15,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access,
- LANDLOCK_ACCESS_FS_TRUNCATE |
- LANDLOCK_ACCESS_FS_IOCTL_DEV);
- KUNIT_EXPECT_EQ(test, quiet, false);
-
- /* Both quiet (same layer so quietness must be the same) */
- quiet_optional_accesses = 0b11;
-
- access = LANDLOCK_ACCESS_FS_TRUNCATE;
- KUNIT_EXPECT_EQ(test, 15,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
- KUNIT_EXPECT_EQ(test, quiet, true);
-
- access = LANDLOCK_ACCESS_FS_TRUNCATE | LANDLOCK_ACCESS_FS_IOCTL_DEV;
- KUNIT_EXPECT_EQ(test, 15,
- get_layer_from_deny_masks(
- &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
- deny_mask, quiet_optional_accesses, &quiet));
- KUNIT_EXPECT_EQ(test, access,
- LANDLOCK_ACCESS_FS_TRUNCATE |
- LANDLOCK_ACCESS_FS_IOCTL_DEV);
- KUNIT_EXPECT_EQ(test, quiet, true);
-}
-
-#endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
-
-static bool is_valid_request(const struct landlock_request *const request)
-{
- if (WARN_ON_ONCE(request->layer_plus_one > LANDLOCK_MAX_NUM_LAYERS))
- return false;
-
- if (WARN_ON_ONCE(!(!!request->layer_plus_one ^ !!request->access)))
- return false;
-
- if (request->access) {
- if (WARN_ON_ONCE(!(!!request->layer_masks ^
- !!request->all_existing_optional_access)))
- return false;
- } else {
- if (WARN_ON_ONCE(request->layer_masks ||
- request->all_existing_optional_access))
- return false;
- }
-
- if (request->deny_masks) {
- if (WARN_ON_ONCE(!request->all_existing_optional_access))
- return false;
- static_assert(sizeof(request->all_existing_optional_access) ==
- sizeof(u32));
- if (WARN_ON_ONCE(
- request->quiet_optional_accesses >=
- BIT(hweight32(
- request->all_existing_optional_access))))
- return false;
- }
-
- return true;
-}
-
static access_mask_t
pick_access_mask_for_request_type(const enum landlock_request_type type,
const struct access_masks access_masks)
@@ -541,62 +153,27 @@ pick_access_mask_for_request_type(const enum landlock_request_type type,
}
/**
- * landlock_log_denial - Create audit records related to a denial
+ * 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.
+ *
+ * Called from landlock_log_denial() with the same arguments.
*/
-void landlock_log_denial(const struct landlock_cred_security *const subject,
- const struct landlock_request *const request)
+void landlock_audit_denial(const struct landlock_cred_security *const subject,
+ 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)
{
struct audit_buffer *ab;
- struct landlock_hierarchy *youngest_denied;
- size_t youngest_layer;
- access_mask_t missing;
- bool object_quiet_flag = false, quiet_applicable_to_access = false;
-
- if (WARN_ON_ONCE(!subject || !subject->domain ||
- !subject->domain->hierarchy || !request))
- return;
-
- if (!is_valid_request(request))
- return;
-
- missing = request->access;
- if (missing) {
- /* Gets the nearest domain that denies the request. */
- if (request->layer_masks) {
- youngest_layer = get_denied_layer(subject->domain,
- &missing,
- request->layer_masks);
- object_quiet_flag =
- request->layer_masks->layers[youngest_layer]
- .quiet;
- } else {
- youngest_layer = get_layer_from_deny_masks(
- &missing, _LANDLOCK_ACCESS_FS_OPTIONAL,
- request->deny_masks,
- request->quiet_optional_accesses,
- &object_quiet_flag);
- }
- youngest_denied =
- get_hierarchy(subject->domain, youngest_layer);
- } else {
- youngest_layer = request->layer_plus_one - 1;
- youngest_denied =
- get_hierarchy(subject->domain, youngest_layer);
- }
-
- if (READ_ONCE(youngest_denied->log_status) == LANDLOCK_LOG_DISABLED)
- return;
-
- /*
- * Consistently keeps track of the number of denied access requests
- * even if audit is currently disabled, or if audit rules currently
- * exclude this record type, or if landlock_restrict_self(2)'s flags
- * quiet logs.
- */
- atomic64_inc(&youngest_denied->num_denials);
+ bool quiet_applicable_to_access = false;
if (!audit_enabled)
return;
@@ -675,23 +252,19 @@ void landlock_log_denial(const struct landlock_cred_security *const subject,
}
/**
- * landlock_log_drop_domain - Create an audit record on domain deallocation
+ * landlock_audit_free_domain - Create an audit record on domain deallocation
*
* @hierarchy: The domain's hierarchy being deallocated.
*
* 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_domain_deferred() called by
- * hook_cred_free().
+ * Called from landlock_log_free_domain().
*/
-void landlock_log_drop_domain(const struct landlock_hierarchy *const hierarchy)
+void landlock_audit_free_domain(const struct landlock_hierarchy *const hierarchy)
{
struct audit_buffer *ab;
- if (WARN_ON_ONCE(!hierarchy))
- return;
-
if (!audit_enabled)
return;
@@ -712,23 +285,3 @@ void landlock_log_drop_domain(const struct landlock_hierarchy *const hierarchy)
hierarchy->id, atomic64_read(&hierarchy->num_denials));
audit_log_end(ab);
}
-
-#ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
-
-static struct kunit_case test_cases[] = {
- /* clang-format off */
- KUNIT_CASE(test_get_hierarchy),
- KUNIT_CASE(test_get_denied_layer),
- KUNIT_CASE(test_get_layer_from_deny_masks),
- {}
- /* clang-format on */
-};
-
-static struct kunit_suite test_suite = {
- .name = "landlock_audit",
- .test_cases = test_cases,
-};
-
-kunit_test_suite(test_suite);
-
-#endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
diff --git a/security/landlock/audit.h b/security/landlock/audit.h
index 4617a855712c..1b36bb3c6cfd 100644
--- a/security/landlock/audit.h
+++ b/security/landlock/audit.h
@@ -8,68 +8,39 @@
#ifndef _SECURITY_LANDLOCK_AUDIT_H
#define _SECURITY_LANDLOCK_AUDIT_H
-#include <linux/audit.h>
-#include <linux/lsm_audit.h>
+#include <linux/types.h>
#include "access.h"
struct landlock_cred_security;
struct landlock_hierarchy;
-
-enum landlock_request_type {
- LANDLOCK_REQUEST_PTRACE = 1,
- LANDLOCK_REQUEST_FS_CHANGE_TOPOLOGY,
- LANDLOCK_REQUEST_FS_ACCESS,
- LANDLOCK_REQUEST_NET_ACCESS,
- LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET,
- LANDLOCK_REQUEST_SCOPE_SIGNAL,
-};
-
-/*
- * We should be careful to only use a variable of this type for
- * landlock_log_denial(). This way, the compiler can remove it entirely if
- * CONFIG_AUDIT is not set.
- */
-struct landlock_request {
- /* Mandatory fields. */
- enum landlock_request_type type;
- struct common_audit_data audit;
-
- /**
- * layer_plus_one: First layer level that denies the request + 1. The
- * extra one is useful to detect uninitialized field.
- */
- size_t layer_plus_one;
-
- /* Required field for configurable access control. */
- access_mask_t access;
-
- /* Required fields for requests with layer masks. */
- const struct layer_masks *layer_masks;
-
- /* Required fields for requests with deny masks. */
- const access_mask_t all_existing_optional_access;
- deny_masks_t deny_masks;
- optional_access_t quiet_optional_accesses;
-};
+struct landlock_request;
#ifdef CONFIG_AUDIT
-void landlock_log_drop_domain(const struct landlock_hierarchy *const hierarchy);
+void landlock_audit_denial(const struct landlock_cred_security *const subject,
+ 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);
-void landlock_log_denial(const struct landlock_cred_security *const subject,
- const struct landlock_request *const request);
+void landlock_audit_free_domain(
+ const struct landlock_hierarchy *const hierarchy);
#else /* CONFIG_AUDIT */
static inline void
-landlock_log_drop_domain(const struct landlock_hierarchy *const hierarchy)
+landlock_audit_denial(const struct landlock_cred_security *const subject,
+ 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)
{
}
static inline void
-landlock_log_denial(const struct landlock_cred_security *const subject,
- const struct landlock_request *const request)
+landlock_audit_free_domain(const struct landlock_hierarchy *const hierarchy)
{
}
diff --git a/security/landlock/cred.c b/security/landlock/cred.c
index 58b544993db4..03449c26247e 100644
--- a/security/landlock/cred.c
+++ b/security/landlock/cred.c
@@ -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)
diff --git a/security/landlock/cred.h b/security/landlock/cred.h
index e7830cfed041..a5ff9957949a 100644
--- a/security/landlock/cred.h
+++ b/security/landlock/cred.h
@@ -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)
diff --git a/security/landlock/domain.c b/security/landlock/domain.c
index 2e0d75175c2a..6444cf27bda2 100644
--- a/security/landlock/domain.c
+++ b/security/landlock/domain.c
@@ -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 */
diff --git a/security/landlock/domain.h b/security/landlock/domain.h
index f0925297dcba..1237e3e25240 100644
--- a/security/landlock/domain.h
+++ b/security/landlock/domain.h
@@ -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);
diff --git a/security/landlock/fs.c b/security/landlock/fs.c
index 0b77d310ffd4..d39da6e9fa8c 100644
--- a/security/landlock/fs.c
+++ b/security/landlock/fs.c
@@ -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);
diff --git a/security/landlock/fs.h b/security/landlock/fs.h
index b4421d9df68f..c16f24e30bd5 100644
--- a/security/landlock/fs.h
+++ b/security/landlock/fs.h
@@ -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
diff --git a/security/landlock/id.h b/security/landlock/id.h
index 45dcfb9e9a8b..2a43c2b523a8 100644
--- a/security/landlock/id.h
+++ b/security/landlock/id.h
@@ -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 */
diff --git a/security/landlock/log.c b/security/landlock/log.c
new file mode 100644
index 000000000000..6dd3373c4ba4
--- /dev/null
+++ b/security/landlock/log.c
@@ -0,0 +1,502 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Landlock - Log helpers
+ *
+ * Copyright © 2023-2025 Microsoft Corporation
+ */
+
+#include <kunit/test.h>
+#include <linux/bitops.h>
+#include <uapi/linux/landlock.h>
+
+#include "access.h"
+#include "audit.h"
+#include "common.h"
+#include "cred.h"
+#include "domain.h"
+#include "limits.h"
+#include "log.h"
+#include "ruleset.h"
+
+static struct landlock_hierarchy *
+get_hierarchy(const struct landlock_domain *const domain, const size_t layer)
+{
+ struct landlock_hierarchy *hierarchy = domain->hierarchy;
+ ssize_t i;
+
+ if (WARN_ON_ONCE(layer >= domain->num_layers))
+ return hierarchy;
+
+ for (i = domain->num_layers - 1; i > layer; i--) {
+ if (WARN_ON_ONCE(!hierarchy->parent))
+ break;
+
+ hierarchy = hierarchy->parent;
+ }
+
+ return hierarchy;
+}
+
+#ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
+
+static void test_get_hierarchy(struct kunit *const test)
+{
+ struct landlock_hierarchy dom0_hierarchy = {
+ .id = 10,
+ };
+ struct landlock_hierarchy dom1_hierarchy = {
+ .parent = &dom0_hierarchy,
+ .id = 20,
+ };
+ struct landlock_hierarchy dom2_hierarchy = {
+ .parent = &dom1_hierarchy,
+ .id = 30,
+ };
+ struct landlock_domain dom2 = {
+ .hierarchy = &dom2_hierarchy,
+ .num_layers = 3,
+ };
+
+ KUNIT_EXPECT_EQ(test, 10, get_hierarchy(&dom2, 0)->id);
+ KUNIT_EXPECT_EQ(test, 20, get_hierarchy(&dom2, 1)->id);
+ KUNIT_EXPECT_EQ(test, 30, get_hierarchy(&dom2, 2)->id);
+ /* KUNIT_EXPECT_EQ(test, 30, get_hierarchy(&dom2, -1)->id); */
+}
+
+#endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
+
+/* Get the youngest layer that denied the access_request. */
+static size_t get_denied_layer(const struct landlock_domain *const domain,
+ access_mask_t *const access_request,
+ const struct layer_masks *masks)
+{
+ for (ssize_t i = ARRAY_SIZE(masks->layers) - 1; i >= 0; i--) {
+ if (masks->layers[i].access & *access_request) {
+ *access_request &= masks->layers[i].access;
+ return i;
+ }
+ }
+
+ /* Not found - fall back to default values */
+ *access_request = 0;
+ return domain->num_layers - 1;
+}
+
+#ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
+
+static void test_get_denied_layer(struct kunit *const test)
+{
+ const struct landlock_domain dom = {
+ .num_layers = 5,
+ };
+ const struct layer_masks masks = {
+ .layers[0].access = LANDLOCK_ACCESS_FS_EXECUTE |
+ LANDLOCK_ACCESS_FS_READ_DIR,
+ .layers[1].access = LANDLOCK_ACCESS_FS_READ_FILE |
+ LANDLOCK_ACCESS_FS_READ_DIR,
+ .layers[2].access = LANDLOCK_ACCESS_FS_REMOVE_DIR,
+ };
+ access_mask_t access;
+
+ access = LANDLOCK_ACCESS_FS_EXECUTE;
+ KUNIT_EXPECT_EQ(test, 0, get_denied_layer(&dom, &access, &masks));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_EXECUTE);
+
+ access = LANDLOCK_ACCESS_FS_READ_FILE;
+ KUNIT_EXPECT_EQ(test, 1, get_denied_layer(&dom, &access, &masks));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_READ_FILE);
+
+ access = LANDLOCK_ACCESS_FS_READ_DIR;
+ KUNIT_EXPECT_EQ(test, 1, get_denied_layer(&dom, &access, &masks));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_READ_DIR);
+
+ access = LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_READ_DIR;
+ KUNIT_EXPECT_EQ(test, 1, get_denied_layer(&dom, &access, &masks));
+ KUNIT_EXPECT_EQ(test, access,
+ LANDLOCK_ACCESS_FS_READ_FILE |
+ LANDLOCK_ACCESS_FS_READ_DIR);
+
+ access = LANDLOCK_ACCESS_FS_EXECUTE | LANDLOCK_ACCESS_FS_READ_DIR;
+ KUNIT_EXPECT_EQ(test, 1, get_denied_layer(&dom, &access, &masks));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_READ_DIR);
+
+ access = LANDLOCK_ACCESS_FS_WRITE_FILE;
+ KUNIT_EXPECT_EQ(test, 4, get_denied_layer(&dom, &access, &masks));
+ KUNIT_EXPECT_EQ(test, access, 0);
+}
+
+#endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
+
+static size_t
+get_layer_from_deny_masks(access_mask_t *const access_request,
+ const access_mask_t all_existing_optional_access,
+ const deny_masks_t deny_masks,
+ optional_access_t quiet_optional_accesses,
+ bool *quiet)
+{
+ const unsigned long access_opt = all_existing_optional_access;
+ const unsigned long access_req = *access_request;
+ access_mask_t missing = 0;
+ size_t youngest_layer = 0;
+ size_t access_index = 0;
+ unsigned long access_bit;
+ bool should_quiet = false;
+
+ /* This will require change with new object types. */
+ WARN_ON_ONCE(access_opt != _LANDLOCK_ACCESS_FS_OPTIONAL);
+
+ for_each_set_bit(access_bit, &access_opt,
+ BITS_PER_TYPE(access_mask_t)) {
+ if (access_req & BIT(access_bit)) {
+ const size_t layer =
+ (deny_masks >>
+ (access_index *
+ HWEIGHT(LANDLOCK_MAX_NUM_LAYERS - 1))) &
+ (LANDLOCK_MAX_NUM_LAYERS - 1);
+ const bool layer_has_quiet =
+ !!(quiet_optional_accesses & BIT(access_index));
+
+ if (layer > youngest_layer) {
+ youngest_layer = layer;
+ missing = BIT(access_bit);
+ should_quiet = layer_has_quiet;
+ } else if (layer == youngest_layer) {
+ missing |= BIT(access_bit);
+ /*
+ * Whether the layer has rules with quiet flag
+ * covering the file accessed does not depend on
+ * the access, and so the following
+ * WARN_ON_ONCE() should not fail.
+ */
+ WARN_ON_ONCE(should_quiet && !layer_has_quiet);
+ should_quiet = layer_has_quiet;
+ }
+ }
+ access_index++;
+ }
+
+ *access_request = missing;
+ *quiet = should_quiet;
+ return youngest_layer;
+}
+
+#ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
+
+static void test_get_layer_from_deny_masks(struct kunit *const test)
+{
+ deny_masks_t deny_mask;
+ access_mask_t access;
+ optional_access_t quiet_optional_accesses;
+ bool quiet;
+
+ /* truncate:0 ioctl_dev:2 */
+ deny_mask = 0x20;
+ quiet_optional_accesses = 0;
+
+ access = LANDLOCK_ACCESS_FS_TRUNCATE;
+ KUNIT_EXPECT_EQ(test, 0,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
+ KUNIT_EXPECT_EQ(test, quiet, false);
+
+ access = LANDLOCK_ACCESS_FS_IOCTL_DEV;
+ KUNIT_EXPECT_EQ(test, 2,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_IOCTL_DEV);
+ KUNIT_EXPECT_EQ(test, quiet, false);
+
+ access = LANDLOCK_ACCESS_FS_TRUNCATE | LANDLOCK_ACCESS_FS_IOCTL_DEV;
+ KUNIT_EXPECT_EQ(test, 2,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_IOCTL_DEV);
+ KUNIT_EXPECT_EQ(test, quiet, false);
+
+ /* layer denying truncate: quiet, ioctl: not quiet */
+ quiet_optional_accesses = 0b01;
+
+ access = LANDLOCK_ACCESS_FS_TRUNCATE;
+ KUNIT_EXPECT_EQ(test, 0,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
+ KUNIT_EXPECT_EQ(test, quiet, true);
+
+ access = LANDLOCK_ACCESS_FS_IOCTL_DEV;
+ KUNIT_EXPECT_EQ(test, 2,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_IOCTL_DEV);
+ KUNIT_EXPECT_EQ(test, quiet, false);
+
+ access = LANDLOCK_ACCESS_FS_TRUNCATE | LANDLOCK_ACCESS_FS_IOCTL_DEV;
+ KUNIT_EXPECT_EQ(test, 2,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_IOCTL_DEV);
+ KUNIT_EXPECT_EQ(test, quiet, false);
+
+ /* Reverse order - truncate:2 ioctl_dev:0 */
+ deny_mask = 0x02;
+ quiet_optional_accesses = 0;
+
+ access = LANDLOCK_ACCESS_FS_TRUNCATE;
+ KUNIT_EXPECT_EQ(test, 2,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
+ KUNIT_EXPECT_EQ(test, quiet, false);
+
+ access = LANDLOCK_ACCESS_FS_IOCTL_DEV;
+ KUNIT_EXPECT_EQ(test, 0,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_IOCTL_DEV);
+ KUNIT_EXPECT_EQ(test, quiet, false);
+
+ access = LANDLOCK_ACCESS_FS_TRUNCATE | LANDLOCK_ACCESS_FS_IOCTL_DEV;
+ KUNIT_EXPECT_EQ(test, 2,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
+ KUNIT_EXPECT_EQ(test, quiet, false);
+
+ /* layer denying truncate: quiet, ioctl: not quiet */
+ quiet_optional_accesses = 0b01;
+
+ access = LANDLOCK_ACCESS_FS_TRUNCATE;
+ KUNIT_EXPECT_EQ(test, 2,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
+ KUNIT_EXPECT_EQ(test, quiet, true);
+
+ access = LANDLOCK_ACCESS_FS_IOCTL_DEV;
+ KUNIT_EXPECT_EQ(test, 0,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_IOCTL_DEV);
+ KUNIT_EXPECT_EQ(test, quiet, false);
+
+ access = LANDLOCK_ACCESS_FS_TRUNCATE | LANDLOCK_ACCESS_FS_IOCTL_DEV;
+ KUNIT_EXPECT_EQ(test, 2,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
+ KUNIT_EXPECT_EQ(test, quiet, true);
+
+ /* layer denying truncate: not quiet, ioctl: quiet */
+ quiet_optional_accesses = 0b10;
+
+ access = LANDLOCK_ACCESS_FS_TRUNCATE;
+ KUNIT_EXPECT_EQ(test, 2,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
+ KUNIT_EXPECT_EQ(test, quiet, false);
+
+ access = LANDLOCK_ACCESS_FS_IOCTL_DEV;
+ KUNIT_EXPECT_EQ(test, 0,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_IOCTL_DEV);
+ KUNIT_EXPECT_EQ(test, quiet, true);
+
+ access = LANDLOCK_ACCESS_FS_TRUNCATE | LANDLOCK_ACCESS_FS_IOCTL_DEV;
+ KUNIT_EXPECT_EQ(test, 2,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
+ KUNIT_EXPECT_EQ(test, quiet, false);
+
+ /* truncate:15 ioctl_dev:15 */
+ deny_mask = 0xff;
+ quiet_optional_accesses = 0;
+
+ access = LANDLOCK_ACCESS_FS_TRUNCATE;
+ KUNIT_EXPECT_EQ(test, 15,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
+ KUNIT_EXPECT_EQ(test, quiet, false);
+
+ access = LANDLOCK_ACCESS_FS_TRUNCATE | LANDLOCK_ACCESS_FS_IOCTL_DEV;
+ KUNIT_EXPECT_EQ(test, 15,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access,
+ LANDLOCK_ACCESS_FS_TRUNCATE |
+ LANDLOCK_ACCESS_FS_IOCTL_DEV);
+ KUNIT_EXPECT_EQ(test, quiet, false);
+
+ /* Both quiet (same layer so quietness must be the same) */
+ quiet_optional_accesses = 0b11;
+
+ access = LANDLOCK_ACCESS_FS_TRUNCATE;
+ KUNIT_EXPECT_EQ(test, 15,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access, LANDLOCK_ACCESS_FS_TRUNCATE);
+ KUNIT_EXPECT_EQ(test, quiet, true);
+
+ access = LANDLOCK_ACCESS_FS_TRUNCATE | LANDLOCK_ACCESS_FS_IOCTL_DEV;
+ KUNIT_EXPECT_EQ(test, 15,
+ get_layer_from_deny_masks(
+ &access, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ deny_mask, quiet_optional_accesses, &quiet));
+ KUNIT_EXPECT_EQ(test, access,
+ LANDLOCK_ACCESS_FS_TRUNCATE |
+ LANDLOCK_ACCESS_FS_IOCTL_DEV);
+ KUNIT_EXPECT_EQ(test, quiet, true);
+}
+
+#endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
+
+static bool is_valid_request(const struct landlock_request *const request)
+{
+ if (WARN_ON_ONCE(request->layer_plus_one > LANDLOCK_MAX_NUM_LAYERS))
+ return false;
+
+ if (WARN_ON_ONCE(!(!!request->layer_plus_one ^ !!request->access)))
+ return false;
+
+ if (request->access) {
+ if (WARN_ON_ONCE(!(!!request->layer_masks ^
+ !!request->all_existing_optional_access)))
+ return false;
+ } else {
+ if (WARN_ON_ONCE(request->layer_masks ||
+ request->all_existing_optional_access))
+ return false;
+ }
+
+ if (request->deny_masks) {
+ if (WARN_ON_ONCE(!request->all_existing_optional_access))
+ return false;
+ static_assert(sizeof(request->all_existing_optional_access) ==
+ sizeof(u32));
+ if (WARN_ON_ONCE(
+ request->quiet_optional_accesses >=
+ BIT(hweight32(
+ request->all_existing_optional_access))))
+ return false;
+ }
+
+ return true;
+}
+
+/**
+ * landlock_log_denial - Log a denied access
+ *
+ * @subject: The Landlock subject's credential denying an action.
+ * @request: Detail of the user space request.
+ */
+void landlock_log_denial(const struct landlock_cred_security *const subject,
+ const struct landlock_request *const request)
+{
+ struct landlock_hierarchy *youngest_denied;
+ size_t youngest_layer;
+ access_mask_t missing;
+ bool object_quiet_flag = false;
+
+ if (WARN_ON_ONCE(!subject || !subject->domain ||
+ !subject->domain->hierarchy || !request))
+ return;
+
+ if (!is_valid_request(request))
+ return;
+
+ missing = request->access;
+ if (missing) {
+ /* Gets the nearest domain that denies the request. */
+ if (request->layer_masks) {
+ youngest_layer = get_denied_layer(subject->domain,
+ &missing,
+ request->layer_masks);
+ object_quiet_flag =
+ request->layer_masks->layers[youngest_layer]
+ .quiet;
+ } else {
+ youngest_layer = get_layer_from_deny_masks(
+ &missing, _LANDLOCK_ACCESS_FS_OPTIONAL,
+ request->deny_masks,
+ request->quiet_optional_accesses,
+ &object_quiet_flag);
+ }
+ youngest_denied =
+ get_hierarchy(subject->domain, youngest_layer);
+ } else {
+ youngest_layer = request->layer_plus_one - 1;
+ youngest_denied =
+ get_hierarchy(subject->domain, youngest_layer);
+ }
+
+ if (READ_ONCE(youngest_denied->log_status) == LANDLOCK_LOG_DISABLED)
+ return;
+
+ /*
+ * Consistently keeps track of the number of denied access requests even
+ * if audit is currently disabled, or if audit rules currently exclude
+ * this record type, or if landlock_restrict_self(2)'s flags quiet logs.
+ */
+ atomic64_inc(&youngest_denied->num_denials);
+
+ landlock_audit_denial(subject, request, youngest_denied, youngest_layer,
+ missing, object_quiet_flag);
+}
+
+/**
+ * landlock_log_free_domain - Log domain deallocation
+ *
+ * @hierarchy: The domain's hierarchy being deallocated.
+ *
+ * Called in a work queue scheduled by landlock_put_domain_deferred() called by
+ * hook_cred_free().
+ */
+void landlock_log_free_domain(const struct landlock_hierarchy *const hierarchy)
+{
+ if (WARN_ON_ONCE(!hierarchy))
+ return;
+
+ landlock_audit_free_domain(hierarchy);
+}
+
+#ifdef CONFIG_SECURITY_LANDLOCK_KUNIT_TEST
+
+static struct kunit_case test_cases[] = {
+ /* clang-format off */
+ KUNIT_CASE(test_get_hierarchy),
+ KUNIT_CASE(test_get_denied_layer),
+ KUNIT_CASE(test_get_layer_from_deny_masks),
+ {}
+ /* clang-format on */
+};
+
+static struct kunit_suite test_suite = {
+ .name = "landlock_log",
+ .test_cases = test_cases,
+};
+
+kunit_test_suite(test_suite);
+
+#endif /* CONFIG_SECURITY_LANDLOCK_KUNIT_TEST */
diff --git a/security/landlock/log.h b/security/landlock/log.h
new file mode 100644
index 000000000000..25afc17cf055
--- /dev/null
+++ b/security/landlock/log.h
@@ -0,0 +1,77 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Landlock - Log helpers
+ *
+ * Copyright © 2023-2025 Microsoft Corporation
+ */
+
+#ifndef _SECURITY_LANDLOCK_LOG_H
+#define _SECURITY_LANDLOCK_LOG_H
+
+#include <linux/lsm_audit.h>
+
+#include "access.h"
+
+struct landlock_cred_security;
+struct landlock_hierarchy;
+
+enum landlock_request_type {
+ LANDLOCK_REQUEST_PTRACE = 1,
+ LANDLOCK_REQUEST_FS_CHANGE_TOPOLOGY,
+ LANDLOCK_REQUEST_FS_ACCESS,
+ LANDLOCK_REQUEST_NET_ACCESS,
+ LANDLOCK_REQUEST_SCOPE_ABSTRACT_UNIX_SOCKET,
+ LANDLOCK_REQUEST_SCOPE_SIGNAL,
+};
+
+/*
+ * We should be careful to only use a variable of this type for
+ * landlock_log_denial(). This way, the compiler can remove it entirely if
+ * CONFIG_SECURITY_LANDLOCK_LOG is not set.
+ */
+struct landlock_request {
+ /* Mandatory fields. */
+ enum landlock_request_type type;
+ struct common_audit_data audit;
+
+ /**
+ * layer_plus_one: First layer level that denies the request + 1. The
+ * extra one is useful to detect uninitialized field.
+ */
+ size_t layer_plus_one;
+
+ /* Required field for configurable access control. */
+ access_mask_t access;
+
+ /* Required fields for requests with layer masks. */
+ const struct layer_masks *layer_masks;
+
+ /* Required fields for requests with deny masks. */
+ const access_mask_t all_existing_optional_access;
+ deny_masks_t deny_masks;
+ optional_access_t quiet_optional_accesses;
+};
+
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
+
+void landlock_log_free_domain(const struct landlock_hierarchy *const hierarchy);
+
+void landlock_log_denial(const struct landlock_cred_security *const subject,
+ const struct landlock_request *const request);
+
+#else /* CONFIG_SECURITY_LANDLOCK_LOG */
+
+static inline void
+landlock_log_free_domain(const struct landlock_hierarchy *const hierarchy)
+{
+}
+
+static inline void
+landlock_log_denial(const struct landlock_cred_security *const subject,
+ const struct landlock_request *const request)
+{
+}
+
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
+
+#endif /* _SECURITY_LANDLOCK_LOG_H */
diff --git a/security/landlock/net.c b/security/landlock/net.c
index 7447738ca2e6..e27b3ba15664 100644
--- a/security/landlock/net.c
+++ b/security/landlock/net.c
@@ -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"
diff --git a/security/landlock/syscalls.c b/security/landlock/syscalls.c
index fe8505dc0ba5..0ad20a6f9564 100644
--- a/security/landlock/syscalls.c
+++ b/security/landlock/syscalls.c
@@ -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) {
diff --git a/security/landlock/task.c b/security/landlock/task.c
index 40e6bfa4bc75..c0da22736ea0 100644
--- a/security/landlock/task.c
+++ b/security/landlock/task.c
@@ -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;
}
--
2.54.0
^ permalink raw reply related
* [PATCH v3 07/20] tracing: Add __print_untrusted_str()
From: Mickaël Salaün @ 2026-07-22 17:11 UTC (permalink / raw)
To: Günther Noack, Steven Rostedt
Cc: Mickaël Salaün, Christian Brauner, Jann Horn, Jeff Xu,
Justin Suess, Kees Cook, Masami Hiramatsu, Mathieu Desnoyers,
Matthieu Buffet, Mikhail Ivanov, Tingmao Wang, kernel-team,
linux-security-module, linux-trace-kernel
In-Reply-To: <20260722171159.2776765-1-mic@digikod.net>
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 <gnoack@google.com>
Cc: Masami Hiramatsu <mhiramat@kernel.org>
Cc: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Cc: Steven Rostedt <rostedt@goodmis.org>
Cc: Tingmao Wang <m@maowtm.org>
Signed-off-by: Mickaël Salaün <mic@digikod.net>
---
Changes since v2:
https://patch.msgid.link/20260406143717.1815792-6-mic@digikod.net
- Add a Return: kdoc for trace_print_untrusted_str_seq() and rename its
declaration parameter to src.
Changes since v1:
https://patch.msgid.link/20250523165741.693976-4-mic@digikod.net
- 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(+)
diff --git a/include/linux/trace_events.h b/include/linux/trace_events.h
index 308c76b57d13..4ece9b8d9d6b 100644
--- a/include/linux/trace_events.h
+++ b/include/linux/trace_events.h
@@ -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)
diff --git a/include/trace/stages/stage3_trace_output.h b/include/trace/stages/stage3_trace_output.h
index 181b81335781..0235dbd11b52 100644
--- a/include/trace/stages/stage3_trace_output.h
+++ b/include/trace/stages/stage3_trace_output.h
@@ -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) \
({ \
diff --git a/include/trace/stages/stage7_class_define.h b/include/trace/stages/stage7_class_define.h
index 47008897a795..f29a82e7a4c4 100644
--- a/include/trace/stages/stage7_class_define.h
+++ b/include/trace/stages/stage7_class_define.h
@@ -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
diff --git a/kernel/trace/trace_output.c b/kernel/trace/trace_output.c
index a5ad76175d10..f0a9b29b3e36 100644
--- a/kernel/trace/trace_output.c
+++ b/kernel/trace/trace_output.c
@@ -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)
{
--
2.54.0
^ permalink raw reply related
* Re: [PATCH v3 03/20] landlock: Split struct landlock_domain from struct landlock_ruleset
From: Justin Suess @ 2026-07-22 21:12 UTC (permalink / raw)
To: Mickaël Salaün
Cc: Günther Noack, Steven Rostedt, Christian Brauner, Jann Horn,
Jeff Xu, Kees Cook, Masami Hiramatsu, Mathieu Desnoyers,
Matthieu Buffet, Mikhail Ivanov, Tingmao Wang, kernel-team,
linux-security-module, linux-trace-kernel
In-Reply-To: <20260722171159.2776765-4-mic@digikod.net>
On Wed, Jul 22, 2026 at 07:11:35PM +0200, Mickaël Salaün wrote:
> 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
> [...]
^ permalink raw reply
* Re: [PATCH] apparmor: update website link
From: Serge Hallyn @ 2026-07-22 22:36 UTC (permalink / raw)
To: Ryan Lee
Cc: Baruch Siach, John Johansen, John Johansen, Georgia Garcia,
apparmor, linux-security-module
In-Reply-To: <CAKCV-6vP2FKgTj5PT3xB_TDL+zLk7xYf2BNw6mKXfPb3OO2TWA@mail.gmail.com>
Jul 22, 2026 11:41:27 Ryan Lee <ryan.lee@canonical.com>:
> On Tue, Jul 21, 2026 at 4:40 AM Baruch Siach <baruch@tkos.co.il> wrote:
>>
>> apparmor.wiki.kernel.org redirects to the current website.
Sure, but kernel.org seems less likely to go away, and the redirect can
easily be updated if needed. Up to John of course, but i would leave it
as is.
>> Signed-off-by: Baruch Siach <baruch@tkos.co.il>
>> ---
>> security/apparmor/Kconfig | 2 +-
>> 1 file changed, 1 insertion(+), 1 deletion(-)
>>
>> diff --git a/security/apparmor/Kconfig b/security/apparmor/Kconfig
>> index 1e3bd44643da..472aa38254be 100644
>> --- a/security/apparmor/Kconfig
>> +++ b/security/apparmor/Kconfig
>> @@ -11,7 +11,7 @@ config SECURITY_APPARMOR
>> This enables the AppArmor security module.
>> Required userspace tools (if they are not included in your
>> distribution) and further information may be found at
>> - http://apparmor.wiki.kernel.org
>> + https://wiki.apparmor.net
>>
>> If you are unsure how to answer this question, answer N.
>>
>> --
>> 2.53.0
>>
>>
>
> Reviewed-by: Ryan Lee <ryan.lee@canonical.com>
^ permalink raw reply
* Re: [PATCH] apparmor: update website link
From: John Johansen @ 2026-07-22 23:53 UTC (permalink / raw)
To: Serge Hallyn, Ryan Lee
Cc: Baruch Siach, John Johansen, Georgia Garcia, apparmor,
linux-security-module
In-Reply-To: <48d44625-7fa2-4e1c-8821-4d22208421ea@hallyn.com>
On 7/22/26 15:36, Serge Hallyn wrote:
> Jul 22, 2026 11:41:27 Ryan Lee <ryan.lee@canonical.com>:
>
>> On Tue, Jul 21, 2026 at 4:40 AM Baruch Siach <baruch@tkos.co.il> wrote:
>>>
>>> apparmor.wiki.kernel.org redirects to the current website.
>
>
> Sure, but kernel.org seems less likely to go away, and the redirect can
> easily be updated if needed. Up to John of course, but i would leave it
> as is.
>
I am unsure of the best course, but atm I am inclined to leave it with
kernel.org, Like you said the redirect can easily be updated.
>
>
>>> Signed-off-by: Baruch Siach <baruch@tkos.co.il>
>>> ---
>>> security/apparmor/Kconfig | 2 +-
>>> 1 file changed, 1 insertion(+), 1 deletion(-)
>>>
>>> diff --git a/security/apparmor/Kconfig b/security/apparmor/Kconfig
>>> index 1e3bd44643da..472aa38254be 100644
>>> --- a/security/apparmor/Kconfig
>>> +++ b/security/apparmor/Kconfig
>>> @@ -11,7 +11,7 @@ config SECURITY_APPARMOR
>>> This enables the AppArmor security module.
>>> Required userspace tools (if they are not included in your
>>> distribution) and further information may be found at
>>> - http://apparmor.wiki.kernel.org
>>> + https://wiki.apparmor.net
>>>
>>> If you are unsure how to answer this question, answer N.
>>>
>>> --
>>> 2.53.0
>>>
>>>
>>
>> Reviewed-by: Ryan Lee <ryan.lee@canonical.com>
>
^ permalink raw reply
* Re: unix_stream_connect and socket address resolution
From: Günther Noack @ 2026-07-23 9:53 UTC (permalink / raw)
To: John Ericson
Cc: Günther Noack, David Laight, Kuniyuki Iwashima,
David S . Miller, Eric Dumazet, Jakub Kicinski, Paolo Abeni,
Cong Wang, Simon Horman, Christian Brauner, David Rheinsberg,
Andy Lutomirski, Sergei Zimmerman, network dev,
Mickaël Salaün, Paul Moore, linux-security-module, LKML
In-Reply-To: <e4adebd8-181a-47b7-b82b-b6d9baa6b203@app.fastmail.com>
On Wed, Jul 22, 2026 at 12:02:24PM -0400, John Ericson wrote:
> Thanks Günther!
>
> This example makes sense to me. The behavior still feels a little odd to
> me, but I can understand the practical benefit of what you describe, and
> also why changing it would definitely cause breakage.
>
> I have one addendum to ask then which is: what if before the loop we
> pre-resolve the parent directory as a concrete `struct path`, and then
> on each iteration of the loop resolve only the final path component to
> the socket itself? (That is a single-component lookup relative to the
> pre-resolved parent, to be clear.)
I am not sure about that. I think the difficult question here are the
ordering guarantees on file system operations:
The file system can be in a different state in the first and the second
half of the path walk, and I'm not sure whether that wouldn't violate
file system ordering guarantees. If you intend to send such a patch,
I'd recommend to loop in some file system experts (e.g. Christian
Brauner).
What is the underlying problem that such a patch would solve though?
Do you think that the performance on retry is such a concern?
(After all, you'd also have to do a "split" lookup in the happy case,
and it sounds likely that that the retry improvement does not amortize
the happy path penalty?)
(This would have to be explained in the commit message as well, per [1])
[1] https://docs.kernel.org/process/submitting-patches.html#describe-your-changes
> Per your example, a legitimate server restart recreates the socket inode
> in the same directory, so this still picks up the new socket and
> reconnects, while avoiding the effect where a concurrent
> ancestor-directory rename causes a wildly different socket to be
> resolved. Hopefully this preserves the intended use-case.
>
> Note that this does mean recreating the parent directory itself at the
> same path would no longer be followed, and a rename/unlink of the pinned
> parent would cause the lookup to fail rather than resolve elsewhere.
> That seems like the intended, safer direction to me, but flagging it as
> a deliberate semantic change rather than an accident.
>
> If this sounds like an acceptable middle-ground to everyone, I'd be happy to implement it.
—Günther
^ permalink raw reply
* Re: [PATCH v1] selftests/landlock: Add tests for O_TMPFILE
From: Günther Noack @ 2026-07-23 12:04 UTC (permalink / raw)
To: Mickaël Salaün
Cc: linux-security-module, Takao Sato, Willy Tarreau, brauner, viro
In-Reply-To: <20260722151354.2736457-1-mic@digikod.net>
On Wed, Jul 22, 2026 at 05:13:52PM +0200, Mickaël Salaün wrote:
> open(2) with O_TMPFILE creates its unnamed inode through vfs_tmpfile(),
> which, unlike normal file creation, calls neither security_path_mknod()
> nor security_inode_create(). It is nonetheless mediated: vfs_tmpfile()
> opens the inode through the filesystem's ->tmpfile() operation, which
> reaches security_file_open() via finish_open(). The open is therefore
> checked like any other, and materializing the file with linkat(2) is
> checked like any other link.
>
> Add tests for both paths so O_TMPFILE cannot bypass Landlock.
>
> Cc: Günther Noack <gnoack@google.com>
> Signed-off-by: Mickaël Salaün <mic@digikod.net>
> ---
> tools/testing/selftests/landlock/fs_test.c | 251 +++++++++++++++++++++
> 1 file changed, 251 insertions(+)
>
> diff --git a/tools/testing/selftests/landlock/fs_test.c b/tools/testing/selftests/landlock/fs_test.c
> index cdb47fc1fc0a..b826b2c6a8f0 100644
> --- a/tools/testing/selftests/landlock/fs_test.c
> +++ b/tools/testing/selftests/landlock/fs_test.c
> @@ -450,6 +450,25 @@ static int test_open(const char *const path, const int flags)
> return test_open_rel(AT_FDCWD, path, flags);
> }
>
> +/*
> + * Opens an anonymous O_TMPFILE inode in the directory dir. O_TMPFILE is always
> + * combined with O_WRONLY or O_RDWR, so the caller must pass one of them in
> + * flags.
> + */
> +static int test_tmpfile(const char *const dir, const int flags)
> +{
> + int fd;
> +
> + fd = open(dir, O_TMPFILE | flags | O_CLOEXEC, 0700);
^^^^
The file mode doesn't seem to be used in the test. According to the man page,
it's only relevant when you later do a linkat(), but even then this
functionality seems unrelated to Landlock and is not tested here, I think.
> + if (fd < 0)
> + return errno;
> +
> + if (close(fd) != 0)
> + return errno;
> +
> + return 0;
> +}
> +
The test_open() function does the exact same thing, except that it doesn't
enforce O_TMPFILE. But because the test_open() function mirrors the syscall
parameters, you can pass O_TMPFILE as a flag from the outside, by calling it
with:
EXPECT_EQ(0, test_open(dir_s1d2, O_TMPFILE|O_WRONLY));
I find that preferrable over using a special test_tmpfile() helper, because it
is not much longer than what you have now, and it is very implicit here what
parameters we are passing to open(2) -- and the interface of open(2) is already
well-known. For a test_tmpfile() helper, you'd always have to look up what that
function does.
> TEST_F_FORK(layout1, no_restriction)
> {
> ASSERT_EQ(0, test_open(dir_s1d1, O_RDONLY));
> @@ -2140,6 +2159,238 @@ TEST_F_FORK(layout1, link)
> ASSERT_EQ(0, link(file1_s1d3, file2_s1d3));
> }
>
> +/*
> + * O_TMPFILE does not go through the path_mknod hook: vfs_tmpfile() creates the
> + * inode without calling security_path_mknod(). These tests verify that the
> + * resulting file is still mediated, via the file_open hook, so O_TMPFILE cannot
> + * be used to bypass Landlock.
> + */
> +
> +/*
> + * An O_TMPFILE open requires WRITE_FILE (and READ_FILE for O_RDWR) on the
> + * directory hierarchy, exactly like any other writable open. It does not
> + * require (nor is it granted by) MAKE_REG: the anonymous inode is not yet a
> + * named file. O_TMPFILE always implies write access, so a read-only request is
> + * rejected by the VFS with EINVAL before Landlock is consulted; Landlock must
> + * not change that into EACCES.
> + */
> +TEST_F_FORK(layout1, open_tmpfile)
> +{
> + const struct rule rules[] = {
> + /* Write allowed, but neither MAKE_REG nor READ_FILE. */
> + {
> + .path = dir_s1d1,
> + .access = LANDLOCK_ACCESS_FS_WRITE_FILE,
> + },
> + /* Both read and write allowed. */
> + {
> + .path = dir_s1d2,
> + .access = LANDLOCK_ACCESS_FS_READ_FILE |
> + LANDLOCK_ACCESS_FS_WRITE_FILE,
> + },
> + /* File-creation right without write. */
> + {
> + .path = dir_s2d1,
> + .access = LANDLOCK_ACCESS_FS_MAKE_REG,
> + },
> + {},
> + };
> +
> + /* Baseline: an unsandboxed O_TMPFILE open works. */
> + EXPECT_EQ(0, test_tmpfile(dir_s1d1, O_WRONLY));
> + EXPECT_EQ(0, test_tmpfile(dir_s2d1, O_RDWR));
> + EXPECT_EQ(0, test_tmpfile(dir_s3d1, O_RDWR));
Nit: Should they all threee use O_RDWR?
> +
> + /* O_TMPFILE requires write access: read-only is EINVAL at the VFS. */
> + EXPECT_EQ(EINVAL, test_tmpfile(dir_s1d1, O_RDONLY));
> +
> + enforce_fs(_metadata,
> + LANDLOCK_ACCESS_FS_READ_FILE |
> + LANDLOCK_ACCESS_FS_WRITE_FILE |
> + LANDLOCK_ACCESS_FS_MAKE_REG,
> + rules);
> +
> + /* Write is enough for an O_WRONLY tmpfile; MAKE_REG is not needed. */
> + EXPECT_EQ(0, test_tmpfile(dir_s1d1, O_WRONLY));
> + /* O_RDWR additionally needs READ_FILE, which is absent here. */
> + EXPECT_EQ(EACCES, test_tmpfile(dir_s1d1, O_RDWR));
> +
> + /* Read and write allowed: both open modes succeed. */
> + EXPECT_EQ(0, test_tmpfile(dir_s1d2, O_WRONLY));
> + EXPECT_EQ(0, test_tmpfile(dir_s1d2, O_RDWR));
> +
> + /* MAKE_REG without WRITE_FILE does not allow the open. */
> + EXPECT_EQ(EACCES, test_tmpfile(dir_s2d1, O_WRONLY));
> + EXPECT_EQ(EACCES, test_tmpfile(dir_s2d1, O_RDWR));
> +
> + /* No rule at all: the open is denied. */
> + EXPECT_EQ(EACCES, test_tmpfile(dir_s3d1, O_WRONLY));
> + EXPECT_EQ(EACCES, test_tmpfile(dir_s3d1, O_RDWR));
> +
> + /*
> + * A read-only O_TMPFILE stays EINVAL under Landlock, whether the
> + * directory is fully allowed or has no rule: the VFS rejects the flag
> + * combination before the file_open hook, so Landlock never turns it
> + * into EACCES.
> + */
> + EXPECT_EQ(EINVAL, test_tmpfile(dir_s1d2, O_RDONLY));
> + EXPECT_EQ(EINVAL, test_tmpfile(dir_s3d1, O_RDONLY));
> +}
> +
> +/*
> + * When the ruleset handles neither file read nor write access, Landlock has no
> + * opinion on an O_TMPFILE open and must not interfere with it.
If the intent is to demonstrate that only READ_FILE and WRITE_FILE interfere
with O_TMPFILE, I would suggest that (a) the ruleset should "handle" everything
but these two, and (b) we do not need to pass any rules as exceptions to that?
enforce_fs(_metadata, ACCESS_ALL & ~(READ_FILE | WRITE_FILE), NULL);
> + */
> +TEST_F_FORK(layout1, open_tmpfile_unhandled)
> +{
> + const struct rule rules[] = {
> + {
> + .path = dir_s1d2,
> + .access = LANDLOCK_ACCESS_FS_READ_DIR,
> + },
> + {},
> + };
> +
> + enforce_fs(_metadata, LANDLOCK_ACCESS_FS_READ_DIR, rules);
> +
> + EXPECT_EQ(0, test_tmpfile(dir_s1d1, O_WRONLY));
> + EXPECT_EQ(0, test_tmpfile(dir_s1d3, O_RDWR));
> + EXPECT_EQ(0, test_tmpfile(dir_s3d1, O_RDWR));
> +}
> +
> +/*
> + * Materializing an anonymous O_TMPFILE into its creation directory with
> + * linkat(AT_EMPTY_PATH) is gated by MAKE_REG on that directory, even though
> + * obtaining the writable tmpfile only required WRITE_FILE. This is the check
> + * that stops O_TMPFILE from creating a named file where the sandbox forbids
> + * file creation. Linking into the same directory does not involve reparenting,
> + * so REFER is not required.
> + */
> +TEST_F_FORK(layout1, link_tmpfile)
> +{
> + int fd;
> + const struct rule rules[] = {
> + /* Write only: the tmpfile opens but cannot be linked. */
> + {
> + .path = dir_s1d1,
> + .access = LANDLOCK_ACCESS_FS_WRITE_FILE,
> + },
> + /* Write and MAKE_REG: the tmpfile opens and can be linked. */
> + {
> + .path = dir_s2d1,
> + .access = LANDLOCK_ACCESS_FS_WRITE_FILE |
> + LANDLOCK_ACCESS_FS_MAKE_REG,
> + },
> + {},
> + };
> +
> + /* Frees names in the two directories for the new links. */
> + ASSERT_EQ(0, unlink(file1_s1d1));
> + ASSERT_EQ(0, unlink(file1_s2d1));
> +
> + enforce_fs(_metadata,
> + LANDLOCK_ACCESS_FS_WRITE_FILE | LANDLOCK_ACCESS_FS_MAKE_REG,
> + rules);
> +
> + /*
> + * WRITE_FILE is enough to obtain the anonymous tmpfile. linkat(2) with
> + * AT_EMPTY_PATH needs no capability because the fd's open-time
> + * credentials match the caller's. Linking into the same directory does
> + * not require REFER (no reparenting), only MAKE_REG, which is absent
> + * here.
> + */
> + fd = open(dir_s1d1, O_TMPFILE | O_WRONLY | O_CLOEXEC, 0700);
> + ASSERT_LE(0, fd);
> + ASSERT_EQ(-1, linkat(fd, "", AT_FDCWD, file1_s1d1, AT_EMPTY_PATH));
> + EXPECT_EQ(EACCES, errno);
> + EXPECT_EQ(0, close(fd));
> +
> + /* With MAKE_REG on the directory, the same link is allowed. */
> + fd = open(dir_s2d1, O_TMPFILE | O_WRONLY | O_CLOEXEC, 0700);
> + ASSERT_LE(0, fd);
> + EXPECT_EQ(0, linkat(fd, "", AT_FDCWD, file1_s2d1, AT_EMPTY_PATH));
> + EXPECT_EQ(0, close(fd));
> +}
> +
> +/*
> + * Linking a tmpfile into a different directory is a reparenting operation: like
> + * any cross-directory link it requires LANDLOCK_ACCESS_FS_REFER. Without it,
> + * materializing the tmpfile outside its creation directory is denied with
> + * EXDEV, so a tmpfile cannot escape its origin hierarchy.
Because a O_TMPFILE is always a regular file, I think for most Landlock access
rights, it does not make a difference. If I understand this correctly, the only
two access rights where it does make a difference would be EXECUTE and TRUNCATE,
because they are the ones which apply to regular files where the refer rule
matters. Is that correct? Maybe they would be worth mentioning as a
motivational example here, to show that this makes an actual difference for
O_TMPFILE?
> + */
> +TEST_F_FORK(layout1, link_tmpfile_reparent_without_refer)
> +{
> + int fd;
> + const struct rule rules[] = {
> + /* Source directory: only the tmpfile open is allowed. */
> + {
> + .path = dir_s1d1,
> + .access = LANDLOCK_ACCESS_FS_WRITE_FILE,
> + },
> + /* Destination directory: file creation is allowed. */
> + {
> + .path = dir_s2d1,
> + .access = LANDLOCK_ACCESS_FS_MAKE_REG,
> + },
> + {},
> + };
> +
> + /* Frees a name in the destination directory for the new link. */
> + ASSERT_EQ(0, unlink(file1_s2d1));
> +
> + enforce_fs(_metadata,
> + LANDLOCK_ACCESS_FS_WRITE_FILE | LANDLOCK_ACCESS_FS_MAKE_REG,
> + rules);
> +
> + fd = open(dir_s1d1, O_TMPFILE | O_WRONLY | O_CLOEXEC, 0700);
> + ASSERT_LE(0, fd);
> + /* Cross-directory link without REFER is denied with EXDEV. */
> + ASSERT_EQ(-1, linkat(fd, "", AT_FDCWD, file1_s2d1, AT_EMPTY_PATH));
> + EXPECT_EQ(EXDEV, errno);
> + EXPECT_EQ(0, close(fd));
> +}
> +
> +/*
> + * With LANDLOCK_ACCESS_FS_REFER on both directories, a tmpfile created in one
> + * directory can be linked into another. The destination needs only MAKE_REG
> + * (plus REFER), not WRITE_FILE: the reparenting check compares file access
> + * rights, and the tmpfile gains none by moving to a directory that grants only
> + * the directory-level creation right.
In other words, linking the tmpfile into a directory that grants fewer rights on
it is fine. The only required rights in the destination directory are REFER and
MAKE_REG, because those are required for the linking itself. This checks out,
but it's already a basic property that REFER has in the normal case as well. We
can test it for completeness, but it doesn't seem particularly special to the
tmpfile case. (Would be OK to drop imho, but I'm not feeling strongly about
it.)
> + */
> +TEST_F_FORK(layout1, link_tmpfile_reparent_with_refer)
> +{
> + int fd;
> + const struct rule rules[] = {
> + /* Source: tmpfile open (write) and reparenting. */
> + {
> + .path = dir_s1d1,
> + .access = LANDLOCK_ACCESS_FS_WRITE_FILE |
> + LANDLOCK_ACCESS_FS_REFER,
> + },
> + /* Destination: file creation and reparenting, but no write. */
> + {
> + .path = dir_s2d1,
> + .access = LANDLOCK_ACCESS_FS_MAKE_REG |
> + LANDLOCK_ACCESS_FS_REFER,
> + },
> + {},
> + };
> +
> + /* Frees a name in the destination directory for the new link. */
> + ASSERT_EQ(0, unlink(file1_s2d1));
> +
> + enforce_fs(_metadata,
> + LANDLOCK_ACCESS_FS_WRITE_FILE | LANDLOCK_ACCESS_FS_MAKE_REG |
> + LANDLOCK_ACCESS_FS_REFER,
> + rules);
> +
> + fd = open(dir_s1d1, O_TMPFILE | O_WRONLY | O_CLOEXEC, 0700);
> + ASSERT_LE(0, fd);
> + /* REFER on both sides plus MAKE_REG on the destination allows it. */
> + EXPECT_EQ(0, linkat(fd, "", AT_FDCWD, file1_s2d1, AT_EMPTY_PATH));
> + EXPECT_EQ(0, close(fd));
> +}
> +
> static int test_rename(const char *const oldpath, const char *const newpath)
> {
> if (rename(oldpath, newpath))
> --
> 2.54.0
>
P.S.: I checked the Sashiko review as well and it did not spot any issues in these tests.
https://sashiko.dev/#/patchset/20260722151354.2736457-1-mic%40digikod.net
(It believes that it spotted a bug in the kernel code, but that is better
investigated separately of this patch.)
—Günther
^ permalink raw reply
* Re: [PATCH v3 0/3] keys: fix keyring assoc-array out-of-bounds read and index inconsistency
From: Jarkko Sakkinen @ 2026-07-23 12:53 UTC (permalink / raw)
To: Michael Bommarito
Cc: David Howells, Andrew Morton, Paul Moore, James Morris,
Serge E . Hallyn, keyrings, linux-security-module, linux-kernel,
Linus Torvalds
In-Reply-To: <amDiI4jc6fsbUK_X@kernel.org>
On Wed, Jul 22, 2026 at 06:30:43PM +0300, Jarkko Sakkinen wrote:
> On Sun, Jul 19, 2026 at 12:15:02PM -0400, Michael Bommarito wrote:
> > An unprivileged keyring whose keys collide through the description-chunk
> > path can drive assoc_array node splitting into an out-of-bounds slot write.
> > Patch 1 stops the out-of-bounds read in keyring_get_key_chunk(); patch 2
> > makes the chunk byte order agree with keyring_diff_objects(); patch 3 fixes
> > the shortcut-walk trim so the walk cannot be steered down the wrong
> > descendant.
> >
> > v3 changes (patch 1 only; patches 2 and 3 are unchanged):
> > Per Jarkko's review, patch 1 no longer extends the existing
> > keyring_get_key_chunk() declaration line; the new offset is declared on its
> > own line as unsigned int. No functional change.
> >
> > Patches 2 and 3 are unchanged from v2 and carry Jarkko's Reviewed-by.
> >
> > v2: https://lore.kernel.org/keyrings/20260714115451.3773164-1-michael.bommarito@gmail.com/
> > v1: https://lore.kernel.org/keyrings/20260712014500.480410-1-michael.bommarito@gmail.com/
> >
> > Michael Bommarito (3):
> > keys: fix out-of-bounds read in keyring_get_key_chunk()
> > keys: make keyring key-chunk byte order agree with
> > keyring_diff_objects()
> > assoc_array: trim the final shortcut word using the current chunk end
> >
> > lib/assoc_array.c | 3 ++-
> > security/keys/keyring.c | 14 ++++++++------
> > 2 files changed, 10 insertions(+), 7 deletions(-)
> >
> >
> > base-commit: 2c7c88a412aa6d09cd04b414211b4ef8553b5309
> > --
> > 2.53.0
> >
>
> I'm setting up the testing environment now and hopefully have final
> feedback within let's say "hours" (i.e. I'll do the job, and it takes what
> it takes).
Good news. I got it tested. I'll push and mirror the patches to
linux-next. Once they show up there, I'll send a PR to Linus.
Reviewed-by: Jarkko Sakkinen <jarkko@kernel.org>
Tested-by: Jarkko Sakkinen <jarkko@kernel.org> # Done with the provided
# reproducer.
Really good work IMHO and also great example of legit use of
AI assisted patches in my books. Thank you.
BR, Jarkko
^ permalink raw reply
* Re: [RFC PATCH 3/4] xfs: replace ns_capable_noaudit()
From: Serge E. Hallyn @ 2026-07-23 13:29 UTC (permalink / raw)
To: cem
Cc: linux-fsdevel, jack, djwong, hch, serge, linux-security-module,
linux-kernel, linux-xfs
In-Reply-To: <20260626114533.102138-4-cem@kernel.org>
On Fri, Jun 26, 2026 at 01:45:22PM +0200, cem@kernel.org wrote:
> From: Carlos Maiolino <cem@kernel.org>
>
> We don't need to use ns_capable_noaudit() as all we care is the initial
> user namespace, use capable_noaudit() instead.
Looks like some of your other xfs fixes conflict with this. Do
you mind sending out a new set, and I'll pull them into the caps-next
branch?
thanks,
-serge
> Signed-off-by: Carlos Maiolino <cmaiolino@redhat.com>
> ---
> fs/xfs/xfs_trans_dquot.c | 2 +-
> 1 file changed, 1 insertion(+), 1 deletion(-)
>
> diff --git a/fs/xfs/xfs_trans_dquot.c b/fs/xfs/xfs_trans_dquot.c
> index 50e5b323f7f1..30c2f6ec0aac 100644
> --- a/fs/xfs/xfs_trans_dquot.c
> +++ b/fs/xfs/xfs_trans_dquot.c
> @@ -835,7 +835,7 @@ xfs_trans_dqresv(
> if ((flags & XFS_QMOPT_FORCE_RES) == 0 &&
> dqp->q_id &&
> xfs_dquot_is_enforced(dqp) &&
> - !ns_capable_noaudit(&init_user_ns, CAP_SYS_RESOURCE)) {
> + !capable_noaudit(CAP_SYS_RESOURCE)) {
> int quota_nl;
> bool fatal;
>
> --
> 2.54.0
^ permalink raw reply
* Re: [PATCH] apparmor: update website link
From: Baruch Siach @ 2026-07-23 16:43 UTC (permalink / raw)
To: John Johansen
Cc: Serge Hallyn, Ryan Lee, John Johansen, Georgia Garcia, apparmor,
linux-security-module
In-Reply-To: <ba05df8c-fb79-4a14-a9b9-15e50e7dc4bc@canonical.com>
Hi John, Serge,
On Wed, Jul 22 2026, John Johansen wrote:
> On 7/22/26 15:36, Serge Hallyn wrote:
>> Jul 22, 2026 11:41:27 Ryan Lee <ryan.lee@canonical.com>:
>>
>>> On Tue, Jul 21, 2026 at 4:40 AM Baruch Siach <baruch@tkos.co.il> wrote:
>>>>
>>>> apparmor.wiki.kernel.org redirects to the current website.
>> Sure, but kernel.org seems less likely to go away, and the redirect can
>> easily be updated if needed. Up to John of course, but i would leave it
>> as is.
>
> I am unsure of the best course, but atm I am inclined to leave it with
> kernel.org, Like you said the redirect can easily be updated.
Another problem this patch fixes is the use of unauthenticated
HTTP. This is less than ideal for a security feature. A MITM attacker
can easily redirect to somewhere else.
So a patch only switching to HTTPS should be fine, right?
baruch
>>>> Signed-off-by: Baruch Siach <baruch@tkos.co.il>
>>>> ---
>>>> security/apparmor/Kconfig | 2 +-
>>>> 1 file changed, 1 insertion(+), 1 deletion(-)
>>>>
>>>> diff --git a/security/apparmor/Kconfig b/security/apparmor/Kconfig
>>>> index 1e3bd44643da..472aa38254be 100644
>>>> --- a/security/apparmor/Kconfig
>>>> +++ b/security/apparmor/Kconfig
>>>> @@ -11,7 +11,7 @@ config SECURITY_APPARMOR
>>>> This enables the AppArmor security module.
>>>> Required userspace tools (if they are not included in your
>>>> distribution) and further information may be found at
>>>> - http://apparmor.wiki.kernel.org
>>>> + https://wiki.apparmor.net
>>>>
>>>> If you are unsure how to answer this question, answer N.
>>>
>>> Reviewed-by: Ryan Lee <ryan.lee@canonical.com>
--
~. .~ Tk Open Systems
=}------------------------------------------------ooO--U--Ooo------------{=
- baruch@tkos.co.il - tel: +972.52.368.4656, http://www.tkos.co.il -
^ permalink raw reply
* [PATCH] capability: remove non-kernel-doc comments
From: Randy Dunlap @ 2026-07-23 16:52 UTC (permalink / raw)
To: linux-security-module
Cc: Randy Dunlap, Paul Moore, James Morris, Serge E. Hallyn
Convert 2 "/**" comments to use plain C "/*" comment style to avoid
kernel-doc warnings:
Warning: include/uapi/linux/capability.h:114 expecting prototype for
POSIX(). Prototype was for CAP_CHOWN() instead
Warning: include/uapi/linux/capability.h:175 expecting prototype for
Linux(). Prototype was for CAP_SETPCAP() instead
Signed-off-by: Randy Dunlap <rdunlap@infradead.org>
---
Cc: Paul Moore <paul@paul-moore.com>
Cc: James Morris <jmorris@namei.org>
Cc: "Serge E. Hallyn" <serge@hallyn.com>
include/uapi/linux/capability.h | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
--- linux-next-20260722.orig/include/uapi/linux/capability.h
+++ linux-next-20260722/include/uapi/linux/capability.h
@@ -104,9 +104,9 @@ struct vfs_ns_cap_data {
#endif
-/**
- ** POSIX-draft defined capabilities.
- **/
+/*
+ * POSIX-draft defined capabilities.
+ */
/* In a system with the [_POSIX_CHOWN_RESTRICTED] option defined, this
overrides the restriction of changing file ownership and group
@@ -159,9 +159,9 @@ struct vfs_ns_cap_data {
#define CAP_SETUID 7
-/**
- ** Linux-specific capabilities
- **/
+/*
+ * Linux-specific capabilities
+ */
/* Without VFS support for capabilities:
* Transfer any capability in your permitted set to any pid,
^ permalink raw reply
* Re: [PATCH] capability: remove non-kernel-doc comments
From: Paul Moore @ 2026-07-23 17:08 UTC (permalink / raw)
To: Randy Dunlap; +Cc: linux-security-module, James Morris, Serge E. Hallyn
In-Reply-To: <20260723165209.226050-1-rdunlap@infradead.org>
On Thu, Jul 23, 2026 at 12:52 PM Randy Dunlap <rdunlap@infradead.org> wrote:
>
> Convert 2 "/**" comments to use plain C "/*" comment style to avoid
> kernel-doc warnings:
>
> Warning: include/uapi/linux/capability.h:114 expecting prototype for
> POSIX(). Prototype was for CAP_CHOWN() instead
> Warning: include/uapi/linux/capability.h:175 expecting prototype for
> Linux(). Prototype was for CAP_SETPCAP() instead
>
> Signed-off-by: Randy Dunlap <rdunlap@infradead.org>
> ---
> Cc: Paul Moore <paul@paul-moore.com>
> Cc: James Morris <jmorris@namei.org>
> Cc: "Serge E. Hallyn" <serge@hallyn.com>
>
> include/uapi/linux/capability.h | 12 ++++++------
> 1 file changed, 6 insertions(+), 6 deletions(-)
I'm assuming Serge will take this via the capabilities tree, but I can
always take it via the LSM tree if he prefers.
Reviewed-by: Paul Moore <paul@paul-moore.com>
--
paul-moore.com
^ permalink raw reply
* Re: [PATCH] apparmor: update website link
From: John Johansen @ 2026-07-23 17:12 UTC (permalink / raw)
To: Baruch Siach, John Johansen
Cc: Serge Hallyn, Ryan Lee, John Johansen, Georgia Garcia, apparmor,
linux-security-module
In-Reply-To: <87bjbxodw7.fsf@tarshish>
On 7/23/26 09:43, Baruch Siach wrote:
> Hi John, Serge,
>
> On Wed, Jul 22 2026, John Johansen wrote:
>> On 7/22/26 15:36, Serge Hallyn wrote:
>>> Jul 22, 2026 11:41:27 Ryan Lee <ryan.lee@canonical.com>:
>>>
>>>> On Tue, Jul 21, 2026 at 4:40 AM Baruch Siach <baruch@tkos.co.il> wrote:
>>>>> apparmor.wiki.kernel.org redirects to the current website.
>>> Sure, but kernel.org seems less likely to go away, and the redirect can
>>> easily be updated if needed. Up to John of course, but i would leave it
>>> as is.
>> I am unsure of the best course, but atm I am inclined to leave it with
>> kernel.org, Like you said the redirect can easily be updated.
> Another problem this patch fixes is the use of unauthenticated
> HTTP. This is less than ideal for a security feature. A MITM attacker
> can easily redirect to somewhere else.
>
> So a patch only switching to HTTPS should be fine, right?
>
switching to HTTP is fine, if you want to submit a patch that does that.
>>>>> Signed-off-by: Baruch Siach <baruch@tkos.co.il>
>>>>> ---
>>>>> security/apparmor/Kconfig | 2 +-
>>>>> 1 file changed, 1 insertion(+), 1 deletion(-)
>>>>>
>>>>> diff --git a/security/apparmor/Kconfig b/security/apparmor/Kconfig
>>>>> index 1e3bd44643da..472aa38254be 100644
>>>>> --- a/security/apparmor/Kconfig
>>>>> +++ b/security/apparmor/Kconfig
>>>>> @@ -11,7 +11,7 @@ config SECURITY_APPARMOR
>>>>> This enables the AppArmor security module.
>>>>> Required userspace tools (if they are not included in your
>>>>> distribution) and further information may be found at
>>>>> - http://apparmor.wiki.kernel.org
>>>>> + https://wiki.apparmor.net
>>>>>
>>>>> If you are unsure how to answer this question, answer N.
>>>> Reviewed-by: Ryan Lee <ryan.lee@canonical.com>
^ permalink raw reply
* [PATCH] apparmor: switch website link to https
From: Baruch Siach @ 2026-07-23 17:25 UTC (permalink / raw)
To: John Johansen, John Johansen, Georgia Garcia
Cc: apparmor, linux-security-module, Baruch Siach
Should make harder for MITM to redirect to somewhere else.
Signed-off-by: Baruch Siach <baruch@tkos.co.il>
---
This could be considered v2 of the patch linked below, following
feedback.
https://lore.kernel.org/all/2ce1d4ec18b2b47ee7ddd9c1ad7be68e185aa69c.1784632742.git.baruch@tkos.co.il/
---
security/apparmor/Kconfig | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/security/apparmor/Kconfig b/security/apparmor/Kconfig
index 1e3bd44643da..e1bfd164a23a 100644
--- a/security/apparmor/Kconfig
+++ b/security/apparmor/Kconfig
@@ -11,7 +11,7 @@ config SECURITY_APPARMOR
This enables the AppArmor security module.
Required userspace tools (if they are not included in your
distribution) and further information may be found at
- http://apparmor.wiki.kernel.org
+ https://apparmor.wiki.kernel.org
If you are unsure how to answer this question, answer N.
--
2.53.0
^ permalink raw reply related
* Re: [PATCH 0/2] doc: LSM: update usage document for current LSM stacking
From: Casey Schaufler @ 2026-07-23 17:47 UTC (permalink / raw)
To: Lincoln Wallace, paul, corbet
Cc: skhan, linux-doc, linux-kernel, linux-security-module,
penguin-kernel, rdunlap, Casey Schaufler
In-Reply-To: <20260714013832.977443-1-locnnil0@gmail.com>
On 7/13/2026 6:38 PM, Lincoln Wallace wrote:
> The LSM usage document (Documentation/admin-guide/LSM/index.rst) has
> not kept up with the LSM stacking infrastructure. It still describes
> CONFIG_DEFAULT_SECURITY, which no longer exists, and its description
> of the module ordering in /sys/kernel/security/lsm does not match
> what the framework actually does.
I've been stewing on this since it came up. We should probably
remove the somewhat complicated logic from the Kconfig files if
it's not adding value.
>
> Patch 1 updates the selection mechanism description to CONFIG_LSM and
> the "lsm=" parameter, keeping "security=" documented as the deprecated
> legacy option. This revisits an earlier attempt by Randy Dunlap [1]
> that was rejected for treating the two parameters as equivalent; the
> new text keeps them distinct.
>
> Patch 2 fixes the ordering description: lockdown precedes capability
> when CONFIG_SECURITY_LOCKDOWN_LSM_EARLY is enabled, the integrity
> modules are always placed at the end of the list, and the remaining
> modules follow the order given by CONFIG_LSM or "lsm=".
>
> [1] https://lore.kernel.org/r/20250114225156.10458-1-rdunlap@infradead.org
>
> Lincoln Wallace (2):
> doc: LSM: describe CONFIG_LSM and lsm= as the selection mechanism
> doc: LSM: fix module ordering description for /sys/kernel/security/lsm
>
> Documentation/admin-guide/LSM/index.rst | 20 ++++++++++++++------
> 1 file changed, 14 insertions(+), 6 deletions(-)
>
^ permalink raw reply
* Re: [PATCH] apparmor: switch website link to https
From: John Johansen @ 2026-07-23 18:12 UTC (permalink / raw)
To: Baruch Siach, John Johansen, Georgia Garcia
Cc: apparmor, linux-security-module
In-Reply-To: <5bdb0bfc41a89f58bcf9aa3e0fe062090a1fb2bd.1784827554.git.baruch@tkos.co.il>
On 7/23/26 10:25, Baruch Siach wrote:
> Should make harder for MITM to redirect to somewhere else.
>
> Signed-off-by: Baruch Siach <baruch@tkos.co.il>
Acked-by: John Johansen <john.johansen@canonical.com>
I have pulled this into the apparmor tree
> ---
> This could be considered v2 of the patch linked below, following
> feedback.
>
> https://lore.kernel.org/all/2ce1d4ec18b2b47ee7ddd9c1ad7be68e185aa69c.1784632742.git.baruch@tkos.co.il/
> ---
> security/apparmor/Kconfig | 2 +-
> 1 file changed, 1 insertion(+), 1 deletion(-)
>
> diff --git a/security/apparmor/Kconfig b/security/apparmor/Kconfig
> index 1e3bd44643da..e1bfd164a23a 100644
> --- a/security/apparmor/Kconfig
> +++ b/security/apparmor/Kconfig
> @@ -11,7 +11,7 @@ config SECURITY_APPARMOR
> This enables the AppArmor security module.
> Required userspace tools (if they are not included in your
> distribution) and further information may be found at
> - http://apparmor.wiki.kernel.org
> + https://apparmor.wiki.kernel.org
>
> If you are unsure how to answer this question, answer N.
>
^ permalink raw reply
page: next (older) | prev (newer) | latest
- recent:[subjects (threaded)|topics (new)|topics (active)]
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox