Skip to contentSkip to conversation

ptrace: keep task's mm around in separate exit_mm field post-exit

PATCH In review Christian Brauner 3 participants 13 messages May 16 – May 19

Subsystems (11)
lore
Share & tools
lore

Christian Brauner

author maintainer
#0 lore raw

PATCH 1/1 ptrace: keep task's mm around in separate exit_mm field post-exit

From: Jann Horn <[email protected]>

__ptrace_may_access() checks can happen on target tasks that are in the middle of do_exit(), past exit_mm(). At that point, the ->mm pointer has been NULLed out, and the mm_struct has been mmput().

Unfortunately, the mm_struct contains the dumpability and the user_ns in which the task last went through execve(), and we need those for __ptrace_may_access(). Currently, that problem is handled by failing open:
If the ->mm is gone, we assume that the task was dumpable. In some edge cases, this could potentially expose access to things like /proc/$pid/fd/$fd of originally non-dumpable processes. (exit_files() comes after exit_mm(), so the file descriptor table is still there when we've gone through exit_mm().)

I believe that this patch may be the least bad option to fix this - keep the mm_struct (but not process memory) around with an mmgrab() reference from exit_mm() until the task goes away completely.

Note that this moves free_task() down in order to make mmdrop_async() available without a forward declaration.

Christian Brauner (Amutable) <[email protected]> says:

I massaged the patch a bit and rewrote parts of the commit message.

The cached task->user_dumpable bit introduced by commit 31e62c2ebbfd ("ptrace: slightly saner 'get_dumpable() logic'") is removed here: the mmgrab'd exit_mm reference supplies the real dumpable flag and the original user_ns. exit_mm() now publishes ->exit_mm before clearing ->mm so that task_still_dumpable() readers cannot observe both NULL on a user task.

Fixes bfedb589252c ("mm: Add a user_ns owner to mm_struct and fix ptrace permission checks")

---
In 2020 Jann actually pointed to the exact bug class that the recent ptrace bug used and asked for a architecturally very clean fix to be merged but it never got anywhere.

In the off-list ptrace discussion I brought up my intention to have this merged on top. So this rebases Jann's patch [1] which addresses the root cause directly: stash an mmgrab() reference to the mm_struct in task->exit_mm during exit_mm(), and release it via mmdrop_async() in free_task(). The pinned mm_struct keeps the address space metadata (flags, user_ns) reachable for the full lifetime of the task_struct without keeping the actual memory mappings alive. ptrace_may_access() then simply takes the exit_mm into account. The exit_mm field is separate and none of the other in-kernel callers need to change so there's no regression risks.

Beyond ptrace, the fact that task->mm isn't accessible post-exit anymore causes complications for other series. Minchan Kim's recent PROCESS_MRELEASE_REAP_KILL series [2] describes the same shape from the OOM-reaper side: process_mrelease() racing against do_exit() ends up with task->mm and falls over with -ESRCH, deferring reclamation indefinitely under Android LMKD pressure. That series works around it by moving the SIGKILL injection into process_mrelease() itself, but the underlying issue is identical: callers legitimately need to reach the mm of a task after exit. That whole patch becomes rather simple with this fix.

Note that I had already brought this up with some mm folks that were involved in the ptrace issue off-list.

Also note that the upstream patch has at least two regressions. Reading the exit status from /proc/<pid>/stat and opening /proc/<pid>/ns/{pid,user} of a zombie. The latter I've used multiple times from inside a container for non-dumpable tasks for nested and non-nested containers. Afaict, both will now be denied because we resort to checking in the initial userns for non-dumpable tasks. And tools like Incus do nested containers so I also suspect that anything that relies on looking at the userns or pidns of zombies risks spurious failures.

I think we should do the clean thing and let ptrace look at the actual mm state post exit. Keep it in a separate field and there's no regression risk for users that expect task->mm itself to be NULL post exit.

[1] https://lore.kernel.org/r/[email protected]
[2] https://lore.kernel.org/r/[email protected]

---
 include/linux/sched.h |  4 +---
 kernel/exit.c         |  3 ++-
 kernel/fork.c         | 64 ++++++++++++++++++++++++++-------------------------
 kernel/ptrace.c       | 20 +++++++++++-----
 4 files changed, 50 insertions(+), 41 deletions(-)
include/linux/sched.h +1 -3
index ee06cba5c6f5..7cefeb6cbba7 100644
@@ -961,6 +961,7 @@ struct task_struct {
 
 	struct mm_struct		*mm;
 	struct mm_struct		*active_mm;
+	struct mm_struct		*exit_mm;
 
 	int				exit_state;
 	int				exit_code;
@@ -1002,9 +1003,6 @@ struct task_struct {
 	unsigned			sched_rt_mutex:1;
 #endif
 
-	/* Save user-dumpable when mm goes away */
-	unsigned			user_dumpable:1;
-
 	/* Bit to tell TOMOYO we're in execve(): */
 	unsigned			in_execve:1;
 	unsigned			in_iowait:1;
kernel/exit.c +2 -1
index f50d73c272d6..9af227c23e2b 100644
@@ -571,7 +571,8 @@ static void exit_mm(void)
 	 */
 	smp_mb__after_spinlock();
 	local_irq_disable();
-	current->user_dumpable = (get_dumpable(mm) == SUID_DUMP_USER);
+	mmgrab(mm);
+	current->exit_mm = mm;
 	current->mm = NULL;
 	membarrier_update_current_mm(NULL);
 	enter_lazy_tlb(mm, current);
kernel/fork.c +33 -31

76 lines not on this page · raw message

kernel/ptrace.c +14 -6
index 130043bfc209..2955a59c18cf 100644
@@ -272,18 +272,26 @@ static bool ptrace_has_cap(struct user_namespace *ns, unsigned int mode)
 	return ns_capable(ns, CAP_SYS_PTRACE);
 }
 
-static bool task_still_dumpable(struct task_struct *task, unsigned int mode)
+/*
+ * Decide whether ptrace access to @task is allowed based on its mm.
+ * Reads the dumpable flag and user_ns from ->mm, or from ->exit_mm if
+ * the task has gone through exit_mm(). Note that kernel threads may have
+ * neither.
+ */
+static bool may_access_mm(struct task_struct *task, unsigned int mode)
 {
 	struct mm_struct *mm = task->mm;
+	struct user_namespace *mm_userns = &init_user_ns;
+
+	if (!mm)
+		mm = task->exit_mm;
 	if (mm) {
 		if (get_dumpable(mm) == SUID_DUMP_USER)
 			return true;
-		return ptrace_has_cap(mm->user_ns, mode);
+		mm_userns = mm->user_ns;
 	}
 
-	if (task->user_dumpable)
-		return true;
-	return ptrace_has_cap(&init_user_ns, mode);
+	return ptrace_has_cap(mm_userns, mode);
 }
 
 /* Returns 0 on success, -errno on denial. */
@@ -350,7 +358,7 @@ static int __ptrace_may_access(struct task_struct *task, unsigned int mode)
 	 * Pairs with a write barrier in commit_creds().
 	 */
 	smp_rmb();
-	if (!task_still_dumpable(task, mode))
+	if (!may_access_mm(task, mode))
 		return -EPERM;
 
 	return security_ptrace_access_check(task, mode);

---
base-commit: 6916d5703ddf9a38f1f6c2cc793381a24ee914c6
change-id: 20260516-work-exit_mm-5aba5fb06d71

#1 lore raw
Quoted 2 lines · Christian Brauner

I massaged the patch a bit and rewrote parts of the commit message.

I still don't really like this. I think it's disgusting to add a pointer just for ptrace_may_access(), particularly with 99% of users already checking the mm for other reasons _anyway_.

IOW, that user_dumpable bit was a minimal bandaid for bad behavior without breaking old code.

And the fix is *NOT* to make the bandaid bigger, but to just fix the things that are broken.

And Christian - right now pidfd is broken. THAT was always the real security bug here. Let's not change exit just because pidfd did the wrong thing and didn't check the mm like it should have.

It might make sense to change the 'mode' argument to be something more flexible and something that forces people to *think* about the zombie situation.

That mode thing is already a bitmap, so one bit could be "require it to have a MM", but I think it sjhould probably be done in a way that forces the callers to think about it a bit more.

There's only like 20 call sites: let's *not* add a pointer to 'struct task_struct' when 15 of those call sites either already check that there's a mm, or explicitly don't care and handle the mm vs not-mm cases themselves.

Linus

#2 lore raw
Quoted 4 lines · Linus Torvalds

That mode thing is already a bitmap, so one bit could be "require it to have a MM", but I think it should probably be done in a way that forces the callers to think about it a bit more.

The whole "fscreds or realcreds" bit is completely broken too. So I do think that we really need to just fundamentally fix ptrace_may_access(), and change the calling convention.

Just as an example, look at proc_pid_wchan(). It uses that

if (!ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS))

thing, and that's pure and utter garbage. It's a very traditional bug, but it's a bug.

Why?

Because the creds used for IO should *not* be the current creds. They should be the *open-time* creds. That code shouldn't use "current_cred->fsuid" AT ALL. It should use file->f_cred for credential checking.

This is a classic mistake where you make a suid binary a file you opened - open it as regular user, pass it in to a suid binary as 'stdin' or 'stdout'/ 'stderr', and get information (or overwrite things) that way that you shouldn't have had permissions to do.

The user filesystem creds should be used for *open* time checking, not for read/write time checking.

Now, this wchan thing is a case of "not really impotant enough to worry about", but it's an example of how this ptrace_may_access() interface is fundamentally broken.

So the problem really is ptrace_may_access(), and that thing needs fundamental fixes. We should not add exit_mm to try to paper over the real issues.

Linus

author maintainer
#3 lore raw
Quoted 3 lines

So the problem really is ptrace_may_access(), and that thing needs fundamental fixes. We should not add exit_mm to try to paper over the real issues.

If we can improve ptrace_may_access() in additional ways I'm very happy.

One thing that I would like to mention is that forcing callers of this api to reason about post-exit, zombie, or mm behavior has potential for a lot of subtle bugs. Dealing with mm sharing and dumpability implications is rather subtle so I think doing it within the api itself would be preferable.

I've also appended a patch that makes pidfd_getfd() check for exiting tasks after a successful ptrace check. Please do feel free to apply it directly if you agree.

From c64938bbcf9f473db0e95b714746e57b03efc334 Mon Sep 17 00:00:00 2001
From: Christian Brauner <[email protected]>
Date: Mon, 18 May 2026 10:32:11 +0200
Subject: [PATCH] pidfd: refuse access to tasks that have started exiting
harder

The recent ptrace fix closed a hole where someone could rely on task->mm becoming NULL during do_exit() to bypass dumpability checks. This api here leans on on the very same check and so inherits the fix.

But there is no good reason to let it succeed at all once the target has entered do_exit(). PF_EXITING is set by exit_signals() at the very top of do_exit(), before exit_mm() and exit_files() run. Once we observe it, the task is committed to dying and exit_files() will release the fdtable shortly.

Fixes 8649c322f75c ("pid: Implement pidfd_getfd syscall")
---
 kernel/pid.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
kernel/pid.c +5 -3
index fd5c2d4aa349..f55189a3d07d 100644
@@ -885,10 +885,12 @@ static struct file *__pidfd_fget(struct task_struct *task, int fd)
 	if (ret)
 		return ERR_PTR(ret);
 
-	if (ptrace_may_access(task, PTRACE_MODE_ATTACH_REALCREDS))
-		file = fget_task(task, fd);
-	else
+	if (!ptrace_may_access(task, PTRACE_MODE_ATTACH_REALCREDS))
 		file = ERR_PTR(-EPERM);
+	else if (task->flags & PF_EXITING)
+		file = ERR_PTR(-ESRCH);
+	else
+		file = fget_task(task, fd);
 
 	up_read(&task->signal->exec_update_lock);
 
Signature · 1 line
2.47.3
#4 lore raw
In reply to Linus Torvalds
Quoted 30 lines · Linus Torvalds
Quoted 4 lines · Linus Torvalds

That mode thing is already a bitmap, so one bit could be "require it to have a MM", but I think it should probably be done in a way that forces the callers to think about it a bit more.

The whole "fscreds or realcreds" bit is completely broken too. So I do think that we really need to just fundamentally fix ptrace_may_access(), and change the calling convention.

Just as an example, look at proc_pid_wchan(). It uses that

if (!ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS))

thing, and that's pure and utter garbage. It's a very traditional bug, but it's a bug.

Why?

Because the creds used for IO should *not* be the current creds. They should be the *open-time* creds. That code shouldn't use "current_cred->fsuid" AT ALL. It should use file->f_cred for credential checking.

This is a classic mistake where you make a suid binary a file you opened - open it as regular user, pass it in to a suid binary as 'stdin' or 'stdout'/ 'stderr', and get information (or overwrite things) that way that you shouldn't have had permissions to do.

Quoted 6 lines

The user filesystem creds should be used for *open* time checking, not for read/write time checking.

Now, this wchan thing is a case of "not really impotant enough to worry about", but it's an example of how this ptrace_may_access() interface is fundamentally broken.

The current implementation of PTRACE_MODE_READ_FSCREDS is appropriate for stuff like proc_ns_get_link().

I agree that calling ptrace_may_access() in proc_pid_wchan() is wrong; but I think a good fix for this is to do the ptrace_may_access() check at open() time, and only allow read()ing from the resulting file as long as the target process hasn't called execve() in the meantime.

We could try to do ptrace_may_access() with ->f_cred at read() time, but it would not entirely work because ptrace_may_access() looks at things other than the caller's credentials - there is that same_thread_group() check, and yama_ptrace_access_check() also looks at process hierarchy (in the case of PTRACE_MODE_ATTACH_FSCREDS).

#5 lore raw
In reply to Linus Torvalds
Quoted 10 lines · Linus Torvalds
Quoted 1 line · Christian Brauner

I massaged the patch a bit and rewrote parts of the commit message.

I still don't really like this. I think it's disgusting to add a pointer just for ptrace_may_access(), particularly with 99% of users already checking the mm for other reasons _anyway_.

IOW, that user_dumpable bit was a minimal bandaid for bad behavior without breaking old code.

Quoted 6 lines

And the fix is *NOT* to make the bandaid bigger, but to just fix the things that are broken.

And Christian - right now pidfd is broken. THAT was always the real security bug here. Let's not change exit just because pidfd did the wrong thing and didn't check the mm like it should have.

I mean... /proc/$pid/task/fd/$n probably has the same problem, no? pidfd_getfd() is just more severe because it directly creates an FD for the file, instead of going through normal VFS open() permission checks. But /proc/$pid/task/fd/$n is theoretically also dangerous for stuff like anonymous pipes or memfds, where security mainly relies on not being able to reach the inode.

Quoted 7 lines

It might make sense to change the 'mode' argument to be something more flexible and something that forces people to *think* about the zombie situation.

That mode thing is already a bitmap, so one bit could be "require it to have a MM", but I think it sjhould probably be done in a way that forces the callers to think about it a bit more.

I think that would be kind of ugly because here, the MM is not actually used for memory management thing; instead, the MM is just used as the one place we have that stores state that is shared between threads, and is not reused across() execve (so if you're looking at the MM of a task in the middle of exiting, you won't see information that actually belongs to another thread that has gone through execve() of a new executable). Basically like a signal_struct that is replaced on execve().

If we were to have a flag like that, it should probably semantically be "require the task to not be exiting/dead"; but I think that wouldn't be very useful, because I think userspace expects procfs to still mostly work for zombie processes?

#6 lore raw
Quoted 2 lines · Jann Horn

I mean... /proc/$pid/task/fd/$n probably has the same problem, no?

Possibly. That said, the permissions on that directory changes when the process becomes a zombie, so it might almost accidentally be ok.

Quoted 5 lines

pidfd_getfd() is just more severe because it directly creates an FD for the file, instead of going through normal VFS open() permission checks. But /proc/$pid/task/fd/$n is theoretically also dangerous for stuff like anonymous pipes or memfds, where security mainly relies on not being able to reach the inode.

If your security depends on "not reading the inode", your security is not security, it's a joke.

The /proc/pid/ interface has been around forever, and that's ignoring regular ptrace too. Files have absolutely *never* been private, and anybody who thinks they are some private thing is just wrong.

And being a zombie doesn't even change that - files can stay around afterwards, and it's not a problem.

I really think the *only* bug was literally the whole "people didn't think about mm->dumpable as a security thing wrt zombies"

(And the entirely unrelated bug of IO-time vs open-time, which we've had many many times because it's such an easy mistake to make).

Quoted 4 lines

I think that would be kind of ugly because here, the MM is not actually used for memory management thing; instead, the MM is just used as the one place we have that stores state that is shared between threads

I agree. Except it is *not* "the one place". We have multiple shared places.

In fact, I wonder if we should simply just move "dumpable" into "struct sighand_struct" instead (or "signal_struct"). Those stay around until the task is released, and they kind of are more natural for core dumping, since it's about signals.

I think dumpability being in the mm struct is mostly a historical accident, and the fact that it was about core-dumping that writes out the mm image. And in the very historical setting, the "same thread" was about the mm.

But core dumping is certainly *also* about the signal state that writes out the mm image. In fact, the 'struct core_state' pointer is in 'struct signal_struct'.

And with pthreads, the "same thread" is actually mostly about signal state (ie the defining feature really is that signal group). Obviously pthreads doesn't know about clone() and other options.

What I think really matters is that execve() will always unshare everything, because that's when you get more permissions. So whether it's the mm or signal_struct or sighand_struct doesn't much metter.

But in some respects the signal structs would really be better options for all of this. Both for the pthreads reasons and for the "they stay around for zombies".

Hmm.

Linus

#7 lore raw
Quoted 7 lines · Linus Torvalds
Quoted 2 lines · Jann Horn

I mean... /proc/$pid/task/fd/$n probably has the same problem, no?

Possibly. That said, the permissions on that directory changes when the process becomes a zombie, so it might almost accidentally be ok.

Quoted 8 lines
Quoted 5 lines

pidfd_getfd() is just more severe because it directly creates an FD for the file, instead of going through normal VFS open() permission checks. But /proc/$pid/task/fd/$n is theoretically also dangerous for stuff like anonymous pipes or memfds, where security mainly relies on not being able to reach the inode.

If your security depends on "not reading the inode", your security is not security, it's a joke.

I mean... __shmem_file_setup() explicitly creates files with S_IRWXUGO, and that is what memfd_create() uses. So the security of memfds in particular always relies on the inode not being reachable, unless LSM restrictions are involved.

user@vm:/tmp$ cat memfd_test.c
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

int main(void) {
system("grep ^Umask /proc/$PPID/status");

int memfd = memfd_create("foo", MFD_CLOEXEC);
char cmd[1000];
sprintf(cmd, "stat --dereference /proc/$PPID/fd/%d", memfd); system(cmd);
}

user@vm:/tmp$ gcc -o memfd_test memfd_test.c
user@vm:/tmp$ ./memfd_test
Umask:0002
  File: /proc/699/fd/3
  Size: 0         Blocks: 0          IO Block: 4096   regular empty file
Device: 0,1 Inode: 2064        Links: 0
Access: (0777/-rwxrwxrwx)  Uid: ( 1000/    user)   Gid: ( 1000/    user)
Access: 2026-05-18 18:24:31.669411864 +0000
Modify: 2026-05-18 18:24:31.669411864 +0000
Change: 2026-05-18 18:24:31.669411864 +0000
 Birth: 2026-05-18 18:24:31.669411864 +0000
user@vm:/tmp$

(Anonymous pipes are less problematic in this aspect, get_pipe_inode() uses the current_fsuid() and sets mode 0600.)

Quoted 18 lines

The /proc/pid/ interface has been around forever, and that's ignoring regular ptrace too. Files have absolutely *never* been private, and anybody who thinks they are some private thing is just wrong.

And being a zombie doesn't even change that - files can stay around afterwards, and it's not a problem.

I really think the *only* bug was literally the whole "people didn't think about mm->dumpable as a security thing wrt zombies"

(And the entirely unrelated bug of IO-time vs open-time, which we've had many many times because it's such an easy mistake to make).

Quoted 4 lines

I think that would be kind of ugly because here, the MM is not actually used for memory management thing; instead, the MM is just used as the one place we have that stores state that is shared between threads

Quoted 6 lines

I agree. Except it is *not* "the one place". We have multiple shared places.

In fact, I wonder if we should simply just move "dumpable" into "struct sighand_struct" instead (or "signal_struct"). Those stay around until the task is released, and they kind of are more natural for core dumping, since it's about signals.

I think signal_struct is not unshared on exec; so in this sequence of events:

- task T1 is a non-dumpable task
- task T1 creates another thread T2
- T2 exits
- T1 goes through execve and becomes dumpable

I believe T1 and T2 are still associated with the same signal_struct, which means that even though T2 is part of the pre-execve process, it shares state with the post-execve process and it would wrongly be considered dumpable.

I hadn't realized that the sighand_struct is unshared on execve, I guess putting it in sighand_struct might be an option. (An implementation detail regarding that is that a task can currently lose its sighand_struct while there are still references held to the task, but I guess changing that would be easy.)

author maintainer
#8 lore raw
Quoted 91 lines · Jann Horn
Quoted 7 lines · Linus Torvalds
Quoted 2 lines · Jann Horn

I mean... /proc/$pid/task/fd/$n probably has the same problem, no?

Possibly. That said, the permissions on that directory changes when the process becomes a zombie, so it might almost accidentally be ok.

Quoted 8 lines
Quoted 5 lines

pidfd_getfd() is just more severe because it directly creates an FD for the file, instead of going through normal VFS open() permission checks. But /proc/$pid/task/fd/$n is theoretically also dangerous for stuff like anonymous pipes or memfds, where security mainly relies on not being able to reach the inode.

If your security depends on "not reading the inode", your security is not security, it's a joke.

I mean... __shmem_file_setup() explicitly creates files with S_IRWXUGO, and that is what memfd_create() uses. So the security of memfds in particular always relies on the inode not being reachable, unless LSM restrictions are involved.

user@vm:/tmp$ cat memfd_test.c
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

int main(void) {
system("grep ^Umask /proc/$PPID/status");

int memfd = memfd_create("foo", MFD_CLOEXEC);
char cmd[1000];
sprintf(cmd, "stat --dereference /proc/$PPID/fd/%d", memfd); system(cmd);
}

user@vm:/tmp$ gcc -o memfd_test memfd_test.c
user@vm:/tmp$ ./memfd_test
Umask:0002
  File: /proc/699/fd/3
  Size: 0         Blocks: 0          IO Block: 4096   regular empty file
Device: 0,1 Inode: 2064        Links: 0
Access: (0777/-rwxrwxrwx)  Uid: ( 1000/    user)   Gid: ( 1000/    user)
Access: 2026-05-18 18:24:31.669411864 +0000
Modify: 2026-05-18 18:24:31.669411864 +0000
Change: 2026-05-18 18:24:31.669411864 +0000
 Birth: 2026-05-18 18:24:31.669411864 +0000
user@vm:/tmp$

(Anonymous pipes are less problematic in this aspect, get_pipe_inode() uses the current_fsuid() and sets mode 0600.)

Quoted 18 lines

The /proc/pid/ interface has been around forever, and that's ignoring regular ptrace too. Files have absolutely *never* been private, and anybody who thinks they are some private thing is just wrong.

And being a zombie doesn't even change that - files can stay around afterwards, and it's not a problem.

I really think the *only* bug was literally the whole "people didn't think about mm->dumpable as a security thing wrt zombies"

(And the entirely unrelated bug of IO-time vs open-time, which we've had many many times because it's such an easy mistake to make).

Quoted 4 lines

I think that would be kind of ugly because here, the MM is not actually used for memory management thing; instead, the MM is just used as the one place we have that stores state that is shared between threads

Quoted 6 lines

I agree. Except it is *not* "the one place". We have multiple shared places.

In fact, I wonder if we should simply just move "dumpable" into "struct sighand_struct" instead (or "signal_struct"). Those stay around until the task is released, and they kind of are more natural for core dumping, since it's about signals.

I think signal_struct is not unshared on exec; so in this sequence of events:

- task T1 is a non-dumpable task
- task T1 creates another thread T2
- T2 exits
- T1 goes through execve and becomes dumpable

I believe T1 and T2 are still associated with the same signal_struct, which means that even though T2 is part of the pre-execve process, it shares state with the post-execve process and it would wrongly be considered dumpable.

Quoted 5 lines

I hadn't realized that the sighand_struct is unshared on execve, I guess putting it in sighand_struct might be an option. (An implementation detail regarding that is that a task can currently lose its sighand_struct while there are still references held to the task, but I guess changing that would be easy.)

struct sighand_struct is not unshared on CLONE_VM (without CLONE_THREAD) during fork(). IOW, it's possible to do CLONE_VM without CLONE_SIGHAND. Right now commit_creds() broadcasts dumpability changes to all tasks using the given mm. If we move it to struct sighand_struct we break that. Forcing CLONE_VM to imply CLONE_SIGHAND would break vfork().

author maintainer
#9 lore raw
Quoted 98 lines · Christian Brauner
Quoted 91 lines · Jann Horn
Quoted 7 lines · Linus Torvalds
Quoted 2 lines · Jann Horn

I mean... /proc/$pid/task/fd/$n probably has the same problem, no?

Possibly. That said, the permissions on that directory changes when the process becomes a zombie, so it might almost accidentally be ok.

Quoted 8 lines
Quoted 5 lines

pidfd_getfd() is just more severe because it directly creates an FD for the file, instead of going through normal VFS open() permission checks. But /proc/$pid/task/fd/$n is theoretically also dangerous for stuff like anonymous pipes or memfds, where security mainly relies on not being able to reach the inode.

If your security depends on "not reading the inode", your security is not security, it's a joke.

I mean... __shmem_file_setup() explicitly creates files with S_IRWXUGO, and that is what memfd_create() uses. So the security of memfds in particular always relies on the inode not being reachable, unless LSM restrictions are involved.

user@vm:/tmp$ cat memfd_test.c
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

int main(void) {
system("grep ^Umask /proc/$PPID/status");

int memfd = memfd_create("foo", MFD_CLOEXEC);
char cmd[1000];
sprintf(cmd, "stat --dereference /proc/$PPID/fd/%d", memfd); system(cmd);
}

user@vm:/tmp$ gcc -o memfd_test memfd_test.c
user@vm:/tmp$ ./memfd_test
Umask:0002
  File: /proc/699/fd/3
  Size: 0         Blocks: 0          IO Block: 4096   regular empty file
Device: 0,1 Inode: 2064        Links: 0
Access: (0777/-rwxrwxrwx)  Uid: ( 1000/    user)   Gid: ( 1000/    user)
Access: 2026-05-18 18:24:31.669411864 +0000
Modify: 2026-05-18 18:24:31.669411864 +0000
Change: 2026-05-18 18:24:31.669411864 +0000
 Birth: 2026-05-18 18:24:31.669411864 +0000
user@vm:/tmp$

(Anonymous pipes are less problematic in this aspect, get_pipe_inode() uses the current_fsuid() and sets mode 0600.)

Quoted 18 lines

The /proc/pid/ interface has been around forever, and that's ignoring regular ptrace too. Files have absolutely *never* been private, and anybody who thinks they are some private thing is just wrong.

And being a zombie doesn't even change that - files can stay around afterwards, and it's not a problem.

I really think the *only* bug was literally the whole "people didn't think about mm->dumpable as a security thing wrt zombies"

(And the entirely unrelated bug of IO-time vs open-time, which we've had many many times because it's such an easy mistake to make).

Quoted 4 lines

I think that would be kind of ugly because here, the MM is not actually used for memory management thing; instead, the MM is just used as the one place we have that stores state that is shared between threads

Quoted 6 lines

I agree. Except it is *not* "the one place". We have multiple shared places.

In fact, I wonder if we should simply just move "dumpable" into "struct sighand_struct" instead (or "signal_struct"). Those stay around until the task is released, and they kind of are more natural for core dumping, since it's about signals.

I think signal_struct is not unshared on exec; so in this sequence of events:

- task T1 is a non-dumpable task
- task T1 creates another thread T2
- T2 exits
- T1 goes through execve and becomes dumpable

I believe T1 and T2 are still associated with the same signal_struct, which means that even though T2 is part of the pre-execve process, it shares state with the post-execve process and it would wrongly be considered dumpable.

Quoted 5 lines

I hadn't realized that the sighand_struct is unshared on execve, I guess putting it in sighand_struct might be an option. (An implementation detail regarding that is that a task can currently lose its sighand_struct while there are still references held to the task, but I guess changing that would be easy.)

Quoted 5 lines

struct sighand_struct is not unshared on CLONE_VM (without CLONE_THREAD) during fork(). IOW, it's possible to do CLONE_VM without CLONE_SIGHAND. Right now commit_creds() broadcasts dumpability changes to all tasks using the given mm. If we move it to struct sighand_struct we break that. Forcing CLONE_VM to imply CLONE_SIGHAND would break vfork().

One thing I played with is to move dumpability and exec namespace into struct task_exec_state which hangs around until the task is freed. This kind of works and effectively splits the permission related stuff out of struct mm_struct. The problem is that callers now need to take care that exec_state and mm_struct are in-sync. And we have various interactions there. There's at least task_lock() and exec_update_lock(). For example, mm_access() relies on exec_update_lock() so task->exec_state needs to be updated alongside task->mm during exec_mmap(). It's all doable but it's certainly subtle on its own. One advantage one could argue for, is that this move makes it clear that dumpability is not just a concept tied to mm but is used for permission checks beyond it.

Anyway, I have a draft of this. Please, it's not pretty and it's a PoC I've done it so that we can look at something rather than just wave hands. I don't even know if it compiles.

From c64938bbcf9f473db0e95b714746e57b03efc334 Mon Sep 17 00:00:00 2001
From: Christian Brauner <[email protected]>
Date: Mon, 18 May 2026 10:32:11 +0200
Subject: [PATCH] pidfd: refuse access to tasks that have started exiting
harder

The recent ptrace fix closed a hole where someone could rely on task->mm becoming NULL during do_exit() to bypass dumpability checks. This api here leans on on the very same check and so inherits the fix.

But there is no good reason to let it succeed at all once the target has entered do_exit(). PF_EXITING is set by exit_signals() at the very top of do_exit(), before exit_mm() and exit_files() run. Once we observe it, the task is committed to dying and exit_files() will release the fdtable shortly.

Fixes 8649c322f75c ("pid: Implement pidfd_getfd syscall")
---
 kernel/pid.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
kernel/pid.c +5 -3
index fd5c2d4aa349..f55189a3d07d 100644
@@ -885,10 +885,12 @@ static struct file *__pidfd_fget(struct task_struct *task, int fd)
 	if (ret)
 		return ERR_PTR(ret);
 
-	if (ptrace_may_access(task, PTRACE_MODE_ATTACH_REALCREDS))
-		file = fget_task(task, fd);
-	else
+	if (!ptrace_may_access(task, PTRACE_MODE_ATTACH_REALCREDS))
 		file = ERR_PTR(-EPERM);
+	else if (task->flags & PF_EXITING)
+		file = ERR_PTR(-ESRCH);
+	else
+		file = fget_task(task, fd);
 
 	up_read(&task->signal->exec_update_lock);
 
Signature · 1 line
2.47.3
#10 lore raw
Quoted 3 lines · Christian Brauner

One thing I played with is to move dumpability and exec namespace into struct task_exec_state which hangs around until the task is freed.

I like that just because it would actually make *sense* to have some kind of "this is the state that we got at execve time", and just share it across all processes that started from that execve.

But I'd go much further than you presumably did - I'd not tie it to 'struct mm_struct' AT ALL. Even a regular fork() would just keep the "this is the execve() that started this all".

Because I'm not 100% convinced we really want to synchronize any of this with 'struct mm_struct'. Yes, it's what the historical behavior is, but does it really make a lot of sense?

In reality, all "normal" programs will either share nothing, or share everything. And in many ways, 'struct mm_struct' is not really special wrt any of the other things we're sharing. Certainly not for anything that uses

    ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS);

which literally has nothing to do with the mm.

For that one, it would actually make more sense to have dumpability flag be about 'struct files_struct' (or 'struct fs_struct'). But keeping it all in some "this was the exec that gave us the original rules" would actually make a *lot* more sense, even if it then got shared between fork() cases.

Because imaging that you had a setuid process that started out with elevated privileges, and then forked a lot of helpers. Those helpers still have information that may be privileged, and if they do a 'setreuid()' to drop privileges, that information may still be valid.

Only when it really does a new exec has it changed "domains".

Now *that* would actually make a ton of sense to me. And perhaps more importantly, that kind of "this is the state we got at execve time" could then contain the actual execve credentials and namespace, so then ptrace_may_access() could really use *that* information, and not the odd hodgepodge of "mm->dumpable" and "cred->user_ns" and "mm->user_ns".

Again: what makes "cred->user_ns" and "mm->user_ns" so special - and we use both of them for different cred tests - but then we happily cross pid namespaces, for example, as long as the kernel mapping is the same?

So I think having a "exec context" would make a *lot* of sense. And be quite conceptually simple: it would basically be a subset of our existing 'bprm', except it would be attached to the thread, and then clone - all forms of it - would just increase the refcount on it.

Yes, this would be *very* different from the current 'tied to 'struct mm_struct'" model, and very visibly so across fork(), but I really think it would finally make all of it make *sense*.

Think of the fundamental race of a suid binary that then does a fork(), drops privileges in the child, and does an 'execve()'. The child process really has a *lot* of potentially very sensitive information in its mm, but currently we think it's all accessible to the user that matches the dropped privileges. Isn't that fundamentally wrong? Having a exec_state would fix it very naturally..

Linus

author maintainer
#11 lore raw
Quoted 60 lines · Linus Torvalds
Quoted 3 lines · Christian Brauner

One thing I played with is to move dumpability and exec namespace into struct task_exec_state which hangs around until the task is freed.

I like that just because it would actually make *sense* to have some kind of "this is the state that we got at execve time", and just share it across all processes that started from that execve.

But I'd go much further than you presumably did - I'd not tie it to 'struct mm_struct' AT ALL. Even a regular fork() would just keep the "this is the execve() that started this all".

Because I'm not 100% convinced we really want to synchronize any of this with 'struct mm_struct'. Yes, it's what the historical behavior is, but does it really make a lot of sense?

In reality, all "normal" programs will either share nothing, or share everything. And in many ways, 'struct mm_struct' is not really special wrt any of the other things we're sharing. Certainly not for anything that uses

    ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS);

which literally has nothing to do with the mm.

For that one, it would actually make more sense to have dumpability flag be about 'struct files_struct' (or 'struct fs_struct'). But keeping it all in some "this was the exec that gave us the original rules" would actually make a *lot* more sense, even if it then got shared between fork() cases.

Because imaging that you had a setuid process that started out with elevated privileges, and then forked a lot of helpers. Those helpers still have information that may be privileged, and if they do a 'setreuid()' to drop privileges, that information may still be valid.

Only when it really does a new exec has it changed "domains".

Now *that* would actually make a ton of sense to me. And perhaps more importantly, that kind of "this is the state we got at execve time" could then contain the actual execve credentials and namespace, so then ptrace_may_access() could really use *that* information, and not the odd hodgepodge of "mm->dumpable" and "cred->user_ns" and "mm->user_ns".

Again: what makes "cred->user_ns" and "mm->user_ns" so special - and we use both of them for different cred tests - but then we happily cross pid namespaces, for example, as long as the kernel mapping is the same?

So I think having a "exec context" would make a *lot* of sense. And be quite conceptually simple: it would basically be a subset of our existing 'bprm', except it would be attached to the thread, and then clone - all forms of it - would just increase the refcount on it.

Yes, this would be *very* different from the current 'tied to 'struct mm_struct'" model, and very visibly so across fork(), but I really think it would finally make all of it make *sense*.

Quoted 6 lines

Think of the fundamental race of a suid binary that then does a fork(), drops privileges in the child, and does an 'execve()'. The child process really has a *lot* of potentially very sensitive information in its mm, but currently we think it's all accessible to the user that matches the dropped privileges. Isn't that fundamentally wrong? Having a exec_state would fix it very naturally..

I failed to actually append the thing I intended to append... So for completeness sake I'm resending it here.

 arch/arm64/kernel/mte.c          | 13 ++++--
 drivers/firmware/efi/efi.c       |  1 -
 fs/coredump.c                    | 22 ++++-----
 fs/exec.c                        | 62 +++++++++++++++++++------
 fs/pidfs.c                       | 22 ++++-----
 fs/proc/base.c                   | 41 ++++++++--------
 include/linux/binfmts.h          |  2 +
 include/linux/coredump.h         |  4 ++
 include/linux/mm_types.h         |  9 ++--
 include/linux/sched.h            |  7 +--
 include/linux/sched/coredump.h   | 50 +++++++-------------
 include/linux/sched/exec_state.h | 22 +++++++++
 init/init_task.c                 | 10 ++++
 kernel/cred.c                    |  2 +-
 kernel/exit.c                    |  1 -
 kernel/fork.c                    | 80 +++++++++++++++++++++++++++++---
 kernel/kthread.c                 |  1 -
 kernel/ptrace.c                  | 32 ++++++-------
 kernel/sys.c                     |  6 +--
 mm/init-mm.c                     |  1 -
 20 files changed, 248 insertions(+), 140 deletions(-)
 create mode 100644 include/linux/sched/exec_state.h
arch/arm64/kernel/mte.c +9 -4
index 6874b16d0657..76bc51cd0564 100644
@@ -9,6 +9,7 @@
 #include <linux/mm.h>
 #include <linux/prctl.h>
 #include <linux/sched.h>
+#include <linux/sched/exec_state.h>
 #include <linux/sched/mm.h>
 #include <linux/string.h>
 #include <linux/swap.h>
@@ -531,22 +532,26 @@ static int access_remote_tags(struct task_struct *tsk, unsigned long addr,
 			      struct iovec *kiov, unsigned int gup_flags)
 {
 	struct mm_struct *mm;
+	bool allowed;
 	int ret;
 
 	mm = get_task_mm(tsk);
 	if (!mm)
 		return -EPERM;
 
-	if (!tsk->ptrace || (current != tsk->parent) ||
-	    ((get_dumpable(mm) != SUID_DUMP_USER) &&
-	     !ptracer_capable(tsk, mm->user_ns))) {
+	rcu_read_lock();
+	allowed = tsk->ptrace && (current == tsk->parent) &&
+		  ((get_dumpable(tsk) == TASK_DUMPABLE_OWNER) ||
+		   ptracer_capable(tsk, tsk->exec_state->user_ns));
+	rcu_read_unlock();
+
+	if (!allowed) {
 		mmput(mm);
 		return -EPERM;
 	}
 
 	ret = __access_remote_tags(mm, addr, kiov, gup_flags);
 	mmput(mm);
-
 	return ret;
 }
 
drivers/firmware/efi/efi.c +0 -1
index d04be38f1750..ae78bc021b41 100644
@@ -73,7 +73,6 @@ struct mm_struct efi_mm = {
 	MMAP_LOCK_INITIALIZER(efi_mm)
 	.page_table_lock	= __SPIN_LOCK_UNLOCKED(efi_mm.page_table_lock),
 	.mmlist			= LIST_HEAD_INIT(efi_mm.mmlist),
-	.user_ns		= &init_user_ns,
 #ifdef CONFIG_SCHED_MM_CID
 	.mm_cid.lock		= __RAW_SPIN_LOCK_UNLOCKED(efi_mm.mm_cid.lock),
 #endif
fs/coredump.c +8 -14
index bb6fdb1f458e..dae8a0dec219 100644
@@ -395,8 +395,7 @@ static bool coredump_parse(struct core_name *cn, struct coredump_params *cprm,
 							  cred->gid));
 				break;
 			case 'd':
-				err = cn_printf(cn, "%d",
-					__get_dumpable(cprm->mm_flags));
+				err = cn_printf(cn, "%d", cprm->dumpable);
 				break;
 			/* signal that caused the coredump */
 			case 's':
@@ -869,11 +868,11 @@ static inline void coredump_sock_shutdown(struct file *file) { }
 static inline bool coredump_socket(struct core_name *cn, struct coredump_params *cprm) { return false; }
 #endif
 
-/* cprm->mm_flags contains a stable snapshot of dumpability flags. */
+/* cprm->dumpable is the snapshot of task dumpability at dump start. */
 static inline bool coredump_force_suid_safe(const struct coredump_params *cprm)
 {
 	/* Require nonrelative corefile path and be extra careful. */
-	return __get_dumpable(cprm->mm_flags) == SUID_DUMP_ROOT;
+	return cprm->dumpable == TASK_DUMPABLE_ROOT;
 }
 
 static bool coredump_file(struct core_name *cn, struct coredump_params *cprm,
@@ -1085,7 +1084,7 @@ static inline bool coredump_skip(const struct coredump_params *cprm,
 		return true;
 	if (!binfmt->core_dump)
 		return true;
-	if (!__get_dumpable(cprm->mm_flags))
+	if (cprm->dumpable == TASK_DUMPABLE_OFF)
 		return true;
 	return false;
 }
@@ -1170,14 +1169,9 @@ void vfs_coredump(const kernel_siginfo_t *siginfo)
 	struct coredump_params cprm = {
 		.siginfo = siginfo,
 		.limit = rlimit(RLIMIT_CORE),
-		/*
-		 * We must use the same mm->flags while dumping core to avoid
-		 * inconsistency of bit flags, since this flag is not protected
-		 * by any locks.
-		 *
-		 * Note that we only care about MMF_DUMP* flags.
-		 */
-		.mm_flags = __mm_flags_get_dumpable(mm),
+		/* Snapshot MMF_DUMP_FILTER_* (unlocked) and dumpable for the dump. */
+		.mm_flags = __mm_flags_get_word(mm),
+		.dumpable = get_dumpable(current),
 		.vma_meta = NULL,
 		.cpu = raw_smp_processor_id(),
 	};
@@ -1419,7 +1413,7 @@ EXPORT_SYMBOL(dump_align);
 
 void validate_coredump_safety(void)
 {
-	if (suid_dumpable == SUID_DUMP_ROOT &&
+	if (suid_dumpable == TASK_DUMPABLE_ROOT &&
 	    core_pattern[0] != '/' && core_pattern[0] != '|' && core_pattern[0] != '@') {
 
 		coredump_report_failure("Unsafe core_pattern used with fs.suid_dumpable=2: "
fs/exec.c +48 -14

151 lines not on this page · raw message

fs/pidfs.c +9 -13
index 1cce4f34a051..0d6d0152de0b 100644
@@ -338,14 +338,14 @@ static inline bool pid_in_current_pidns(const struct pid *pid)
 	return false;
 }
 
-static __u32 pidfs_coredump_mask(unsigned long mm_flags)
+static __u32 pidfs_coredump_mask(enum task_dumpable dumpable)
 {
-	switch (__get_dumpable(mm_flags)) {
-	case SUID_DUMP_USER:
+	switch (dumpable) {
+	case TASK_DUMPABLE_OWNER:
 		return PIDFD_COREDUMP_USER;
-	case SUID_DUMP_ROOT:
+	case TASK_DUMPABLE_ROOT:
 		return PIDFD_COREDUMP_ROOT;
-	case SUID_DUMP_DISABLE:
+	case TASK_DUMPABLE_OFF:
 		return PIDFD_COREDUMP_SKIP;
 	default:
 		WARN_ON_ONCE(true);
@@ -434,13 +434,9 @@ static long pidfd_info(struct file *file, unsigned int cmd, unsigned long arg)
 
 	if ((mask & PIDFD_INFO_COREDUMP) && !kinfo.coredump_mask) {
 		guard(task_lock)(task);
-		if (task->mm) {
-			unsigned long flags = __mm_flags_get_dumpable(task->mm);
-
-			kinfo.coredump_mask = pidfs_coredump_mask(flags);
-			kinfo.mask |= PIDFD_INFO_COREDUMP;
-			/* No coredump actually took place, so no coredump signal. */
-		}
+		kinfo.coredump_mask = pidfs_coredump_mask(get_dumpable(task));
+		kinfo.mask |= PIDFD_INFO_COREDUMP;
+		/* No coredump actually took place, so no coredump signal. */
 	}
 
 	/* Unconditionally return identifiers and credentials, the rest only on request */
@@ -779,7 +775,7 @@ void pidfs_coredump(const struct coredump_params *cprm)
 	VFS_WARN_ON_ONCE(attr == PIDFS_PID_DEAD);
 
 	/* Note how we were coredumped and that we coredumped. */
-	attr->coredump_mask = pidfs_coredump_mask(cprm->mm_flags) |
+	attr->coredump_mask = pidfs_coredump_mask(cprm->dumpable) |
 			      PIDFD_COREDUMPED;
 	/* If coredumping is set to skip we should never end up here. */
 	VFS_WARN_ON_ONCE(attr->coredump_mask & PIDFD_COREDUMP_SKIP);
fs/proc/base.c +20 -21

61 lines not on this page · raw message

include/linux/binfmts.h +2 -0
index 65abd5ab8836..a8379f4eee61 100644
@@ -25,6 +25,8 @@ struct linux_binprm {
 	struct page *page[MAX_ARG_PAGES];
 #endif
 	struct mm_struct *mm;
+	/* user_ns published to task->exec_state at execve, narrowed by would_dump(). */
+	struct user_namespace *user_ns;
 	unsigned long p; /* current top of mem */
 	unsigned int
 		/* Should an execfd be passed to userspace? */
include/linux/coredump.h +4 -0
index 68861da4cf7c..7b38ee2e7913 100644
@@ -5,6 +5,7 @@
 #include <linux/types.h>
 #include <linux/mm.h>
 #include <linux/fs.h>
+#include <linux/sched/coredump.h>
 #include <asm/siginfo.h>
 
 #ifdef CONFIG_COREDUMP
@@ -20,7 +21,10 @@ struct coredump_params {
 	const kernel_siginfo_t *siginfo;
 	struct file *file;
 	unsigned long limit;
+	/* MMF_DUMP_FILTER_* bits, snapshot of mm->flags at dump start. */
 	unsigned long mm_flags;
+	/* Snapshot of dumpable at dump start. */
+	enum task_dumpable dumpable;
 	int cpu;
 	loff_t written;
 	loff_t pos;
include/linux/mm_types.h +4 -5
index a308e2c23b82..9588ce3b16df 100644
@@ -1342,7 +1342,6 @@ struct mm_struct {
 		 */
 		struct task_struct __rcu *owner;
 #endif
-		struct user_namespace *user_ns;
 
 		/* store ref to file /proc/<pid>/exe symlink points to */
 		struct file __rcu *exe_file;
@@ -1907,11 +1906,11 @@ enum {
 /* mm flags */
 
 /*
- * The first two bits represent core dump modes for set-user-ID,
- * the modes are SUID_DUMP_* defined in linux/sched/coredump.h
+ * Bits 0 and 1 were dumpability; that moved to task->exec_state.  Reserve
+ * the bits so MMF_DUMP_FILTER_* positions stay stable for the
+ * /proc/<pid>/coredump_filter ABI.
  */
 #define MMF_DUMPABLE_BITS 2
-#define MMF_DUMPABLE_MASK (BIT(MMF_DUMPABLE_BITS) - 1)
 /* coredump filter bits */
 #define MMF_DUMP_ANON_PRIVATE	2
 #define MMF_DUMP_ANON_SHARED	3
@@ -1972,7 +1971,7 @@ enum {
 #define MMF_TOPDOWN		31	/* mm searches top down by default */
 #define MMF_TOPDOWN_MASK	BIT(MMF_TOPDOWN)
 
-#define MMF_INIT_LEGACY_MASK	(MMF_DUMPABLE_MASK | MMF_DUMP_FILTER_MASK |\
+#define MMF_INIT_LEGACY_MASK	(MMF_DUMP_FILTER_MASK |\
 				 MMF_DISABLE_THP_MASK | MMF_HAS_MDWE_MASK |\
 				 MMF_VM_MERGE_ANY_MASK | MMF_TOPDOWN_MASK)
 
include/linux/sched.h +4 -3
index ee06cba5c6f5..f74350f50901 100644
@@ -85,6 +85,7 @@ struct seq_file;
 struct sighand_struct;
 struct signal_struct;
 struct task_delay_info;
+struct task_exec_state;
 struct task_group;
 struct task_struct;
 struct timespec64;
@@ -962,6 +963,9 @@ struct task_struct {
 	struct mm_struct		*mm;
 	struct mm_struct		*active_mm;
 
+	/* Exec-time state outliving exit_mm(); see <linux/sched/exec_state.h>. */
+	struct task_exec_state __rcu	*exec_state;
+
 	int				exit_state;
 	int				exit_code;
 	int				exit_signal;
@@ -1002,9 +1006,6 @@ struct task_struct {
 	unsigned			sched_rt_mutex:1;
 #endif
 
-	/* Save user-dumpable when mm goes away */
-	unsigned			user_dumpable:1;
-
 	/* Bit to tell TOMOYO we're in execve(): */
 	unsigned			in_execve:1;
 	unsigned			in_iowait:1;
include/linux/sched/coredump.h +16 -34

59 lines not on this page · raw message

include/linux/sched/exec_state.h new file +22 -0
new file mode 100644
index 000000000000..759acc3d7a7f
@@ -0,0 +1,22 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _LINUX_SCHED_EXEC_STATE_H
+#define _LINUX_SCHED_EXEC_STATE_H
+
+#include <linux/rcupdate.h>
+#include <linux/refcount.h>
+#include <linux/sched/coredump.h>
+
+struct user_namespace;
+
+struct task_exec_state {
+	refcount_t		count;
+	enum task_dumpable	dumpable;
+	struct user_namespace	*user_ns;
+	struct rcu_head		rcu;
+};
+
+struct task_exec_state *alloc_task_exec_state(struct user_namespace *user_ns);
+struct task_exec_state *dup_task_exec_state(const struct task_exec_state *old);
+void put_task_exec_state(struct task_exec_state *es);
+
+#endif /* _LINUX_SCHED_EXEC_STATE_H */
init/init_task.c +10 -0
index b5f48ebdc2b6..47a651b05058 100644
@@ -7,6 +7,8 @@
 #include <linux/sched/rt.h>
 #include <linux/sched/task.h>
 #include <linux/sched/ext.h>
+#include <linux/sched/exec_state.h>
+#include <linux/user_namespace.h>
 #include <linux/init.h>
 #include <linux/fs.h>
 #include <linux/mm.h>
@@ -56,6 +58,13 @@ static struct sighand_struct init_sighand = {
 	.signalfd_wqh	= __WAIT_QUEUE_HEAD_INITIALIZER(init_sighand.signalfd_wqh),
 };
 
+/* init to 2 - one for init_task, one to ensure it is never freed */
+static struct task_exec_state init_task_exec_state = {
+	.count		= REFCOUNT_INIT(2),
+	.dumpable	= TASK_DUMPABLE_OWNER,
+	.user_ns	= &init_user_ns,
+};
+
 #ifdef CONFIG_SHADOW_CALL_STACK
 unsigned long init_shadow_call_stack[SCS_SIZE / sizeof(long)] = {
 	[(SCS_SIZE / sizeof(long)) - 1] = SCS_END_MAGIC
@@ -113,6 +122,7 @@ struct task_struct init_task __aligned(L1_CACHE_BYTES) = {
 	.nr_cpus_allowed= NR_CPUS,
 	.mm		= NULL,
 	.active_mm	= &init_mm,
+	.exec_state	= &init_task_exec_state,
 	.restart_block	= {
 		.fn = do_no_restart_syscall,
 	},
kernel/cred.c +1 -1
index 12a7b1ce5131..ac855c15b51e 100644
@@ -385,7 +385,7 @@ int commit_creds(struct cred *new)
 	    !gid_eq(old->fsgid, new->fsgid) ||
 	    !cred_cap_issubset(old, new)) {
 		if (task->mm)
-			set_dumpable(task->mm, suid_dumpable);
+			set_dumpable(suid_dumpable);
 		task->pdeath_signal = 0;
 		/*
 		 * If a task drops privileges and becomes nondumpable,
kernel/exit.c +0 -1
index f50d73c272d6..9a909993ab1d 100644
@@ -571,7 +571,6 @@ static void exit_mm(void)
 	 */
 	smp_mb__after_spinlock();
 	local_irq_disable();
-	current->user_dumpable = (get_dumpable(mm) == SUID_DUMP_USER);
 	current->mm = NULL;
 	membarrier_update_current_mm(NULL);
 	enter_lazy_tlb(mm, current);
kernel/fork.c +74 -6

158 lines not on this page · raw message

kernel/kthread.c +0 -1
index 791210daf8b4..63beb59b7a3d 100644
@@ -1619,7 +1619,6 @@ void kthread_use_mm(struct mm_struct *mm)
 
 	WARN_ON_ONCE(!(tsk->flags & PF_KTHREAD));
 	WARN_ON_ONCE(tsk->mm);
-	WARN_ON_ONCE(!mm->user_ns);
 
 	/*
 	 * It is possible for mm to be the same as tsk->active_mm, but
kernel/ptrace.c +14 -18
index 130043bfc209..e7ca2c768745 100644
@@ -13,6 +13,7 @@
 #include <linux/sched.h>
 #include <linux/sched/mm.h>
 #include <linux/sched/coredump.h>
+#include <linux/sched/exec_state.h>
 #include <linux/sched/task.h>
 #include <linux/errno.h>
 #include <linux/mm.h>
@@ -45,21 +46,21 @@ int ptrace_access_vm(struct task_struct *tsk, unsigned long addr,
 		     void *buf, int len, unsigned int gup_flags)
 {
 	struct mm_struct *mm;
-	int ret;
+	bool allowed;
+	int ret = 0;
 
 	mm = get_task_mm(tsk);
 	if (!mm)
 		return 0;
 
-	if (!tsk->ptrace ||
-	    (current != tsk->parent) ||
-	    ((get_dumpable(mm) != SUID_DUMP_USER) &&
-	     !ptracer_capable(tsk, mm->user_ns))) {
-		mmput(mm);
-		return 0;
-	}
+	rcu_read_lock();
+	allowed = tsk->ptrace && (current == tsk->parent) &&
+		  ((get_dumpable(tsk) == TASK_DUMPABLE_OWNER) ||
+		   ptracer_capable(tsk, tsk->exec_state->user_ns));
+	rcu_read_unlock();
 
-	ret = access_remote_vm(mm, addr, buf, len, gup_flags);
+	if (allowed)
+		ret = access_remote_vm(mm, addr, buf, len, gup_flags);
 	mmput(mm);
 
 	return ret;
@@ -274,16 +275,11 @@ static bool ptrace_has_cap(struct user_namespace *ns, unsigned int mode)
 
 static bool task_still_dumpable(struct task_struct *task, unsigned int mode)
 {
-	struct mm_struct *mm = task->mm;
-	if (mm) {
-		if (get_dumpable(mm) == SUID_DUMP_USER)
-			return true;
-		return ptrace_has_cap(mm->user_ns, mode);
-	}
-
-	if (task->user_dumpable)
+	if (get_dumpable(task) == TASK_DUMPABLE_OWNER)
 		return true;
-	return ptrace_has_cap(&init_user_ns, mode);
+
+	guard(rcu)();
+	return ptrace_has_cap(task->exec_state->user_ns, mode);
 }
 
 /* Returns 0 on success, -errno on denial. */
kernel/sys.c +3 -3
index 62e842055cc9..59f106bb9f23 100644
@@ -2565,14 +2565,14 @@ SYSCALL_DEFINE5(prctl, int, option, unsigned long, arg2, unsigned long, arg3,
 		error = put_user(me->pdeath_signal, (int __user *)arg2);
 		break;
 	case PR_GET_DUMPABLE:
-		error = get_dumpable(me->mm);
+		error = get_dumpable(me);
 		break;
 	case PR_SET_DUMPABLE:
-		if (arg2 != SUID_DUMP_DISABLE && arg2 != SUID_DUMP_USER) {
+		if (arg2 != TASK_DUMPABLE_OFF && arg2 != TASK_DUMPABLE_OWNER) {
 			error = -EINVAL;
 			break;
 		}
-		set_dumpable(me->mm, arg2);
+		set_dumpable(arg2);
 		break;
 
 	case PR_SET_UNALIGN:
mm/init-mm.c +0 -1
index c5556bb9d5f0..3e792aad7626 100644
@@ -43,7 +43,6 @@ struct mm_struct init_mm = {
 	.vma_writer_wait = __RCUWAIT_INITIALIZER(init_mm.vma_writer_wait),
 	.mm_lock_seq	= SEQCNT_ZERO(init_mm.mm_lock_seq),
 #endif
-	.user_ns	= &init_user_ns,
 #ifdef CONFIG_SCHED_MM_CID
 	.mm_cid.lock = __RAW_SPIN_LOCK_UNLOCKED(init_mm.mm_cid.lock),
 #endif
Signature · 1 line
2.47.3
#12 lore raw
Quoted 3 lines · Christian Brauner

I failed to actually append the thing I intended to append... So for completeness sake I'm resending it here.

Ok, this looks good, but as mentioned, I think we should *not* do that "copy_exec_state()" at all.

Because I think it's actively wrong for the reasons outlined: it just keeps the existing race with anybody doing

fork -> drop priv -> exec

open. Or, for that matter any suid binary that relies on the traditional "fork helpers" model rathe than using threads.

So I'd suggest at least trying to only do the refcount update at clone() time, regardless of any CLONE_VM.

*If* that causes compatibility problems we might then be forced to do the bad old copy, but I really suspect it won't. The only semantic difference will be for fork() that isn't followed by an execve() (and wasn't dumpable), and that is

(a) very rare (both the "not dumpable" _and_ the "fork rather than
threads", and the combination is rarer still)

(b) I really think such a situation has potentially secret data in
the address space and the new semantics are much better and more logical

Now, I might well not think of some situation where a suid program forks and drops privileges and we actually *want* the end result to be dumpable, but as mentioned, at that point we *could* do your "copy_exec_state()". But I think it would be better to try without it first.

Other than that issue, this approach really does feel like the RightThing(tm) to me.

Linus