Skip to contentSkip to conversation

BPF interface for applying Landlock rulesets

PATCH Superseded Justin Suess 3 participants 23 messages Aug 31 – Sep 2

Subsystems (9)
Documentation Kselftest BPF Tracing +5 more subsystems

v2 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

v2 cover BPF interface for applying Landlock rulesets

Howdy,

This series lets BPF programs apply an existing, userspace-created Landlock ruleset to a program during exec. The goal is unchanged from the RFC [1] and v1 [2]: BPF does not create, inspect, or mutate Landlock policy, it only decides whether a ruleset that was already created and validated through Landlock's existing userspace API should be applied, based on runtime exec context. The policy is in place before the first instruction of the new program runs, closing the race a userspace supervisor cannot.

The bottom line change in v2: the kfunc interface is now fully LSM-generic.

The bpf_landlock_* kfuncs have been dropped in favor of bpf_lsm_policy_* kfuncs that carry no LSM-specific details: no kfunc argument names an LSM anywhere in the interface. This is done without turning the kfuncs into an ioctl-like multiplexer; see the usage example for the ergonomics.

This design choice was based on feedback from Paul Moore [3] and Mickaël Salaün [4]. There was some discussion of whether LSMs should expose LSM-specific interfaces, and concern that a generic interface would have poor ergonomics / become an ioctl-like multiplexer.

While initially I argued against a generic interface, ultimately I believe I've found a design that is LSM-generic without the cons / poor ergonomics of an ioctl-like interface.

The key is a new struct lsm_policy_object, internal to the LSM framework:

struct lsm_policy_object {
u64 lsmid; /* routes the object to the LSM that owns it */ u32 type; /* LSM-private tag for its own object types */
};

The owning LSM embeds this struct in its own policy structure (here, the Landlock ruleset), and a pointer to it is the BPF-facing kptr.

The kfuncs dispatch an lsm_policy_object pointer to the owning LSM based on the lsmid. The LSM checks the type tag (Landlock has only LANDLOCK_POLICY_TYPE_RULESET) and recovers its own object with:

   container_of(object, struct landlock_ruleset, policy_object);

The fd translation is the one call with no object to dispatch on, and it needs no LSM_ID_* argument either: a policy object fd refers to a file associated with the owning LSM's own userspace interface, so the fd is identified by its fops pointer. The kfunc passes the fd to each policy_object_from_fd implementation; an LSM claims its own fds and declines anyone else's with -EOPNOTSUPP, so the fd reaches exactly the LSM that created it. A program that expects a policy of one specific LSM can still assert its intent by reading the lsmid off the returned kptr.

One benefit of this: since all LSMs share the one kptr type, objects from multiple LSMs can be stored in the same map, allowing users to create LSM-agnostic programs.

The interface
===

Effectively, the kfuncs are security hooks called by a BPF program.

The kfuncs operate on the generic struct lsm_policy_object (the struct any LSM policy object must embed), rather than an LSM-specific type:

  bpf_lsm_policy_from_fd(fd, flags)         KF_ACQUIRE | KF_RET_NULL | KF_SLEEPABLE
  bpf_lsm_policy_acquire(object)            KF_ACQUIRE | KF_RCU | KF_RET_NULL
  bpf_lsm_policy_release(object)            KF_RELEASE

bpf_lsm_policy_apply_bprm(object, bprm, flags) KF_SLEEPABLE

The interface is owned by the LSM framework in security/bpf_lsm_kfuncs.c. An LSM participates by implementing four ordinary hooks:

policy_object_from_fd(fd, &object)
policy_object_get(object)
policy_object_put(object)
bprm_apply_policy_object(bprm, object, flags)

These hooks are unlike any other in the kernel: they have no security_*() wrappers in security.c because they have no in-kernel callers. Their only entry point is BPF, and the BPF entry point is the kfunc, so the kfuncs in security/bpf_lsm_kfuncs.c play the role the security_*() wrappers play for other hooks, dispatching the static call to the LSM matching the object's lsmid.

As they implement LSM-dispatch logic like any other hook, they cannot be placed outside security/ without exposing LSM internals in an undesirable way.

Usage TL;DR
===

A syscall program, run in the supervisor's context, translates a ruleset fd and parks the reference in a map; a sleepable LSM program on bprm_creds_for_exec()/bprm_creds_from_file() applies it:

  /* setup (BPF_PROG_TYPE_SYSCALL, supervisor's task context) */
  obj = bpf_lsm_policy_from_fd(ruleset_fd, 0);
  old = bpf_kptr_xchg(&map_val->policy, obj);

  /* enforcement (sleepable BPF_PROG_TYPE_LSM on a bprm hook) */
  bpf_rcu_read_lock();
  obj = bpf_lsm_policy_acquire(map_val->policy);
  bpf_rcu_read_unlock();
  if (obj) {
          bpf_lsm_policy_apply_bprm(obj, bprm, 0);
          bpf_lsm_policy_release(obj);
  }

Notice that no LSM is named anywhere in this process: the LSM information is carried entirely by the fd and the lsm_policy_object. The caller need not pass an LSM ID or LSM-specific opcode at all. The same program could apply a policy object from LSM A and LSM B by simply changing the fd, with zero code changes.

(A caller that needs LSM-specific logic still has the option of reading lsm_policy_object->lsmid.)

The acquire kfunc is what lets concurrent executions share the one reference stored in the map: each program execution takes a reference of its own under an RCU read lock, instead of taking exclusive ownership of the stored one with bpf_kptr_xchg() (which would prevent concurrent application). Both the acquire path and the hook backing it are new in v2.

The lifetime contract for embedding lsm_policy_object
===

Collapsing every provider into one BTF type makes the lifetime rules part of the interface rather than a per-LSM agreement. Any LSM-specific policy structure embedding lsm_policy_object must provide the following semantics:

- The type field of lsm_policy_object must be nonzero.
- The object must be reference counted.
- The object must be RCU protected, and freed only after an RCU grace period.
- get acquires with inc-not-zero semantics and may fail against a concurrent last put. Implementing policy_object_get is optional.
- put must be callable from contexts that cannot sleep: map teardown drops map-held references through the registered kptr destructor. Implementing policy_object_put is mandatory, even if policy_object_get is not implemented.

This contract was picked to be implementable by other LSMs in the future, and closely mirrors the contract backing the task_struct, cgroup, and bpf_crypto_ctx kptrs.

Whether to implement policy_object_get is up to the individual LSM, and the choice selects between shared and unique pointers:
implementing it (as Landlock does here) lets programs acquire additional references to the object under RCU, while leaving it out yields an object whose pointer cannot be copied after creation, only atomically exchanged with bpf_kptr_xchg(). Both models fit the same interface.

Landlock specifics
===

The bprm hook accepts the landlock_restrict_self(2) flags with their usual semantics except LANDLOCK_RESTRICT_SELF_TSYNC (rejected: it targets the calling threads, not the execution). LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS is honored atomically with the
restriction: both are staged on the bprm credentials and applied past the exec point of no return, so the executed task starts no_new_privs if and only if it starts confined, and a failed execution leaves the calling task untouched.

Enforcement through BPF is as observable as the syscall: committing a staged restriction emits the same landlock_enforce_domain trace event, and the create/free domain events stay balanced on every path, including executions aborted before the point of no return.

Notably, rulesets are now RCU protected, which is what allows enforcement to share the stored kptr instead of xchg-ing it in and out of the map.

Changes since v1
===

- The interface is fully generic: the per-LSM kptr type (struct bpf_landlock_ruleset), the erasure to void *, and the security_kfunc_*() shims dispatching on an explicit LSM_ID_* argument are gone. struct lsm_policy_object (lsmid + LSM-private type tag) is embedded in the LSM's own object and resolved with container_of(), so no LSM type crosses the LSM boundary in either direction.
- The per-LSM kfuncs (bpf_landlock_*) are replaced by the four LSM-agnostic bpf_lsm_policy_* kfuncs above; they moved from kernel/bpf/bpf_lsm.c to security/bpf_lsm_kfuncs.c as the LSM framework's own BPF interface. kernel/bpf explicitly would not make sense here because the kfuncs themselves implement LSM dispatch logic, an LSM-internal functionality.
- New shared-acquisition model: the policy_object_get hook and the bpf_lsm_policy_acquire() kfunc (KF_RCU, backed by refcount_inc_not_zero()) let concurrent executions share one map slot. Landlock frees rulesets after an RCU grace period to back it, and struct lsm_policy_object is registered in the verifier's rcu_protected_types.
- The lifetime rules above are now the documented interface contract, not per-kfunc notes.
- LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS, whose series [5] has been picked up by the Landlock tree since v1 was posted, is honored on the exec path with the same atomicity as the syscall.
- The staged enforcement emits landlock_enforce_domain at the exec point of no return, with a selftest attached to the tracepoint.
- The selftests are split in two: the properties of the interface itself (the verifier-side filter rules, reference leak rejection, RCU acquisition, and the from_fd error contract) are tested with no LSM dependency alongside the kfuncs, while the end-to-end enforcement tests sit with the Landlock provider.
- Still no new UAPI: no map type, no new flag, no ABI bump; the type tag and its enum are kernel-internal.

This series is based on the Landlock tree's next branch [6]: it depends on the ruleset/domain split, the tracepoint series, and the LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS flag. The BPF CI bot will therefore fail to apply this series onto bpf-next. To cover CI, the full branch has been submitted manually to BPF CI on GitHub Actions [7].

The series is structured with LSM framework patches first: patches 1-2 add the hooks, 3 is trivial macro motion, 4-7 the kfuncs, 8 the interface documentation, and 9 its LSM-independent selftests.

The Landlock provider follows: patches 10-13 add it, 14 its selftests, and 15 its documentation.

[1] https://lore.kernel.org/linux-security-module/[email protected]/
[2] https://lore.kernel.org/bpf/[email protected]/
[3] https://lore.kernel.org/linux-security-module/CAHC9VhSSzNBCSvy4cQHh6OOM4-EvHF+bmrB9=V1y=Lj53RvxQQ@mail.gmail.com/
[4] https://lore.kernel.org/linux-security-module/[email protected]/
[5] https://lore.kernel.org/linux-security-module/[email protected]/
[6] https://git.kernel.org/pub/scm/linux/kernel/git/mic/linux.git/log/?h=next
[7] https://github.com/kernel-patches/bpf/pull/13522

Justin Suess (15):
lsm: Add the LSM policy object lifetime hooks
lsm: Add the bprm_apply_policy_object LSM hook
lsm: Move the lsm_for_each_hook() macro to security/lsm.h
lsm: Add the bpf_lsm_policy_release kfunc and policy object destructor
lsm: Add the bpf_lsm_policy_from_fd kfunc
lsm: Add the bpf_lsm_policy_acquire kfunc
lsm: Add the bpf_lsm_policy_apply_bprm kfunc
lsm: Document the LSM policy object interface selftests/bpf: Add tests for the LSM policy object kfuncs
landlock: Expose the ruleset fd lookup to the rest of Landlock
landlock: Factor the credential restriction out of
landlock_restrict_self()
landlock: Free rulesets after an RCU grace period
landlock: Implement the LSM policy object hooks selftests/bpf: Test the LSM policy object kfuncs with Landlock
landlock: Document the BPF policy interface

 Documentation/security/landlock.rst           |  38 ++
 Documentation/security/lsm-development.rst    |  49 ++
 Documentation/trace/events-landlock.rst       |   5 +-
 MAINTAINERS                                   |   1 +
 include/linux/lsm_hook_defs.h                 |   6 +
 include/linux/security.h                      |  11 +
 include/trace/events/landlock.h               |  15 +-
 kernel/bpf/bpf_lsm.c                          |   4 +
 kernel/bpf/verifier.c                         |   3 +
 security/Makefile                             |   2 +-
 security/bpf_lsm_kfuncs.c                     | 251 +++++++++
 security/landlock/Makefile                    |   2 +
 security/landlock/bpf.c                       | 152 +++++
 security/landlock/bpf.h                       |  21 +
 security/landlock/cred.c                      | 148 ++++-
 security/landlock/cred.h                      |  47 ++
 security/landlock/limits.h                    |   4 +
 security/landlock/ruleset.c                   |  30 +-
 security/landlock/ruleset.h                   |  75 ++-
 security/landlock/setup.c                     |   2 +
 security/landlock/syscalls.c                  | 105 +---
 security/lsm.h                                |   6 +
 security/security.c                           |   5 -
 tools/testing/selftests/bpf/config            |   1 +
 tools/testing/selftests/bpf/config.x86_64     |   2 +-
 .../bpf/prog_tests/lsm_policy_kfuncs.c        |  54 ++
 .../bpf/prog_tests/lsm_policy_landlock.c      | 522 ++++++++++++++++++
 .../selftests/bpf/progs/lsm_policy_kfuncs.c   |  52 ++
 .../bpf/progs/lsm_policy_kfuncs_failure.c     | 154 ++++++
 .../selftests/bpf/progs/lsm_policy_landlock.c | 142 +++++
 30 files changed, 1786 insertions(+), 123 deletions(-)
 create mode 100644 security/bpf_lsm_kfuncs.c
 create mode 100644 security/landlock/bpf.c
 create mode 100644 security/landlock/bpf.h
 create mode 100644 tools/testing/selftests/bpf/prog_tests/lsm_policy_kfuncs.c
 create mode 100644 tools/testing/selftests/bpf/prog_tests/lsm_policy_landlock.c
 create mode 100644 tools/testing/selftests/bpf/progs/lsm_policy_kfuncs.c
 create mode 100644 tools/testing/selftests/bpf/progs/lsm_policy_kfuncs_failure.c
 create mode 100644 tools/testing/selftests/bpf/progs/lsm_policy_landlock.c

base-commit: 172b6a6d8463562b0cbebfd66f770b078f81966b

Signature · 1 line
2.55.0
#1 lore raw

PATCH v2 1/15 lsm: Add the LSM policy object lifetime hooks

Add struct lsm_policy_object, the identity an LSM embeds in a policy object it shares with BPF programs, and the three hooks managing such an object's lifetime:

policy_object_from_fd(fd, &object)
policy_object_get(object)
policy_object_put(object)

The object records the owning LSM's LSM_ID_* value. The BPF kfuncs built on these hooks dispatch each call on an object to the one LSM matching its lsmid, which resolves the containing object with container_of(); the framework never interprets an object beyond its lsmid. The type field discriminates between the owning LSM's own policy object kinds and is private to it, with 0 reserved as "unset" so a zeroed, untagged object fails every type check.

from_fd has no object to route by: the fd refers to a file set up through the owning LSM's own userspace interface, so the fd itself identifies its LSM. The framework offers the fd to every implementation in turn; an LSM declines a fd that is not one of its policy objects with -EOPNOTSUPP, and any other error is a definitive translation failure.

The hooks back referenced BPF kptrs, which imposes the same lifetime contract on every implementation: from_fd returns a reference on a live object, get acquires with inc-not-zero semantics and fails with -ENOENT once the count dropped to zero, put may be called from contexts that cannot sleep (BPF drives it from map destructors), and the containing object is freed only after an RCU grace period, as programs load policy object kptrs from maps under RCU and may examine an object concurrently with its last put.

The hooks are excluded from the "bpf" LSM's attachment points. The object-routed hooks are unreachable there, as LSM_ID_BPF policy objects cannot exist; for from_fd, whose walk visits every implementation, a BPF program cannot fill the object out parameter, so an attachment returning 0 would hand the caller an uninitialized pointer.

Cc Paul Moore <[email protected]>
Cc Casey Schaufler <[email protected]>
---
 include/linux/lsm_hook_defs.h |  4 ++++
 include/linux/security.h      | 11 +++++++++++
 kernel/bpf/bpf_lsm.c          |  3 +++
 3 files changed, 18 insertions(+)
include/linux/lsm_hook_defs.h +4 -0
index 65c9609ec207..d7684407737a 100644
@@ -452,6 +452,10 @@ LSM_HOOK(int, 0, bpf_token_create, struct bpf_token *token, union bpf_attr *attr
 LSM_HOOK(void, LSM_RET_VOID, bpf_token_free, struct bpf_token *token)
 LSM_HOOK(int, 0, bpf_token_cmd, const struct bpf_token *token, enum bpf_cmd cmd)
 LSM_HOOK(int, 0, bpf_token_capable, const struct bpf_token *token, int cap)
+LSM_HOOK(int, -EOPNOTSUPP, policy_object_from_fd, int fd,
+	 struct lsm_policy_object **object)
+LSM_HOOK(int, -EOPNOTSUPP, policy_object_get, struct lsm_policy_object *object)
+LSM_HOOK(void, LSM_RET_VOID, policy_object_put, struct lsm_policy_object *object)
 #endif /* CONFIG_BPF_SYSCALL */
 
 LSM_HOOK(int, 0, locked_down, enum lockdown_reason what)
include/linux/security.h +11 -0
index 153e9043058f..5e423bea080e 100644
@@ -168,6 +168,17 @@ struct lsm_prop {
 	struct lsm_prop_bpf bpf;
 };
 
+/*
+ * Identity of a policy object an LSM shares with BPF programs,
+ * embedded in the LSM's own object.  @lsmid identifies the owning
+ * LSM; @type discriminates that LSM's policy object types, with 0
+ * reserved as "unset".
+ */
+struct lsm_policy_object {
+	u64 lsmid;
+	u32 type;
+};
+
 extern const char *const lockdown_reasons[LOCKDOWN_CONFIDENTIALITY_MAX+1];
 
 /* These functions are in security/commoncap.c */
kernel/bpf/bpf_lsm.c +3 -0
index 1433809bb166..d06744d72e04 100644
@@ -56,6 +56,9 @@ BTF_ID(func, bpf_lsm_xfrm_decode_session)
 #endif
 BTF_ID(func, bpf_lsm_ismaclabel)
 BTF_ID(func, bpf_lsm_file_alloc_security)
+BTF_ID(func, bpf_lsm_policy_object_from_fd)
+BTF_ID(func, bpf_lsm_policy_object_get)
+BTF_ID(func, bpf_lsm_policy_object_put)
 BTF_SET_END(bpf_lsm_disabled_hooks)
 
 /* List of LSM hooks that should operate on 'current' cgroup regardless
Signature · 1 line
2.55.0
#7 lore raw

PATCH v2 2/15 lsm: Add the bprm_apply_policy_object LSM hook

In reply to Justin Suess

Add the first policy object operation, applying a policy to the credentials prepared for an execution:

bprm_apply_policy_object(bprm, object, flags)

The hook is only called between the preparation and the commitment of the bprm's credentials, i.e. from a bprm_creds_for_exec() or bprm_creds_from_file() context, where the executed task can still be arranged to start confined by the policy.

How the policy composes with restrictions the credentials already carry, and the meaning of @flags, are defined by the implementing LSM, which must reject unsupported flags with -EINVAL. An LSM with no notion of applying a policy object to an execution does not implement the hook, and the calling kfunc fails with -EOPNOTSUPP.

Like the lifetime hooks, this hook is excluded from the "bpf" LSM's attachment points, as the targeted dispatch makes an attachment there unreachable.

Cc Paul Moore <[email protected]>
Cc Casey Schaufler <[email protected]>
---
 include/linux/lsm_hook_defs.h | 2 ++
 kernel/bpf/bpf_lsm.c          | 1 +
 2 files changed, 3 insertions(+)
include/linux/lsm_hook_defs.h +2 -0
index d7684407737a..ddb15bea383e 100644
@@ -452,6 +452,8 @@ LSM_HOOK(int, 0, bpf_token_create, struct bpf_token *token, union bpf_attr *attr
 LSM_HOOK(void, LSM_RET_VOID, bpf_token_free, struct bpf_token *token)
 LSM_HOOK(int, 0, bpf_token_cmd, const struct bpf_token *token, enum bpf_cmd cmd)
 LSM_HOOK(int, 0, bpf_token_capable, const struct bpf_token *token, int cap)
+LSM_HOOK(int, -EOPNOTSUPP, bprm_apply_policy_object, struct linux_binprm *bprm,
+	 struct lsm_policy_object *object, u32 flags)
 LSM_HOOK(int, -EOPNOTSUPP, policy_object_from_fd, int fd,
 	 struct lsm_policy_object **object)
 LSM_HOOK(int, -EOPNOTSUPP, policy_object_get, struct lsm_policy_object *object)
kernel/bpf/bpf_lsm.c +1 -0
index d06744d72e04..d5859553f7f8 100644
@@ -56,6 +56,7 @@ BTF_ID(func, bpf_lsm_xfrm_decode_session)
 #endif
 BTF_ID(func, bpf_lsm_ismaclabel)
 BTF_ID(func, bpf_lsm_file_alloc_security)
+BTF_ID(func, bpf_lsm_bprm_apply_policy_object)
 BTF_ID(func, bpf_lsm_policy_object_from_fd)
 BTF_ID(func, bpf_lsm_policy_object_get)
 BTF_ID(func, bpf_lsm_policy_object_put)
Signature · 1 line
2.55.0
#8 lore raw

PATCH v2 3/15 lsm: Move the lsm_for_each_hook() macro to security/lsm.h

In reply to Justin Suess

Move the lsm_for_each_hook() iterator from security/security.c to security/lsm.h, verbatim: a following commit adds a user outside security.c, the file implementing the LSM policy object kfuncs. No functional change.

Cc Paul Moore <[email protected]>
Cc Casey Schaufler <[email protected]>
---
 security/lsm.h      | 6 ++++++
 security/security.c | 5 -----
 2 files changed, 6 insertions(+), 5 deletions(-)
security/lsm.h +6 -0
index 32f808ad4335..264ae63290a8 100644
@@ -24,6 +24,12 @@ extern bool lsm_debug;
 extern unsigned int lsm_active_cnt;
 extern const struct lsm_id *lsm_idlist[];
 
+/* Iterate over the active implementations of a given hook */
+#define lsm_for_each_hook(scall, NAME)					\
+	for (scall = static_calls_table.NAME;				\
+	     scall - static_calls_table.NAME < MAX_LSM_COUNT; scall++)  \
+		if (static_key_enabled(&scall->active->key))
+
 /* LSM blob configuration */
 extern struct lsm_blob_sizes blob_sizes;
 
security/security.c +0 -5
index 71aea8fdf014..0a6fa21cc31b 100644
@@ -495,11 +495,6 @@ OUT:									\
 	RC;								\
 })
 
-#define lsm_for_each_hook(scall, NAME)					\
-	for (scall = static_calls_table.NAME;				\
-	     scall - static_calls_table.NAME < MAX_LSM_COUNT; scall++)  \
-		if (static_key_enabled(&scall->active->key))
-
 /* Security operations */
 
 /**
Signature · 1 line
2.55.0
#9 lore raw

PATCH v2 4/15 lsm: Add the bpf_lsm_policy_release kfunc and policy object destructor

In reply to Justin Suess

Add security/bpf_lsm_kfuncs.c, the home of the kfuncs exposing LSM policy objects to BPF programs, with the first of them:

bpf_lsm_policy_release(object) KF_RELEASE

The kfuncs are the LSM framework's own BPF interface: there is no per-LSM kfunc and no intermediate security_*() layer. Each kfunc walks the matching hook's implementation list and calls the one registered by the LSM whose lsmid the policy object carries. Calling a kfunc for an LSM that is not active or has no policy object support fails at runtime rather than hiding the kfunc at verification time, so BPF program loading is independent of the boot-time LSM configuration.

A policy object reference is meant to be handed over through a map kptr field, so also register a destructor for struct
lsm_policy_object: map-held references are dropped on map teardown, possibly from a context that cannot sleep, which the policy_object_put() hook contract accounts for. For the same reason the kfunc is not KF_SLEEPABLE, and the filter adds no per-kfunc rule:
releasing a reference must be allowed wherever one can be held. The filter itself is needed because BPF_PROG_TYPE_LSM and BPF_PROG_TYPE_SYSCALL, the two registered program types, share their kfunc lookup buckets with other program types.

---
 MAINTAINERS               |  1 +
 security/Makefile         |  2 +-
 security/bpf_lsm_kfuncs.c | 98 +++++++++++++++++++++++++++++++++++++++
 3 files changed, 100 insertions(+), 1 deletion(-)
 create mode 100644 security/bpf_lsm_kfuncs.c
MAINTAINERS +1 -0
index f5301c30ea91..2af6a25a1399 100644
@@ -5037,6 +5037,7 @@ F:	kernel/bpf/bpf_lsm.c
 F:	kernel/bpf/bpf_lsm_proto.c
 F:	kernel/trace/bpf_trace.c
 F:	security/bpf/
+F:	security/bpf_lsm_kfuncs.c
 
 BPF [SELFTESTS] (Test Runners & Infrastructure)
 M:	Andrii Nakryiko <[email protected]>
security/Makefile +1 -1
index 4601230ba442..a9364ea9828b 100644
@@ -23,7 +23,7 @@ obj-$(CONFIG_SECURITY_LOADPIN)		+= loadpin/
 obj-$(CONFIG_SECURITY_SAFESETID)       += safesetid/
 obj-$(CONFIG_SECURITY_LOCKDOWN_LSM)	+= lockdown/
 obj-$(CONFIG_CGROUPS)			+= device_cgroup.o
-obj-$(CONFIG_BPF_LSM)			+= bpf/
+obj-$(CONFIG_BPF_LSM)			+= bpf/ bpf_lsm_kfuncs.o
 obj-$(CONFIG_SECURITY_LANDLOCK)		+= landlock/
 obj-$(CONFIG_SECURITY_IPE)		+= ipe/
 
security/bpf_lsm_kfuncs.c new file +98 -0

98 lines not on this page · raw message

Signature · 1 line
2.55.0
#10 lore raw

PATCH v2 5/15 lsm: Add the bpf_lsm_policy_from_fd kfunc

In reply to Justin Suess

Add the kfunc translating a file descriptor into a referenced policy object:

bpf_lsm_policy_from_fd(fd, flags)
KF_ACQUIRE|KF_RET_NULL|KF_SLEEPABLE

No argument names an LSM: a policy object fd refers to a file set up through the owning LSM's own userspace interface so the fd itself identifies the LSM asked to translate it. The kfunc offers the fd to every policy_object_from_fd implementation in turn until one claims it.

Following the convention of the lsm_*(2) syscalls, @flags belongs to the framework and is reserved: the kfunc returns NULL for @flags != 0.

A policy object fd is only meaningful in the fd table of the process that set the object up, while an LSM program runs in the context of the task it mediates, so the filter makes this kfunc exclusive to syscall programs (BPF_PROG_TYPE_SYSCALL), which run in the context of the task invoking them. The acquired object may be released with bpf_lsm_policy_release().

---
 security/bpf_lsm_kfuncs.c | 53 +++++++++++++++++++++++++++++++++++++--
 1 file changed, 51 insertions(+), 2 deletions(-)
security/bpf_lsm_kfuncs.c +51 -2
index e1190215d477..988dcd6f4dd9 100644
@@ -14,11 +14,50 @@
 
 __bpf_kfunc_start_defs();
 
+/**
+ * bpf_lsm_policy_from_fd - Get an LSM policy object from a fd
+ * @fd: file descriptor referring to a policy object, resolved in the
+ *      file descriptor table of the task running the program
+ * @flags: reserved for future use, must be 0
+ *
+ * Translate @fd, as set up through the owning LSM's own userspace
+ * interface, into a referenced policy object.  The fd identifies the
+ * LSM asked to translate it: each LSM recognizes its own fds and
+ * declines every other.  Only syscall programs may call this kfunc:
+ * they run in the context of the task invoking them, where the fd is
+ * meaningful.  The reference must be released with
+ * bpf_lsm_policy_release().
+ *
+ * Return: A referenced policy object, or NULL if @flags is not 0, if
+ * no enabled LSM recognizes @fd as one of its policy objects, or if
+ * the recognizing LSM fails to translate it.
+ */
+__bpf_kfunc struct lsm_policy_object *bpf_lsm_policy_from_fd(int fd, u32 flags)
+{
+	struct lsm_static_call *scall;
+	struct lsm_policy_object *object;
+	int err;
+
+	if (flags)
+		return NULL;
+
+	lsm_for_each_hook(scall, policy_object_from_fd) {
+		err = scall->hl->hook.policy_object_from_fd(fd, &object);
+		if (err == -EOPNOTSUPP)
+			/* Not this LSM's fd: let another claim it. */
+			continue;
+		if (err)
+			return NULL;
+		return object;
+	}
+	return NULL;
+}
+
 /**
  * bpf_lsm_policy_release - Release a policy object reference
  * @object: policy object to release
  *
- * Release an acquired reference on a policy object.
+ * Release a reference acquired with bpf_lsm_policy_from_fd().
  */
 __bpf_kfunc void bpf_lsm_policy_release(struct lsm_policy_object *object)
 {
@@ -44,6 +83,8 @@ CFI_NOSEAL(bpf_lsm_policy_release_dtor);
 __bpf_kfunc_end_defs();
 
 BTF_KFUNCS_START(bpf_lsm_policy_kfunc_ids)
+BTF_ID_FLAGS(func, bpf_lsm_policy_from_fd,
+	     KF_ACQUIRE | KF_RET_NULL | KF_SLEEPABLE)
 BTF_ID_FLAGS(func, bpf_lsm_policy_release, KF_RELEASE)
 BTF_KFUNCS_END(bpf_lsm_policy_kfunc_ids)
 
@@ -51,10 +92,14 @@ BTF_ID_LIST(bpf_lsm_policy_dtor_ids)
 BTF_ID(struct, lsm_policy_object)
 BTF_ID(func, bpf_lsm_policy_release_dtor)
 
+BTF_ID_LIST_SINGLE(bpf_lsm_policy_from_fd_ids, func, bpf_lsm_policy_from_fd)
+
 /*
  * BPF_PROG_TYPE_LSM and BPF_PROG_TYPE_SYSCALL share their kfunc
  * lookup buckets with other program types, so restricting the policy
- * kfuncs requires a filter.
+ * kfuncs requires a filter.  A policy object fd is only meaningful in
+ * the fd table of the task that set the object up: the fd kfunc is
+ * exclusive to syscall programs, which run in that task's context.
  */
 static int bpf_lsm_policy_kfunc_filter(const struct bpf_prog *prog,
 				       u32 kfunc_id)
@@ -64,7 +109,11 @@ static int bpf_lsm_policy_kfunc_filter(const struct bpf_prog *prog,
 
 	switch (prog->type) {
 	case BPF_PROG_TYPE_SYSCALL:
+		return 0;
 	case BPF_PROG_TYPE_LSM:
+		if (kfunc_id == bpf_lsm_policy_from_fd_ids[0])
+			return -EACCES;
+
 		return 0;
 	default:
 		return -EACCES;
Signature · 1 line
2.55.0
#11 lore raw

PATCH v2 6/15 lsm: Add the bpf_lsm_policy_acquire kfunc

In reply to Justin Suess

Add the kfunc acquiring a reference on a policy object the program does not own:

bpf_lsm_policy_acquire(object) KF_ACQUIRE|KF_RCU|KF_RET_NULL

bpf_kptr_xchg() is the only way to take an owned pointer out of a map kptr field, and it empties the slot: concurrent executions of an enforcement program would race for the one stored reference. Modeled after bpf_task_acquire(), this kfunc removes the exclusivity: a program loads the kptr field with a plain read under bpf_rcu_read_lock(), acquires its own reference through the policy_object_get hook, and leaves the map slot untouched. The acquired reference survives bpf_rcu_read_unlock(), carrying over to a sleepable bpf_lsm_policy_apply_bprm() call, and is released with bpf_lsm_policy_release().

Adding struct lsm_policy_object to the verifier's rcu_protected_types set makes the plain load yield an RCU-protected pointer instead of an untrusted one. This is where the policy object contract's RCU requirements become load-bearing: the kfunc and the get hook examine the object concurrently with a possible last put, which is safe because implementations free only after an RCU grace period and acquire with inc-not-zero semantics. A failed get makes the kfunc return NULL, per KF_RET_NULL.

The kfunc does not sleep and is meaningful wherever a policy object pointer can be loaded, so the filter adds no per-kfunc rule.

---
 kernel/bpf/verifier.c     |  3 +++
 security/bpf_lsm_kfuncs.c | 34 +++++++++++++++++++++++++++++++++-
 2 files changed, 36 insertions(+), 1 deletion(-)
kernel/bpf/verifier.c +3 -0
index 7aa47342dc65..ba9972c572e1 100644
@@ -4394,6 +4394,9 @@ BTF_ID(struct, task_struct)
 #ifdef CONFIG_CRYPTO
 BTF_ID(struct, bpf_crypto_ctx)
 #endif
+#ifdef CONFIG_BPF_LSM
+BTF_ID(struct, lsm_policy_object)
+#endif
 BTF_SET_END(rcu_protected_types)
 
 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
security/bpf_lsm_kfuncs.c +33 -1
index 988dcd6f4dd9..43a4bf57fd31 100644
@@ -14,6 +14,36 @@
 
 __bpf_kfunc_start_defs();
 
+/**
+ * bpf_lsm_policy_acquire - Acquire a reference on a shared policy object
+ * @object: RCU-protected pointer to a policy object, e.g. loaded from
+ *          a map kptr field under bpf_rcu_read_lock()
+ *
+ * Acquire a reference of its own on a policy object the program does
+ * not own, so that any number of concurrent program executions can
+ * use the object shared through one map kptr field, without emptying
+ * it as bpf_kptr_xchg() would.  The returned reference stays valid
+ * after bpf_rcu_read_unlock() and must be released with
+ * bpf_lsm_policy_release().
+ *
+ * Return: A referenced policy object, or NULL if the object's
+ * reference count concurrently dropped to zero.
+ */
+__bpf_kfunc struct lsm_policy_object *
+bpf_lsm_policy_acquire(struct lsm_policy_object *object)
+{
+	struct lsm_static_call *scall;
+
+	lsm_for_each_hook(scall, policy_object_get) {
+		if (scall->hl->lsmid->id != object->lsmid)
+			continue;
+		if (scall->hl->hook.policy_object_get(object))
+			return NULL;
+		return object;
+	}
+	return NULL;
+}
+
 /**
  * bpf_lsm_policy_from_fd - Get an LSM policy object from a fd
  * @fd: file descriptor referring to a policy object, resolved in the
@@ -57,7 +87,8 @@ __bpf_kfunc struct lsm_policy_object *bpf_lsm_policy_from_fd(int fd, u32 flags)
  * bpf_lsm_policy_release - Release a policy object reference
  * @object: policy object to release
  *
- * Release a reference acquired with bpf_lsm_policy_from_fd().
+ * Release a reference acquired with bpf_lsm_policy_from_fd() or
+ * bpf_lsm_policy_acquire().
  */
 __bpf_kfunc void bpf_lsm_policy_release(struct lsm_policy_object *object)
 {
@@ -83,6 +114,7 @@ CFI_NOSEAL(bpf_lsm_policy_release_dtor);
 __bpf_kfunc_end_defs();
 
 BTF_KFUNCS_START(bpf_lsm_policy_kfunc_ids)
+BTF_ID_FLAGS(func, bpf_lsm_policy_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
 BTF_ID_FLAGS(func, bpf_lsm_policy_from_fd,
 	     KF_ACQUIRE | KF_RET_NULL | KF_SLEEPABLE)
 BTF_ID_FLAGS(func, bpf_lsm_policy_release, KF_RELEASE)
Signature · 1 line
2.55.0
#12 lore raw

PATCH v2 7/15 lsm: Add the bpf_lsm_policy_apply_bprm kfunc

In reply to Justin Suess

Add the kfunc applying a policy object to an execution:

bpf_lsm_policy_apply_bprm(object, bprm, flags) KF_SLEEPABLE

It asks the LSM owning @object, through the bprm_apply_policy_object hook, to restrict the credentials prepared in @bprm, so that the executed task starts confined by the policy. The meaning of @flags and the composition with restrictions the credentials already carry are the owning LSM's; an LSM without execution policy support makes the call fail with -EOPNOTSUPP.

The kfunc runs the hook in a root memcg charging scope: the policy restricts the execution on behalf of the BPF program, not of the mediated task, so what the owning LSM allocates to compute it, e.g. Landlock's merged domain, is not charged to the task the program supervises.

The filter makes the kfunc exclusive to the sleepable LSM programs attached to the bprm_creds_for_exec() or bprm_creds_from_file() hooks, the only contexts where the bprm's credentials are prepared but not yet committed.

---
 security/bpf_lsm_kfuncs.c | 72 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 72 insertions(+)
security/bpf_lsm_kfuncs.c +72 -0
index 43a4bf57fd31..743752b5852e 100644
@@ -2,16 +2,25 @@
 
 /* BPF kfuncs exposing LSM policy objects. */
 
+#include <linux/binfmts.h>
 #include <linux/bpf.h>
 #include <linux/btf.h>
 #include <linux/btf_ids.h>
 #include <linux/cfi.h>
 #include <linux/init.h>
 #include <linux/lsm_hooks.h>
+#include <linux/memcontrol.h>
+#include <linux/sched/mm.h>
 #include <linux/security.h>
 
 #include "lsm.h"
 
+/* The sleepable LSM hooks bpf_lsm_policy_apply_bprm() may be called from. */
+BTF_SET_START(bpf_lsm_policy_bprm_hooks)
+BTF_ID(func, bpf_lsm_bprm_creds_for_exec)
+BTF_ID(func, bpf_lsm_bprm_creds_from_file)
+BTF_SET_END(bpf_lsm_policy_bprm_hooks)
+
 __bpf_kfunc_start_defs();
 
 /**
@@ -44,6 +53,49 @@ bpf_lsm_policy_acquire(struct lsm_policy_object *object)
 	return NULL;
 }
 
+/**
+ * bpf_lsm_policy_apply_bprm - Apply a policy object to exec credentials
+ * @object: policy object to apply
+ * @bprm: execution context providing the prepared credentials to
+ *        restrict
+ * @flags: flags defined by the LSM owning @object
+ *
+ * Ask the LSM owning @object to restrict the credentials prepared in
+ * @bprm with it, so that the executed task starts confined by the
+ * policy.  How the policy composes with restrictions the credentials
+ * already carry, and the meaning of @flags, are defined by the owning
+ * LSM.  @object is only borrowed: the caller keeps its reference.
+ * The hook runs in a root memcg charging scope: policy the LSM
+ * computes on behalf of the program is not charged to the mediated
+ * task.
+ *
+ * Return: 0 on success, -EOPNOTSUPP if the LSM owning @object does
+ * not support applying policy to an execution, -EINVAL on unsupported
+ * @flags, other negative values on LSM-specific failures.
+ */
+__bpf_kfunc int bpf_lsm_policy_apply_bprm(struct lsm_policy_object *object,
+					  struct linux_binprm *bprm, u32 flags)
+{
+	struct lsm_static_call *scall;
+	struct mem_cgroup *old_memcg;
+	int err;
+
+	lsm_for_each_hook(scall, bprm_apply_policy_object) {
+		if (scall->hl->lsmid->id != object->lsmid)
+			continue;
+		/*
+		 * The hook runs on behalf of the BPF program, not of the
+		 * mediated task: charge its allocations to the root memcg.
+		 */
+		old_memcg = set_active_memcg(root_mem_cgroup);
+		err = scall->hl->hook.bprm_apply_policy_object(bprm, object,
+							       flags);
+		set_active_memcg(old_memcg);
+		return err;
+	}
+	return -EOPNOTSUPP;
+}
+
 /**
  * bpf_lsm_policy_from_fd - Get an LSM policy object from a fd
  * @fd: file descriptor referring to a policy object, resolved in the
@@ -115,6 +167,7 @@ __bpf_kfunc_end_defs();
 
 BTF_KFUNCS_START(bpf_lsm_policy_kfunc_ids)
 BTF_ID_FLAGS(func, bpf_lsm_policy_acquire, KF_ACQUIRE | KF_RCU | KF_RET_NULL)
+BTF_ID_FLAGS(func, bpf_lsm_policy_apply_bprm, KF_SLEEPABLE)
 BTF_ID_FLAGS(func, bpf_lsm_policy_from_fd,
 	     KF_ACQUIRE | KF_RET_NULL | KF_SLEEPABLE)
 BTF_ID_FLAGS(func, bpf_lsm_policy_release, KF_RELEASE)
@@ -124,6 +177,8 @@ BTF_ID_LIST(bpf_lsm_policy_dtor_ids)
 BTF_ID(struct, lsm_policy_object)
 BTF_ID(func, bpf_lsm_policy_release_dtor)
 
+BTF_ID_LIST_SINGLE(bpf_lsm_policy_apply_bprm_ids, func,
+		   bpf_lsm_policy_apply_bprm)
 BTF_ID_LIST_SINGLE(bpf_lsm_policy_from_fd_ids, func, bpf_lsm_policy_from_fd)
 
 /*
@@ -132,6 +187,8 @@ BTF_ID_LIST_SINGLE(bpf_lsm_policy_from_fd_ids, func, bpf_lsm_policy_from_fd)
  * kfuncs requires a filter.  A policy object fd is only meaningful in
  * the fd table of the task that set the object up: the fd kfunc is
  * exclusive to syscall programs, which run in that task's context.
+ * Applying policy to an execution is exclusive to the sleepable bprm
+ * LSM hooks the operation is specified for.
  */
 static int bpf_lsm_policy_kfunc_filter(const struct bpf_prog *prog,
 				       u32 kfunc_id)
@@ -141,11 +198,26 @@ static int bpf_lsm_policy_kfunc_filter(const struct bpf_prog *prog,
 
 	switch (prog->type) {
 	case BPF_PROG_TYPE_SYSCALL:
+		if (kfunc_id == bpf_lsm_policy_apply_bprm_ids[0])
+			return -EACCES;
 		return 0;
 	case BPF_PROG_TYPE_LSM:
 		if (kfunc_id == bpf_lsm_policy_from_fd_ids[0])
 			return -EACCES;
 
+		if (kfunc_id == bpf_lsm_policy_apply_bprm_ids[0]) {
+			/*
+			 * BPF_LSM_CGROUP programs run under classic
+			 * RCU and cannot sleep.
+			 */
+			if (prog->expected_attach_type == BPF_LSM_CGROUP)
+				return -EACCES;
+
+			if (!btf_id_set_contains(&bpf_lsm_policy_bprm_hooks,
+						 prog->aux->attach_btf_id))
+				return -EACCES;
+		}
+
 		return 0;
 	default:
 		return -EACCES;
Signature · 1 line
2.55.0
#13 lore raw

PATCH v2 8/15 lsm: Document the LSM policy object interface

In reply to Justin Suess

Describe the split of responsibilities in lsm-development.rst: the LSM framework owns the BPF-facing kfuncs, an LSM opts in by embedding struct lsm_policy_object, tagged with its lsmid and an LSM-private type, and implementing ordinary LSM hooks, and the lifetime contract those hooks must satisfy comes from BPF's execution model.

Cc Paul Moore <[email protected]>
Cc Casey Schaufler <[email protected]>
---
 Documentation/security/lsm-development.rst | 49 ++++++++++++++++++++++
 1 file changed, 49 insertions(+)
Documentation/security/lsm-development.rst +49 -0
index 5895e529da7f..190d9b8f2346 100644
@@ -15,3 +15,52 @@ see ``security/security.c`` and associated structures:
 
 .. kernel-doc:: security/security.c
    :export:
+
+LSM policy objects and BPF kfuncs
+=================================
+
+The LSM framework implements an interface for individual LSMs to
+expose their policy through BPF kfuncs and kptrs. An LSM may not
+export any kfunc or other BPF interface directly.
+
+An LSM opts in by embedding ``struct lsm_policy_object`` in one of
+its own objects, setting its ``lsmid`` to the LSM's ``LSM_ID_*``
+value and its ``type`` to a nonzero value of the LSM's choosing, and
+implementing the policy object hooks (``policy_object_from_fd``,
+``policy_object_get``, ``policy_object_put``, and per-operation hooks
+such as ``bprm_apply_policy_object``) like any other hook, resolving
+the containing object with ``container_of()``. The ``type`` namespace
+is private to the owning LSM, which uses it to tell its own policy
+object kinds apart; the framework never interprets it, and 0 is
+reserved as "unset".
+
+The kfuncs, defined once in ``security/bpf_lsm_kfuncs.c``, dispatch
+each call on an object to the single LSM matching its ``lsmid``. The
+fd translation has no object yet: the framework offers the fd to
+every ``policy_object_from_fd`` implementation in turn, and an LSM
+declines a fd that is not one of its own with ``-EOPNOTSUPP``; any
+other error fails the translation. A program that expects a policy of
+a specific LSM can read the returned object's ``lsmid``. Either way,
+a BPF program reaches an LSM the same way every other kernel caller
+does, through an LSM hook, while the BPF verifier tracks the object
+as a referenced kptr.
+
+An LSM opting in must satisfy the lifetime contract that BPF's
+execution model imposes: the containing object is reference counted,
+``policy_object_get`` acquires with inc-not-zero semantics and fails
+once the count dropped to zero, ``policy_object_put`` may be called
+from contexts that cannot sleep (map destructors), and the object's
+memory is freed only after an RCU grace period, as programs load
+policy object kptrs from BPF maps under RCU. Hooks for operations an
+LSM does not provide are simply not implemented: the corresponding
+kfunc then fails with ``-EOPNOTSUPP`` at runtime. Whether the LSM
+providing an operation is built in and active is likewise a runtime
+property: the kfuncs are always registered when ``CONFIG_BPF_LSM`` is
+enabled, so BPF program loading is independent of the boot-time LSM
+configuration.
+
+.. kernel-doc:: security/bpf_lsm_kfuncs.c
+   :identifiers: bpf_lsm_policy_acquire
+                 bpf_lsm_policy_apply_bprm
+                 bpf_lsm_policy_from_fd
+                 bpf_lsm_policy_release
Signature · 1 line
2.55.0
#14 lore raw

PATCH v2 9/15 selftests/bpf: Add tests for the LSM policy object kfuncs

In reply to Justin Suess

Test the properties of the policy object interface that hold independently of any LSM implementing the hooks.

The failure programs pin down the verifier-side contract: the kfuncs are rejected in tracing programs, the fd kfunc in LSM programs, the apply kfunc in syscall programs, on non-bprm LSM hooks and in non-sleepable programs, leaked references fail verification, and a kptr loaded outside an RCU read-side section cannot be acquired.

The syscall program checks the runtime contract of bpf_lsm_policy_from_fd(): a bad fd, a fd that is no LSM's policy object, and a nonzero value of the reserved flags all resolve to NULL.

Exercising the kfuncs against an LSM actually providing policy objects is left to that LSM's own tests.

---
 .../bpf/prog_tests/lsm_policy_kfuncs.c        |  54 ++++++
 .../selftests/bpf/progs/lsm_policy_kfuncs.c   |  52 ++++++
 .../bpf/progs/lsm_policy_kfuncs_failure.c     | 154 ++++++++++++++++++
 3 files changed, 260 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/lsm_policy_kfuncs.c
 create mode 100644 tools/testing/selftests/bpf/progs/lsm_policy_kfuncs.c
 create mode 100644 tools/testing/selftests/bpf/progs/lsm_policy_kfuncs_failure.c
tools/testing/selftests/bpf/prog_tests/lsm_policy_kfuncs.c new file +54 -0
new file mode 100644
index 000000000000..9f4ffb5f47be
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright © 2026 Justin Suess <[email protected]> */
+
+#include <test_progs.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include "lsm_policy_kfuncs.skel.h"
+#include "lsm_policy_kfuncs_failure.skel.h"
+
+/*
+ * Runtime contract of bpf_lsm_policy_from_fd(), independent of any
+ * LSM implementing the policy object hooks: a bad fd, a fd that is no
+ * LSM's policy object, and a nonzero value of the reserved flags all
+ * resolve to NULL.
+ */
+static void test_from_fd_null(void)
+{
+	LIBBPF_OPTS(bpf_test_run_opts, opts);
+	struct lsm_policy_kfuncs *skel;
+	char tmp_path[] = "/tmp/lsm_policy_kfuncs_XXXXXX";
+	int tmp_fd, err;
+
+	tmp_fd = mkstemp(tmp_path);
+	if (!ASSERT_GE(tmp_fd, 0, "mkstemp"))
+		return;
+
+	skel = lsm_policy_kfuncs__open_and_load();
+	if (!ASSERT_OK_PTR(skel, "skel_open_and_load"))
+		goto out_close;
+	skel->bss->plain_fd = tmp_fd;
+
+	err = bpf_prog_test_run_opts(bpf_program__fd(skel->progs.check_from_fd),
+				     &opts);
+	if (!ASSERT_OK(err, "check_from_fd_run") ||
+	    !ASSERT_OK(opts.retval, "check_from_fd_retval"))
+		goto out_destroy;
+
+	ASSERT_TRUE(skel->bss->got_null_for_bad_fd, "bad_fd_null");
+	ASSERT_TRUE(skel->bss->got_null_for_plain_fd, "plain_fd_null");
+	ASSERT_TRUE(skel->bss->got_null_for_bad_flags, "bad_flags_null");
+out_destroy:
+	lsm_policy_kfuncs__destroy(skel);
+out_close:
+	close(tmp_fd);
+	unlink(tmp_path);
+}
+
+void test_lsm_policy_kfuncs(void)
+{
+	if (test__start_subtest("from_fd_null"))
+		test_from_fd_null();
+	RUN_TESTS(lsm_policy_kfuncs_failure);
+}
tools/testing/selftests/bpf/progs/lsm_policy_kfuncs.c new file +52 -0

52 lines not on this page · raw message

tools/testing/selftests/bpf/progs/lsm_policy_kfuncs_failure.c new file +154 -0

154 lines not on this page · raw message

Signature · 1 line
2.55.0
#15 lore raw

PATCH v2 10/15 landlock: Expose the ruleset fd lookup to the rest of Landlock

In reply to Justin Suess

Rename get_ruleset_from_fd() to landlock_get_ruleset_from_fd() and give it external linkage within Landlock, declared in ruleset.h next to the other ruleset lifetime helpers.

A following commit implements the LSM kfunc policy hooks, which need to translate a ruleset fd into a landlock_ruleset reference from outside syscalls.c. No behavioral change.

Cc Mickaël Salaün <[email protected]>
---
 security/landlock/ruleset.h  | 3 +++
 security/landlock/syscalls.c | 9 +++++----
 2 files changed, 8 insertions(+), 4 deletions(-)
security/landlock/ruleset.h +3 -0
index b536fa0425b7..b58e3d9846af 100644
@@ -214,6 +214,9 @@ int landlock_store_rule(struct landlock_rules *const rules,
 
 void landlock_free_rules(struct landlock_rules *const rules);
 
+struct landlock_ruleset *landlock_get_ruleset_from_fd(const int fd,
+						      const fmode_t mode);
+
 /**
  * landlock_get_rule_root - Get the root of a rule tree by key type
  *
security/landlock/syscalls.c +5 -4
index 1d02d57f4c48..cb294a3582ae 100644
@@ -305,8 +305,8 @@ SYSCALL_DEFINE3(landlock_create_ruleset,
  * Returns an owned ruleset from a FD. It is thus needed to call
  * landlock_put_ruleset() on the return value.
  */
-static struct landlock_ruleset *get_ruleset_from_fd(const int fd,
-						    const fmode_t mode)
+struct landlock_ruleset *landlock_get_ruleset_from_fd(const int fd,
+						      const fmode_t mode)
 {
 	CLASS(fd, ruleset_f)(fd);
 	struct landlock_ruleset *ruleset;
@@ -486,7 +486,7 @@ SYSCALL_DEFINE4(landlock_add_rule, const int, ruleset_fd,
 		return -EINVAL;
 
 	/* Gets and checks the ruleset. */
-	ruleset = get_ruleset_from_fd(ruleset_fd, FMODE_CAN_WRITE);
+	ruleset = landlock_get_ruleset_from_fd(ruleset_fd, FMODE_CAN_WRITE);
 	if (IS_ERR(ruleset))
 		return PTR_ERR(ruleset);
 
@@ -585,7 +585,8 @@ SYSCALL_DEFINE2(landlock_restrict_self, const int, ruleset_fd, const __u32,
 	      (flags & ~LANDLOCK_RESTRICT_SELF_TSYNC) ==
 		      LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF)) {
 		/* Gets and checks the ruleset. */
-		ruleset = get_ruleset_from_fd(ruleset_fd, FMODE_CAN_READ);
+		ruleset = landlock_get_ruleset_from_fd(ruleset_fd,
+						       FMODE_CAN_READ);
 		if (IS_ERR(ruleset))
 			return PTR_ERR(ruleset);
 	}
Signature · 1 line
2.55.0
#16 lore raw

PATCH v2 11/15 landlock: Factor the credential restriction out of landlock_restrict_self()

In reply to Justin Suess

Split the core of landlock_restrict_self() into two credential helpers:

landlock_prepare_restriction() - translate the
landlock_restrict_self(2) flags, merge the ruleset with the credentials' domain, and configure the new domain's log state, producing a struct landlock_restriction: the complete new state that the enforcement gives to a credential.

landlock_apply_restriction() - enforce a computed restriction on
credentials exclusively owned by the caller. This step cannot fail, so a caller may run it past its last point of failure.

The merge runs under @ruleset->lock and the landlock_create_domain trace event is emitted before the lock is released, exactly as in the syscall before this change: the event still observes the ruleset snapshot that was merged, and it still fires before any thread-sync wait. Committing the hierarchy out of LANDLOCK_LOG_UNCOMMITTED moves along with it, so every domain computed by landlock_prepare_restriction() has its create/free trace events balanced, whether or not it ends up enforced.

The syscall behaves exactly as before: prepare and apply run back to back on the prepared credentials. The no_new_privs/CAP_SYS_ADMIN precheck, the flag mask check, the TSYNC handling, and the landlock_enforce_domain trace event are syscall policy and stay in place.

The point of the split is that application is decoupled from
computation: a following commit restricts an execution from a BPF kfunc by staging a prepared restriction in the binprm credentials and applying it at the exec point of no return, with the flag translation, domain merge, and log configuration in one shared place.

The restriction records the flags it was computed with instead of translating them into per-flag fields: consumers read the staged flags at application time, so a future flag that must be honored at enforcement travels with the restriction automatically, with no per-flag plumbing in the callers.

Cc Mickaël Salaün <[email protected]>
---
 security/landlock/cred.c     | 132 +++++++++++++++++++++++++++++++++++
 security/landlock/cred.h     |  31 ++++++++
 security/landlock/syscalls.c |  96 ++++---------------------
 3 files changed, 178 insertions(+), 81 deletions(-)
security/landlock/cred.c +132 -0
index 03449c26247e..f02706f12c7d 100644
@@ -8,14 +8,146 @@
  */
 
 #include <linux/binfmts.h>
+#include <linux/bits.h>
 #include <linux/cred.h>
+#include <linux/err.h>
+#include <linux/errno.h>
 #include <linux/lsm_hooks.h>
+#include <linux/mutex.h>
+#include <uapi/linux/landlock.h>
 
 #include "common.h"
 #include "cred.h"
+#include "domain.h"
 #include "ruleset.h"
 #include "setup.h"
 
+#include <trace/events/landlock.h>
+
+/**
+ * landlock_prepare_restriction - Compute a credential restriction
+ *
+ * @llcred: Landlock credentials to restrict: provides the parent domain and
+ *          the previous log configuration.  Not modified.
+ * @ruleset: Ruleset to enforce, or NULL for a log-configuration-only change.
+ * @flags: landlock_restrict_self(2) flags.  The caller is responsible for
+ *         validating them against the set of flags it supports.
+ * @restriction: Computed restriction.  On success, holds a reference on
+ *               @restriction->domain (if any), which
+ *               landlock_apply_restriction() transfers to the restricted
+ *               credentials.
+ *
+ * The restriction builds on @llcred's current state: the caller must apply
+ * it to (or stage it for) these same credentials.
+ *
+ * Return: 0 on success, -errno on failure.
+ */
+int landlock_prepare_restriction(
+	const struct landlock_cred_security *const llcred,
+	struct landlock_ruleset *const ruleset, const u32 flags,
+	struct landlock_restriction *const restriction)
+{
+	struct landlock_domain *new_dom;
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
+	/* Translates "off" and "on" flags to booleans. */
+	const bool log_same_exec =
+		!(flags & LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF);
+	const bool log_new_exec =
+		!!(flags & LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON);
+	const bool prev_log_subdomains = !llcred->log_subdomains_off;
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
+
+	*restriction = (struct landlock_restriction){
+		.flags = flags,
+	};
+
+	if (!ruleset)
+		return 0;
+
+	mutex_lock(&ruleset->lock);
+	new_dom = landlock_merge_ruleset(llcred->domain, ruleset);
+	if (IS_ERR(new_dom)) {
+		mutex_unlock(&ruleset->lock);
+		return PTR_ERR(new_dom);
+	}
+	/*
+	 * Emits the domain-creation event while @ruleset->lock is still
+	 * held, right after the merge, so an eBPF program attached to
+	 * the tracepoint reads the exact ruleset that was merged into
+	 * the domain: a consistent snapshot that a concurrent
+	 * landlock_add_rule() (which holds the same lock) cannot
+	 * modify.
+	 *
+	 * This must not be delayed past the return of this function.
+	 * Holding @ruleset->lock across
+	 * landlock_restrict_sibling_threads() would hang: a sibling
+	 * thread blocked in landlock_add_rule() on the same
+	 * @ruleset->lock cannot run the task_work that thread-sync
+	 * waits for (the lock wait is uninterruptible).  Emitting here
+	 * keeps the lock off the thread-sync path.
+	 *
+	 * The trade-off is that the event fires for a domain that may
+	 * never be enforced: a later (rare) thread-sync failure or an
+	 * aborted execution drops it.  Those paths free the domain,
+	 * which emits the matching free_domain event so the create/free
+	 * pair stays balanced.
+	 */
+	trace_landlock_create_domain(new_dom, ruleset);
+	mutex_unlock(&ruleset->lock);
+
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
+	new_dom->hierarchy->log_same_exec = log_same_exec;
+	new_dom->hierarchy->log_new_exec = log_new_exec;
+	/*
+	 * The creation event fired above, so move the domain out of
+	 * LANDLOCK_LOG_UNCOMMITTED: its free_domain event must fire
+	 * too, even if the domain is dropped before being enforced.
+	 * Audit logging may still be disabled (DISABLED); tracing
+	 * observes it anyway.
+	 */
+	if ((!log_same_exec && !log_new_exec) || !prev_log_subdomains)
+		new_dom->hierarchy->log_status = LANDLOCK_LOG_DISABLED;
+	else
+		new_dom->hierarchy->log_status = LANDLOCK_LOG_PENDING;
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
+
+	restriction->domain = new_dom;
+	return 0;
+}
+
+/**
+ * landlock_apply_restriction - Enforce a computed restriction on credentials
+ *
+ * @llcred: Landlock credentials to restrict, exclusively owned by the caller
+ *          (prepared and not yet committed).
+ * @restriction: Restriction computed by landlock_prepare_restriction()
+ *               against the same credential state; its domain reference is
+ *               transferred to @llcred.
+ *
+ * Cannot fail, so that a caller may apply a restriction past its last point
+ * of failure, e.g. an exec point of no return.
+ */
+void landlock_apply_restriction(struct landlock_cred_security *const llcred,
+				struct landlock_restriction *const restriction)
+{
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
+	if (restriction->flags & LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF)
+		llcred->log_subdomains_off = true;
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
+
+	if (!restriction->domain)
+		return;
+
+	/* Replaces the old domain. */
+	landlock_put_domain(llcred->domain);
+	llcred->domain = restriction->domain;
+	restriction->domain = NULL;
+
+#ifdef CONFIG_SECURITY_LANDLOCK_LOG
+	llcred->domain_exec |= BIT(llcred->domain->num_layers - 1);
+#endif /* CONFIG_SECURITY_LANDLOCK_LOG */
+}
+
 static void hook_cred_transfer(struct cred *const new,
 			       const struct cred *const old)
 {
security/landlock/cred.h +31 -0
index a5ff9957949a..88fa97fc3bd2 100644
@@ -21,6 +21,29 @@
 #include "ruleset.h"
 #include "setup.h"
 
+/**
+ * struct landlock_restriction - Computed credential restriction
+ *
+ * The result of landlock_prepare_restriction(): the new state that
+ * enforcing a ruleset with a set of landlock_restrict_self(2) flags
+ * gives to a credential, decoupled from its application.  It is
+ * enforced with landlock_apply_restriction(), either right away
+ * (landlock_restrict_self(2)) or after a staging period (restriction
+ * of an execution).
+ */
+struct landlock_restriction {
+	/**
+	 * @domain: New domain to enforce, owning a reference.  NULL if the
+	 * restriction only carries a log configuration change.
+	 */
+	struct landlock_domain *domain;
+	/**
+	 * @flags: landlock_restrict_self(2) flags the restriction was
+	 * computed with, validated by the caller.
+	 */
+	u32 flags;
+};
+
 /**
  * struct landlock_cred_security - Credential security blob
  *
@@ -152,6 +175,14 @@ landlock_get_applicable_subject(const struct cred *const cred,
 	return NULL;
 }
 
+int landlock_prepare_restriction(
+	const struct landlock_cred_security *const llcred,
+	struct landlock_ruleset *const ruleset, const u32 flags,
+	struct landlock_restriction *const restriction);
+
+void landlock_apply_restriction(struct landlock_cred_security *const llcred,
+				struct landlock_restriction *const restriction);
+
 __init void landlock_add_cred_hooks(void);
 
 #endif /* _SECURITY_LANDLOCK_CRED_H */
security/landlock/syscalls.c +15 -81

137 lines not on this page · raw message

Signature · 1 line
2.55.0
#17 lore raw

PATCH v2 12/15 landlock: Free rulesets after an RCU grace period

In reply to Justin Suess

Defer every ruleset free behind an RCU grace period, and keep the fields that stay readable while a free is pending out of the union that overlays the deferred-free work item.

The policy_object_get LSM hook lets a caller holding only an RCU-protected pointer to a ruleset (e.g. loaded from a BPF map kptr field under rcu_read_lock()) race a refcount_inc_not_zero() against the drop of the last reference. For that to be sound, the ruleset's memory, and its reference count in particular, must remain valid until every RCU reader that could still observe the pointer is done:
free the ruleset through queue_rcu_work(), which waits for a grace period before running the free work.

The work item is overlaid with the fields that no one may touch once @usage reaches zero: @lock, @quiet_masks and @handled_masks. @usage itself stays outside the union so a racing reader observes zero instead of the work item's bytes, and the tracing fields @version and @id stay outside too because the landlock_free_ruleset trace event reads them when the queued work finally runs.

Since queueing the work never sleeps, the might_sleep() annotation is dropped: a following commit releases ruleset references from BPF object destructors that cannot sleep.

Cc Mickaël Salaün <[email protected]>
---
 security/landlock/ruleset.c | 24 ++++++++++++++---
 security/landlock/ruleset.h | 54 ++++++++++++++++++++++++-------------
 2 files changed, 57 insertions(+), 21 deletions(-)
security/landlock/ruleset.c +21 -3
index 0d07707523cd..00a6b9938fd1 100644
@@ -21,6 +21,7 @@
 #include <linux/refcount.h>
 #include <linux/slab.h>
 #include <linux/spinlock.h>
+#include <linux/workqueue.h>
 #include <uapi/linux/landlock.h>
 
 #include "access.h"
@@ -346,9 +347,26 @@ static void free_ruleset(struct landlock_ruleset *const ruleset)
 	kfree(ruleset);
 }
 
+static void free_ruleset_work(struct work_struct *const work)
+{
+	struct landlock_ruleset *ruleset;
+
+	ruleset = container_of(to_rcu_work(work), struct landlock_ruleset,
+			       work_free);
+	free_ruleset(ruleset);
+}
+
+/*
+ * RCU readers (cf. the policy_object_get LSM hook) may call
+ * refcount_inc_not_zero() on a ruleset they hold no reference to: the memory
+ * must survive a grace period after the last put.  Queueing the free also
+ * makes this callable from contexts that cannot sleep (cf. the
+ * policy_object_put LSM hook).
+ */
 void landlock_put_ruleset(struct landlock_ruleset *const ruleset)
 {
-	might_sleep();
-	if (ruleset && refcount_dec_and_test(&ruleset->usage))
-		free_ruleset(ruleset);
+	if (ruleset && refcount_dec_and_test(&ruleset->usage)) {
+		INIT_RCU_WORK(&ruleset->work_free, free_ruleset_work);
+		queue_rcu_work(system_dfl_wq, &ruleset->work_free);
+	}
 }
security/landlock/ruleset.h +36 -18

76 lines not on this page · raw message

Signature · 1 line
2.55.0
#18 lore raw

PATCH v2 13/15 landlock: Implement the LSM policy object hooks

In reply to Justin Suess

Implement the generic LSM hooks exposing Landlock rulesets as policy objects to BPF. The new code is gated on CONFIG_BPF_LSM, the only configuration where the kfuncs calling the hooks exist.

struct lsm_policy_object is embedded in struct landlock_ruleset and tagged with LSM_ID_LANDLOCK and LANDLOCK_POLICY_TYPE_RULESET at ruleset creation; the hooks resolve the ruleset with container_of() and no Landlock type crosses the LSM boundary. The type namespace is private to Landlock and routes the container_of() resolution once several policy object types exist: the consuming hooks reject an object of an unexpected type with -EINVAL (the put hook, which cannot fail, warns instead), while from_fd only produces objects and needs no check. The embedded object sits outside the union overlaying the deferred-free work item: an RCU reader may still read its identity while a queued free waits out the grace period.

- policy_object_from_fd() translates a ruleset fd, created with landlock_create_ruleset(2) and populated with landlock_add_rule(2), into an owned ruleset reference, validated the same way as for the Landlock syscalls (ruleset file type, FMODE_CAN_READ). A fd referring to a file that is not a Landlock ruleset is declined with -EOPNOTSUPP instead of the syscall's -EBADFD: it may be another LSM's policy object, and the decline lets the framework offer it to the LSM it belongs to.

- policy_object_put() releases such a reference. The hook may be reached from BPF object destructors that cannot sleep, which is
fine: ruleset puts queue the free as RCU work.

- policy_object_get() acquires an additional reference for a caller that only holds an RCU-protected pointer, e.g. loaded from a BPF map kptr field under rcu_read_lock(). The reference is taken with refcount_inc_not_zero(); the racing reader's access to the ruleset memory is safe because rulesets are freed after an RCU grace period.

- bprm_apply_policy_object() shares the landlock_restrict_self(2)
path: it calls landlock_prepare_restriction() on the credentials prepared in the binprm and stages the computed restriction (the merged struct landlock_domain) in their Landlock blob. The flags are the landlock_restrict_self(2) flags; only LANDLOCK_RESTRICT_SELF_TSYNC is rejected with -EINVAL because the restriction targets the execution, not the calling threads.

LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS is honored, not ignored: the syscall implements it directly in landlock_restrict_self(), so the staged path reads it back from the staged restriction's flags and sets no_new_privs on the executing task at application time. The executed program then starts with no_new_privs set, binding it and all its descendants; the current execution's
privilege computation is unaffected, as the bprm credentials (including any setuid elevation) were computed before bprm_committing_creds().

The staged restriction is enforced by a bprm_committing_creds() hook with the same landlock_apply_restriction() call as the syscall, past the exec point of no return: an execution either starts confined by the domain or, if it fails earlier, leaves the calling task untouched. The applied layer is accounted in domain_exec so the LOG_SAME_EXEC and LOG_NEW_EXEC audit flags follow the executed program. There is no no_new_privs/CAP_SYS_ADMIN precondition here:
gating who may load a policy-applying BPF program is the BPF attachment's privilege model.

The application emits the landlock_enforce_domain trace event, keeping the event's invariant that every enforcement falls between the domain's create_domain and free_domain events. The process is single-threaded past de_thread(), so the single event concludes the operation with complete == 1 and process_wide == 1. no_new_privs reports the post-flag state; on this path a value of 0 carries no authorization meaning and only tells the observer that the confined program can still elevate through future setuid execs, which the event's documentation now spells out.

The staged restriction's lifetime is fully covered: a second bprm_apply_policy_object() call on the same execution releases and replaces the previously staged restriction, an execution failing before the point of no return releases it through hook_cred_free(), and the application clears the staged domain so committed task credentials never carry one. landlock_cred_copy(), now also used by hook_cred_transfer(), upholds that invariant by never copying a staged restriction.

Cc Mickaël Salaün <[email protected]>
---
 include/trace/events/landlock.h |  15 +++-
 security/landlock/Makefile      |   2 +
 security/landlock/bpf.c         | 152 ++++++++++++++++++++++++++++++++
 security/landlock/bpf.h         |  21 +++++
 security/landlock/cred.c        |  16 ++--
 security/landlock/cred.h        |  16 ++++
 security/landlock/limits.h      |   4 +
 security/landlock/ruleset.c     |   6 ++
 security/landlock/ruleset.h     |  22 +++++
 security/landlock/setup.c       |   2 +
 10 files changed, 245 insertions(+), 11 deletions(-)
 create mode 100644 security/landlock/bpf.c
 create mode 100644 security/landlock/bpf.h
include/trace/events/landlock.h +12 -3
index f82588f6f90e..012ab9dcccb2 100644
@@ -500,13 +500,22 @@ TRACE_EVENT(landlock_create_domain,
  *                enforcement time: 1 if set (by a prior
  *                :manpage:`prctl(2)` %PR_SET_NO_NEW_PRIVS or by
  *                %LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS), 0 if the domain
- *                was enforced with %CAP_SYS_ADMIN instead.
+ *                was enforced with %CAP_SYS_ADMIN instead, or without
+ *                either precondition on the BPF exec path (see below).
  *
  * Emitted for each thread sys_landlock_restrict_self() enforces the
  * domain on, in that thread's own context, right after its
  * commit_creds(), so it fires only once the thread is irreversibly
- * enforcing the domain (aborted operations emit none).  Not
- * balanced; every enforcement falls between the domain's
+ * enforcing the domain (aborted operations emit none).  Also emitted
+ * at execve(2)'s point of no return when a BPF-staged policy object
+ * is applied to the execution (see bpf_lsm_policy_apply_bprm()): the
+ * process is single-threaded after de_thread(), so the single event
+ * has @complete == 1 and @process_wide == 1.  On that path,
+ * @no_new_privs == 0 carries no authorization meaning (the authority
+ * is the privilege to attach the BPF program, not
+ * no_new_privs/%CAP_SYS_ADMIN); it only tells the observer that the
+ * confined program can still elevate through future setuid execs.
+ * Not balanced; every enforcement falls between the domain's
  * landlock_create_domain and landlock_free_domain events.
  *
  * @complete == 1 && @process_wide == 1 means the whole process is
security/landlock/Makefile +2 -0
index 2711f4876939..606bc91522e2 100644
@@ -20,3 +20,5 @@ landlock-$(CONFIG_SECURITY_LANDLOCK_LOG) += \
 landlock-$(CONFIG_AUDIT) += audit.o
 
 landlock-$(CONFIG_TRACEPOINTS) += trace.o
+
+landlock-$(CONFIG_BPF_LSM) += bpf.o
security/landlock/bpf.c new file +152 -0

152 lines not on this page · raw message

security/landlock/bpf.h new file +21 -0
new file mode 100644
index 000000000000..7c0f199c630a
@@ -0,0 +1,21 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * Landlock - LSM policy object hooks
+ *
+ * Copyright © 2026 Justin Suess <[email protected]>
+ */
+
+#ifndef _SECURITY_LANDLOCK_BPF_H
+#define _SECURITY_LANDLOCK_BPF_H
+
+#include <linux/init.h>
+
+#ifdef CONFIG_BPF_LSM
+__init void landlock_add_bpf_hooks(void);
+#else /* CONFIG_BPF_LSM */
+static inline void landlock_add_bpf_hooks(void)
+{
+}
+#endif /* CONFIG_BPF_LSM */
+
+#endif /* _SECURITY_LANDLOCK_BPF_H */
security/landlock/cred.c +8 -8
index f02706f12c7d..8e5b1b6c165e 100644
@@ -151,11 +151,7 @@ void landlock_apply_restriction(struct landlock_cred_security *const llcred,
 static void hook_cred_transfer(struct cred *const new,
 			       const struct cred *const old)
 {
-	const struct landlock_cred_security *const old_llcred =
-		landlock_cred(old);
-
-	landlock_get_domain(old_llcred->domain);
-	*landlock_cred(new) = *old_llcred;
+	landlock_cred_copy(landlock_cred(new), landlock_cred(old));
 }
 
 static int hook_cred_prepare(struct cred *const new,
@@ -167,10 +163,14 @@ static int hook_cred_prepare(struct cred *const new,
 
 static void hook_cred_free(struct cred *const cred)
 {
-	struct landlock_domain *const dom = landlock_cred(cred)->domain;
+	struct landlock_cred_security *const llcred = landlock_cred(cred);
+
+	landlock_put_domain_deferred(llcred->domain);
 
-	if (dom)
-		landlock_put_domain_deferred(dom);
+#ifdef CONFIG_BPF_LSM
+	/* Releases a restriction staged for an aborted execution. */
+	landlock_put_domain_deferred(llcred->staged.domain);
+#endif /* CONFIG_BPF_LSM */
 }
 
 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
security/landlock/cred.h +16 -0
index 88fa97fc3bd2..9a2971197892 100644
@@ -59,6 +59,16 @@ struct landlock_cred_security {
 	 */
 	struct landlock_domain *domain;
 
+#ifdef CONFIG_BPF_LSM
+	/**
+	 * @staged: Restriction staged by the bprm_apply_policy_object() hook,
+	 * owning its domain reference, applied at bprm_committing_creds().
+	 * Only ever set on credentials prepared for an execution; committed
+	 * task credentials never carry a staged restriction.
+	 */
+	struct landlock_restriction staged;
+#endif /* CONFIG_BPF_LSM */
+
 #ifdef CONFIG_SECURITY_LANDLOCK_LOG
 	/**
 	 * @domain_exec: Bitmask identifying the domain layers that were enforced by
@@ -99,6 +109,12 @@ static inline void landlock_cred_copy(struct landlock_cred_security *dst,
 	*dst = *src;
 
 	landlock_get_domain(src->domain);
+
+#ifdef CONFIG_BPF_LSM
+	/* Only bprm credentials own a staged restriction: never copied. */
+	WARN_ON_ONCE(src->staged.domain);
+	dst->staged = (struct landlock_restriction){};
+#endif /* CONFIG_BPF_LSM */
 }
 
 static inline struct landlock_domain *landlock_get_current_domain(void)
security/landlock/limits.h +4 -0
index 1a7c5fb8f6fd..9aeb99b2f173 100644
@@ -37,6 +37,10 @@
 #define LANDLOCK_LAST_RESTRICT_SELF	LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS
 #define LANDLOCK_MASK_RESTRICT_SELF	((LANDLOCK_LAST_RESTRICT_SELF << 1) - 1)
 
+/* Subset of the restrict-self flags applicable to an execution. */
+#define LANDLOCK_MASK_RESTRICT_BINPRM \
+	(LANDLOCK_MASK_RESTRICT_SELF & ~LANDLOCK_RESTRICT_SELF_TSYNC)
+
 /* clang-format on */
 
 #endif /* _SECURITY_LANDLOCK_LIMITS_H */
security/landlock/ruleset.c +6 -0
index 00a6b9938fd1..6de326b71a5a 100644
@@ -23,6 +23,7 @@
 #include <linux/spinlock.h>
 #include <linux/workqueue.h>
 #include <uapi/linux/landlock.h>
+#include <uapi/linux/lsm.h>
 
 #include "access.h"
 #include "id.h"
@@ -51,6 +52,11 @@ landlock_create_ruleset(const access_mask_t fs_access_mask,
 	mutex_init(&new_ruleset->lock);
 	new_ruleset->rules.root_inode = RB_ROOT;
 
+#ifdef CONFIG_BPF_LSM
+	new_ruleset->policy_object.lsmid = LSM_ID_LANDLOCK;
+	new_ruleset->policy_object.type = LANDLOCK_POLICY_TYPE_RULESET;
+#endif /* CONFIG_BPF_LSM */
+
 #if IS_ENABLED(CONFIG_INET)
 	new_ruleset->rules.root_net_port = RB_ROOT;
 #endif /* IS_ENABLED(CONFIG_INET) */
security/landlock/ruleset.h +22 -0
index 1465f8a5c464..22edb140bb7f 100644
@@ -15,6 +15,7 @@
 #include <linux/mutex.h>
 #include <linux/rbtree.h>
 #include <linux/refcount.h>
+#include <linux/security.h>
 #include <linux/workqueue.h>
 
 #include "access.h"
@@ -146,6 +147,16 @@ struct landlock_rules {
 	u32 num_rules;
 };
 
+#ifdef CONFIG_BPF_LSM
+/*
+ * Landlock's lsm_policy_object types.  The namespace is private to
+ * Landlock; 0 stays reserved as "unset".
+ */
+enum landlock_policy_type {
+	LANDLOCK_POLICY_TYPE_RULESET = 1,
+};
+#endif /* CONFIG_BPF_LSM */
+
 /**
  * struct landlock_ruleset - Landlock ruleset
  *
@@ -157,6 +168,17 @@ struct landlock_ruleset {
 	 * @rules: Red-black tree storage for rules.
 	 */
 	struct landlock_rules rules;
+
+#ifdef CONFIG_BPF_LSM
+	/**
+	 * @policy_object: Identity under which the ruleset is handed out
+	 * to BPF programs as a referenced kptr: the LSM policy kfuncs
+	 * dispatch back to Landlock through its lsmid.  Kept outside the
+	 * union with @work_free: RCU readers may read its lsmid while a
+	 * queued free waits out the grace period.
+	 */
+	struct lsm_policy_object policy_object;
+#endif /* CONFIG_BPF_LSM */
 	/**
 	 * @usage: Number of file descriptors referencing this ruleset.  Kept
 	 * outside the union with @work_free: RCU readers may still call
security/landlock/setup.c +2 -0
index 47dac1736f10..3b7e18edadfb 100644
@@ -11,6 +11,7 @@
 #include <linux/lsm_hooks.h>
 #include <uapi/linux/lsm.h>
 
+#include "bpf.h"
 #include "common.h"
 #include "cred.h"
 #include "errata.h"
@@ -68,6 +69,7 @@ static int __init landlock_init(void)
 	landlock_add_task_hooks();
 	landlock_add_fs_hooks();
 	landlock_add_net_hooks();
+	landlock_add_bpf_hooks();
 	landlock_init_id();
 	landlock_initialized = true;
 	pr_info("Up and running.\n");
Signature · 1 line
2.55.0
#19 lore raw

PATCH v2 14/15 selftests/bpf: Test the LSM policy object kfuncs with Landlock

In reply to Justin Suess

Exercise the policy object kfuncs against an LSM actually providing policy objects, complementing the LSM-independent tests of the verifier-side and from_fd contracts.

The programs mirror the intended usage: a syscall program acquires a Landlock ruleset with bpf_lsm_policy_from_fd() and parks it in a map kptr field; an LSM program on bprm_creds_for_exec() loads the field under bpf_rcu_read_lock(), takes its own reference with bpf_lsm_policy_acquire(), and applies the ruleset with bpf_lsm_policy_apply_bprm(). The prog_tests runner checks that:

- a monitored execution starts confined (a handled-but-not-allowed write fails) while an unmonitored one is untouched,
- two concurrent monitored executions are both restricted from the one shared map slot,
- the landlock_restrict_self(2) log flags are accepted while LANDLOCK_RESTRICT_SELF_TSYNC is rejected with -EINVAL and leaves the execution unrestricted,
- LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS makes the executed program start with no_new_privs set, while an execution without it stays non-nnp,
- a second apply call on the same execution replaces the staged restriction rather than failing,
- an execution failing past the bprm hook (ENOEXEC) discards the staged restriction and leaves the caller unconfined,
- the object's identity is BTF-readable off the trusted kptr: the LSM-private type tag is nonzero, and the lsmid is LSM_ID_LANDLOCK with the fd alone having routed the translation,
- the bprm application emits a single landlock_enforce_domain event, observed by a tp_btf program: complete == 1, process_wide == 1, and no_new_privs reporting the post-flag state.

---
 tools/testing/selftests/bpf/config            |   1 +
 tools/testing/selftests/bpf/config.x86_64     |   2 +-
 .../bpf/prog_tests/lsm_policy_landlock.c      | 522 ++++++++++++++++++
 .../selftests/bpf/progs/lsm_policy_landlock.c | 142 +++++
 4 files changed, 666 insertions(+), 1 deletion(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/lsm_policy_landlock.c
 create mode 100644 tools/testing/selftests/bpf/progs/lsm_policy_landlock.c
tools/testing/selftests/bpf/config +1 -0
index ea7044f30adc..2fa734497461 100644
@@ -120,6 +120,7 @@ CONFIG_SAMPLES=y
 CONFIG_SAMPLE_LIVEPATCH=m
 CONFIG_SECURITY=y
 CONFIG_SECURITYFS=y
+CONFIG_SECURITY_LANDLOCK=y
 CONFIG_SYN_COOKIES=y
 CONFIG_TEST_BPF=m
 CONFIG_UDMABUF=y
tools/testing/selftests/bpf/config.x86_64 +1 -1
index 42ad817b00ae..13ca4906b67f 100644
@@ -126,7 +126,7 @@ CONFIG_LEGACY_VSYSCALL_NONE=y
 CONFIG_LOG_BUF_SHIFT=21
 CONFIG_LOG_CPU_MAX_BUF_SHIFT=0
 CONFIG_LOGO=y
-CONFIG_LSM="selinux,bpf,integrity"
+CONFIG_LSM="landlock,selinux,bpf,integrity"
 CONFIG_MAC_PARTITION=y
 CONFIG_MAGIC_SYSRQ=y
 CONFIG_MCORE2=y
tools/testing/selftests/bpf/prog_tests/lsm_policy_landlock.c new file +522 -0

522 lines not on this page · raw message

tools/testing/selftests/bpf/progs/lsm_policy_landlock.c new file +142 -0

142 lines not on this page · raw message

Signature · 1 line
2.55.0
#22 lore raw

PATCH v2 15/15 landlock: Document the BPF policy interface

In reply to Justin Suess

Describe how the generic LSM policy kfuncs apply to Landlock
rulesets: the program-side flow, the staged restriction and its trace event, the LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS semantics on an execution, and why the bprm path carries no no_new_privs/ CAP_SYS_ADMIN precondition. Note the new emission point in the trace events overview.

Cc Mickaël Salaün <[email protected]>
---
 Documentation/security/landlock.rst     | 38 +++++++++++++++++++++++++
 Documentation/trace/events-landlock.rst |  5 +++-
 2 files changed, 42 insertions(+), 1 deletion(-)
Documentation/security/landlock.rst +38 -0
index 2d6e1076484e..ddc0d149ae8f 100644
@@ -130,6 +130,44 @@ The reasoning is:
   restrictions, because access within the same scope is already
   allowed based on ``LANDLOCK_ACCESS_FS_RESOLVE_UNIX``.
 
+BPF kfuncs
+==========
+
+BPF programs can apply a userspace-created Landlock ruleset to an
+execution, through the generic LSM policy kfuncs (see
+Documentation/security/lsm-development.rst).  A syscall program
+(``BPF_PROG_TYPE_SYSCALL``), running in the context of the process
+that set the ruleset up, acquires the ruleset with
+``bpf_lsm_policy_from_fd()`` and typically hands it over through a
+map kptr field; a sleepable LSM BPF program attached to the
+``bprm_creds_for_exec`` or ``bprm_creds_from_file`` hooks then
+enforces it on an execution with ``bpf_lsm_policy_apply_bprm()``.
+
+The restriction is staged in the Landlock blob of the credentials
+prepared for the execution and committed past the exec point of no
+return, so a failed execution leaves the calling task untouched.  The
+commitment emits the ``landlock_enforce_domain`` trace event (see
+Documentation/trace/events-landlock.rst).  The kfunc flags take the
+``landlock_restrict_self(2)`` flags with their usual semantics, with
+the exception of ``LANDLOCK_RESTRICT_SELF_TSYNC``, which is rejected:
+the restriction targets the execution, not the calling threads.
+
+``LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS`` makes the executed program
+start with no_new_privs set, binding it and all its descendants.  It
+does not affect the current execution's privilege computation: the
+bprm credentials, including any setuid elevation, are computed before
+the flag is set.
+
+Unlike ``landlock_restrict_self(2)``, the bprm path has no
+no_new_privs/``CAP_SYS_ADMIN`` precondition: a task that is not
+no_new_privs can carry a BPF-applied domain, and its setuid
+executions still elevate while confined.  This is sound because
+attaching the BPF program is itself privileged, granting the same
+power as the syscall's ``CAP_SYS_ADMIN`` carve-out.
+
+Executions may run concurrently: each takes its own reference on
+the shared ruleset with ``bpf_lsm_policy_acquire()``.
+
 Tests
 =====
 
Documentation/trace/events-landlock.rst +4 -1
index af9267cca47d..6cec3194af0b 100644
@@ -34,7 +34,10 @@ Landlock trace events are organized in four categories:
 - ``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
+- ``landlock_enforce_domain``: a domain is enforced on a thread.  Also
+  emitted at ``execve(2)``'s point of no return when a BPF program has
+  staged a policy on the execution (see the BPF kfuncs section of
+  Documentation/security/landlock.rst)
 
 **Denial events** are emitted when an access is denied:
 
Signature · 1 line
2.55.0
#2 lore raw

Re: [PATCH v2 01/15] lsm: Add the LSM policy object lifetime hooks

In reply to Justin Suess
Quoted 3 lines · Justin Suess

Add struct lsm_policy_object, the identity an LSM embeds in a policy object it shares with BPF programs, and the three hooks managing such an object's lifetime:

I am not seeing the cover letter for this patch set. Are you sending it to the LSM list? Without that I do not have sufficient context to comment on the patches (1,2,3 and 8) that you have sent.

What I do see has me quite concerned. It's possible the cover letter will addresses my issues. If nothing else, I assume it describes what a "policy object" is, and what it's for.

#3 lore raw

Re: [PATCH v2 01/15] lsm: Add the LSM policy object lifetime hooks

Quoted 5 lines · Casey Schaufler
Quoted 3 lines · Justin Suess

Add struct lsm_policy_object, the identity an LSM embeds in a policy object it shares with BPF programs, and the three hooks managing such an object's lifetime:

Quoted 8 lines

I am not seeing the cover letter for this patch set. Are you sending it to the LSM list? Without that I do not have sufficient context to comment on the patches (1,2,3 and 8) that you have sent.

What I do see has me quite concerned. It's possible the cover letter will addresses my issues. If nothing else, I assume it describes what a "policy object" is, and what it's for.

Indeed it did get sent to linux-security-module, it's up on lore as such.

https://lore.kernel.org/linux-security-module/[email protected]/

Possibly got caught in your spam filter?

Indeed it does provide important context about lsm_policy_object.

Thanks,
Justin

#20 lore raw

Re: [PATCH v2 14/15] selftests/bpf: Test the LSM policy object kfuncs with Landlock

In reply to Justin Suess
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] File descriptors leak on the error path in test_restrict_binprm_discard(). --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] File descriptors leak on the error path in test_restrict_binprm_discard(). --

commit 7fa3010dd885254cc82b6aa2f6f254ee83a13717
Author: Justin Suess <[email protected]>

selftests/bpf: Test the LSM policy object kfuncs with Landlock

This commit adds tests for LSM policy object kfuncs interacting with Landlock. It tests execution confinement, audit log flags, and concurrent application using a syscall program and BPF RCU lock management.

Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/lsm_policy_landlock.c new file +0 -0
new file mode 100644
index 0000000000000..9270b39f5e3a7

[ ... ]

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/lsm_policy_landlock.c new file +10 -0
+static void test_restrict_binprm_discard(void)
+{
+	struct policy_test_env env;
+	char garbage_path[] = "/tmp/lsm_policy_garbage_XXXXXX";
+	int garbage_fd, pipe_fds[2];
+	char buf = 0;
+	pid_t pid;
+
+	if (setup_env(&env))
+		goto out;

[ ... ]

tools/testing/selftests/bpf/prog_tests/lsm_policy_landlock.c line 392

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/lsm_policy_landlock.c new file +10 -0
+	if (!ASSERT_OK(pipe(pipe_fds), "pipe"))
+		goto out_unlink;
+
+	/*
+	 * Cannot use spawn_exec_child(): the same process must test its
+	 * write access after the failed exec.
+	 */
+	pid = fork();
+	if (!ASSERT_GE(pid, 0, "fork"))
+		goto out_unlink;

[Severity: Low]
Does this code leak the file descriptors created by pipe() if fork() fails?

If fork() fails here, the code jumps directly to the out_unlink label, and it appears neither pipe_fds[0] nor pipe_fds[1] are closed before exiting the function.

The spawn_exec_child() helper function introduced in this same commit properly closes both descriptors on fork failure. Should similar cleanup be added here?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
#21 lore raw

Re: [PATCH v2 14/15] selftests/bpf: Test the LSM policy object kfuncs with Landlock

Quoted 44 lines · On Mon, Aug 31, 2026 at 07:53:26PM +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] File descriptors leak on the error path in test_restrict_binprm_discard(). --

commit 7fa3010dd885254cc82b6aa2f6f254ee83a13717
Author: Justin Suess <[email protected]>

selftests/bpf: Test the LSM policy object kfuncs with Landlock

This commit adds tests for LSM policy object kfuncs interacting with Landlock. It tests execution confinement, audit log flags, and concurrent application using a syscall program and BPF RCU lock management.

Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/lsm_policy_landlock.c new file +0 -0
new file mode 100644
index 0000000000000..9270b39f5e3a7

[ ... ]

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/lsm_policy_landlock.c new file +10 -0
+static void test_restrict_binprm_discard(void)
+{
+	struct policy_test_env env;
+	char garbage_path[] = "/tmp/lsm_policy_garbage_XXXXXX";
+	int garbage_fd, pipe_fds[2];
+	char buf = 0;
+	pid_t pid;
+
+	if (setup_env(&env))
+		goto out;

[ ... ]

tools/testing/selftests/bpf/prog_tests/lsm_policy_landlock.c line 392

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/lsm_policy_landlock.c new file +10 -0
+	if (!ASSERT_OK(pipe(pipe_fds), "pipe"))
+		goto out_unlink;
+
+	/*
+	 * Cannot use spawn_exec_child(): the same process must test its
+	 * write access after the failed exec.
+	 */
+	pid = fork();
+	if (!ASSERT_GE(pid, 0, "fork"))
+		goto out_unlink;

[Severity: Low]
Does this code leak the file descriptors created by pipe() if fork() fails?

Quoted 7 lines

If fork() fails here, the code jumps directly to the out_unlink label, and it appears neither pipe_fds[0] nor pipe_fds[1] are closed before exiting the function.

The spawn_exec_child() helper function introduced in this same commit properly closes both descriptors on fork failure. Should similar cleanup be added here?

Will fix.

I think that's sashiko's only nit for this patchset.

https://sashiko.dev/#/patchset/[email protected]

The BPF CI AI review bot didn't run on this since the patchset can't based on a bpf tree until it catches up to the recent Landlock changes.

Justin

Quoted 2 lines
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
#4 lore raw

Re: [PATCH v2 01/15] lsm: Add the LSM policy object lifetime hooks

In reply to Justin Suess
Quoted 71 lines · Justin Suess

Add struct lsm_policy_object, the identity an LSM embeds in a policy object it shares with BPF programs, and the three hooks managing such an object's lifetime:

policy_object_from_fd(fd, &object)
policy_object_get(object)
policy_object_put(object)

The object records the owning LSM's LSM_ID_* value. The BPF kfuncs built on these hooks dispatch each call on an object to the one LSM matching its lsmid, which resolves the containing object with container_of(); the framework never interprets an object beyond its lsmid. The type field discriminates between the owning LSM's own policy object kinds and is private to it, with 0 reserved as "unset" so a zeroed, untagged object fails every type check.

from_fd has no object to route by: the fd refers to a file set up through the owning LSM's own userspace interface, so the fd itself identifies its LSM. The framework offers the fd to every implementation in turn; an LSM declines a fd that is not one of its policy objects with -EOPNOTSUPP, and any other error is a definitive translation failure.

The hooks back referenced BPF kptrs, which imposes the same lifetime contract on every implementation: from_fd returns a reference on a live object, get acquires with inc-not-zero semantics and fails with -ENOENT once the count dropped to zero, put may be called from contexts that cannot sleep (BPF drives it from map destructors), and the containing object is freed only after an RCU grace period, as programs load policy object kptrs from maps under RCU and may examine an object concurrently with its last put.

The hooks are excluded from the "bpf" LSM's attachment points. The object-routed hooks are unreachable there, as LSM_ID_BPF policy objects cannot exist; for from_fd, whose walk visits every implementation, a BPF program cannot fill the object out parameter, so an attachment returning 0 would hand the caller an uninitialized pointer.

Cc Paul Moore <[email protected]>
Cc Casey Schaufler <[email protected]>
---
 include/linux/lsm_hook_defs.h |  4 ++++
 include/linux/security.h      | 11 +++++++++++
 kernel/bpf/bpf_lsm.c          |  3 +++
 3 files changed, 18 insertions(+)
include/linux/lsm_hook_defs.h +4 -0
index 65c9609ec207..d7684407737a 100644
@@ -452,6 +452,10 @@ LSM_HOOK(int, 0, bpf_token_create, struct bpf_token *token, union bpf_attr *attr
 LSM_HOOK(void, LSM_RET_VOID, bpf_token_free, struct bpf_token *token)
 LSM_HOOK(int, 0, bpf_token_cmd, const struct bpf_token *token, enum bpf_cmd cmd)
 LSM_HOOK(int, 0, bpf_token_capable, const struct bpf_token *token, int cap)
+LSM_HOOK(int, -EOPNOTSUPP, policy_object_from_fd, int fd,
+	 struct lsm_policy_object **object)
+LSM_HOOK(int, -EOPNOTSUPP, policy_object_get, struct lsm_policy_object *object)
+LSM_HOOK(void, LSM_RET_VOID, policy_object_put, struct lsm_policy_object *object)
 #endif /* CONFIG_BPF_SYSCALL */
 
 LSM_HOOK(int, 0, locked_down, enum lockdown_reason what)
include/linux/security.h +0 -0
index 153e9043058f..5e423bea080e 100644
@@ -168,6 +168,17 @@ struct lsm_prop {
 	struct lsm_prop_bpf bpf;
 };
 

include/linux/security.h struct lsm_prop { · line 180

Quoted 10 lines
include/linux/security.h +10 -0
+/*
+ * Identity of a policy object an LSM shares with BPF programs,
+ * embedded in the LSM's own object.  @lsmid identifies the owning
+ * LSM; @type discriminates that LSM's policy object types, with 0
+ * reserved as "unset".
+ */
+struct lsm_policy_object {
+	u64 lsmid;
+	u32 type;
+};

For some clarity:

lsm_policy_object is just a handle to a refcounted lsm-private struct.

It can't be forged / created manually because it's a trusted kernel pointer, so the only way to get it is through policy_object_from_fd. And you cannot mutate any part of it from BPF.

But it's what enables the generic model. Calling it a "policy object" may be short sighted though, that term is heavily overloaded in the LSM space. I don't want to prescribe any restrictions on what an LSM can use it for, after all some LSM have no notion of "policy" at all or have a different meaning for it.

For SELinux, this "lsm_policy_object" could be an sid, for AppArmor an aa_label, for Smack a label, etc. The intention was to allow writing programs that don't care about any details of a particular LSM.

Justin

Quoted 21 lines
include/linux/security.h +1 -0
+
 extern const char *const lockdown_reasons[LOCKDOWN_CONFIDENTIALITY_MAX+1];
 
 /* These functions are in security/commoncap.c */
kernel/bpf/bpf_lsm.c +3 -0
index 1433809bb166..d06744d72e04 100644
@@ -56,6 +56,9 @@ BTF_ID(func, bpf_lsm_xfrm_decode_session)
 #endif
 BTF_ID(func, bpf_lsm_ismaclabel)
 BTF_ID(func, bpf_lsm_file_alloc_security)
+BTF_ID(func, bpf_lsm_policy_object_from_fd)
+BTF_ID(func, bpf_lsm_policy_object_get)
+BTF_ID(func, bpf_lsm_policy_object_put)
 BTF_SET_END(bpf_lsm_disabled_hooks)
 
 /* List of LSM hooks that should operate on 'current' cgroup regardless
Signature · 1 line
2.55.0
#5 lore raw

Re: [PATCH v2 01/15] lsm: Add the LSM policy object lifetime hooks

Quoted 96 lines · Justin Suess
Quoted 71 lines · Justin Suess

Add struct lsm_policy_object, the identity an LSM embeds in a policy object it shares with BPF programs, and the three hooks managing such an object's lifetime:

policy_object_from_fd(fd, &object)
policy_object_get(object)
policy_object_put(object)

The object records the owning LSM's LSM_ID_* value. The BPF kfuncs built on these hooks dispatch each call on an object to the one LSM matching its lsmid, which resolves the containing object with container_of(); the framework never interprets an object beyond its lsmid. The type field discriminates between the owning LSM's own policy object kinds and is private to it, with 0 reserved as "unset" so a zeroed, untagged object fails every type check.

from_fd has no object to route by: the fd refers to a file set up through the owning LSM's own userspace interface, so the fd itself identifies its LSM. The framework offers the fd to every implementation in turn; an LSM declines a fd that is not one of its policy objects with -EOPNOTSUPP, and any other error is a definitive translation failure.

The hooks back referenced BPF kptrs, which imposes the same lifetime contract on every implementation: from_fd returns a reference on a live object, get acquires with inc-not-zero semantics and fails with -ENOENT once the count dropped to zero, put may be called from contexts that cannot sleep (BPF drives it from map destructors), and the containing object is freed only after an RCU grace period, as programs load policy object kptrs from maps under RCU and may examine an object concurrently with its last put.

The hooks are excluded from the "bpf" LSM's attachment points. The object-routed hooks are unreachable there, as LSM_ID_BPF policy objects cannot exist; for from_fd, whose walk visits every implementation, a BPF program cannot fill the object out parameter, so an attachment returning 0 would hand the caller an uninitialized pointer.

Cc Paul Moore <[email protected]>
Cc Casey Schaufler <[email protected]>
---
 include/linux/lsm_hook_defs.h |  4 ++++
 include/linux/security.h      | 11 +++++++++++
 kernel/bpf/bpf_lsm.c          |  3 +++
 3 files changed, 18 insertions(+)
include/linux/lsm_hook_defs.h +4 -0
index 65c9609ec207..d7684407737a 100644
@@ -452,6 +452,10 @@ LSM_HOOK(int, 0, bpf_token_create, struct bpf_token *token, union bpf_attr *attr
 LSM_HOOK(void, LSM_RET_VOID, bpf_token_free, struct bpf_token *token)
 LSM_HOOK(int, 0, bpf_token_cmd, const struct bpf_token *token, enum bpf_cmd cmd)
 LSM_HOOK(int, 0, bpf_token_capable, const struct bpf_token *token, int cap)
+LSM_HOOK(int, -EOPNOTSUPP, policy_object_from_fd, int fd,
+	 struct lsm_policy_object **object)
+LSM_HOOK(int, -EOPNOTSUPP, policy_object_get, struct lsm_policy_object *object)
+LSM_HOOK(void, LSM_RET_VOID, policy_object_put, struct lsm_policy_object *object)
 #endif /* CONFIG_BPF_SYSCALL */
 
 LSM_HOOK(int, 0, locked_down, enum lockdown_reason what)
include/linux/security.h +0 -0
index 153e9043058f..5e423bea080e 100644
@@ -168,6 +168,17 @@ struct lsm_prop {
 	struct lsm_prop_bpf bpf;
 };
 

include/linux/security.h struct lsm_prop { · line 180

Quoted 10 lines
include/linux/security.h +10 -0
+/*
+ * Identity of a policy object an LSM shares with BPF programs,
+ * embedded in the LSM's own object.  @lsmid identifies the owning
+ * LSM; @type discriminates that LSM's policy object types, with 0
+ * reserved as "unset".
+ */
+struct lsm_policy_object {
+	u64 lsmid;
+	u32 type;
+};

For some clarity:

lsm_policy_object is just a handle to a refcounted lsm-private struct.

It can't be forged / created manually because it's a trusted kernel pointer, so the only way to get it is through policy_object_from_fd. And you cannot mutate any part of it from BPF.

But it's what enables the generic model. Calling it a "policy object" may be short sighted though, that term is heavily overloaded in the LSM space. I don't want to prescribe any restrictions on what an LSM can use it for, after all some LSM have no notion of "policy" at all or have a different meaning for it.

Quoted 3 lines

For SELinux, this "lsm_policy_object" could be an sid, for AppArmor an aa_label, for Smack a label, etc. The intention was to allow writing programs that don't care about any details of a particular LSM.

Why aren't you using an lsm_prop pointer? What if the operation you're planning to perform is relevant to multiple active LSMs? Today you can't use SELinux and AppArmor together on an upstream Linus kernel, but that should be changing sometime this decade.

#6 lore raw

Re: [PATCH v2 01/15] lsm: Add the LSM policy object lifetime hooks

Quoted 97 lines · Casey Schaufler
Quoted 96 lines · Justin Suess
Quoted 71 lines · Justin Suess

Add struct lsm_policy_object, the identity an LSM embeds in a policy object it shares with BPF programs, and the three hooks managing such an object's lifetime:

policy_object_from_fd(fd, &object)
policy_object_get(object)
policy_object_put(object)

The object records the owning LSM's LSM_ID_* value. The BPF kfuncs built on these hooks dispatch each call on an object to the one LSM matching its lsmid, which resolves the containing object with container_of(); the framework never interprets an object beyond its lsmid. The type field discriminates between the owning LSM's own policy object kinds and is private to it, with 0 reserved as "unset" so a zeroed, untagged object fails every type check.

from_fd has no object to route by: the fd refers to a file set up through the owning LSM's own userspace interface, so the fd itself identifies its LSM. The framework offers the fd to every implementation in turn; an LSM declines a fd that is not one of its policy objects with -EOPNOTSUPP, and any other error is a definitive translation failure.

The hooks back referenced BPF kptrs, which imposes the same lifetime contract on every implementation: from_fd returns a reference on a live object, get acquires with inc-not-zero semantics and fails with -ENOENT once the count dropped to zero, put may be called from contexts that cannot sleep (BPF drives it from map destructors), and the containing object is freed only after an RCU grace period, as programs load policy object kptrs from maps under RCU and may examine an object concurrently with its last put.

The hooks are excluded from the "bpf" LSM's attachment points. The object-routed hooks are unreachable there, as LSM_ID_BPF policy objects cannot exist; for from_fd, whose walk visits every implementation, a BPF program cannot fill the object out parameter, so an attachment returning 0 would hand the caller an uninitialized pointer.

Cc Paul Moore <[email protected]>
Cc Casey Schaufler <[email protected]>
---
 include/linux/lsm_hook_defs.h |  4 ++++
 include/linux/security.h      | 11 +++++++++++
 kernel/bpf/bpf_lsm.c          |  3 +++
 3 files changed, 18 insertions(+)
include/linux/lsm_hook_defs.h +4 -0
index 65c9609ec207..d7684407737a 100644
@@ -452,6 +452,10 @@ LSM_HOOK(int, 0, bpf_token_create, struct bpf_token *token, union bpf_attr *attr
 LSM_HOOK(void, LSM_RET_VOID, bpf_token_free, struct bpf_token *token)
 LSM_HOOK(int, 0, bpf_token_cmd, const struct bpf_token *token, enum bpf_cmd cmd)
 LSM_HOOK(int, 0, bpf_token_capable, const struct bpf_token *token, int cap)
+LSM_HOOK(int, -EOPNOTSUPP, policy_object_from_fd, int fd,
+	 struct lsm_policy_object **object)
+LSM_HOOK(int, -EOPNOTSUPP, policy_object_get, struct lsm_policy_object *object)
+LSM_HOOK(void, LSM_RET_VOID, policy_object_put, struct lsm_policy_object *object)
 #endif /* CONFIG_BPF_SYSCALL */
 
 LSM_HOOK(int, 0, locked_down, enum lockdown_reason what)
include/linux/security.h +0 -0
index 153e9043058f..5e423bea080e 100644
@@ -168,6 +168,17 @@ struct lsm_prop {
 	struct lsm_prop_bpf bpf;
 };
 

include/linux/security.h struct lsm_prop { · line 180

Quoted 10 lines
include/linux/security.h +10 -0
+/*
+ * Identity of a policy object an LSM shares with BPF programs,
+ * embedded in the LSM's own object.  @lsmid identifies the owning
+ * LSM; @type discriminates that LSM's policy object types, with 0
+ * reserved as "unset".
+ */
+struct lsm_policy_object {
+	u64 lsmid;
+	u32 type;
+};

For some clarity:

lsm_policy_object is just a handle to a refcounted lsm-private struct.

It can't be forged / created manually because it's a trusted kernel pointer, so the only way to get it is through policy_object_from_fd. And you cannot mutate any part of it from BPF.

But it's what enables the generic model. Calling it a "policy object" may be short sighted though, that term is heavily overloaded in the LSM space. I don't want to prescribe any restrictions on what an LSM can use it for, after all some LSM have no notion of "policy" at all or have a different meaning for it.

Quoted 5 lines
Quoted 3 lines

For SELinux, this "lsm_policy_object" could be an sid, for AppArmor an aa_label, for Smack a label, etc. The intention was to allow writing programs that don't care about any details of a particular LSM.

Why aren't you using an lsm_prop pointer? What if the operation you're

So lsm_prop from my understanding allows multiple LSMs to store their data for one *shared* kernel object in a structured way. (i.e one object; multiple lsms using it)

lsm_policy_object is sort of the opposite case:

In this case, the object is *owned* by a particular LSM. Think a Landlock ruleset, smack label, or aa_label etc, that could never foreeably have a semantic meaning to other LSM.

Quoted 4 lines

planning to perform is relevant to multiple active LSMs? Today you can't use SELinux and AppArmor together on an upstream Linus kernel, but that should be changing sometime this decade.

The object is not relevant to other LSMs by construction. The lsm_policy_object is an lsm internal object, specific to the LSM.

You'd never make an lsm_policy_object for an inode, dentry, socket, etc.

So if you wanted to use LSM A and LSM B with this API, you'd need to acquire each of their policy objects in turn. But you apply them both with the same API, without having to care about LSM details.

Justin