Re: [PATCH] fork/pid: Fix use-after-free in __task_pid_nr_ns

From: Qing Wang

Date: Tue Jan 06 2026 - 05:58:41 EST


On Tue, 06 Jan 2026 at 17:04, Oleg Nesterov <oleg@xxxxxxxxxx> wrote:
> At first glance this is racy. Can't task->signal be freed right after
> the check?
>
> And... Can't we make another fix? If copy_process() fails and does
> free_signal_struct(), the child has not been added to rcu protected
> lists and init_task_pid(child) was not called yet.
>
> So perhaps something like the patch below can work?
>
> Oleg.
> ---
>
> --- x/kernel/events/core.c
> +++ x/kernel/events/core.c
> @@ -1422,16 +1422,17 @@ unclone_ctx(struct perf_event_context *c
> static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
> enum pid_type type)
> {
> - u32 nr;
> + u32 nr = 0;
> /*
> * only top level events have the pid namespace they were created in
> */
> if (event->parent)
> event = event->parent;
>
> - nr = __task_pid_nr_ns(p, type, event->ns);
> + if (pid_alive(p))
> + nr = __task_pid_nr_ns(p, type, event->ns);
> /* avoid -1 if it is idle thread or runs in another ns */
> - if (!nr && !pid_alive(p))
> + if (!nr)
> nr = -1;
> return nr;
> }

Could we put the checking 'pid_alive(task)' into __task_pid_nr_ns()?
Because there is another similar use case here.

arch/s390/kernel/perf_cpum_sf.c
619,9: pid = __task_pid_nr_ns(tsk, type, event->ns);

---

diff --git a/kernel/pid.c b/kernel/pid.c
index a31771bc89c1..e8826731fa47 100644
--- a/kernel/pid.c
+++ b/kernel/pid.c
@@ -515,7 +515,7 @@ pid_t __task_pid_nr_ns(struct task_struct *task, enum pid_type type,
rcu_read_lock();
if (!ns)
ns = task_active_pid_ns(current);
- if (ns)
+ if (ns && pid_alive(task))
nr = pid_nr_ns(rcu_dereference(*task_pid_ptr(task, type)), ns);
rcu_read_unlock();