Landlock multithreaded enforcement
Subsystems (4)
Günther Noack
reviewerv3 cover Landlock multithreaded enforcement
This patch set adds the LANDLOCK_RESTRICT_SELF_TSYNC flag to landlock_restrict_self(). With this flag, the passed Landlock ruleset will not only be applied to the calling thread, but to all threads which belong to the same process.
Motivation
==========
TL;DR: The libpsx/nptl(7) signal hack which we use in user space for multi-threaded Landlock enforcement is incompatible with Landlock's signal scoping support. Landlock can restrict the use of signals across Landlock domains, but we need signals ourselves in user space in ways that are not permitted any more under these restrictions.
Enabling Landlock proves to be difficult in processes that are already multi-threaded at the time of enforcement:
* Enforcement in only one thread is usually a mistake because threads do not normally have proper security boundaries between them.
* Also, multithreading is unavoidable in some circumstances, such as when using Landlock from a Go program. Go programs are already multithreaded by the time that they enter the "func main()".
So far, the approach in Go[1] was to use libpsx[2]. This library implements the mechanism described in nptl(7) [3]: It keeps track of all threads with a linker hack and then makes all threads do the same syscall by registering a signal handler for them and invoking it.
With commit 54a6e6bbf3be ("landlock: Add signal scoping"), Landlock gained the ability to restrict the use of signals across different Landlock domains.
Landlock's signal scoping support is incompatible with the libpsx approach of enabling Landlock:
(1) With libpsx, although all threads enforce the same ruleset object, they technically do the operation separately and end up in distinct Landlock domains. This breaks signaling across threads when using LANDLOCK_SCOPE_SIGNAL.
(2) Cross-thread Signals are themselves needed to enforce further nested Landlock domains across multiple threads. So nested Landlock policies become impossible there.
In addition to Landlock itself, cross-thread signals are also needed for other seemingly-harmless API calls like the setuid(2) [4] and for the use of libcap (co-developed with libpsx), which have the same problem where the underlying syscall only applies to the calling thread.
Implementation details
======================
Enforcement prerequisites
-------------------------
Normally, the prerequisite for enforcing a Landlock policy is to either have CAP_SYS_ADMIN or the no_new_privs flag. With LANDLOCK_RESTRICT_SELF_TSYNC, the no_new_privs flag will automatically be applied for sibling threads if the caller had it.
These prerequisites and the "TSYNC" behavior work the same as for Seccomp and its SECCOMP_FILTER_FLAG_TSYNC flag.
Pseudo-signals
--------------
Landlock domains are stored in struct cred, and a task's struct cred can only be modified by the task itself [6].
To make that work, we use task_work_add() to register a pseudo-signal for each of the affected threads. At signal execution time, these tasks will coordinate to switch out their Landlock policy in lockstep with each other, guaranteeing all-or-nothing semantics.
This implementation can be thought of as a kernel-side implementation of the userspace hack that glibc/NPTL use for setuid(2) [3] [4], and which libpsx implements for libcap [2].
Finding all sibling threads
---------------------------
In order to avoid grabbing the global task_list_lock, we employ the scheme proposed by Jann Horn in [7]:
1. Loop through the list of sibling threads
2. Schedule a pseudo-signal for each and make each thread wait in the pseudo-signal
3. Go back to 1. and look for more sibling thread that we have not seen yet
Do this until no more new threads are found. As all threads were waiting in their pseudo-signals, they can not spawn additional threads and we found them all.
Coordination between tasks
--------------------------
As tasks run their pseudo-signal task work, they coordinate through the following completions:
- all_prepared (with counter num_preparing)
When done, all new sibling threads in the inner loop(!) of finding new threads are now in their pseudo-signal handlers and have prepared the struct cred object to commit (or written an error into the shared "preparation_error").
The lifetime of all_prepared is only the inner loop of finding new threads.
- ready_to_commit
When done, the outer loop of finding new threads is done and all sibling threads have prepared their struct cred object. Marked completed by the calling thread.
- all_finished
When done, all sibling threads are done executing their pseudo-signal handlers.
Use of credentials API
----------------------
Under normal circumstances, sibling threads share the same struct cred object. To avoid unnecessary duplication, if we find that a thread uses the same struct cred as the calling thread, we side-step the normal use of the credentials API [6] and place a pointer to that existing struct cred instead of creating a new one using prepare_creds() in the sibling thread.
Noteworthy discussion points
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* We are side-stepping the normal credentials API [6], by re-wiring an existing struct cred object instead of calling prepare_creds().
We can technically avoid it, but it would create unnecessary duplicate struct cred objects in multithreaded scenarios.
Change Log
==========
v3:
- bigger organizational changes
- move tsync logic into own file
- tsync: extract count_additional_threads() and schedule_task_work()
- code style
- restrict_one_thread, syscalls.c: use err instead of res (mic)
- restrict_one_thread: inline current_cred variable
- restrict_one_thread: add comment to shortcut logic (mic)
- rsync_works helpers: use size_t i for loop vars
- landlock_cred_copy: skip redundant NULL checks
- function name: s,tsync_works_free,tsync_works_release, (mic)
- tsync_works_grow_by: kzalloc into a temporary variable for clarity (mic)
- tsync_works_contains_task: make struct task_works const
- bugs
- handle kmalloc family failures correctly (jannh)
- tsync_works_release: check task NULL ptr before put
- s/put_task_struct_rcu_user/put_task_struct/ (jannh)
- concurrency bugs
- schedule_task_work: do not return error when encountering exiting tasks This can happen during normal operation, we should not error due to it (jannh)
- landlock_restrict_sibling_threads: make current hold the num_unfinished/all_finished barrier (more robust, jannh)
- un-wedge the deadlock using wait_for_completion_interruptible (jannh) See "testing" below and discussion in
https://lore.kernel.org/all/CAG48ez1oS9kANZBq1bt+D76MX03DPHAFp76GJt7z5yx-Na1VLQ@mail.gmail.com/
- logic
- tsync_works_grow_by(): grow to size+n, not capacity+n
- tsync_works_grow_by(): add overflow check for capacity increase
- landlock_restrict_self(): make TSYNC and LOG flags work together
- set no_new_privs in the same way as seccomp,
whenever the calling thread had it
- testing
- add test where multiple threads call landlock_restrict_self() concurrently
- test that no_new_privs is implicitly enabled for sibling threads
- bump ABI version to v8
- documentation improvements
- document ABI v8
- move flag documentation into the landlock.h header
- comment: Explain why we do not need sighand->siglock or cred_guard_mutex
- various comment improvements
- reminder above struct landlock_cred_security about updating landlock_cred_copy on changes
v2:
- https://lore.kernel.org/all/[email protected]/
- Semantics:
- Threads implicitly set NO_NEW_PRIVS unless they have CAP_SYS_ADMIN, to fulfill Landlock policy enforcement prerequisites
- Landlock policy gets unconditionally overridden even if the previously established Landlock domains in sibling threads were diverging.
- Restructure discovery of all sibling threads, with the algorithm proposed by Jann Horn [7]: Loop through threads multiple times, and get them all stuck in the pseudo signal (task work), until no new sibling threads show up.
- Use RCU lock when iterating over sibling threads.
- Override existing Landlock domains of other threads,
instead of applying a new Landlock policy on top
- Directly re-wire the struct cred for sibling threads, instread of creating a new one with prepare_creds().
- Tests:
- Remove multi_threaded_failure test
(The only remaining failure case is ENOMEM,
there is no good way to provoke that in a selftest)
- Add test for success despite diverging Landlock domains.
[1] https://github.com/landlock-lsm/go-landlock
[2] https://sites.google.com/site/fullycapable/who-ordered-libpsx
[3] https://man.gnoack.org/7/nptl
[4] https://man.gnoack.org/2/setuid#VERSIONS
[5] https://lore.kernel.org/all/[email protected]/
[6] https://www.kernel.org/doc/html/latest/security/credentials.html
[7] https://lore.kernel.org/all/CAG48ez0pWg3OTABfCKRk5sWrURM-HdJhQMcWedEppc_z1rrVJw@mail.gmail.com/
Günther Noack (3):
landlock: Multithreading support for landlock_restrict_self()
landlock: selftests for LANDLOCK_RESTRICT_SELF_TSYNC
landlock: Document LANDLOCK_RESTRICT_SELF_TSYNC
Documentation/userspace-api/landlock.rst | 8 + include/uapi/linux/landlock.h | 13 + security/landlock/Makefile | 2 +- security/landlock/cred.h | 12 + security/landlock/limits.h | 2 +- security/landlock/syscalls.c | 66 ++- security/landlock/tsync.c | 555 ++++++++++++++++++ security/landlock/tsync.h | 16 + tools/testing/selftests/landlock/base_test.c | 8 +- tools/testing/selftests/landlock/tsync_test.c | 161 +++++ 10 files changed, 810 insertions(+), 33 deletions(-) create mode 100644 security/landlock/tsync.c create mode 100644 security/landlock/tsync.h create mode 100644 tools/testing/selftests/landlock/tsync_test.c
Signature · 1 line
2.52.0.177.g9f829587af-goog
Günther Noack
reviewerPATCH v3 1/3 landlock: Multithreading support for landlock_restrict_self()
Introduce the LANDLOCK_RESTRICT_SELF_TSYNC flag. With this flag, a given Landlock ruleset is applied to all threads of the calling process, instead of only the current one.
Without this flag, multithreaded userspace programs currently resort to using the nptl(7)/libpsx hack for multithreaded policy enforcement, which is also used by libcap and for setuid(2). Using this userspace-based scheme, the threads of a process enforce the same Landlock policy, but the resulting Landlock domains are still separate. The domains being separate causes multiple problems:
* When using Landlock's "scoped" access rights, the domain identity is used to determine whether an operation is permitted. As a result, when using LANLDOCK_SCOPE_SIGNAL, signaling between sibling threads stops working. This is a problem for programming languages and frameworks which are inherently multithreaded (e.g. Go).
* In audit logging, the domains of separate threads in a process will get logged with different domain IDs, even when they are based on the same ruleset FD, which migth confuse users.
--- include/uapi/linux/landlock.h | 13 + security/landlock/Makefile | 2 +- security/landlock/cred.h | 12 + security/landlock/limits.h | 2 +- security/landlock/syscalls.c | 66 ++- security/landlock/tsync.c | 555 +++++++++++++++++++ security/landlock/tsync.h | 16 + tools/testing/selftests/landlock/base_test.c | 2 +- 8 files changed, 638 insertions(+), 30 deletions(-) create mode 100644 security/landlock/tsync.c create mode 100644 security/landlock/tsync.h
include/uapi/linux/landlock.h +13 -0
@@ -117,11 +117,24 @@ struct landlock_ruleset_attr {* future nested domains, not the one being created. It can also be used * with a @ruleset_fd value of -1 to mute subdomain logs without creating a * domain. +* +* The following flag supports policy enforcement in multithreaded processes: +* +* %LANDLOCK_RESTRICT_SELF_TSYNC +* Applies the new Landlock configuration atomically to all threads of the +* current process, including the Landlock domain and logging +* configuration. This overrides the Landlock configuration of sibling +* threads, irrespective of previously established Landlock domains and +* logging configurations on these threads. +* +* If the calling thread is running with no_new_privs, this operation +* enables no_new_privs on the sibling threads as well. */ /* clang-format off */ #define LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF (1U << 0)#define LANDLOCK_RESTRICT_SELF_LOG_NEW_EXEC_ON (1U << 1)#define LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF (1U << 2) +#define LANDLOCK_RESTRICT_SELF_TSYNC (1U << 3)/* clang-format on */ /**
security/landlock/Makefile +1 -1
@@ -1,6 +1,6 @@ obj-$(CONFIG_SECURITY_LANDLOCK) := landlock.o -landlock-y := setup.o syscalls.o object.o ruleset.o \ +landlock-y := setup.o syscalls.o tsync.o object.o ruleset.o \ cred.o task.o fs.o landlock-$(CONFIG_INET) += net.o
security/landlock/cred.h +12 -0
@@ -26,6 +26,8 @@* This structure is packed to minimize the size of struct * landlock_file_security. However, it is always aligned in the LSM cred blob, * see lsm_set_blob_size(). +* +* When updating this, also update landlock_cred_copy() if needed. */ struct landlock_cred_security {/**
@@ -65,6 +67,16 @@ landlock_cred(const struct cred *cred)return cred->security + landlock_blob_sizes.lbs_cred; } +static inline void landlock_cred_copy (struct landlock_cred_security *dst, +const struct landlock_cred_security *src) +{ +landlock_put_ruleset (dst->domain); + + *dst = *src; + +landlock_get_ruleset (src->domain); +} +static inline struct landlock_ruleset *landlock_get_current_domain (void ) {return landlock_cred (current_cred ())->domain;
security/landlock/limits.h +1 -1
@@ -31,7 +31,7 @@#define LANDLOCK_MASK_SCOPE ((LANDLOCK_LAST_SCOPE << 1) - 1)#define LANDLOCK_NUM_SCOPE __const_hweight64(LANDLOCK_MASK_SCOPE) -#define LANDLOCK_LAST_RESTRICT_SELF LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF +#define LANDLOCK_LAST_RESTRICT_SELF LANDLOCK_RESTRICT_SELF_TSYNC#define LANDLOCK_MASK_RESTRICT_SELF ((LANDLOCK_LAST_RESTRICT_SELF << 1) - 1)/* clang-format on */
security/landlock/syscalls.c +39 -27
100 lines not on this page · raw message
security/landlock/tsync.c new file +555 -0
555 lines not on this page · raw message
security/landlock/tsync.h new file +16 -0
@@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ +/* +* Landlock LSM - Cross-thread ruleset enforcement +* +* Copyright 2025 Google LLC +*/ + +#ifndef _SECURITY_LANDLOCK_TSYNC_H +#define _SECURITY_LANDLOCK_TSYNC_H + +#include "cred.h" + +int landlock_restrict_sibling_threads (const struct cred *old_cred, +const struct cred *new_cred); + +#endif /* _SECURITY_LANDLOCK_TSYNC_H */
tools/testing/selftests/landlock/base_test.c +1 -1
@@ -76,7 +76,7 @@ TEST(abi_version)const struct landlock_ruleset_attr ruleset_attr = { .handled_access_fs =LANDLOCK_ACCESS_FS_READ_FILE , }; -ASSERT_EQ (7 ,landlock_create_ruleset (NULL ,0 , +ASSERT_EQ (8 ,landlock_create_ruleset (NULL ,0 ,LANDLOCK_CREATE_RULESET_VERSION )); ASSERT_EQ(-1, landlock_create_ruleset(&ruleset_attr, 0,
Signature · 1 line
2.52.0.177.g9f829587af-goog
Günther Noack
reviewerPATCH v3 2/3 landlock: selftests for LANDLOCK_RESTRICT_SELF_TSYNC
In reply to Günther NoackExercise various scenarios where Landlock domains are enforced across all of a processes' threads.
--- tools/testing/selftests/landlock/base_test.c | 6 +- tools/testing/selftests/landlock/tsync_test.c | 161 ++++++++++++++++++ 2 files changed, 164 insertions(+), 3 deletions(-) create mode 100644 tools/testing/selftests/landlock/tsync_test.c
tools/testing/selftests/landlock/base_test.c +3 -3
@@ -288,7 +288,7 @@ TEST(restrict_self_fd)EXPECT_EQ (EBADFD , errno); } -TEST (restrict_self_fd_flags) +TEST (restrict_self_fd_logging_flags) {int fd;
@@ -304,9 +304,9 @@ TEST(restrict_self_fd_flags)EXPECT_EQ (EBADFD , errno); } -TEST (restrict_self_flags) +TEST (restrict_self_logging_flags) { -const __u32 last_flag =LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF ; +const __u32 last_flag =LANDLOCK_RESTRICT_SELF_TSYNC ;/* Tests invalid flag combinations. */
tools/testing/selftests/landlock/tsync_test.c new file +161 -0
161 lines not on this page · raw message
Signature · 1 line
2.52.0.177.g9f829587af-goog
Günther Noack
reviewerPATCH v3 3/3 landlock: Document LANDLOCK_RESTRICT_SELF_TSYNC
In reply to Günther NoackAdd documentation for LANDLOCK_RESTRICT_SELF_TSYNC. It does not need to go into the main example, but it has a section in the ABI compatibility notes. In the HTML rendering, the main reference is the system call documentation, which is included from the landlock.h header file.
--- Documentation/userspace-api/landlock.rst | 8 ++++++++ 1 file changed, 8 insertions(+)
Documentation/userspace-api/landlock.rst +8 -0
@@ -604,6 +604,14 @@ Landlock audit events with the ``LANDLOCK_RESTRICT_SELF_LOG_SAME_EXEC_OFF``, sys_landlock_restrict_self(). See Documentation/admin-guide/LSM/landlock.rst for more details on audit. +Thread synchronization (ABI < 8) +-------------------------------- + +Starting with the Landlock ABI version 8, it is now possible to +enforce Landlock rulesets across all threads of the calling process +using the ``LANDLOCK_RESTRICT_SELF_TSYNC`` flag passed to +sys_landlock_restrict_self(). + .. _kernel_support: Kernel support
Signature · 1 line
2.52.0.177.g9f829587af-goog
Mickaël Salaün
maintainerGood job for writing this complex mechanic (and the related doc), this patch series is great! It's been in linux-next for a few weeks and I'll take it for Linux 7.0
I did some cosmetic changes though, you'll find them in my commits. Some more tests are needed but I'll take this series for now.
Thanks!
Quoted 249 lines · Günther Noack
This patch set adds the
LANDLOCK_RESTRICT_SELF_TSYNCflag tolandlock_restrict_self(). With this flag, the passed Landlock ruleset will not only be applied to the calling thread, but to all threads which belong to the same process.Motivation
==========TL;DR: The libpsx/nptl(7) signal hack which we use in user space for multi-threaded Landlock enforcement is incompatible with Landlock's signal scoping support. Landlock can restrict the use of signals across Landlock domains, but we need signals ourselves in user space in ways that are not permitted any more under these restrictions.
Enabling Landlock proves to be difficult in processes that are already multi-threaded at the time of enforcement:
* Enforcement in only one thread is usually a mistake because threads do not normally have proper security boundaries between them.
* Also, multithreading is unavoidable in some circumstances, such as when using Landlock from a Go program. Go programs are already multithreaded by the time that they enter the "func
main()".So far, the approach in Go[1] was to use libpsx[2]. This library implements the mechanism described in nptl(7) [3]: It keeps track of all threads with a linker hack and then makes all threads do the same syscall by registering a signal handler for them and invoking it.
With commit
54a6e6bbf3be("landlock: Add signal scoping"), Landlock gained the ability to restrict the use of signals across different Landlock domains.Landlock's signal scoping support is incompatible with the libpsx approach of enabling Landlock:
(1) With libpsx, although all threads enforce the same ruleset object, they technically do the operation separately and end up in distinct Landlock domains. This breaks signaling across threads when using
LANDLOCK_SCOPE_SIGNAL.(2) Cross-thread Signals are themselves needed to enforce further nested Landlock domains across multiple threads. So nested Landlock policies become impossible there.
In addition to Landlock itself, cross-thread signals are also needed for other seemingly-harmless API calls like the setuid(2) [4] and for the use of libcap (co-developed with libpsx), which have the same problem where the underlying syscall only applies to the calling thread.
Implementation details
======================Enforcement prerequisites
-------------------------Normally, the prerequisite for enforcing a Landlock policy is to either have
CAP_SYS_ADMINor theno_new_privsflag. WithLANDLOCK_RESTRICT_SELF_TSYNC, theno_new_privsflag will automatically be applied for sibling threads if the caller had it.These prerequisites and the "TSYNC" behavior work the same as for Seccomp and its
SECCOMP_FILTER_FLAG_TSYNCflag.Pseudo-signals
--------------Landlock domains are stored in struct cred, and a task's struct cred can only be modified by the task itself [6].
To make that work, we use
task_work_add()to register a pseudo-signal for each of the affected threads. At signal execution time, these tasks will coordinate to switch out their Landlock policy in lockstep with each other, guaranteeing all-or-nothing semantics.This implementation can be thought of as a kernel-side implementation of the userspace hack that glibc/NPTL use for setuid(2) [3] [4], and which libpsx implements for libcap [2].
Finding all sibling threads
---------------------------In order to avoid grabbing the global
task_list_lock, we employ the scheme proposed by Jann Horn in [7]:1. Loop through the list of sibling threads
2. Schedule a pseudo-signal for each and make each thread wait in the pseudo-signal
3. Go back to 1. and look for more sibling thread that we have not seen yetDo this until no more new threads are found. As all threads were waiting in their pseudo-signals, they can not spawn additional threads and we found them all.
Coordination between tasks
--------------------------As tasks run their pseudo-signal task work, they coordinate through the following completions:
-
all_prepared(with counternum_preparing)When done, all new sibling threads in the inner loop(!) of finding new threads are now in their pseudo-signal handlers and have prepared the struct cred object to commit (or written an error into the shared "
preparation_error").The lifetime of
all_preparedis only the inner loop of finding new threads.-
ready_to_commitWhen done, the outer loop of finding new threads is done and all sibling threads have prepared their struct cred object. Marked completed by the calling thread.
-
all_finishedWhen done, all sibling threads are done executing their pseudo-signal handlers.
Use of credentials API
----------------------Under normal circumstances, sibling threads share the same struct cred object. To avoid unnecessary duplication, if we find that a thread uses the same struct cred as the calling thread, we side-step the normal use of the credentials API [6] and place a pointer to that existing struct cred instead of creating a new one using
prepare_creds()in the sibling thread.Noteworthy discussion points
~~~~~~~~~~~~~~~~~~~~~~~~~~~~* We are side-stepping the normal credentials API [6], by re-wiring an existing struct cred object instead of calling
prepare_creds().We can technically avoid it, but it would create unnecessary duplicate struct cred objects in multithreaded scenarios.
Change Log
==========v3:
- bigger organizational changes
- move tsync logic into own file
- tsync: extractcount_additional_threads()andschedule_task_work()
- code style
-restrict_one_thread,syscalls.c: use err instead of res (mic)
-restrict_one_thread: inlinecurrent_credvariable
-restrict_one_thread: add comment to shortcut logic (mic)
-rsync_workshelpers: usesize_ti for loop vars
-landlock_cred_copy: skip redundant NULL checks
- function name: s,tsync_works_free,tsync_works_release, (mic)
-tsync_works_grow_by: kzalloc into a temporary variable for clarity (mic)
-tsync_works_contains_task: make structtask_worksconst
- bugs
- handle kmalloc family failures correctly (jannh)
-tsync_works_release: check task NULL ptr before put
- s/put_task_struct_rcu_user/put_task_struct/ (jannh)
- concurrency bugs
-schedule_task_work: do not return error when encountering exiting tasks This can happen during normal operation, we should not error due to it (jannh)
-landlock_restrict_sibling_threads: make current hold the num_unfinished/all_finished barrier (more robust, jannh)
- un-wedge the deadlock usingwait_for_completion_interruptible(jannh) See "testing" below and discussion in
https://lore.kernel.org/all/CAG48ez1oS9kANZBq1bt+D76MX03DPHAFp76GJt7z5yx-Na1VLQ@mail.gmail.com/
- logic
-tsync_works_grow_by(): grow to size+n, not capacity+n
-tsync_works_grow_by(): add overflow check for capacity increase
-landlock_restrict_self(): make TSYNC and LOG flags work together
- setno_new_privsin the same way as seccomp,
whenever the calling thread had it
- testing
- add test where multiple threads calllandlock_restrict_self()concurrently
- test thatno_new_privsis implicitly enabled for sibling threads
- bump ABI version to v8
- documentation improvements
- document ABI v8
- move flag documentation into thelandlock.hheader
- comment: Explain why we do not needsighand->siglockorcred_guard_mutex
- various comment improvements
- reminder above structlandlock_cred_securityabout updatinglandlock_cred_copyon changesv2:
- https://lore.kernel.org/all/[email protected]/
- Semantics:
- Threads implicitly setNO_NEW_PRIVSunless they haveCAP_SYS_ADMIN, to fulfill Landlock policy enforcement prerequisites
- Landlock policy gets unconditionally overridden even if the previously established Landlock domains in sibling threads were diverging.
- Restructure discovery of all sibling threads, with the algorithm proposed by Jann Horn [7]: Loop through threads multiple times, and get them all stuck in the pseudo signal (task work), until no new sibling threads show up.
- Use RCU lock when iterating over sibling threads.
- Override existing Landlock domains of other threads,
instead of applying a new Landlock policy on top
- Directly re-wire the struct cred for sibling threads, instread of creating a new one withprepare_creds().
- Tests:
- Removemulti_threaded_failuretest
(The only remaining failure case is ENOMEM,
there is no good way to provoke that in a selftest)
- Add test for success despite diverging Landlock domains.[1] https://github.com/landlock-lsm/go-landlock
[2] https://sites.google.com/site/fullycapable/who-ordered-libpsx
[3] https://man.gnoack.org/7/nptl
[4] https://man.gnoack.org/2/setuid#VERSIONS
[5] https://lore.kernel.org/all/[email protected]/
[6] https://www.kernel.org/doc/html/latest/security/credentials.html
[7] https://lore.kernel.org/all/CAG48ez0pWg3OTABfCKRk5sWrURM-HdJhQMcWedEppc_z1rrVJw@mail.gmail.com/Günther Noack (3):
landlock: Multithreading support forlandlock_restrict_self()
landlock: selftests forLANDLOCK_RESTRICT_SELF_TSYNC
landlock: DocumentLANDLOCK_RESTRICT_SELF_TSYNCDocumentation/userspace-api/landlock.rst | 8 + include/uapi/linux/landlock.h | 13 + security/landlock/Makefile | 2 +- security/landlock/cred.h | 12 + security/landlock/limits.h | 2 +- security/landlock/syscalls.c | 66 ++- security/landlock/tsync.c | 555 ++++++++++++++++++ security/landlock/tsync.h | 16 + tools/testing/selftests/landlock/base_test.c | 8 +- tools/testing/selftests/landlock/tsync_test.c | 161 +++++ 10 files changed, 810 insertions(+), 33 deletions(-) create mode 100644 security/landlock/tsync.c create mode 100644 security/landlock/tsync.h create mode 100644 tools/testing/selftests/landlock/tsync_test.cSignature · 1 line
2.52.0.177.g9f829587af-goog
Mickaël Salaün
maintainerRe: [PATCH v3 2/3] landlock: selftests for LANDLOCK_RESTRICT_SELF_TSYNC
In reply to Günther NoackThese tests are useful but there are two missing parts:
- testing the restriction of each thread;
- testing the domain ID of each thread.
I'll merge this whole series but could you please extend this test file with a new patch?
Quoted 81 lines · Günther Noack
Exercise various scenarios where Landlock domains are enforced across all of a processes' threads.
Cc Andrew G. Morgan <[email protected]>Cc John Johansen <[email protected]>Cc Mickaël Salaün <[email protected]>Cc Paul Moore <[email protected]>Signed-off-by Günther Noack <[email protected]>--- tools/testing/selftests/landlock/base_test.c | 6 +- tools/testing/selftests/landlock/tsync_test.c | 161 ++++++++++++++++++ 2 files changed, 164 insertions(+), 3 deletions(-) create mode 100644 tools/testing/selftests/landlock/tsync_test.ctools/testing/selftests/landlock/base_test.c +3
-3@@ -288,7 +288,7 @@ TEST(restrict_self_fd)EXPECT_EQ (EBADFD , errno); } -TEST (restrict_self_fd_flags) +TEST (restrict_self_fd_logging_flags) {int fd;@@ -304,9 +304,9 @@ TEST(restrict_self_fd_flags)EXPECT_EQ (EBADFD , errno); } -TEST (restrict_self_flags) +TEST (restrict_self_logging_flags) { -const __u32 last_flag =LANDLOCK_RESTRICT_SELF_LOG_SUBDOMAINS_OFF ; +const __u32 last_flag =LANDLOCK_RESTRICT_SELF_TSYNC ;/* Tests invalid flag combinations. */ tools/testing/selftests/landlock/tsync_test.c new file +35
-0@@ -0,0 +1,161 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* Landlock tests - Enforcing the same restrictions across multiple threads +* +* Copyright © 2025 Günther Noack <[email protected]> +*/ + +#define _GNU_SOURCE +#include <pthread.h> +#include <sys/prctl.h> +#include <linux/landlock.h> + +#include "common.h" + +/* create_ruleset - Create a simple ruleset FD common to all tests */ +static int create_ruleset (struct __test_metadata *const _metadata) +{ +struct landlock_ruleset_attr ruleset_attr = { + .handled_access_fs = (LANDLOCK_ACCESS_FS_WRITE_FILE | +LANDLOCK_ACCESS_FS_TRUNCATE ), + }; +const int ruleset_fd = +landlock_create_ruleset (&ruleset_attr,sizeof (ruleset_attr),0 ); + + ASSERT_LE(0, ruleset_fd) + { +TH_LOG ("landlock_create_ruleset: %s" ,strerror (errno)); + } +return ruleset_fd; +} + +TEST (single_threaded_success) +{ +const int ruleset_fd =create_ruleset (_metadata); +
tools/testing/selftests/landlock/tsync_test.c line 45
Quoted 10 lines
tools/testing/selftests/landlock/tsync_test.c new file +10
-0+disable_caps (_metadata); + +ASSERT_EQ (0 ,prctl (PR_SET_NO_NEW_PRIVS ,1 ,0 ,0 ,0 )); +ASSERT_EQ (0 ,landlock_restrict_self (ruleset_fd, +LANDLOCK_RESTRICT_SELF_TSYNC )); + +ASSERT_EQ (0 ,close (ruleset_fd)); +} + +void store_no_new_privs (void *data)
I fixed the helpers to make them static.
Quoted 120 lines
tools/testing/selftests/landlock/tsync_test.c new file +116
-0+{ +bool *nnp = data; + +if (!nnp) +return ; + *nnp =prctl (PR_GET_NO_NEW_PRIVS ,0 ,0 ,0 ,0 ); +} + +void *idle (void *data) +{ +pthread_cleanup_push (store_no_new_privs, data); + +while (true) +sleep (1 ); + +pthread_cleanup_pop (1 ); +} + +TEST (multi_threaded_success) +{ +pthread_t t1, t2; +bool no_new_privs1, no_new_privs2; +const int ruleset_fd =create_ruleset (_metadata); + +disable_caps (_metadata); + +ASSERT_EQ (0 ,pthread_create (&t1,NULL , idle, &no_new_privs1)); +ASSERT_EQ (0 ,pthread_create (&t2,NULL , idle, &no_new_privs2)); + +ASSERT_EQ (0 ,prctl (PR_SET_NO_NEW_PRIVS ,1 ,0 ,0 ,0 )); + +EXPECT_EQ (0 ,landlock_restrict_self (ruleset_fd, +LANDLOCK_RESTRICT_SELF_TSYNC )); + +ASSERT_EQ (0 ,pthread_cancel (t1)); +ASSERT_EQ (0 ,pthread_cancel (t2)); +ASSERT_EQ (0 ,pthread_join (t1,NULL )); +ASSERT_EQ (0 ,pthread_join (t2,NULL )); + +/* The no_new_privs flag was implicitly enabled on all threads. */ +EXPECT_TRUE (no_new_privs1); +EXPECT_TRUE (no_new_privs2); + +ASSERT_EQ (0 ,close (ruleset_fd)); +} + +TEST (multi_threaded_success_despite_diverging_domains) +{ +pthread_t t1, t2; +const int ruleset_fd =create_ruleset (_metadata); + +disable_caps (_metadata); + +ASSERT_EQ (0 ,prctl (PR_SET_NO_NEW_PRIVS ,1 ,0 ,0 ,0 )); + +ASSERT_EQ (0 ,pthread_create (&t1,NULL , idle,NULL )); +ASSERT_EQ (0 ,pthread_create (&t2,NULL , idle,NULL )); + +/* +* The main thread enforces a ruleset, +* thereby bringing the threads' Landlock domains out of sync. +*/ +EXPECT_EQ (0 ,landlock_restrict_self (ruleset_fd,0 )); + +/* Still, TSYNC succeeds, bringing the threads in sync again. */ +EXPECT_EQ (0 ,landlock_restrict_self (ruleset_fd, +LANDLOCK_RESTRICT_SELF_TSYNC )); + +ASSERT_EQ (0 ,pthread_cancel (t1)); +ASSERT_EQ (0 ,pthread_cancel (t2)); +ASSERT_EQ (0 ,pthread_join (t1,NULL )); +ASSERT_EQ (0 ,pthread_join (t2,NULL )); +ASSERT_EQ (0 ,close (ruleset_fd)); +} + +struct thread_restrict_data { +pthread_t t; +int ruleset_fd; +int result; +}; + +void *thread_restrict (void *data) +{ +struct thread_restrict_data *d = data; + + d->result =landlock_restrict_self (d->ruleset_fd, +LANDLOCK_RESTRICT_SELF_TSYNC ); +return NULL ; +} + +TEST (competing_enablement) +{ +const int ruleset_fd =create_ruleset (_metadata); +struct thread_restrict_data d[] = { + { .ruleset_fd = ruleset_fd }, + { .ruleset_fd = ruleset_fd }, + }; + +disable_caps (_metadata); + +ASSERT_EQ (0 ,prctl (PR_SET_NO_NEW_PRIVS ,1 ,0 ,0 ,0 )); +ASSERT_EQ (0 ,pthread_create (&d[0 ].t,NULL , thread_restrict, &d[0 ])); +ASSERT_EQ (0 ,pthread_create (&d[1 ].t,NULL , thread_restrict, &d[1 ])); + +/* Wait for threads to finish. */ +ASSERT_EQ (0 ,pthread_join (d[0 ].t,NULL )); +ASSERT_EQ (0 ,pthread_join (d[1 ].t,NULL )); + +/* Expect that both succeeded. */ +EXPECT_EQ (0 , d[0 ].result); +EXPECT_EQ (0 , d[1 ].result); + +ASSERT_EQ (0 ,close (ruleset_fd)); +} + +TEST_HARNESS_MAIN Signature · 1 line
2.52.0.177.g9f829587af-goog
Mickaël Salaün
maintainerFYI, syzkaller now supports this new flag, and it has been fuzzed for a few months (before being merged):
https://github.com/google/syzkaller/commit/e5e258750ba4cad4408ac45a26c0aafff51d45b1
Quoted 259 lines · Mickaël Salaün
Good job for writing this complex mechanic (and the related doc), this patch series is great! It's been in linux-next for a few weeks and I'll take it for Linux 7.0
I did some cosmetic changes though, you'll find them in my commits. Some more tests are needed but I'll take this series for now.
Thanks!
Quoted 249 lines · Günther Noack
This patch set adds the
LANDLOCK_RESTRICT_SELF_TSYNCflag tolandlock_restrict_self(). With this flag, the passed Landlock ruleset will not only be applied to the calling thread, but to all threads which belong to the same process.Motivation
==========TL;DR: The libpsx/nptl(7) signal hack which we use in user space for multi-threaded Landlock enforcement is incompatible with Landlock's signal scoping support. Landlock can restrict the use of signals across Landlock domains, but we need signals ourselves in user space in ways that are not permitted any more under these restrictions.
Enabling Landlock proves to be difficult in processes that are already multi-threaded at the time of enforcement:
* Enforcement in only one thread is usually a mistake because threads do not normally have proper security boundaries between them.
* Also, multithreading is unavoidable in some circumstances, such as when using Landlock from a Go program. Go programs are already multithreaded by the time that they enter the "func
main()".So far, the approach in Go[1] was to use libpsx[2]. This library implements the mechanism described in nptl(7) [3]: It keeps track of all threads with a linker hack and then makes all threads do the same syscall by registering a signal handler for them and invoking it.
With commit
54a6e6bbf3be("landlock: Add signal scoping"), Landlock gained the ability to restrict the use of signals across different Landlock domains.Landlock's signal scoping support is incompatible with the libpsx approach of enabling Landlock:
(1) With libpsx, although all threads enforce the same ruleset object, they technically do the operation separately and end up in distinct Landlock domains. This breaks signaling across threads when using
LANDLOCK_SCOPE_SIGNAL.(2) Cross-thread Signals are themselves needed to enforce further nested Landlock domains across multiple threads. So nested Landlock policies become impossible there.
In addition to Landlock itself, cross-thread signals are also needed for other seemingly-harmless API calls like the setuid(2) [4] and for the use of libcap (co-developed with libpsx), which have the same problem where the underlying syscall only applies to the calling thread.
Implementation details
======================Enforcement prerequisites
-------------------------Normally, the prerequisite for enforcing a Landlock policy is to either have
CAP_SYS_ADMINor theno_new_privsflag. WithLANDLOCK_RESTRICT_SELF_TSYNC, theno_new_privsflag will automatically be applied for sibling threads if the caller had it.These prerequisites and the "TSYNC" behavior work the same as for Seccomp and its
SECCOMP_FILTER_FLAG_TSYNCflag.Pseudo-signals
--------------Landlock domains are stored in struct cred, and a task's struct cred can only be modified by the task itself [6].
To make that work, we use
task_work_add()to register a pseudo-signal for each of the affected threads. At signal execution time, these tasks will coordinate to switch out their Landlock policy in lockstep with each other, guaranteeing all-or-nothing semantics.This implementation can be thought of as a kernel-side implementation of the userspace hack that glibc/NPTL use for setuid(2) [3] [4], and which libpsx implements for libcap [2].
Finding all sibling threads
---------------------------In order to avoid grabbing the global
task_list_lock, we employ the scheme proposed by Jann Horn in [7]:1. Loop through the list of sibling threads
2. Schedule a pseudo-signal for each and make each thread wait in the pseudo-signal
3. Go back to 1. and look for more sibling thread that we have not seen yetDo this until no more new threads are found. As all threads were waiting in their pseudo-signals, they can not spawn additional threads and we found them all.
Coordination between tasks
--------------------------As tasks run their pseudo-signal task work, they coordinate through the following completions:
-
all_prepared(with counternum_preparing)When done, all new sibling threads in the inner loop(!) of finding new threads are now in their pseudo-signal handlers and have prepared the struct cred object to commit (or written an error into the shared "
preparation_error").The lifetime of
all_preparedis only the inner loop of finding new threads.-
ready_to_commitWhen done, the outer loop of finding new threads is done and all sibling threads have prepared their struct cred object. Marked completed by the calling thread.
-
all_finishedWhen done, all sibling threads are done executing their pseudo-signal handlers.
Use of credentials API
----------------------Under normal circumstances, sibling threads share the same struct cred object. To avoid unnecessary duplication, if we find that a thread uses the same struct cred as the calling thread, we side-step the normal use of the credentials API [6] and place a pointer to that existing struct cred instead of creating a new one using
prepare_creds()in the sibling thread.Noteworthy discussion points
~~~~~~~~~~~~~~~~~~~~~~~~~~~~* We are side-stepping the normal credentials API [6], by re-wiring an existing struct cred object instead of calling
prepare_creds().We can technically avoid it, but it would create unnecessary duplicate struct cred objects in multithreaded scenarios.
Change Log
==========v3:
- bigger organizational changes
- move tsync logic into own file
- tsync: extractcount_additional_threads()andschedule_task_work()
- code style
-restrict_one_thread,syscalls.c: use err instead of res (mic)
-restrict_one_thread: inlinecurrent_credvariable
-restrict_one_thread: add comment to shortcut logic (mic)
-rsync_workshelpers: usesize_ti for loop vars
-landlock_cred_copy: skip redundant NULL checks
- function name: s,tsync_works_free,tsync_works_release, (mic)
-tsync_works_grow_by: kzalloc into a temporary variable for clarity (mic)
-tsync_works_contains_task: make structtask_worksconst
- bugs
- handle kmalloc family failures correctly (jannh)
-tsync_works_release: check task NULL ptr before put
- s/put_task_struct_rcu_user/put_task_struct/ (jannh)
- concurrency bugs
-schedule_task_work: do not return error when encountering exiting tasks This can happen during normal operation, we should not error due to it (jannh)
-landlock_restrict_sibling_threads: make current hold the num_unfinished/all_finished barrier (more robust, jannh)
- un-wedge the deadlock usingwait_for_completion_interruptible(jannh) See "testing" below and discussion in
https://lore.kernel.org/all/CAG48ez1oS9kANZBq1bt+D76MX03DPHAFp76GJt7z5yx-Na1VLQ@mail.gmail.com/
- logic
-tsync_works_grow_by(): grow to size+n, not capacity+n
-tsync_works_grow_by(): add overflow check for capacity increase
-landlock_restrict_self(): make TSYNC and LOG flags work together
- setno_new_privsin the same way as seccomp,
whenever the calling thread had it
- testing
- add test where multiple threads calllandlock_restrict_self()concurrently
- test thatno_new_privsis implicitly enabled for sibling threads
- bump ABI version to v8
- documentation improvements
- document ABI v8
- move flag documentation into thelandlock.hheader
- comment: Explain why we do not needsighand->siglockorcred_guard_mutex
- various comment improvements
- reminder above structlandlock_cred_securityabout updatinglandlock_cred_copyon changesv2:
- https://lore.kernel.org/all/[email protected]/
- Semantics:
- Threads implicitly setNO_NEW_PRIVSunless they haveCAP_SYS_ADMIN, to fulfill Landlock policy enforcement prerequisites
- Landlock policy gets unconditionally overridden even if the previously established Landlock domains in sibling threads were diverging.
- Restructure discovery of all sibling threads, with the algorithm proposed by Jann Horn [7]: Loop through threads multiple times, and get them all stuck in the pseudo signal (task work), until no new sibling threads show up.
- Use RCU lock when iterating over sibling threads.
- Override existing Landlock domains of other threads,
instead of applying a new Landlock policy on top
- Directly re-wire the struct cred for sibling threads, instread of creating a new one withprepare_creds().
- Tests:
- Removemulti_threaded_failuretest
(The only remaining failure case is ENOMEM,
there is no good way to provoke that in a selftest)
- Add test for success despite diverging Landlock domains.[1] https://github.com/landlock-lsm/go-landlock
[2] https://sites.google.com/site/fullycapable/who-ordered-libpsx
[3] https://man.gnoack.org/7/nptl
[4] https://man.gnoack.org/2/setuid#VERSIONS
[5] https://lore.kernel.org/all/[email protected]/
[6] https://www.kernel.org/doc/html/latest/security/credentials.html
[7] https://lore.kernel.org/all/CAG48ez0pWg3OTABfCKRk5sWrURM-HdJhQMcWedEppc_z1rrVJw@mail.gmail.com/Günther Noack (3):
landlock: Multithreading support forlandlock_restrict_self()
landlock: selftests forLANDLOCK_RESTRICT_SELF_TSYNC
landlock: DocumentLANDLOCK_RESTRICT_SELF_TSYNCDocumentation/userspace-api/landlock.rst | 8 + include/uapi/linux/landlock.h | 13 + security/landlock/Makefile | 2 +- security/landlock/cred.h | 12 + security/landlock/limits.h | 2 +- security/landlock/syscalls.c | 66 ++- security/landlock/tsync.c | 555 ++++++++++++++++++ security/landlock/tsync.h | 16 + tools/testing/selftests/landlock/base_test.c | 8 +- tools/testing/selftests/landlock/tsync_test.c | 161 +++++ 10 files changed, 810 insertions(+), 33 deletions(-) create mode 100644 security/landlock/tsync.c create mode 100644 security/landlock/tsync.h create mode 100644 tools/testing/selftests/landlock/tsync_test.cSignature · 1 line
2.52.0.177.g9f829587af-goog