INFO: task hung in restrict_one_thread_callback
Subsystems (2)
A message that is not in the archive (sent off-list or not yet received): F1E9B1BEBD8867CA+092eea18-94c7-4c65-a466-95cd3628a88c@uniontech.com
Hello,
syzbot has tested the proposed patch and the reproducer did not trigger any issue:
Tested on:
commit: d4906ae1 Add linux-next specific files for 20260220 git tree: linux-next console output: https://syzkaller.appspot.com/x/log.txt?x=13ea89e6580000 kernel config: https://syzkaller.appspot.com/x/.config?x=51f859f3211496bc dashboard link: https://syzkaller.appspot.com/bug?extid=7ea2f5e9dfd468201817 compiler: Debian clang version 21.1.8 (++20251221033036+2078da43e25a-1~exp1~20251221153213.50), Debian LLD 21.1.8 patch: https://syzkaller.appspot.com/x/patch.diff?x=15f0595a580000
Note: testing is done by a robot and is best-effort only.
Hi all,
Thanks to syzbot for the testing and confirmation.
Since I am relatively new to the inner workings of this specific subsystem, I would like to take a few days to thoroughly study the root cause
(the task_work and mutex interaction) and prepare a detailed and proper commit message.
I will send out the formal patch (v1) to the mailing list later.
Best regards,
Yihan Ding
Quoted 19 lines · syzbot
Hello,
syzbot has tested the proposed patch and the reproducer did not trigger any issue:
Reported-by [email protected]Tested-by [email protected]Tested on:
commit: d4906ae1 Add linux-next specific files for 20260220 git tree: linux-next console output: https://syzkaller.appspot.com/x/log.txt?x=13ea89e6580000 kernel config: https://syzkaller.appspot.com/x/.config?x=51f859f3211496bc dashboard link: https://syzkaller.appspot.com/bug?extid=7ea2f5e9dfd468201817 compiler: Debian clang version 21.1.8 (++20251221033036+2078da43e25a-1~exp1~20251221153213.50), Debian LLD 21.1.8 patch: https://syzkaller.appspot.com/x/patch.diff?x=15f0595a580000Note: testing is done by a robot and is best-effort only.
Hello Ding!
Quoted 5 lines · Ding Yihan
Since I am relatively new to the inner workings of this specific subsystem, I would like to take a few days to thoroughly study the root cause
(thetask_workand mutex interaction) and prepare a detailed and proper commit message.I will send out the formal patch (v1) to the mailing list later.
Thank you very much for preparing a patch, and especially also for forwarding this to us. (The original syzkaller report was somehow not addressed to Landlock or the LSM list. We should fix that.)
Timing wise, the feature was picked up for the 7.0 release, so we still have some time to fix it before this is stable.
As an early review for the patch:
Background:
We had previously convinced ourselves that grabbing the cred_guard_mutex was not necessary. To quote the comment in landlock_restrict_sibling_threads():
Unlike seccomp, which modifies sibling tasks directly, we do not need to acquire the cred_guard_mutex and sighand->siglock:
- As in our case, all threads are themselves exchanging their own struct cred through the credentials API, no locks are needed for that.
- Our for_each_thread() loops are protected by RCU.
- We do not acquire a lock to keep the list of sibling threads stable between our for_each_thread loops. If the list of available sibling threads changes between these for_each_thread loops, we make up for that by continuing to look for threads until they are all discovered and have entered their task_work, where they are unable to spawn new threads.
The question of locking cred_guard_mutex came up in the patch discussion multiple times as well, the most recent discussion was:
https://lore.kernel.org/all/[email protected]/
If it helps, I keep some of my own notes for this particular feature on https://wiki.gnoack.org/LandlockMultithreadedEnforcement.
(Very) tentative investigation:
In the Syzkaller report [2], it seems that the reproducer [2.1] is creating two rulesets and then enforcing them in parallel, a scenario which we are exercising in the TEST(competing_enablement) in tools/testing/selftests/landlock/tsync_test.c already, but which has not failed in my own selftest runs.
In the crash report, there are four threads in total:
* Two are stuck in the line wait_for_completion(&ctx->ready_to_commit);
in the per-thread task work (line 128 [4.1])
* Two are stuck in the line wait_for_completion(&shared_ctx.all_prepared)
in the calling thread's coordination logic (line 539 [4.2])
In line 539, we are already on the code path where we detected that we are getting interrupted by another thread and where we are attempting to deal with the scenario where two landlock_restrict_self() calls compete. This is detected on line 523 when wait_for_completion_interruptible() is true. The approach to handle this is to set the overall -ERESTARTNOINTR error and cancel the work that has been ongoing so far, by canceling the task works that did not start running yet and waiting for the ones that did start running (that is the step where we are blocked!). The reasoning there was that these task works will all hit the "all_prepared" stage now, but as we can see in the stack trace, the task works that are actively running are already on line 128 and have passed the "all_prepared" stage).
Differences I can see between syzkaller and our own test:
* The reproducer also calls openat() and then twice socketpair(). These syscalls should be unrelated, but it's possible that the "async" invocation of socketpair() contributes to adding more threads. (Assuming that "async" means "in new thread" in syzkaller)
* Syzkaller gives it more attempts. ([2.2])
I do not understand yet what went wrong in our scheme and need to look deeper.
Ding, do you have more insights into it from your debugging?
Thanks,
–Günther
For reference:
[1] Report Mail: https://lore.kernel.org/all/[email protected]/
[2] Report: https://syzkaller.appspot.com/bug?extid=7ea2f5e9dfd468201817
[2.1] Reproducer: https://syzkaller.appspot.com/text?tag=ReproSyz&x=16e41c02580000
[2.2] Reproducer (C): https://syzkaller.appspot.com/text?tag=ReproC&x=15813652580000
[3] Patch: https://lore.kernel.org/all/[email protected]/
[4.1] https://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.git/tree/security/landlock/tsync.c?id=635c467cc14ebdffab3f77610217c1dacaf88e8c#n128
[4.2] https://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.git/tree/security/landlock/tsync.c?id=635c467cc14ebdffab3f77610217c1dacaf88e8c#n539
Quoted 33 lines · Günther Noack
(Very) tentative investigation:
In the Syzkaller report [2], it seems that the reproducer [2.1] is creating two rulesets and then enforcing them in parallel, a scenario which we are exercising in the
TEST(competing_enablement)intools/testing/selftests/landlock/tsync_test.calready, but which has not failed in my own selftest runs.In the crash report, there are four threads in total:
* Two are stuck in the line
wait_for_completion(&ctx->ready_to_commit);
in the per-thread task work (line 128 [4.1])
* Two are stuck in the linewait_for_completion(&shared_ctx.all_prepared)
in the calling thread's coordination logic (line 539 [4.2])In line 539, we are already on the code path where we detected that we are getting interrupted by another thread and where we are attempting to deal with the scenario where two
landlock_restrict_self()calls compete. This is detected on line 523 whenwait_for_completion_interruptible()is true. The approach to handle this is to set the overall-ERESTARTNOINTRerror and cancel the work that has been ongoing so far, by canceling the task works that did not start running yet and waiting for the ones that did start running (that is the step where we are blocked!). The reasoning there was that these task works will all hit the "all_prepared" stage now, but as we can see in the stack trace, the task works that are actively running are already on line 128 and have passed the "all_prepared" stage).Differences I can see between syzkaller and our own test:
Quoted 8 lines
* The reproducer also calls
openat()and then twicesocketpair(). These syscalls should be unrelated, but it's possible that the "async" invocation ofsocketpair()contributes to adding more threads. (Assuming that "async" means "in new thread" in syzkaller)
* Syzkaller gives it more attempts. ([2.2])I do not understand yet what went wrong in our scheme and need to look deeper.
OK, I think I understand now. Our existing recovery code for this conflict is this:
/*
* Decrement num_preparing for current, to undo that we initialized it
* to 1 a few lines above.
*/
if (atomic_dec_return(&shared_ctx.num_preparing) > 0) {
if (wait_for_completion_interruptible(
&shared_ctx.all_prepared)) {
/* In case of interruption, we need to retry the system call. */
atomic_set(&shared_ctx.preparation_error,
-ERESTARTNOINTR);
/*
* Cancel task works for tasks that did not start running yet,
* and decrement all_prepared and num_unfinished accordingly.
*/
cancel_tsync_works(&works, &shared_ctx);
/*
* The remaining task works have started running, so waiting for
* their completion will finish.
*/
wait_for_completion(&shared_ctx.all_prepared);
}
}When I wrote this, I assumed, as the last comment states, that the task works which we could not cancel, are already running.
I was wrong there, because I had misunderstood task_work_run(). When the task works get run there, it first *atomically dequeues the entire queue of scheduled task works*, and then runs them sequentially.
That is why, if we have one task work that belongs to the first landlock_restrict_self() call and one which belongs to the other, the task work which is scheduled later can (a) not be dequeued with cancel_tsync_works() any more, and (b) also has not started running yet.
Now the only thing that is necessary to produce the deadlock is that we have a pair of threads where the task works for the restriction calls have been scheduled in different order. When the two landlock_restrict_self() calls end up in the recovery path quoted above, they will wait for one of their task works to run which is blocked from running by another task work that is scheduled before and does not finish either.
(Just pasting a brain dump here to save you some time hunting for the root cause. I don't know the best solution yet either.)
–Günther
Quoted 49 lines · Günther Noack
OK, I think I understand now. Our existing recovery code for this conflict is this:
/*
* Decrementnum_preparingfor current, to undo that we initialized it
* to 1 a few lines above.
*/if (atomic_dec_return(&shared_ctx.num_preparing) > 0) { if (wait_for_completion_interruptible( &shared_ctx.all_prepared)) { /* In case of interruption, we need to retry the system call. */ atomic_set(&shared_ctx.preparation_error, -ERESTARTNOINTR); /* * Cancel task works for tasks that did not start running yet, * and decrement all_prepared and num_unfinished accordingly. */ cancel_tsync_works(&works, &shared_ctx); /* * The remaining task works have started running, so waiting for * their completion will finish. */ wait_for_completion(&shared_ctx.all_prepared); } }When I wrote this, I assumed, as the last comment states, that the task works which we could not cancel, are already running.
I was wrong there, because I had misunderstood
task_work_run(). When the task works get run there, it first *atomically dequeues the entire queue of scheduled task works*, and then runs them sequentially.That is why, if we have one task work that belongs to the first
landlock_restrict_self()call and one which belongs to the other, the task work which is scheduled later can (a) not be dequeued withcancel_tsync_works()any more, and (b) also has not started running yet.Now the only thing that is necessary to produce the deadlock is that we have a pair of threads where the task works for the restriction calls have been scheduled in different order. When the two
landlock_restrict_self()calls end up in the recovery path quoted above, they will wait for one of their task works to run which is blocked from running by another task work that is scheduled before and does not finish either.
Quoted 2 lines
(Just pasting a brain dump here to save you some time hunting for the root cause. I don't know the best solution yet either.)
Let me propose the following fixes:
1. Immediate fix for that specific issue
----------------------------------------
Proposal:
* Remove the wait_for_completion(&shared_ctx.all_prepared) call in the code snippet above.
* Rewrite surrounding comments: Be clear about the fact that cancel_tsync_works() is an opportunistic improvement, but we don't have a guarantee at all that it cancels any of the enqueued task works (because task_work_run might already have popped them off).
This removes the hold-and-wait dependency circle between the threads, which produces the observed deadlock. The way that we shut down now is that we exit the main loop (happens already without it, but we might also "break" to be explicit).
I think that this fix or an equivalent one is needed here, because in either way, our assumptions in the quoted code above were wrong.
2. Can we reason constructively about correctness?
--------------------------------------------------
The remaining question: If on the shutdown path, we can not actually remove all the enqueued task works, under what circumstances are we even able to interrupt and return from the landlock_restrict_self() system call?
2.1 For n competing restrict_self calls, n-1 of them need to get interrupted
----------------------------------------------------------------------------
To answer this, consider a multithreaded process with threads named "red", "green" and "blue" and many additional threads: When "red", "green" and "blue" enforce landlock_restrict_self() concurrently, due to differing iteration order, we might end up enqueueing the task works on other threads in all of the following combinations:
t0: R G B <- front of queue t1: R B G t2: G R B t3: G B R t4: B R G t5: B G R
In this configuration, for any of the landlock_restrict_self() system calls to even return (successfully or unsuccessfully), at least two threads must receive an interrupt and therefore remove their enqueued task works from the front of the queue. Assuming those are green and blue, we get:
t0: R <- front of queue t1: R t2: G R t3: G B R t4: B R t5: B G R
(This works because after the patch above, all of the enqueued G and B works finish even if there are remaining G and B works that are still blocked by an "R" entry.)
Now, "R" is in the front of the queue, and the landlock_restrict_self() call for the red thread can finish normally, even without it being interrupted.
Once the "R" task works are done as well, the remaining G and B works can run and finish as well.
This scheme generalizes: If we have n competing landlock_restrict_self() calls, then in worst case, at least n-1 of these system calls need to be interrupted so that they can all terminate.
2.2 Can we guarantee that two system calls get interrupted?
-----------------------------------------------------------
In case of competing landlock_restrict_self() calls, I think it is possible that not all relevant system calls get seen. The scenario is one where we have a "red" and "green" thread calling landlock_restrict_self().
(a set of additional threads)
t0: task_works: R G
t1: task_works: G R
tR: red thread
tG: green thread
In the red thread, the following happens:
* Under RCU, count the number of total threads => get a low number
* Allocate space for that number of task_works
* Under RCU
* Enqueue "R" into t0 and t1
* Enqueue "R" for some of the "additional threads"
* But we do not have enough pre-allocated space to enqueue "R" for the green thread tG.
The same thing happens in the green thread as well.
The result is that we still have a deadlock between t0 and t1, but neither the red nor the green thread get interrupted so that they can resolve it.
(FWIW, you could resolve it from the outside by sending a signal to the red or green thread manually, but it is not guaranteed to happen on its own.)
Caveat: I am making pessimistic assumptions about the iteration order of the task list here, and I am assuming that the number of "additional threads" is swinging up and down during the competing enforcement, so that the enforcing threads are mis-approximating the required space for memory pre-allocation.
2.3 Possible resolutions
------------------------
* We could try to interrupt all sibling threads during the teardown, to fix the issue discussed in 2.2. (Downside: Complicated, more expensive)
* The reason why landlock_restrict_self() can't return is because it needs to wait until all task works are done before it can free the memory. Alternatively, we could make the task works take ownership of these memory structures (refcounting the shared_ctx). (Downside:
The used memory is not linear to the number of threads any more.)
Side remark: In testing, I had the impression that the landlock_restrict_self() calls can go into a retry loop for a while where all competing threads get interrupted all the time; in a debug build, when the Syzkaller test prints out a line for each attempt, sometimes it was hanging for seconds and *then* resolving itself again.
3 Conclusion
---------------
I would prefer if the final solution would not require deadlock reasoning at that level and we could do it in simpler way. I therefore propose to do what Ding Yihan suggested, and what we had also discussed previously in the code review:
* Let's serialize the landlock_restrict_self()-with-TSYNC operations through the cred_guard_mutex.
This will resolve the issue where competing landlock_restrict_self() calls with TSYNC can deadlock. It will also remove the jittery behavior for that worst case where the conflict is resolved through retry.
So in my mind, we need both patches:
* The fix to the cleanup path from 1. above, to make interruption work more reliably and to correct the misunderstandings in the comments.
* cred_guard_mutex to serialize the TSYNC invocations.
Please let me know what you think.
Thanks,
–Günther
Hi Günther,
Thank you for the detailed analysis and the clear breakdown. Apologies for the delayed response. I spent the last couple of days thoroughly reading through the previous mailing list discussions. I was trying hard to see if there was any viable pure lockless design that could solve this concurrency issue while preserving the original architecture.
However, after looking at the complexities you outlined, I completely agree with your conclusion: serializing the TSYNC operations is indeed the most robust and reasonable path forward to prevent the deadlock.
Regarding the lock choice, since 'cred_guard_mutex' is explicitly marked as deprecated for new code in the kernel,maybe we can use its modern replacement: 'exec_update_lock' (using down_write_trylock / up_write on current->signal). This aligns with the current subsystem standards and was also briefly touched upon by Jann in the older discussions.
I fully understand the requirement for the two-part patch series:
1. Cleaning up the cancellation logic and comments.
2. Introducing the serialization lock for TSYNC.
I will take some time to draft and test this patch series properly. I also plan to discuss this with my kernel colleagues here at UnionTech to see if they have any additional suggestions on the implementation details before I submit it.
I will send out the v1 patch series to the list as soon as it is ready. Thanks again for your guidance and the great discussion!
Best regards,
Yihan Ding
Quoted 215 lines · Günther Noack
Quoted 49 lines · Günther Noack
OK, I think I understand now. Our existing recovery code for this conflict is this:
/*
* Decrementnum_preparingfor current, to undo that we initialized it
* to 1 a few lines above.
*/if (atomic_dec_return(&shared_ctx.num_preparing) > 0) { if (wait_for_completion_interruptible( &shared_ctx.all_prepared)) { /* In case of interruption, we need to retry the system call. */ atomic_set(&shared_ctx.preparation_error, -ERESTARTNOINTR); /* * Cancel task works for tasks that did not start running yet, * and decrement all_prepared and num_unfinished accordingly. */ cancel_tsync_works(&works, &shared_ctx); /* * The remaining task works have started running, so waiting for * their completion will finish. */ wait_for_completion(&shared_ctx.all_prepared); } }When I wrote this, I assumed, as the last comment states, that the task works which we could not cancel, are already running.
I was wrong there, because I had misunderstood
task_work_run(). When the task works get run there, it first *atomically dequeues the entire queue of scheduled task works*, and then runs them sequentially.That is why, if we have one task work that belongs to the first
landlock_restrict_self()call and one which belongs to the other, the task work which is scheduled later can (a) not be dequeued withcancel_tsync_works()any more, and (b) also has not started running yet.Now the only thing that is necessary to produce the deadlock is that we have a pair of threads where the task works for the restriction calls have been scheduled in different order. When the two
landlock_restrict_self()calls end up in the recovery path quoted above, they will wait for one of their task works to run which is blocked from running by another task work that is scheduled before and does not finish either.Quoted 2 lines
(Just pasting a brain dump here to save you some time hunting for the root cause. I don't know the best solution yet either.)
Let me propose the following fixes:
1. Immediate fix for that specific issue
----------------------------------------Proposal:
* Remove thewait_for_completion(&shared_ctx.all_prepared)call in the code snippet above.
* Rewrite surrounding comments: Be clear about the fact thatcancel_tsync_works()is an opportunistic improvement, but we don't have a guarantee at all that it cancels any of the enqueued task works (becausetask_work_runmight already have popped them off).This removes the hold-and-wait dependency circle between the threads, which produces the observed deadlock. The way that we shut down now is that we exit the main loop (happens already without it, but we might also "break" to be explicit).
I think that this fix or an equivalent one is needed here, because in either way, our assumptions in the quoted code above were wrong.
2. Can we reason constructively about correctness?
--------------------------------------------------The remaining question: If on the shutdown path, we can not actually remove all the enqueued task works, under what circumstances are we even able to interrupt and return from the
landlock_restrict_self()system call?2.1 For n competing
restrict_selfcalls, n-1 of them need to get interrupted
----------------------------------------------------------------------------To answer this, consider a multithreaded process with threads named "red", "green" and "blue" and many additional threads: When "red", "green" and "blue" enforce
landlock_restrict_self()concurrently, due to differing iteration order, we might end up enqueueing the task works on other threads in all of the following combinations:t0: R G B <- front of queue t1: R B G t2: G R B t3: G B R t4: B R G t5: B G RIn this configuration, for any of the
landlock_restrict_self()system calls to even return (successfully or unsuccessfully), at least two threads must receive an interrupt and therefore remove their enqueued task works from the front of the queue. Assuming those are green and blue, we get:t0: R <- front of queue t1: R t2: G R t3: G B R t4: B R t5: B G R(This works because after the patch above, all of the enqueued G and B works finish even if there are remaining G and B works that are still blocked by an "R" entry.)
Now, "R" is in the front of the queue, and the
landlock_restrict_self()call for the red thread can finish normally, even without it being interrupted.Once the "R" task works are done as well, the remaining G and B works can run and finish as well.
This scheme generalizes: If we have n competing
landlock_restrict_self()calls, then in worst case, at least n-1 of these system calls need to be interrupted so that they can all terminate.2.2 Can we guarantee that two system calls get interrupted?
-----------------------------------------------------------In case of competing
landlock_restrict_self()calls, I think it is possible that not all relevant system calls get seen. The scenario is one where we have a "red" and "green" thread callinglandlock_restrict_self().(a set of additional threads)
t0:task_works: R G
t1:task_works: G R
tR: red thread
tG: green threadIn the red thread, the following happens:
* Under RCU, count the number of total threads => get a low number
* Allocate space for that number oftask_works
* Under RCU
* Enqueue "R" into t0 and t1
* Enqueue "R" for some of the "additional threads"
* But we do not have enough pre-allocated space to enqueue "R" for the green thread tG.The same thing happens in the green thread as well.
The result is that we still have a deadlock between t0 and t1, but neither the red nor the green thread get interrupted so that they can resolve it.
(FWIW, you could resolve it from the outside by sending a signal to the red or green thread manually, but it is not guaranteed to happen on its own.)
Caveat: I am making pessimistic assumptions about the iteration order of the task list here, and I am assuming that the number of "additional threads" is swinging up and down during the competing enforcement, so that the enforcing threads are mis-approximating the required space for memory pre-allocation.
2.3 Possible resolutions
------------------------* We could try to interrupt all sibling threads during the teardown, to fix the issue discussed in 2.2. (Downside: Complicated, more expensive)
* The reason whylandlock_restrict_self()can't return is because it needs to wait until all task works are done before it can free the memory. Alternatively, we could make the task works take ownership of these memory structures (refcounting theshared_ctx). (Downside:
The used memory is not linear to the number of threads any more.)Side remark: In testing, I had the impression that the
landlock_restrict_self()calls can go into a retry loop for a while where all competing threads get interrupted all the time; in a debug build, when the Syzkaller test prints out a line for each attempt, sometimes it was hanging for seconds and *then* resolving itself again.3 Conclusion
---------------I would prefer if the final solution would not require deadlock reasoning at that level and we could do it in simpler way. I therefore propose to do what Ding Yihan suggested, and what we had also discussed previously in the code review:
* Let's serialize the landlock_restrict_self()-with-TSYNC operations through the
cred_guard_mutex.This will resolve the issue where competing
landlock_restrict_self()calls with TSYNC can deadlock. It will also remove the jittery behavior for that worst case where the conflict is resolved through retry.So in my mind, we need both patches:
* The fix to the cleanup path from 1. above, to make interruption work more reliably and to correct the misunderstandings in the comments.
*cred_guard_mutexto serialize the TSYNC invocations.Please let me know what you think.
Thanks,
–Günther
Günther Noack
reviewerHello!
Quoted 21 lines · Ding Yihan
Thank you for the detailed analysis and the clear breakdown. Apologies for the delayed response. I spent the last couple of days thoroughly reading through the previous mailing list discussions. I was trying hard to see if there was any viable pure lockless design that could solve this concurrency issue while preserving the original architecture.
However, after looking at the complexities you outlined, I completely agree with your conclusion: serializing the TSYNC operations is indeed the most robust and reasonable path forward to prevent the deadlock.
Regarding the lock choice, since 'cred_guard_mutex' is explicitly marked as deprecated for new code in the kernel,maybe we can use its modern replacement: 'exec_update_lock' (usingdown_write_trylock/up_writeoncurrent->signal). This aligns with the current subsystem standards and was also briefly touched upon by Jann in the older discussions.
I fully understand the requirement for the two-part patch series:
1. Cleaning up the cancellation logic and comments.
2. Introducing the serialization lock for TSYNC.
Quoted 8 lines
I will take some time to draft and test this patch series properly. I also plan to discuss this with my kernel colleagues here at UnionTech to see if they have any additional suggestions on the implementation details before I submit it.
I will send out the v1 patch series to the list as soon as it is ready. Thanks again for your guidance and the great discussion!
Thank you, Ding, this is much appreciated!
I agree, the exec_update_lock might be the better solution; I also need to familiarize myself more with it to double-check.
—Günther
Hi Günther,
Thank you for the detailed analysis! I completely agree that serializing the TSYNC operations is the right way to prevent this deadlock. I have drafted a patch using exec_update_lock (similar to how seccomp uses cred_guard_mutex).
Regarding your proposal to split this into two patches (one for the cleanup
path and one for the lock): Maybe combining them into a single patch is a better choice. Here is why:
We actually *cannot* remove wait_for_completion(&shared_ctx.all_prepared)
in the interrupt recovery path. Since shared_ctx is allocated on the local stack of the caller, removing the wait would cause a severe Use-After-Free (UAF) if the thread returns to userspace while sibling task_works are still executing and dereferencing ctx.
By adding the lock, we inherently resolve the deadlock, meaning the sibling task_works
will never get stuck. Thus, wait_for_completion becomes perfectly safe to keep,
and it remains strictly necessary to protect the stack memory. Therefore, the "fix" for the cleanup path is simply updating the comments to reflect this reality, which is tightly coupled with the locking fix. It felt more cohesive as a single patch.
I have test the patch on my laptop,and it will not trigger the issue.Let's have syzbot test this combined logic:
#syz test:
--- a/security/landlock/tsync.c
+++ b/security/landlock/tsync.c
@@ -447,6 +447,12 @@ int landlock_restrict_sibling_threads(const struct cred *old_cred,
shared_ctx.new_cred = new_cred;
shared_ctx.set_no_new_privs = task_no_new_privs(current);+ /*
+ * Serialize concurrent TSYNC operations to prevent deadlocks
+ * when multiple threads call landlock_restrict_self() simultaneously.
+ */
+ down_write(¤t->signal->exec_update_lock);
+
/*
* We schedule a pseudo-signal task_work for each of the calling task's
* sibling threads. In the task work, each thread:
@@ -527,14 +533,17 @@ int landlock_restrict_sibling_threads(const struct cred *old_cred,
-ERESTARTNOINTR);
/*- * Cancel task works for tasks that did not start running yet,
- * and decrement all_prepared and num_unfinished accordingly.
+ * Opportunistic improvement: try to cancel task works
+ * for tasks that did not start running yet. We do not
+ * have a guarantee that it cancels any of the enqueued
+ * task works (because task_work_run() might already have
+ * dequeued them).
*/
cancel_tsync_works(&works, &shared_ctx);
/*- * The remaining task works have started running, so waiting for
- * their completion will finish.
+ * We must wait for the remaining task works to finish to
+ * prevent a use-after-free of the local shared_ctx.
*/
wait_for_completion(&shared_ctx.all_prepared);
}@@ -557,5 +566,7 @@ int landlock_restrict_sibling_threads(const struct cred *old_cred,
tsync_works_release(&works);
+ up_write(¤t->signal->exec_update_lock);
+
return atomic_read(&shared_ctx.preparation_error);
}
--
Quoted 40 lines · Günther Noack
Hello!
Quoted 21 lines · Ding Yihan
Thank you for the detailed analysis and the clear breakdown. Apologies for the delayed response. I spent the last couple of days thoroughly reading through the previous mailing list discussions. I was trying hard to see if there was any viable pure lockless design that could solve this concurrency issue while preserving the original architecture.
However, after looking at the complexities you outlined, I completely agree with your conclusion: serializing the TSYNC operations is indeed the most robust and reasonable path forward to prevent the deadlock.
Regarding the lock choice, since 'cred_guard_mutex' is explicitly marked as deprecated for new code in the kernel,maybe we can use its modern replacement: 'exec_update_lock' (usingdown_write_trylock/up_writeoncurrent->signal). This aligns with the current subsystem standards and was also briefly touched upon by Jann in the older discussions.
I fully understand the requirement for the two-part patch series:
1. Cleaning up the cancellation logic and comments.
2. Introducing the serialization lock for TSYNC.Quoted 8 lines
I will take some time to draft and test this patch series properly. I also plan to discuss this with my kernel colleagues here at UnionTech to see if they have any additional suggestions on the implementation details before I submit it.
I will send out the v1 patch series to the list as soon as it is ready. Thanks again for your guidance and the great discussion!Thank you, Ding, this is much appreciated!
I agree, the
exec_update_lockmight be the better solution; I also need to familiarize myself more with it to double-check.—Günther
syzbot
syzbot"---" does not look like a valid git repo address.
Quoted 20 lines
Hi Günther,
Thank you for the detailed analysis! I completely agree that serializing the TSYNC operations is the right way to prevent this deadlock. I have drafted a patch using
exec_update_lock(similar to how seccomp usescred_guard_mutex).Regarding your proposal to split this into two patches (one for the cleanup
path and one for the lock): Maybe combining them into a single patch is a better choice. Here is why:We actually *cannot* remove
wait_for_completion(&shared_ctx.all_prepared)
in the interrupt recovery path. Sinceshared_ctxis allocated on the local stack of the caller, removing the wait would cause a severe Use-After-Free (UAF) if the thread returns to userspace while siblingtask_worksare still executing and dereferencingctx.By adding the lock, we inherently resolve the deadlock, meaning the sibling
task_works
will never get stuck. Thus,wait_for_completionbecomes perfectly safe to keep,
and it remains strictly necessary to protect the stack memory. Therefore, the "fix" for the cleanup path is simply updating the comments to reflect this reality, which is tightly coupled with the locking fix. It felt more cohesive as a single patch.
Quoted 3 lines
I have test the patch on my laptop,and it will not trigger the issue.Let's have syzbot test this combined logic:
#syz test:
"---" does not look like a valid git repo address.
Quoted 134 lines
---
a/security/landlock/tsync.c+++
b/security/landlock/tsync.c(quoted diff) +15
-5@@ -447,6 +447,12 @@ int landlock_restrict_sibling_threads(const struct cred *old_cred, shared_ctx.new_cred = new_cred; shared_ctx.set_no_new_privs = task_no_new_privs(current); + /* + * Serialize concurrent TSYNC operations to prevent deadlocks + * when multiple threads call landlock_restrict_self() simultaneously. + */ + down_write(¤t->signal->exec_update_lock); + /* * We schedule a pseudo-signal task_work for each of the calling task's * sibling threads. In the task work, each thread:@@ -527,14 +533,17 @@ int landlock_restrict_sibling_threads(const struct cred *old_cred, -ERESTARTNOINTR); /* - * Cancel task works for tasks that did not start running yet, - * and decrement all_prepared and num_unfinished accordingly. + * Opportunistic improvement: try to cancel task works + * for tasks that did not start running yet. We do not + * have a guarantee that it cancels any of the enqueued + * task works (because task_work_run() might already have + * dequeued them). */ cancel_tsync_works(&works, &shared_ctx); /* - * The remaining task works have started running, so waiting for - * their completion will finish. + * We must wait for the remaining task works to finish to + * prevent a use-after-free of the local shared_ctx. */ wait_for_completion(&shared_ctx.all_prepared); }@@ -557,5 +566,7 @@ int landlock_restrict_sibling_threads(const struct cred *old_cred, tsync_works_release(&works); + up_write(¤t->signal->exec_update_lock); + return atomic_read(&shared_ctx.preparation_error); } --Quoted 40 lines · Günther Noack
Hello!
Quoted 21 lines · Ding Yihan
Thank you for the detailed analysis and the clear breakdown. Apologies for the delayed response. I spent the last couple of days thoroughly reading through the previous mailing list discussions. I was trying hard to see if there was any viable pure lockless design that could solve this concurrency issue while preserving the original architecture.
However, after looking at the complexities you outlined, I completely agree with your conclusion: serializing the TSYNC operations is indeed the most robust and reasonable path forward to prevent the deadlock.
Regarding the lock choice, since 'cred_guard_mutex' is explicitly marked as deprecated for new code in the kernel,maybe we can use its modern replacement: 'exec_update_lock' (usingdown_write_trylock/up_writeoncurrent->signal). This aligns with the current subsystem standards and was also briefly touched upon by Jann in the older discussions.
I fully understand the requirement for the two-part patch series:
1. Cleaning up the cancellation logic and comments.
2. Introducing the serialization lock for TSYNC.Quoted 8 lines
I will take some time to draft and test this patch series properly. I also plan to discuss this with my kernel colleagues here at UnionTech to see if they have any additional suggestions on the implementation details before I submit it.
I will send out the v1 patch series to the list as soon as it is ready. Thanks again for your guidance and the great discussion!Thank you, Ding, this is much appreciated!
I agree, the
exec_update_lockmight be the better solution; I also need to familiarize myself more with it to double-check.—Günther
PATCH 1/1 landlock: Fix deadlock in restrict_one_thread_callback
In reply to Günther Noacksyzbot found a deadlock in landlock_restrict_sibling_threads(). When multiple threads concurrently call landlock_restrict_self() with sibling thread restriction enabled, they can deadlock by mutually queueing task_works on each other and then blocking in kernel space (waiting for the other to finish).
Fix this by serializing the TSYNC operations within the same process using the exec_update_lock. This prevents concurrent invocations from deadlocking.
Additionally, update the comments in the interrupt recovery path to clarify that cancel_tsync_works() is an opportunistic cleanup, and waiting for completion is strictly necessary to prevent a Use-After-Free of the stack-allocated shared_ctx.
--- security/landlock/tsync.c | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-)
security/landlock/tsync.c +15 -4
@@ -447,6 +447,12 @@ int landlock_restrict_sibling_threads(const struct cred *old_cred, shared_ctx.new_cred = new_cred; shared_ctx.set_no_new_privs =task_no_new_privs (current); +/* +* Serialize concurrent TSYNC operations to prevent deadlocks +* when multiple threads call landlock_restrict_self() simultaneously. +*/ +down_write (¤t->signal->exec_update_lock); +/* * We schedule a pseudo-signal task_work for each of the calling task's * sibling threads. In the task work, each thread:
@@ -527,14 +533,17 @@ int landlock_restrict_sibling_threads(const struct cred *old_cred, -ERESTARTNOINTR);/* -* Cancel task works for tasks that did not start running yet, -* and decrement all_prepared and num_unfinished accordingly. +* Opportunistic improvement: try to cancel task works +* for tasks that did not start running yet. We do not +* have a guarantee that it cancels any of the enqueued +* task works (because task_work_run() might already have +* dequeued them). */ cancel_tsync_works (&works, &shared_ctx);/* -* The remaining task works have started running, so waiting for -* their completion will finish. +* We must wait for the remaining task works to finish to +* prevent a use-after-free of the local shared_ctx. */ wait_for_completion (&shared_ctx.all_prepared); }
@@ -557,5 +566,7 @@ int landlock_restrict_sibling_threads(const struct cred *old_cred,tsync_works_release (&works); +up_write (¤t->signal->exec_update_lock); +return atomic_read (&shared_ctx.preparation_error); }
Signature · 1 line
2.51.0
Re: [PATCH] landlock: Fix deadlock in restrict_one_thread_callback
Hello!
Thanks for sending the patch!
Quoted 28 lines · Yihan Ding
syzbot found a deadlock in
landlock_restrict_sibling_threads(). When multiple threads concurrently calllandlock_restrict_self()with sibling thread restriction enabled, they can deadlock by mutually queueingtask_workson each other and then blocking in kernel space (waiting for the other to finish).Fix this by serializing the TSYNC operations within the same process using the
exec_update_lock. This prevents concurrent invocations from deadlocking.Additionally, update the comments in the interrupt recovery path to clarify that
cancel_tsync_works()is an opportunistic cleanup, and waiting for completion is strictly necessary to prevent a Use-After-Free of the stack-allocatedshared_ctx.Fixes 42fc7e6543f6 ("landlock: Multithreading support for landlock_restrict_self()")Reported-by [email protected]Signed-off-by Yihan Ding <[email protected]>--- security/landlock/tsync.c | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-)security/landlock/tsync.c +0
-0
security/landlock/tsync.c int landlock_restrict_sibling_threads(const struct cred *old_cred, · line 454
Quoted 8 lines
security/landlock/tsync.c +5
-0@@ -447,6 +447,12 @@ int landlock_restrict_sibling_threads(const struct cred *old_cred, shared_ctx.new_cred = new_cred; shared_ctx.set_no_new_privs =task_no_new_privs (current); +/* +* Serialize concurrent TSYNC operations to prevent deadlocks +* when multiple threads call landlock_restrict_self() simultaneously. +*/ +down_write (¤t->signal->exec_update_lock);
Should we use the *_killable variant of this lock acquisition?
Quoted 14 lines
security/landlock/tsync.c +5
-2/* * We schedule a pseudo-signal task_work for each of the calling task's * sibling threads. In the task work, each thread: @@ -527,14 +533,17 @@ int landlock_restrict_sibling_threads(const struct cred *old_cred, -ERESTARTNOINTR);/* -* Cancel task works for tasks that did not start running yet, -* and decrement all_prepared and num_unfinished accordingly. +* Opportunistic improvement: try to cancel task works +* for tasks that did not start running yet. We do not +* have a guarantee that it cancels any of the enqueued +* task works (because task_work_run() might already have +* dequeued them).
security/landlock/tsync.c int landlock_restrict_sibling_threads(const struct cred *old_cred, · line 548
Quoted 10 lines
security/landlock/tsync.c +2
-2*/ cancel_tsync_works (&works, &shared_ctx);/* -* The remaining task works have started running, so waiting for -* their completion will finish. +* We must wait for the remaining task works to finish to +* prevent a use-after-free of the local shared_ctx. */ wait_for_completion (&shared_ctx.all_prepared);
I do not think that we must wait for all_prepared here, as your updated comment says: The landlock_restrict_sibling_threads() function still waits for all of these task works to finish at the bottom where it waits for "all_finished", so there is no UAF on the local shared context?
I would recommend replacing the wait_for_completion(&shared_ctx.all_prepared) call and its comment with an explicit "break":
/*
* Break the loop with error. The cleanup code after the loop
* unblocks the remaining task_works.
*/
break;
Please also update the comment above the complete_all(ready_to_commit):
We now have either (a) all sibling threads blocking and in "prepared" state in the task work, or (b) the preparation error is set. Ask all threads to commit (or abort).
Then it is a bit more explicit about the error handling variant of this.
(FYI, I have tested the patch variant where I only removed the wait_for_completion(all_prepared) call, and where I did *not* add the additional lock at the top. In this configuration, I was unable to get it to hang any more, even with added mdelays. But as discussed in section 2.2 of [1], there are still difficult to reproduce scenarios where this can theoretically fail, and it is better to use the lock at the top.)
[1] https://lore.kernel.org/all/[email protected]/
Please also feel free to split up the change into a part that adds the exec_guard_lock and a part that changes the path where the calling thread gets interrupted. Strictly speaking, the part where we change the interruption logic is only a nicety once we have the exec_guard_lock in place.
Quoted 12 lines
security/landlock/tsync.c +2
-0}@@ -557,5 +566,7 @@ int landlock_restrict_sibling_threads(const struct cred *old_cred,tsync_works_release (&works); +up_write (¤t->signal->exec_update_lock); +return atomic_read (&shared_ctx.preparation_error); }Signature · 1 line
2.51.0
Thanks,
–Günther
Günther Noack
reviewer#syz set subsystems: lsm, kernel