Enforcing Rulesets via eBPF
I propose allowing extending eBPF to allow LSM programs to select and enforce an unmerged Landlock ruleset at exec time.
The key idea is simple: Landlock rulesets would still be created in userspace through the normal Landlock API, but an eBPF program could decide at runtime to apply to a ruleset to an arbitrary process before that process starts executing (ie bprm_creds_for_exec). This would make Landlock usable in places where the target application cannot realistically apply its own restrictions. This could be achieved through a helper function or kfunc.
To be frank, this proposal is a significant divergence from existing Landlock features. eBPF is privileged. Landlock is explicitly designed around being usable from an unprivileged context. So this proposal justifiably should face strong scrutiny for that alone.
But I think eBPF and Landlock would work well together. Both are logically driven kernel features. The programmatic nature of eBPF is a good fit for Landlock, a programmatic LSM.
Background
Linux already has several mechanisms for system-wide access control, mostly in the traditional MAC LSM family (Smack, Tomoyo, SELinux, AppArmor). These systems generally rely on administrator-defined policy, with most of the decision logic living in the LSM itself or in dedicated userspace tooling.
Landlock is different. It is a developer-oriented API: the application builds a ruleset and then restricts itself. That is one of Landlock's strengths. It avoids central policy complexity and keeps the model understandable for application developers, and easy to compose.
But that same design also creates a gap: Landlock is hard to use when the process being sandboxed is not under first-party control.
Where Landlock fits poorly today
Third-party / non-Landlocked binaries
There are many cases where the program being executed is not written to use Landlock directly.
That includes:
- third-party binaries
- legacy or unmaintained software
- programs launched indirectly through wrappers, shells, or service managers.
- trusted container images that can't be modified without breaking the chain of trust.
Today, external Landlock-based sandboxing usually means one of two things:
- wrapping the target executable and applying a ruleset before launching it (Landrun, Firejail)
- trying to precompute a profile that includes every file, library, and configuration path the program may need (Island)
Both approaches are fragile. A launcher of an arbitrary process cannot fully predict what files a program will need at runtime, especially across different systems, distributions, and deployment layouts.
Deep process trees
Landlock's inheritance model is intentionally one-way: once a task is restricted, descendants inherit that domain and can only become more restricted.
That works well when the process tree is fully controlled by the application or supervisor. It works much less well when the interesting target is buried inside a larger tree that includes helper processes, init shims, interpreters, or container runtime glue.
The problem is attaching the right ruleset to the right program at the right moment, without also constraining unrelated parents or intermediaries.
Proposal
The proposal is to let a privileged eBPF policy enforce a pre-created Landlock ruleset during exec.
Conceptually, this would work like this:
- a privileged userspace component creates one or more Landlock rulesets ahead of time
- eBPF stores them as refcounted __kptr objects in a map. (acquiring a reference)
- an eBPF policy observes process execution in an exec-time security hook
- the eBPF policy decides, using runtime context, whether a particular ruleset should be applied
- if it does, the new program starts with that Landlock restriction in place
The important point is that eBPF would not define a new access-control model here. It would only choose when to apply an already valid Landlock policy created through existing APIs
Why eBPF
eBPF is useful here because it can make context-sensitive decisions without forcing Landlock itself to grow a large policy language.
That decision logic could consider information such as:
- executable path
- cgroup or container context
- task ancestry or launcher identity
- service manager metadata
- custom userspace-managed state
This keeps Landlock focused on what it already does well, enforcement, while letting privileged eBPF programs decide where it should be used.
Semantics
This proposal should preserve Landlock's core semantics. Inheritence, domain merging, and layering are unchanged and behave no differently whether enforced through eBPF or landlock_restrict_self.
The intended model is:
- only existing Landlock rulesets can be applied. No ruleset composition or other API duplication into eBPF
- eBPF enforces a ruleset only. It does not mutate rulesets or have visibility into them
- enforcement happens before the new program begins executing
- the resulting restrictions are no weaker than if an appropriate parent process had imposed them directly
- rulesets would be fully composed with future and existing rulesets, and exist as normal once execution begins.
In other words, this should behave as an external target-selection mechanism for Landlock, not as a separate access right or policy construct.
Use cases
Container runtimes
A container runtime could apply Landlock rulesets to programs inside existing images without requiring those application images to be Landlock-aware. (For example, allow the nginx process in this container to bind only to port 80).
Sandboxing tools
External sandbox launchers could choose policies based on runtime context instead of relying entirely on wrapper scripts and static path prediction. These capabilities could be delegated to unprivileged users to manage their own resources.
EDR tools
EDR tools could enforce Landlock policies on executables based on arbitrary logic, regardless of the process's parentage.
Tradeoffs
-
Privileged requirements. This API involves inspecting and mutating system wide credentials. This is fundamentally a privileged operation, and diverges significantly from existing semantics.
-
This proposal is cross-subsystem.
This isn't a proposal that can be implemented unilaterally, the eBPF folks would need a say in this too. This means more approvals and restrictions and waiting for feedback.
- Lack of existing eBPF/in-kernel LSM integration.
There are no integrations between eBPF and any in-kernel LSM (with the notable exception of IMA and the BPF LSM itself). This is mostly uncharted waters.
Why not just make an eBPF LSM?
Landlocks semantics are extremely difficult to impossible to implement in pure eBPF. Correct me if I'm wrong, but I think Landlock originally moved away from eBPF for this reason among others (before becoming a native mainline LSM).
eBPF programs are subject to limitations imposed by the verifier, making implementation of complex logic like domain inheritance, merging trees, and inspection of paths and mountpoints non-trivial.
Allowing eBPF LSMs to use Landlock as a safe, well-tested enforcement engine would make them much more powerful.
POC
I have a simple POC for this, with the implementation being about a ~400 LOC addition. (It ended up suprisingly small).
TLDR;
Userspace:
bpf_map_update_elem(ruleset_map, &key, // key is just an u32 index
ruleset_fd, BPF_ANY); // FD is converted into a refcounted __kptr.
// refcounted by ebpf, and a ref is acquired on the landlock_ruleset.
eBPF:
struct bpf_landlock_ruleset* ruleset = bpf_map_lookup_elem(&ruleset_map, &key);
// in bprm_creds_for_exec(struct linux_binprm *bprm)
bpf_landlock_restrict_binprm(bprm, ruleset, FLAGS); //restriction is applied at execution through a kfunc.
Conclusion
I originally intended this for a personal usecase, which my implementation filled. Feel free to NACK all of this if you don't think it's a good fit 🙂. Some details are omitted here for brevity, I will post the POC on the list as a proper RFC if desired.
I like this idea, that would be very powerful!
FYI, there is also a (partial) alternative approach: #43 (restrictions that only apply after anexecve(2) call), but that would not really cover your use cases.
- a privileged userspace component creates one or more Landlock rulesets ahead of time
It may not need to be privileged, just to have access to a map (tied to an eBPF program loaded by a privileged process).
- eBPF stores them as refcounted __kptr objects in a map. (acquiring a reference)
It would be nice to properly pass Landlock ruleset FDs through eBPF maps so that eBPF programs can reference them, something like a BPF_MAP_TYPE_LANDLOCK_RULESET.
- an eBPF policy observes process execution in an exec-time security hook
- the eBPF policy decides, using runtime context, whether a particular ruleset should be applied
- if it does, the new program starts with that Landlock restriction in place
That would make sense.
In other words, this should behave as an external target-selection mechanism for Landlock, not as a separate access right or policy construct.
Agreed, and it fits with Landlock's model. The eBPF part is fundamentally privileged, but that's required to get useful context.
An alternative would be to have a new landlock_restrict_process() syscall taking a pidfd as argument. The downside of such syscall is that it might be easy to break processes while sandboxing them in the midle of something. So, it would be much safer to restrict on the next execve() call, but we would need to have some context to make an informed decision. For this use case, I think your proposal is simpler and more flexible.
BTW, I'm working on #47 and plan to send a new version next week. The common point is that (tracepoint) eBPF programs would be able to monitor some Landlock states. Both approaches would be complementary.
External sandbox launchers could choose policies based on runtime context instead of relying entirely on wrapper scripts and static path prediction. These capabilities could be delegated to unprivileged users to manage their own resources.
They could be delegated to unprivileged users but this is a slippery path that could lead to vulnerabilites, so this approach should be carefuly considered.
Landlocks semantics are extremely difficult to impossible to implement in pure eBPF. Correct me if I'm wrong, but I think Landlock originally moved away from eBPF for this reason among others (before becoming a native mainline LSM).
Right, I initially developed Landlock as an extension to eBPF, but that didn't fit well with the unprivileged model and it would have been very difficult to get strong security guarantees (and audit/compare them) because of the programmatic approach of eBPF. That led to (the current) Landlock and BPF LSM.
Of course, the main goal of Landlock would stay the same: be accessible to unprivileged users. But, that doesn't mean that privileged processes/eBPF programs cannot use it as well.
Working tree (extremely rough draft / unready): https://github.com/RazeLighter777/linux/tree/landlockebpf6
@l0kod I have some design decisions.
Unlike the MAC attach type for LSM BPF, where it is safe to sleep normally, CGROUP takes place under RCU which is incompatible with existing landlock merge logic.
Would you prefer to refactor the merge logic to be RCU safe or would you rather exclude programs with an attach type CGROUP? (leaning towards latter)
I also am mandating sleepable hooks because merge logic might sleep.
TSYNC doesn't really make sense from the context of pre-execution. I'm returning EINVAL if this flag is passed to bpf_landlock_restrict_binprm (my bpf function kfunc analog for restrict_self)
Is that ok or would you rather ignore the value?
Would you rather have selftests live under BPF or landlock selftests? leaning towards BPF since they have an existing harness.
How to handle no new privs? I need to find out if you can set that in the binprm_creds_for_exec...
@l0kod I have some design decisions.
Unlike the MAC attach type for LSM BPF, where it is safe to sleep normally, CGROUP takes place under RCU which is incompatible with existing landlock merge logic.
Would you prefer to refactor the merge logic to be RCU safe or would you rather exclude programs with an attach type CGROUP? (leaning towards latter)
Hmm, unfortunately we cannot create a domain under RCU, especially because of the memory allocation.
About the cgroups, what would be the use case? Would it be safe? Can we use (or add) an LSM hook instead?
I also am mandating sleepable hooks because merge logic might sleep.
Right.
TSYNC doesn't really make sense from the context of pre-execution. I'm returning EINVAL if this flag is passed to bpf_landlock_restrict_binprm (my bpf function kfunc analog for restrict_self)
Is that ok or would you rather ignore the value?
I guess -EINVAL is the correct approach here. @gnoack ?
Would you rather have selftests live under BPF or landlock selftests? leaning towards BPF since they have an existing harness.
Yes, BPF tests should be with the other BPF tests. They only need to test edge cases that are specific to Landlock with eBPF (e.g. basic access control, valid/invalid flags, nested enforcement up to the limit).
Please try to make them extensible. I'd like to add tests for the tracepoints/eBPF too at a later time.
How to handle no new privs? I need to find out if you can set that in the binprm_creds_for_exec...
This needs careful consideration indeed. I see two approaches:
- Add new prctl and capget helpers: that seems too much.
- Add a new
landlock_restrict_flag(2)flag (for consistency with the kfunc) to automatically set NNP. We can also think about two flags, with one only setting NNP if the process doesn't haveCAP_SYS_ADMINbut I'm not sure it's worth it for now.
I think the simplest approach is to add a LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVS flag and call task_set_no_new_privs() (see tsync.c), but yes, it needs to be safe in the binprm_creds_for_exec context.
@l0kod I have some design decisions. Unlike the MAC attach type for LSM BPF, where it is safe to sleep normally, CGROUP takes place under RCU which is incompatible with existing landlock merge logic. Would you prefer to refactor the merge logic to be RCU safe or would you rather exclude programs with an attach type CGROUP? (leaning towards latter)
Hmm, unfortunately we cannot create a domain under RCU, especially because of the memory allocation.
About the cgroups, what would be the use case? Would it be safe? Can we use (or add) an LSM hook instead?
I was thinking in my mind this could be useful to only have an eBPF program apply landlock restrictions within the context of a certain cgroup, not executing the program at all if not running under that cgroup. But I think this can be done anyway with bpf_get_current_cgroup_id, but requires checking the cgroup id for every execution.
Anyways I think this can be done at a later time, it seems too complex to implement now and I don't think it's strictly necessary.
I also am mandating sleepable hooks because merge logic might sleep.
Right.
TSYNC doesn't really make sense from the context of pre-execution. I'm returning EINVAL if this flag is passed to bpf_landlock_restrict_binprm (my bpf function kfunc analog for restrict_self) Is that ok or would you rather ignore the value?
I guess -EINVAL is the correct approach here. @gnoack ?
Would you rather have selftests live under BPF or landlock selftests? leaning towards BPF since they have an existing harness.
Yes, BPF tests should be with the other BPF tests. They only need to test edge cases that are specific to Landlock with eBPF (e.g. basic access control, valid/invalid flags, nested enforcement up to the limit).
Please try to make them extensible. I'd like to add tests for the tracepoints/eBPF too at a later time.
Gotcha. I'll try to make the tests more generic, right now they're not super extensible. I'm actually having a really hard time debugging them, I've been sending them to the BPF CI and keep getting test failures I can't reproduce locally. They all pass for me running test_progs on my machine.
Feel free to take a look at the CI results.
https://github.com/kernel-patches/bpf/pull/11562
Error: #177/5 landlock_kfuncs/compose_existing_domain_parent_omits_truncate
Error: #177/5 landlock_kfuncs/compose_existing_domain_parent_omits_truncate
test_landlock_kfuncs:PASS:create_parent_union_ruleset 0 nsec
test_landlock_kfuncs:PASS:create_child_union_ruleset 0 nsec
test_landlock_kfuncs:PASS:preload_union_ruleset 0 nsec
test_landlock_kfuncs:PASS:seed_union_file 0 nsec
test_landlock_kfuncs:PASS:run_union_child 0 nsec
assert_allowed_run:PASS:allowed_exited 0 nsec
assert_allowed_run:FAIL:allowed_exit_code unexpected allowed_exit_code: actual 1 != expected 0
assert_allowed_run:PASS:read_allowed_file 0 nsec
assert_allowed_run:FAIL:allowed_file_contents unexpected allowed_file_contents: actual 'original
' != expected 'updated
'
assert_allowed_run:PASS:lookup_calls 0 nsec
assert_allowed_run:PASS:lookup_failed 0 nsec
assert_allowed_run:PASS:restrict_calls 0 nsec
assert_allowed_run:PASS:restrict_ret 0 nsec
assert_allowed_run:PASS:put_calls 0 nsec
assert_allowed_run_no_delete:PASS:delete_calls 0 nsec
+ echo -e '\033[1;33mTest Results:\033[0m'
edit: figured it out. It was a tmpfs problem with other tests, not a bug in the kernel code.
How to handle no new privs? I need to find out if you can set that in the binprm_creds_for_exec...
This needs careful consideration indeed. I see two approaches:
Add new prctl and capget helpers: that seems too much.
Add a new
landlock_restrict_flag(2)flag (for consistency with the kfunc) to automatically set NNP. We can also think about two flags, with one only setting NNP if the process doesn't haveCAP_SYS_ADMINbut I'm not sure it's worth it for now.I think the simplest approach is to add a
LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVSflag and calltask_set_no_new_privs()(see tsync.c), but yes, it needs to be safe in thebinprm_creds_for_execcontext.
I like that idea. Calling task_set_no_new_privs(current) from that hook is safe, since we're calling where the current task is still in the the old pre-exec context.
That also makes enforcing a landlock policy possible in an unprivileged context without calling prctl. Makes the examples a little cleaner. 🙂 but requires an ABI bump and selftests.
RFC v1: https://lore.kernel.org/linux-security-module/[email protected]/
(This ended up being much more of a bigger adventure than I thought!)
This needs careful consideration indeed. I see two approaches:
1. Add new prctl and capget helpers: that seems too much. 2. Add a new `landlock_restrict_flag(2)` flag (for consistency with the kfunc) to automatically set NNP. We can also think about two flags, with one only setting NNP if the process doesn't have `CAP_SYS_ADMIN` but I'm not sure it's worth it for now.
I actually made the flag have this behavior by default. Let me know if you would rather have it be unconditional on CAP_SYS_ADMIN.
I think the simplest approach is to add a
LANDLOCK_RESTRICT_SELF_NO_NEW_PRIVSflag and calltask_set_no_new_privs()(see tsync.c), but yes, it needs to be safe in thebinprm_creds_for_execcontext.
Yeah this ended up not being possible. The hooks (bprm_creds_for_exec and bprm_creds_from_file) happen before the point of no return for exec, so task_set_no_new_privs at the hook stage would leak into the original thread on an AT_EXECVE_CHECK or failed exec, and also mess with the current escalation in the case of bprm_creds_for_exec. I searched and searched but there was no mechanism to add task_set_no_new_privs after the point of no return, so I had to add a bitfield to linux_binprm to force setting task_set_no_new_privs at the correct time.
Not ideal but I'm very open to better ways.
Update for situational awareness:
The proposal for the new map type BPF_MAP_TYPE_LANDLOCK_RULESET doesn't align with BPF UAPI policy for new map types, which states new maps / prog types must be built for multiple use cases.
Song Liu proposed the alternative of a generic FD map type for BPF, which would allow for insertion in userspace of file descriptors and mapping to a strongly typed / refcounted __kptr object 1
@l0kod In a further extension of this idea proposed extending file_operations to support a generic opt-in conversion of FDs to specific __kptr objects. 2
@l0kod earlier proposed basing the BPF exec-time enforcement on the same code path / hooks as a future extension for atomic / side effect free enforcement of Landlock rulesets on the next execution, (see https://github.com/landlock-lsm/linux/issues/43) and the no_new_privs flag past the point of no return. This can be an independent series which this feature can later share a code path with. 3
The logical conclusion here is that this feature will require at least three parts, which will likely need to be independent series:
- The new point-of-no-return flags for NNP and staging domain to execution time in Landlock. Selftests and doc updates.
- The generic FD map implementation for bpf. Selftests and doc updates.
- The BPF kfunc implementations for Landlock using the same point-of-no return staging, usable with the generic fd map. Selftests and doc updates.
Part 1 I have a draft for that can be turned into an RFC. Part 2 is a little trickier, and would need some input and discussion on the BPF lists and possibly other subsystems (fs, mm). I don't have anything for this yet and anyone is welcome to take this up. Part 3 I have a draft for the kptr lifetime management / restriction application kfuncs as well as the portion utilizing the same enforcement path for exectime restrictions in part 1.
Hi @RazeLighter777
Thanks for the idea. I have two concerns:
-
As you mentioned, landlock was designed to be unprivileged, eBPF is not (using BPF token is painful). Making it privilege also brings a an liability. This is why sandlock (https://github.com/multikernel/sandlock) is designed to be unprivileged (otherwise I would just pick eBPF LSM).
-
Your point on static policy is valid and real. However, there are also user-space solutions for this. For example, sandlock provides both dynamic policy and user-defined syscall handlers. With all the infrastructure (thanks to seccomp), it becomes possible to adjust landlock rules at runtime without any kernel changes.
Please let me know your thoughts.
Regards, Cong
Hi @RazeLighter777
Thanks for the idea. I have two concerns:
- As you mentioned, landlock was designed to be unprivileged, eBPF is not (using BPF token is painful). Making it privilege also brings a an liability. This is why sandlock (https://github.com/multikernel/sandlock) is designed to be unprivileged (otherwise I would just pick eBPF LSM).
Landlock already has features available to only users with certain capabilities, like reading audit logs (like landlock's audit logs) or applying a ruleset without no new privs being set.
Landlock is an unprivileged LSM, but it is also not only an unprivileged LSM. Root can use Landlock just fine.
The reason why this eBPF feature would need privileges is that it is designed to apply the sandbox outside the domain. That inherently requires the capability to control the ambient rights on an arbritrary process, exactly what BPF LSM is already capable of.
So I don't see how this significantly increases liability or bypasses any security model.
- Your point on static policy is valid and real. However, there are also user-space solutions for this. For example, sandlock provides both dynamic policy and user-defined syscall handlers. With all the infrastructure (thanks to seccomp), it becomes possible to adjust landlock rules at runtime without any kernel changes.
Please let me know your thoughts.
Perhaps this is a misunderstanding. The goal of this eBPF Landlock proposal isn't dynamic policy! The problem sandlock solves is a different one. The goal is simply to provide access to apply an existing Landlock ruleset, with semantics no different than landlock_restrict_self, just via the LSM hooks for pre-execution. This opens doors for BPF LSM to be able to use the same landlock facilities already available to the process, but apply them from the outside, immediately before execution time.
Sandlock doesn't touch that problem space at all. So it would probably not need to use or care about this feature at all.
Justin
Some updates on this.
When I submitted my RFC, I hit a blocking issue: an existing eBPF bug where destructors for referenced kptrs (including any we'd add for Landlock) could run in NMI context and cause system deadlocks. This affected many existing kptrs and would have affected this submission too. Alexei wanted it fixed before we submitted patches for any new referenced kptrs.
It took a while to reach an agreed-upon solution; it was a hairy problem, and more preexisting bugs turned up along the way that needed separate fixes. A fix coauthored by Kumar and me has been merged into bpf-next! (https://lore.kernel.org/bpf/178110421264.3082243.12632209176778813392.git-patchwork-notify@kernel.org/)
Destructors can now safely use RCU work (like landlock_put_ruleset_deferred) without worrying about running in NMI context, so I can pick this back up.
Having had time to refine the design, I think the cleanest approach is @l0kod's suggestion: add two flags, LANDLOCK_RESTRICT_SELF_ON_EXEC and LANDLOCK_RESTRICT_SELF_NNP_ON_EXEC. These are ordinary userspace flags, so they're useful features in their own right, but implementing them also gets much of the work for the eBPF feature done for free without duplicating code. I want to share as many code paths as possible between the eBPF and userspace uses of Landlock.
LANDLOCK_RESTRICT_SELF_ON_EXEC would stage the domain in a separate pointer (domain_on_exec) in landlock_cred_security. Subsequent calls with LANDLOCK_RESTRICT_SELF_ON_EXEC would be merged into the staged domain. The staged domain would be merged with the current domain in bprm_committing_creds (the point of no return) and then set to NULL, so everything STAGED collapses into one layer. One edge case to handle is making sure the single staged ruleset layer doesn't push us past the maximum number of layers. There are a couple of ways to deal with this, but the most sane to me is to just return E2BIG if staging a domain and then exec()'ing would exceed MAX_LAYERS, and returning E2BIG if calling landlock_restrict_self when a staged domain already is going to put us at MAX_LAYERS. This flag would be mutually exclusive with TSYNC (fixable later if there's demand).
LANDLOCK_RESTRICT_SELF_NNP_ON_EXEC would be complementary; a simple boolean flag within a domain. In bprm_committing_creds, if it's set, we call task_set_no_new_privs(current). That's it. Like LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF, it could be called without a ruleset. It would also be mutually exclusive with TSYNC.
Neither flag would bypass the CAP_SYS_ADMIN || no_new_privs requirement. LANDLOCK_RESTRICT_SELF_NNP_ON_EXEC is a no-op if nnp is already set, so it's primarily useful for CAP_SYS_ADMIN users.
Both flags would also be idempotent: a failure in the exec() call doesn't leave corrupted state, because everything happens at the point of no return.
With these two flags in place, the rest of the additions are pretty trivial. I narrowed it down to:
__bpf_kfunc struct bpf_landlock_ruleset *
bpf_landlock_acquire_ruleset(int fd);
__bpf_kfunc void
bpf_landlock_release_ruleset(struct bpf_landlock_ruleset *ruleset);
bpf_landlock_restrict_on_exec(struct linux_binprm *bprm,
struct bpf_landlock_ruleset *ruleset, int flags);
Each of these has a specific context in which it's allowed to be used.
- bpf_landlock_acquire_ruleset
Callable from syscall context only (BPF_PROG_TYPE_SYSCALL). This gives us access to a specific ruleset and lets us safely look it up by its file descriptor (BPF_PROG_TYPE_SYSCALL programs run within the task context of the calling program). We call landlock_get_ruleset on the landlock_ruleset object and return our wrapped, opaque bpf_landlock_ruleset kptr; a pointer alias with no fields, so we don't expose unstable Landlock internals (we don't want our ruleset structure to become ABI). You can then store it in a map. The BPF verifier checks the objects' lifetime and statically guarantees their eventual release.
- bpf_landlock_release_ruleset
Calls landlock_put_ruleset_deferred on the ruleset. Callable from many program types; basically everything except tracing programs that can run in NMI. The destructor for bpf_landlock_ruleset just calls this function.
- bpf_landlock_restrict_on_exec
Callable from a very specific context: it must be a [BPF_PROG_TYPE_LSM](https://docs.ebpf.io/linux/program-type/BPF_PROG_TYPE_LSM/) with attach type [BPF_LSM_MAC](https://docs.ebpf.io/linux/syscall/BPF_LINK_CREATE/#bpf_lsm_mac), attached to one of two hooks; bprm_creds_for_exec or bprm_creds_from_file. It must also have been loaded with BPF_F_SLEEPABLE set, since the Landlock ruleset is protected by a mutex, which may sleep.
It takes three parameters: the bprm (the binary parameters of the about-to-be-executed binary/interpreter, depending on the hook, important because it carries the pending credentials), the kptr to our bpf_landlock_ruleset acquired from bpf_landlock_acquire_ruleset, and an int flags. It works exactly like landlock_restrict_self, with one main difference: LANDLOCK_RESTRICT_SELF_ON_EXEC is always implied. Every other behavior is identical because they share the exact same code paths; even the ability to pass a NULL ruleset with LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF! The goal is to share as much of the landlock_restrict_self API as possible.
One important consideration: callers of this kfunc are expected to check the return code and deny execution of the binary on error. Otherwise a userspace program could create MAX_LAYERS layers and prevent BPF from enforcing an additional ruleset. This will need clear documentation.
The overall addition and complexity shrink drastically with this design; down to roughly 400 lines of code (excluding tests and docs). I also worked out how to avoid much of the refactoring I'd expected, which shrinks the diff and makes it far easier to review. I'll be testing over the next several days/weeks. Posting now to get feedback and a sanity check on this model.
Good work for the kptr fix!
LANDLOCK_RESTRICT_SELF_ON_EXEC would stage the domain in a separate pointer (domain_on_exec) in landlock_cred_security. Subsequent calls with LANDLOCK_RESTRICT_SELF_ON_EXEC would be merged into the staged domain. The staged domain would be merged with the current domain in bprm_committing_creds (the point of no return) and then set to NULL, so everything STAGED collapses into one layer. One edge case to handle is making sure the single staged ruleset layer doesn't push us past the maximum number of layers. There are a couple of ways to deal with this, but the most sane to me is to just return E2BIG if staging a domain and then exec()'ing would exceed MAX_LAYERS, and returning E2BIG if calling landlock_restrict_self when a staged domain already is going to put us at MAX_LAYERS. This flag would be mutually exclusive with TSYNC (fixable later if there's demand).
It would be simpler and safer to just replace a previously staged domain with the new one.
What worries me the most about this new flag is that the caller of execve(2) might not know about the special execution state it will get. We should at least require the use of LANDLOCK_RESTRICT_SELF_TSYNC to ensure consistency across threads.
We also need to be very careful wrt SUID binaries.
Overall, I'm not 100% convinced of this use case without the ability to tie the policy to a specific exec path or something other than "the next execution from any thread of this process". The eBPF approach enables to identify the full execve context, including the bprm, for which a specific ruleset would make sense, which is not possible with just this new flag.
Why would this flag be a requirement for the eBPF patch series? It looks like an eBPF program called by the right hook would only have to enforce the domain on current, whereas implementing this flag would be much more complex.
LANDLOCK_RESTRICT_SELF_NNP_ON_EXEC would be complementary; a simple boolean flag within a domain. In bprm_committing_creds, if it's set, we call task_set_no_new_privs(current). That's it.
This flag should be uncontroversial and easy to implement.
Like LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF, it could be called without a ruleset.
That's interesting.
It would also be mutually exclusive with TSYNC.
Why?
Good work for the kptr fix!
LANDLOCK_RESTRICT_SELF_ON_EXEC would stage the domain in a separate pointer (domain_on_exec) in landlock_cred_security. Subsequent calls with LANDLOCK_RESTRICT_SELF_ON_EXEC would be merged into the staged domain. The staged domain would be merged with the current domain in bprm_committing_creds (the point of no return) and then set to NULL, so everything STAGED collapses into one layer. One edge case to handle is making sure the single staged ruleset layer doesn't push us past the maximum number of layers. There are a couple of ways to deal with this, but the most sane to me is to just return E2BIG if staging a domain and then exec()'ing would exceed MAX_LAYERS, and returning E2BIG if calling landlock_restrict_self when a staged domain already is going to put us at MAX_LAYERS. This flag would be mutually exclusive with TSYNC (fixable later if there's demand).
It would be simpler and safer to just replace a previously staged domain with the new one.
What worries me the most about this new flag is that the caller of
execve(2)might not know about the special execution state it will get. We should at least require the use ofLANDLOCK_RESTRICT_SELF_TSYNCto ensure consistency across threads.We also need to be very careful wrt SUID binaries.
We can table the exec-time enforcement from userspace for now; I agree, the usecase is unclear. The reason I was trying to do it was to keep feature parity between the landlock BPF side / userspace side.
Overall, I'm not 100% convinced of this use case without the ability to tie the policy to a specific exec path or something other than "the next execution from any thread of this process". The eBPF approach enables to identify the full execve context, including the bprm, for which a specific ruleset would make sense, which is not possible with just this new flag.
Why would this flag be a requirement for the eBPF patch series? It looks like an eBPF program called by the right hook would only have to enforce the domain on
current, whereas implementing this flag would be much more complex.
Strictly speaking, it's not a requirement. If this feature was desired though, ideally they should share the same plumbing since they work almost identically and share the same hook. The LANDLOCK_RESTRICT_SELF_NNP_ON_EXEC is a hard requirement though to ensure we can enforce the correct security model.
LANDLOCK_RESTRICT_SELF_NNP_ON_EXEC would be complementary; a simple boolean flag within a domain. In bprm_committing_creds, if it's set, we call task_set_no_new_privs(current). That's it.
This flag should be uncontroversial and easy to implement.
I'll start with just that flag first. And I can make it work with TSYNC if desired, see the note below about doing it with BPF.
Like LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF, it could be called without a ruleset.
That's interesting.
It would also be mutually exclusive with TSYNC.
Why?
This was conveyed badly, sorry. I meant the entire BPF ruleset enforcement is incompatible with TSYNC. TSYNC doesn't make sense in the bprm_creds_for_exec/creds_from file hooks, since we are executing anyway, the TSYNC would just do nothing (unless the exec fails). But I see zero usecase for wanting that behavior. However, in userspace it would be fine to combine this flag and the TSYNC flag, if you can see a usecase.
Like LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF, it could be called without a ruleset.
That's interesting.
It would also be mutually exclusive with TSYNC.
Why?
This was conveyed badly, sorry. I meant the entire BPF ruleset enforcement is incompatible with TSYNC. TSYNC doesn't make sense in the bprm_creds_for_exec/creds_from file hooks, since we are executing anyway, the TSYNC would just do nothing (unless the exec fails). But I see zero usecase for wanting that behavior.
I agree, the TSYNC flag should not be set by a BPF program attached to this hook because it is a point of no return and would only increase the number of potential errors.
I'm not sure if the kfunc should silently mask this flag or return an error if set.I guess the later would be more future proof (and also a meaningful test case).
However, in userspace it would be fine to combine this flag and the TSYNC flag, if you can see a usecase.
Yes, it would be a natural extension to the TSYNC flag because this flag already set NNP when required, but it doesn't force it if not. Any though @gnoack ?
Callable from a very specific context: it must be a [BPF_PROG_TYPE_LSM](https://docs.ebpf.io/linux/program-type/BPF_PROG_TYPE_LSM/) with attach type [BPF_LSM_MAC](https://docs.ebpf.io/linux/syscall/BPF_LINK_CREATE/#bpf_lsm_mac), attached to one of two hooks; bprm_creds_for_exec or bprm_creds_from_file. It must also have been loaded with BPF_F_SLEEPABLE set, since the Landlock ruleset is protected by a mutex, which may sleep.
The bprm_creds_from_file hook should definitely allow to call the kfunc, but I'm not convinced about bprm_creds_for_exec: it is mostly useful to return an error to user space (before the actual exec), so most of the time a denial. The goal of the kfunc is to only enforce a Landlock domain, and the only errors should be ENOMEM (but it should be rare because accounted to the kernel), and EINVAL for invalid parameters (that should be checked before this point).
The
bprm_creds_from_filehook should definitely allow to call the kfunc, but I'm not convinced aboutbprm_creds_for_exec: it is mostly useful to return an error to user space (before the actual exec), so most of the time a denial. The goal of the kfunc is to only enforce a Landlock domain, and the only errors should beENOMEM(but it should be rare because accounted to the kernel), andEINVALfor invalid parameters (that should be checked before this point).
Well, I guess if we don't care about the interpreter file, the bprm_creds_for_exec hook is enough and it might even be required to check the script/requested file. So you're right to support both hooks.