1 From a15f37a40145c986cdf289a4b88390f35efdecc4 Mon Sep 17 00:00:00 2001
2 From: Oleg Nesterov <oleg@redhat.com>
3 Date: Mon, 15 Sep 2025 14:09:17 +0200
4 Subject: kernel/sys.c: fix the racy usage of task_lock(tsk->group_leader) in sys_prlimit64() paths
6 From: Oleg Nesterov <oleg@redhat.com>
8 commit a15f37a40145c986cdf289a4b88390f35efdecc4 upstream.
10 The usage of task_lock(tsk->group_leader) in sys_prlimit64()->do_prlimit()
13 sys_prlimit64() does get_task_struct(tsk) but this only protects task_struct
14 itself. If tsk != current and tsk is not a leader, this process can exit/exec
15 and task_lock(tsk->group_leader) may use the already freed task_struct.
17 Another problem is that sys_prlimit64() can race with mt-exec which changes
18 ->group_leader. In this case do_prlimit() may take the wrong lock, or (worse)
19 ->group_leader may change between task_lock() and task_unlock().
21 Change sys_prlimit64() to take tasklist_lock when necessary. This is not
22 nice, but I don't see a better fix for -stable.
24 Link: https://lkml.kernel.org/r/20250915120917.GA27702@redhat.com
25 Fixes: 18c91bb2d872 ("prlimit: do not grab the tasklist_lock")
26 Signed-off-by: Oleg Nesterov <oleg@redhat.com>
27 Cc: Christian Brauner <brauner@kernel.org>
28 Cc: Jiri Slaby <jirislaby@kernel.org>
29 Cc: Mateusz Guzik <mjguzik@gmail.com>
30 Cc: <stable@vger.kernel.org>
31 Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
32 Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
34 kernel/sys.c | 22 ++++++++++++++++++++--
35 1 file changed, 20 insertions(+), 2 deletions(-)
39 @@ -1698,6 +1698,7 @@ SYSCALL_DEFINE4(prlimit64, pid_t, pid, u
40 struct rlimit old, new;
41 struct task_struct *tsk;
42 unsigned int checkflags = 0;
47 @@ -1724,8 +1725,25 @@ SYSCALL_DEFINE4(prlimit64, pid_t, pid, u
51 - ret = do_prlimit(tsk, resource, new_rlim ? &new : NULL,
52 - old_rlim ? &old : NULL);
53 + need_tasklist = !same_thread_group(tsk, current);
54 + if (need_tasklist) {
56 + * Ensure we can't race with group exit or de_thread(),
57 + * so tsk->group_leader can't be freed or changed until
58 + * read_unlock(tasklist_lock) below.
60 + read_lock(&tasklist_lock);
61 + if (!pid_alive(tsk))
66 + ret = do_prlimit(tsk, resource, new_rlim ? &new : NULL,
67 + old_rlim ? &old : NULL);
71 + read_unlock(&tasklist_lock);
73 if (!ret && old_rlim) {
74 rlim_to_rlim64(&old, &old64);