Skip to contentSkip to conversation

exec: move sleeping work out of exec_update_lock

RFC PATCH New Christian Brauner 3 participants 24 messages Nov 24

Subsystems (14)
lore
Share & tools
lore

Christian Brauner

author maintainer
#0 lore raw

cover exec: move sleeping work out of exec_update_lock

I've been massaging exec quite a bit to move a bunch of stuff around and get rid of a lot of sleeping work out of that path or at least move it out from precious locks that are used for access checks.

This is another round I plan to upstream. The gist is that we're relying on exec_update_lock in a bunch more places now and we've been willy-nilly moving stuff beneath that lock for a while. That's not sustainable. We need to clean that up and really only do the absolute minimum of work under that lock to avoid stalling tasks indefinitely just because stalls an exec. It's also just good hygiene because it's getting really hard to understand what that lock really protects.

I've spent some time playing with various patches. Some of them went out independently. This is another core chunk:

* proc_ns_readlink() copies the link to userspace with the lock held.

* kcmp(KCMP_EPOLL_TFD) copies the epoll slot from userspace with the lock of both tasks held and then waits for the epoll mutex which epoll_wait() holds across a page fault.

* perf_read() and perf_ioctl() copy to and from userspace with the mutex of the perf context held. perf_event_exec() takes that mutex with exec_update_lock held.

* SELinux ignores a failing replace_fd() when it revokes inherited files during exec.

* A vfork() parent is woken up in exec_mmap() but a child that shares its signal table with the parent only gets a private one after that.

* SELinux and AppArmor revalidate the inherited files from the bprm_committing_creds hook, i.e., with the lock held.

* Move the time namespace switch out of the lock. It doesn't need it.

* Drop the lock right after the new credentials are committed instead of in setup_new_exec().

* Don't take the mmap lock of the old mm in exec_mmap().

* Look up the vma for a link in /proc/<pid>/map_files without exec_update_lock held.

While at it, don't take the mmap lock in exit_mm() either. It's the same leftover. A vfork() child that exits without having exec'ed waits on the mmap lock of the parent it has just woken up.

* A vfork() parent is woken up before the child has left the mm, in exec as well as in exit.

What's left under the lock that can block is the hardware breakpoint flush in flush_thread(), perf_event_exec(), perf_event_exit_task(), the allocation in set_cred_ucounts() and a sleepable bpf lsm program on the bprm_committing_creds hook.

The perf ones still take the mutex of the perf context but perf_read() and perf_ioctl() don't sleep in a page fault with it held anymore.

---
Christian Brauner (19):
proc: copy namespace link after dropping exec_update_lock
kcmp: look up epoll target without exec_update_lock held
perf: copy counter values after dropping ctx->mutex
perf: copy ioctl arguments without ctx->mutex held
selinux: close inherited files that can't be replaced
exec: move unshare_sighand() before exec_mmap() selftests/exec: test exec with a task sleeping in a page fault selftests/exec: test exec with a shared signal table
lsm: add security_bprm_revalidate_files()
bpf: mark bprm_revalidate_files as sleepable
selinux: revalidate inherited files before taking exec_update_lock
apparmor: revalidate inherited files before taking exec_update_lock
exec: drop exec_update_lock after the credentials are committed
exec: switch time namespace after dropping exec_update_lock
exec: don't take the mmap lock of the old mm
exit: don't take the mmap lock in exit_mm()
proc: look up map_files vma without exec_update_lock held
vfork: wake up the parent once the child has left the mm selftests/exec: test when a vfork() parent is woken up

 fs/exec.c                                        |  81 ++--
 fs/proc/base.c                                   |  68 ++-
 fs/proc/namespaces.c                             |   7 +-
 include/linux/lsm_hook_defs.h                    |   1 +
 include/linux/sched/mm.h                         |   4 +-
 include/linux/security.h                         |   5 +
 kernel/bpf/bpf_lsm.c                             |   1 +
 kernel/events/core.c                             | 138 +++---
 kernel/exit.c                                    |  10 +-
 kernel/fork.c                                    |  24 +-
 kernel/kcmp.c                                    |  72 ++-
 security/apparmor/lsm.c                          |  23 +-
 security/security.c                              |  27 +-
 security/selinux/hooks.c                         |  22 +-
 tools/testing/selftests/exec/.gitignore          |   3 +
 tools/testing/selftests/exec/Makefile            |   6 +
 tools/testing/selftests/exec/config              |   3 +
 tools/testing/selftests/exec/unshare-sighand.c   | 236 ++++++++++
 tools/testing/selftests/exec/update-lock-fault.c | 547 +++++++++++++++++++++++
 tools/testing/selftests/exec/vfork-mm.c          | 363 +++++++++++++++
 20 files changed, 1480 insertions(+), 161 deletions(-)

---
base-commit: 666539eecdf4db623f5e3c3e55cf9f2dfad24aa4
change-id: 20261120-work-exec-update_lock-7f4bec04bd81

author maintainer
#1 lore raw

RFC PATCH 1/19 proc: copy namespace link after dropping exec_update_lock

proc_ns_readlink() copies the name of the namespace to userspace under exec_update_lock. If that faults the lock is held for as long as the fault takes. With a buffer in a mapping of a file on a FUSE filesystem or in a range registered with userfaultfd it's the caller who decides how long that is:

locks held by ns-reader/230:
#0: (&sig->exec_update_lock){++++}-{4:4}, at: proc_ns_readlink+0x180/0x340

In the meantime an exec of the task waits for exec_update_lock past the point of no return. And everyone else who needs the exec_update_lock of the task queues up behind the exec. So a read of /proc/<pid>/stat hangs as well:

task:exec-task state:D pid:229

  Call Trace:
   __schedule+0x1691/0x4b00
   schedule+0xe0/0x2e0
   schedule_preempt_disabled+0x11/0x20
   rwsem_down_write_slowpath+0x472/0x1820
   down_write_killable+0x1ba/0x240
   begin_new_exec+0xa4b/0x2df0
   load_elf_binary+0x340/0x4af0
   bprm_execve+0x772/0x1400
   do_execveat_common.isra.0+0x3d9/0x540
   __x64_sys_execve+0x8c/0xc0
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

task:stat-reader state:D pid:231

  Call Trace:
   __schedule+0x1691/0x4b00
   schedule+0xe0/0x2e0
   schedule_preempt_disabled+0x11/0x20
   rwsem_down_read_slowpath+0x5cc/0x10c0
   down_read_killable+0xf1/0x5f0
   do_task_stat+0x13b/0x2870
   proc_single_show+0x110/0x1d0
   seq_read_iter+0x2e4/0x1280
   seq_read+0x29b/0x550
   vfs_read+0x171/0xb20
   ksys_read+0x111/0x250
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

All it takes is being allowed to read the namespace links of the task.

The name is formatted into a buffer on the stack anyway. So drop the lock before it's copied out.

Fixes 6650527444da ("proc: protect ptrace_may_access() with exec_update_lock (part 1)")
---
 fs/proc/namespaces.c | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)
fs/proc/namespaces.c +3 -4
index ea6ec61a0430b..4c91ccbed21ef 100644
@@ -92,12 +92,11 @@ static int proc_ns_readlink(struct dentry *dentry, char __user *buffer, int bufl
 		goto out_put_task;
 
 	res = -EACCES;
-	if (ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS)) {
+	if (ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS))
 		res = ns_get_name(name, sizeof(name), task, ns_ops);
-		if (res >= 0)
-			res = readlink_copy(buffer, buflen, name, strlen(name));
-	}
 	up_read(&task->signal->exec_update_lock);
+	if (res >= 0)
+		res = readlink_copy(buffer, buflen, name, strlen(name));
 out_put_task:
 	put_task_struct(task);
 	return res;
Signature · 1 line
2.53.0
author maintainer
#2 lore raw

RFC PATCH 2/19 kcmp: look up epoll target without exec_update_lock held

In reply to Christian Brauner

kcmp(KCMP_EPOLL_TFD) holds exec_update_lock and two things both of which are susceptible to page fault induced, userspace controlled delays:

(1) cpy struct kcmp_epoll_slot from userspace

locks held by kcmp-reader/233:

    #0: (&sig->exec_update_lock){++++}-{4:4}, at: __do_sys_kcmp+0x2ec/0xb10
    #1: (&sig->exec_update_lock/1){.+.+}-{4:4}, at: __do_sys_kcmp+0x210/0xb10

(2) takes the mutex of the epoll file to look up the target file.

locks held by epoll-waiter/236:

    #0: (&ep->mtx){+.+.}-{4:4}, at: ep_send_events+0x10a/0x9f0
   locks held by kcmp-caller/237:
    #0: (&sig->exec_update_lock){++++}-{4:4}, at: __do_sys_kcmp+0x2ec/0xb10
    #1: (&sig->exec_update_lock/1){.+.+}-{4:4}, at: __do_sys_kcmp+0x210/0xb10
    #2: (&ep->mtx){+.+.}-{4:4}, at: get_epoll_tfile_raw_ptr+0xa5/0x190

In the meantime an exec of either task waits for exec_update_lock past the point of no return. And everyone else who needs the exec_update_lock of that task queues up behind the exec. So a read of /proc/<pid>/stat hangs as well:

task:exec-task state:D pid:235

  Call Trace:
   __schedule+0x1691/0x4b00
   schedule+0xe0/0x2e0
   schedule_preempt_disabled+0x11/0x20
   rwsem_down_write_slowpath+0x472/0x1820
   down_write_killable+0x1ba/0x240
   begin_new_exec+0xa4b/0x2df0
   load_elf_binary+0x340/0x4af0
   bprm_execve+0x772/0x1400
   do_execveat_common.isra.0+0x3d9/0x540
   __x64_sys_execve+0x8c/0xc0
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

task:stat-reader state:D pid:238

  Call Trace:
   __schedule+0x1691/0x4b00
   schedule+0xe0/0x2e0
   schedule_preempt_disabled+0x11/0x20
   rwsem_down_read_slowpath+0x5cc/0x10c0
   down_read_killable+0xf1/0x5f0
   do_task_stat+0x13b/0x2870
   proc_single_show+0x110/0x1d0
   seq_read_iter+0x2e4/0x1280
   seq_read+0x29b/0x550
   vfs_read+0x171/0xb20
   ksys_read+0x111/0x250
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

All it takes is being allowed to kcmp() the two tasks.

Stop that and copy the before the locks are taken. With the locks held only take a reference to the epoll file and look up the target after they have been dropped. The epoll file is still taken from the task after the access check and with exec_update_lock held.

Note that the target is now looked up a moment later. So if the task execs in between and keeps the epoll file the caller may get to compare a target that only the new image registered. The caller still only gets at the epoll file while it's allowed to look at the task and all it learns is how two files compare.

Fixes 0791e3644e5e ("kcmp: add KCMP_EPOLL_TFD mode to compare epoll target files")
---
 kernel/kcmp.c | 72 +++++++++++++++++++++++++++++++++++++++++------------------
 1 file changed, 50 insertions(+), 22 deletions(-)
kernel/kcmp.c +50 -22
index 76476aeee067b..8102e5825efc5 100644
@@ -94,6 +94,34 @@ static int kcmp_lock(struct rw_semaphore *l1, struct rw_semaphore *l2)
 	return err;
 }
 
+static void kcmp_unlock_tasks(struct task_struct *task1,
+			      struct task_struct *task2)
+{
+	kcmp_unlock(&task1->signal->exec_update_lock,
+		    &task2->signal->exec_update_lock);
+}
+
+static int kcmp_lock_tasks(struct task_struct *task1,
+			   struct task_struct *task2)
+{
+	int ret;
+
+	ret = kcmp_lock(&task1->signal->exec_update_lock,
+			&task2->signal->exec_update_lock);
+	if (ret)
+		return ret;
+
+	/*
+	 * One should have enough rights to inspect task details.
+	 */
+	if (ptrace_may_access(task1, PTRACE_MODE_READ_REALCREDS) &&
+	    ptrace_may_access(task2, PTRACE_MODE_READ_REALCREDS))
+		return 0;
+
+	kcmp_unlock_tasks(task1, task2);
+	return -EPERM;
+}
+
 #ifdef CONFIG_EPOLL
 static int kcmp_epoll_target(struct task_struct *task1,
 			     struct task_struct *task2,
@@ -102,18 +130,26 @@ static int kcmp_epoll_target(struct task_struct *task1,
 {
 	struct file *filp, *filp_epoll, *filp_tgt;
 	struct kcmp_epoll_slot slot;
+	int ret;
 
+	/* This may fault so do it before exec_update_lock is taken. */
 	if (copy_from_user(&slot, uslot, sizeof(slot)))
 		return -EFAULT;
 
-	filp = get_file_raw_ptr(task1, idx1);
-	if (!filp)
-		return -EBADF;
+	ret = kcmp_lock_tasks(task1, task2);
+	if (ret)
+		return ret;
 
-	filp_epoll = fget_task(task2, slot.efd);
+	filp = get_file_raw_ptr(task1, idx1);
+	filp_epoll = filp ? fget_task(task2, slot.efd) : NULL;
+	kcmp_unlock_tasks(task1, task2);
 	if (!filp_epoll)
 		return -EBADF;
 
+	/*
+	 * This takes the epoll mutex which is held across page faults. So
+	 * do it after exec_update_lock has been dropped.
+	 */
 	filp_tgt = get_epoll_tfile_raw_ptr(filp_epoll, slot.tfd, slot.toff);
 	fput(filp_epoll);
 
@@ -153,19 +189,16 @@ SYSCALL_DEFINE5(kcmp, pid_t, pid1, pid_t, pid2, int, type,
 
 	rcu_read_unlock();
 
-	/*
-	 * One should have enough rights to inspect task details.
-	 */
-	ret = kcmp_lock(&task1->signal->exec_update_lock,
-			&task2->signal->exec_update_lock);
-	if (ret)
-		goto err;
-	if (!ptrace_may_access(task1, PTRACE_MODE_READ_REALCREDS) ||
-	    !ptrace_may_access(task2, PTRACE_MODE_READ_REALCREDS)) {
-		ret = -EPERM;
-		goto err_unlock;
+	/* Takes and drops exec_update_lock itself. */
+	if (type == KCMP_EPOLL_TFD) {
+		ret = kcmp_epoll_target(task1, task2, idx1, (void __user *)idx2);
+		goto out;
 	}
 
+	ret = kcmp_lock_tasks(task1, task2);
+	if (ret)
+		goto out;
+
 	switch (type) {
 	case KCMP_FILE: {
 		struct file *filp1, *filp2;
@@ -203,18 +236,13 @@ SYSCALL_DEFINE5(kcmp, pid_t, pid1, pid_t, pid2, int, type,
 		ret = -EOPNOTSUPP;
 #endif
 		break;
-	case KCMP_EPOLL_TFD:
-		ret = kcmp_epoll_target(task1, task2, idx1, (void *)idx2);
-		break;
 	default:
 		ret = -EINVAL;
 		break;
 	}
 
-err_unlock:
-	kcmp_unlock(&task1->signal->exec_update_lock,
-		    &task2->signal->exec_update_lock);
-err:
+	kcmp_unlock_tasks(task1, task2);
+out:
 	put_task_struct(task1);
 	put_task_struct(task2);
 
Signature · 1 line
2.53.0
author maintainer
#3 lore raw

RFC PATCH 3/19 perf: copy counter values after dropping ctx->mutex

In reply to Christian Brauner

perf_read() copies the values to userspace with the mutex of the event's context held. If that faults the mutex is held for as long as the fault takes. With a buffer in a mapping of a file on a FUSE filesystem or in a range registered with userfaultfd it's the caller who decides how long that is:

locks held by perf-reader/212:
#0: (&ctx->mutex){+.+.}-{4:4}, at: perf_event_ctx_lock_nested+0x18f/0x360

Since commit 2e498d0a74e5 ("perf: Add support for event removal on exec") perf_event_exec() takes that mutex whenever the task has a perf context. And begin_new_exec() calls it with exec_update_lock held. So an exec of the task the event counts for hangs past the point of no return until the fault is resolved. It can't be killed either:

locks held by exec-task/211:
#0: (&sig->cred_guard_mutex){+.+.}-{4:4}, at: bprm_execve+0xb7/0x1400 #1: (&sig->exec_update_lock){++++}-{4:4}, at: begin_new_exec+0xa4b/0x2df0 #2: (&ctx->mutex){+.+.}-{4:4}, at: perf_event_exec+0x17e/0xe40

task:exec-task state:D pid:211

  Call Trace:
   __schedule+0x1691/0x4b00
   schedule+0xe0/0x2e0
   schedule_preempt_disabled+0x11/0x20
   __mutex_lock+0x6d7/0x2700
   perf_event_exec+0x17e/0xe40
   begin_new_exec+0x1c1e/0x2df0
   load_elf_binary+0x340/0x4af0
   bprm_execve+0x772/0x1400
   do_execveat_common.isra.0+0x3d9/0x540
   __x64_sys_execve+0x8c/0xc0
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

And everyone who needs the exec_update_lock of the task waits with it. Since commit 6650527444da ("proc: protect ptrace_may_access() with exec_update_lock (part 1)") that includes a read of /proc/<pid>/stat:

task:stat-reader state:D pid:214

  Call Trace:
   __schedule+0x1691/0x4b00
   schedule+0xe0/0x2e0
   schedule_preempt_disabled+0x11/0x20
   rwsem_down_read_slowpath+0x5cc/0x10c0
   down_read_killable+0xf1/0x5f0
   do_task_stat+0x13b/0x2870
   proc_single_show+0x110/0x1d0
   seq_read_iter+0x2e4/0x1280
   seq_read+0x29b/0x550
   vfs_read+0x171/0xb20
   ksys_read+0x111/0x250
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

The values are gathered in a kernel buffer anyway. So hand that buffer to perf_read() and copy it out after the mutex has been dropped. What a read returns goes into a struct on the stack of perf_read() that the helpers fill in.

Fixes 2e498d0a74e5 ("perf: Add support for event removal on exec")
---
 kernel/events/core.c | 43 +++++++++++++++++++++++++------------------
 1 file changed, 25 insertions(+), 18 deletions(-)
kernel/events/core.c +25 -18
index e870f12c3ad81..f00eeded212c4 100644
@@ -6188,8 +6188,15 @@ static int __perf_read_group_add(struct perf_event *leader,
 	return ret;
 }
 
-static int perf_read_group(struct perf_event *event,
-				   u64 read_format, char __user *buf)
+/* What a read of an event returns, filled in with ctx->mutex held. */
+struct perf_read_buf {
+	size_t	count;		/* room in the buffer of the reader */
+	u64	values[5];	/* a single event */
+	u64	*group_values;	/* PERF_FORMAT_GROUP, allocated */
+};
+
+static int perf_read_group(struct perf_event *event, u64 read_format,
+			   struct perf_read_buf *rb)
 {
 	struct perf_event *leader = event->group_leader, *child;
 	struct perf_event_context *ctx = leader->ctx;
@@ -6218,23 +6225,20 @@ static int perf_read_group(struct perf_event *event,
 
 	mutex_unlock(&leader->child_mutex);
 
-	ret = event->read_size;
-	if (copy_to_user(buf, values, event->read_size))
-		ret = -EFAULT;
-	goto out;
+	rb->group_values = values;
+	return event->read_size;
 
 unlock:
 	mutex_unlock(&leader->child_mutex);
-out:
 	kfree(values);
 	return ret;
 }
 
-static int perf_read_one(struct perf_event *event,
-				 u64 read_format, char __user *buf)
+static int perf_read_one(struct perf_event *event, u64 read_format,
+			 struct perf_read_buf *rb)
 {
 	u64 enabled, running;
-	u64 values[5];
+	u64 *values = rb->values;
 	int n = 0;
 
 	values[n++] = __perf_event_read_value(event, &enabled, &running);
@@ -6247,9 +6251,6 @@ static int perf_read_one(struct perf_event *event,
 	if (read_format & PERF_FORMAT_LOST)
 		values[n++] = atomic64_read(&event->lost_samples);
 
-	if (copy_to_user(buf, values, n * sizeof(u64)))
-		return -EFAULT;
-
 	return n * sizeof(u64);
 }
 
@@ -6270,7 +6271,7 @@ static bool is_event_hup(struct perf_event *event)
  * Read the performance event - simple non blocking version for now
  */
 static ssize_t
-__perf_read(struct perf_event *event, char __user *buf, size_t count)
+__perf_read(struct perf_event *event, struct perf_read_buf *rb)
 {
 	u64 read_format = event->attr.read_format;
 	int ret;
@@ -6283,14 +6284,14 @@ __perf_read(struct perf_event *event, char __user *buf, size_t count)
 	if (event->state == PERF_EVENT_STATE_ERROR)
 		return 0;
 
-	if (count < event->read_size)
+	if (rb->count < event->read_size)
 		return -ENOSPC;
 
 	WARN_ON_ONCE(event->ctx->parent_ctx);
 	if (read_format & PERF_FORMAT_GROUP)
-		ret = perf_read_group(event, read_format, buf);
+		ret = perf_read_group(event, read_format, rb);
 	else
-		ret = perf_read_one(event, read_format, buf);
+		ret = perf_read_one(event, read_format, rb);
 
 	return ret;
 }
@@ -6299,6 +6300,7 @@ static ssize_t
 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
 {
 	struct perf_event *event = file->private_data;
+	struct perf_read_buf rb = { .count = count };
 	struct perf_event_context *ctx;
 	int ret;
 
@@ -6307,9 +6309,14 @@ perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
 		return ret;
 
 	ctx = perf_event_ctx_lock(event);
-	ret = __perf_read(event, buf, count);
+	ret = __perf_read(event, &rb);
 	perf_event_ctx_unlock(event, ctx);
 
+	/* The copy can sleep in a page fault. Don't hold ctx->mutex for it. */
+	if (ret > 0 && copy_to_user(buf, rb.group_values ?: rb.values, ret))
+		ret = -EFAULT;
+
+	kfree(rb.group_values);
 	return ret;
 }
 
Signature · 1 line
2.53.0
author maintainer
#4 lore raw

RFC PATCH 4/19 perf: copy ioctl arguments without ctx->mutex held

In reply to Christian Brauner

perf_ioctl() calls _perf_ioctl() with the mutex of the event's context held and a number of commands access userspace from there:

- PERF_EVENT_IOC_PERIOD copies the period from userspace.

- PERF_EVENT_IOC_ID copies the id to userspace.

- PERF_EVENT_IOC_SET_FILTER copies the filter string from userspace.

- PERF_EVENT_IOC_QUERY_BPF copies the query from userspace and the ids of the programs back.

- PERF_EVENT_IOC_MODIFY_ATTRIBUTES copies the attributes from userspace.

This is the same problem as for read(). If one of them faults the mutex is held for as long as the fault takes and an exec of the task the event counts for hangs with exec_update_lock held:

locks held by perf-ioctl/217:
#0: (&ctx->mutex){+.+.}-{4:4}, at: perf_event_ctx_lock_nested+0x18f/0x360
locks held by exec-task/216:
#0: (&sig->cred_guard_mutex){+.+.}-{4:4}, at: bprm_execve+0xb7/0x1400 #1: (&sig->exec_update_lock){++++}-{4:4}, at: begin_new_exec+0xa4b/0x2df0 #2: (&ctx->mutex){+.+.}-{4:4}, at: perf_event_exec+0x17e/0xe40
locks held by stat-reader/218:
#0: (&p->lock){+.+.}-{4:4}, at: seq_read_iter+0xc5/0x1280
#1: (&sig->exec_update_lock){++++}-{4:4}, at: do_task_stat+0x13b/0x2870

Copy what comes from userspace before the mutex is taken and what goes to userspace after it has been dropped.

PERF_EVENT_IOC_QUERY_BPF doesn't need the mutex. The programs of a tracepoint are protected by bpf_event_mutex. So call perf_event_query_prog_array() before the mutex is taken.

Fixes 2e498d0a74e5 ("perf: Add support for event removal on exec")
---
 kernel/events/core.c | 93 ++++++++++++++++++++++++++++++++--------------------
 1 file changed, 57 insertions(+), 36 deletions(-)
kernel/events/core.c +57 -36
index f00eeded212c4..5f648e00ae661 100644
@@ -6635,14 +6635,25 @@ static inline bool is_perf_file(struct fd f)
 
 static int perf_event_set_output(struct perf_event *event,
 				 struct perf_event *output_event);
-static int perf_event_set_filter(struct perf_event *event, void __user *arg);
+static int perf_event_set_filter(struct perf_event *event, char *filter_str);
 static int perf_copy_attr(struct perf_event_attr __user *uattr,
 			  struct perf_event_attr *attr);
 static int __perf_event_set_bpf_prog(struct perf_event *event,
 				     struct bpf_prog *prog,
 				     u64 bpf_cookie);
 
-static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
+/*
+ * What perf_ioctl() copies from userspace before it takes ctx->mutex and
+ * what it copies back once it dropped it.
+ */
+struct perf_ioctl_data {
+	u64			value;
+	char			*filter;
+	struct perf_event_attr	attr;
+};
+
+static long _perf_ioctl(struct perf_event *event, unsigned int cmd,
+			unsigned long arg, struct perf_ioctl_data *data)
 {
 	void (*func)(struct perf_event *);
 	u32 flags = arg;
@@ -6665,22 +6676,11 @@ static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned lon
 		return _perf_event_refresh(event, arg);
 
 	case PERF_EVENT_IOC_PERIOD:
-	{
-		u64 value;
+		return _perf_event_period(event, data->value);
 
-		if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
-			return -EFAULT;
-
-		return _perf_event_period(event, value);
-	}
 	case PERF_EVENT_IOC_ID:
-	{
-		u64 id = primary_event_id(event);
-
-		if (copy_to_user((void __user *)arg, &id, sizeof(id)))
-			return -EFAULT;
+		data->value = primary_event_id(event);
 		return 0;
-	}
 
 	case PERF_EVENT_IOC_SET_OUTPUT:
 	{
@@ -6695,7 +6695,7 @@ static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned lon
 	}
 
 	case PERF_EVENT_IOC_SET_FILTER:
-		return perf_event_set_filter(event, (void __user *)arg);
+		return perf_event_set_filter(event, data->filter);
 
 	case PERF_EVENT_IOC_SET_BPF:
 	{
@@ -6729,19 +6729,9 @@ static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned lon
 		return 0;
 	}
 
-	case PERF_EVENT_IOC_QUERY_BPF:
-		return perf_event_query_prog_array(event, (void __user *)arg);
-
-	case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
-		struct perf_event_attr new_attr;
-		int err = perf_copy_attr((struct perf_event_attr __user *)arg,
-					 &new_attr);
+	case PERF_EVENT_IOC_MODIFY_ATTRIBUTES:
+		return perf_event_modify_attr(event, &data->attr);
 
-		if (err)
-			return err;
-
-		return perf_event_modify_attr(event,  &new_attr);
-	}
 	default:
 		return -ENOTTY;
 	}
@@ -6758,6 +6748,7 @@ static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 {
 	struct perf_event *event = file->private_data;
 	struct perf_event_context *ctx;
+	struct perf_ioctl_data data;
 	long ret;
 
 	/* Treat ioctl like writes as it is likely a mutating operation. */
@@ -6765,10 +6756,46 @@ static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 	if (ret)
 		return ret;
 
+	/*
+	 * A copy from or to userspace can sleep in a page fault. Don't hold
+	 * ctx->mutex for it.
+	 */
+	data.filter = NULL;
+	switch (cmd) {
+	case PERF_EVENT_IOC_PERIOD:
+		if (copy_from_user(&data.value, (u64 __user *)arg,
+				   sizeof(data.value)))
+			return -EFAULT;
+		break;
+
+	case PERF_EVENT_IOC_SET_FILTER:
+		data.filter = strndup_user((void __user *)arg, PAGE_SIZE);
+		if (IS_ERR(data.filter))
+			return PTR_ERR(data.filter);
+		break;
+
+	case PERF_EVENT_IOC_QUERY_BPF:
+		/* Looks at the tracepoint's programs under bpf_event_mutex. */
+		return perf_event_query_prog_array(event, (void __user *)arg);
+
+	case PERF_EVENT_IOC_MODIFY_ATTRIBUTES:
+		ret = perf_copy_attr((struct perf_event_attr __user *)arg,
+				     &data.attr);
+		if (ret)
+			return ret;
+		break;
+	}
+
 	ctx = perf_event_ctx_lock(event);
-	ret = _perf_ioctl(event, cmd, arg);
+	ret = _perf_ioctl(event, cmd, arg, &data);
 	perf_event_ctx_unlock(event, ctx);
 
+	kfree(data.filter);
+
+	if (!ret && cmd == PERF_EVENT_IOC_ID &&
+	    copy_to_user((void __user *)arg, &data.value, sizeof(data.value)))
+		return -EFAULT;
+
 	return ret;
 }
 
@@ -12367,14 +12394,9 @@ perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
 	return ret;
 }
 
-static int perf_event_set_filter(struct perf_event *event, void __user *arg)
+static int perf_event_set_filter(struct perf_event *event, char *filter_str)
 {
 	int ret = -EINVAL;
-	char *filter_str;
-
-	filter_str = strndup_user(arg, PAGE_SIZE);
-	if (IS_ERR(filter_str))
-		return PTR_ERR(filter_str);
 
 #ifdef CONFIG_EVENT_TRACING
 	if (perf_event_is_tracing(event)) {
@@ -12399,7 +12421,6 @@ static int perf_event_set_filter(struct perf_event *event, void __user *arg)
 	if (has_addr_filter(event))
 		ret = perf_event_set_addr_filter(event, filter_str);
 
-	kfree(filter_str);
 	return ret;
 }
 
Signature · 1 line
2.53.0
author maintainer
#5 lore raw

RFC PATCH 5/19 selinux: close inherited files that can't be replaced

In reply to Christian Brauner

When an exec transitions to a new SID flush_unauthorized_files() replaces the inherited files the new SID isn't allowed to use with the null device. It uses replace_fd() for that and ignores the return value.

replace_fd() refuses a file descriptor at or above RLIMIT_NOFILE. And a task can lower its own soft limit as it likes. So a task that sets RLIMIT_NOFILE to the number of a file descriptor right before the exec keeps that file open in the new image:

	fd = open(path, O_RDONLY);	/* 3 */
	getrlimit(RLIMIT_NOFILE, &rl);
	rl.rlim_cur = fd;
	setrlimit(RLIMIT_NOFILE, &rl);
	execve(...);

The new SID still can't read from the file as that is checked again on every use. But it holds on to the file and what isn't checked on use like lseek() works.

Before commit ee97cd872d08 ("switch flush_unauthorized_files() to replace_fd()") the file was closed first and stayed closed if its file descriptor couldn't be allocated again. So close the file if it can't be replaced.

Fixes ee97cd872d08 ("switch flush_unauthorized_files() to replace_fd()")
---
 security/selinux/hooks.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
security/selinux/hooks.c +3 -1
index 9950f89dfaa23..4ec9ec723cacc 100644
@@ -2521,7 +2521,9 @@ static inline void flush_unauthorized_files(const struct cred *cred,
 		devnull = NULL;
 	/* replace all the matching ones with this */
 	do {
-		replace_fd(n - 1, devnull, 0);
+		/* replace_fd() fails for an fd at or above RLIMIT_NOFILE. */
+		if (replace_fd(n - 1, devnull, 0) < 0)
+			close_fd(n - 1);
 	} while ((n = iterate_fd(files, n, match_file, cred)) != 0);
 	if (devnull)
 		fput(devnull);
Signature · 1 line
2.53.0
author maintainer
#6 lore raw

RFC PATCH 6/19 exec: move unshare_sighand() before exec_mmap()

In reply to Christian Brauner

A task that called vfork() sleeps until the child has released the mm. During exec that happens in exec_mmap(). A child that was created with CLONE_SIGHAND shares its signal table with the parent and unshare_sighand() only gives it a private one after exec_mmap(). So the parent runs again while the child is still on the table they share. If the parent ignores a signal right after vfork() returned the new image can end up ignoring it as well.

It used to be the other way around. Commit ccf0fa6be026 ("exec: Move exec_mmap right after de_thread in flush_old_exec") moved exec_mmap() in front of it for two reasons. bprm->mm was to tell whether exec is past the point of no return and everything that can wait for userspace indefinitely was to sit in front of the lock that became exec_update_lock.

Move it back to where it used to be, right after de_thread() and the posix timer cleanup. Nothing in between relies on the signal table still being shared. With that the table is private before the parent is woken up. And the new table isn't allocated with exec_update_lock held anymore.

Fixes ccf0fa6be026 ("exec: Move exec_mmap right after de_thread in flush_old_exec")
---
 fs/exec.c | 15 ++++++++-------
 1 file changed, 8 insertions(+), 7 deletions(-)
fs/exec.c +8 -7
index 8d2b14e1d455c..87b78fce609de 100644
@@ -1171,6 +1171,14 @@ int begin_new_exec(struct linux_binprm * bprm)
 	 */
 	posixtimer_exec();
 
+	/*
+	 * Make the signal table private before a vfork() parent that shares
+	 * it is woken up.
+	 */
+	retval = unshare_sighand(me);
+	if (retval)
+		goto out;
+
 	/* see the comment in check_unsafe_exec() */
 	current->fs->in_exec = 0;
 
@@ -1223,13 +1231,6 @@ int begin_new_exec(struct linux_binprm * bprm)
 	if (retval)
 		goto out_unlock;
 
-	/*
-	 * Make the signal table private.
-	 */
-	retval = unshare_sighand(me);
-	if (retval)
-		goto out_unlock;
-
 	me->flags &= ~(PF_RANDOMIZE | PF_FORKNOEXEC |
 					PF_NOFREEZE | PF_NO_SETAFFINITY);
 	flush_thread();
Signature · 1 line
2.53.0
author maintainer
#7 lore raw

RFC PATCH 7/19 selftests/exec: test exec with a task sleeping in a page fault

In reply to Christian Brauner

Test that a task which sleeps in a page fault while it looks at another task doesn't block an exec of that task:

- readlink() on /proc/<pid>/ns/mnt with a buffer that faults

- kcmp() with KCMP_EPOLL_TFD and a slot that faults

- kcmp() with KCMP_EPOLL_TFD while another thread faults in epoll_wait() on the same epoll file

- read() on a perf event of the task with a buffer that faults

- ioctl() on a perf event of the task with an argument that faults, for each command that copies to or from userspace

The buffer is registered with userfaultfd so the fault only completes after the exec had its chance.

---
 tools/testing/selftests/exec/.gitignore          |   1 +
 tools/testing/selftests/exec/Makefile            |   3 +
 tools/testing/selftests/exec/config              |   3 +
 tools/testing/selftests/exec/update-lock-fault.c | 547 +++++++++++++++++++++++
 4 files changed, 554 insertions(+)
tools/testing/selftests/exec/.gitignore +1 -0
index e42ecd4c908d1..4613c68537395 100644
@@ -16,6 +16,7 @@ null-argv
 !load_address.c
 /recursion-depth
 /set-exec
+/update-lock-fault
 xxxxxxxx*
 pipe
 S_I*.test
tools/testing/selftests/exec/Makefile +3 -0
index 91decfa8ff2c1..3756a250f9591 100644
@@ -20,6 +20,7 @@ TEST_FILES := Makefile
 TEST_GEN_PROGS += recursion-depth
 TEST_GEN_PROGS += null-argv
 TEST_GEN_PROGS += check-exec
+TEST_GEN_PROGS += update-lock-fault
 
 # binfmt_misc must not be reachable as an exec source or as a stacking layer,
 # or an 'F' entry can pin the instance that owns it. Unprivileged, no bpf.
@@ -115,6 +116,8 @@ $(OUTPUT)/binfmt_misc_selfpin: ../filesystems/utils.c
 $(OUTPUT)/binfmt_misc_interplimit: CFLAGS += $(TOOLS_INCLUDES)
 $(OUTPUT)/binfmt_misc_interplimit: ../filesystems/utils.c
 
+$(OUTPUT)/update-lock-fault: LDLIBS += -lpthread
+
 # --- binfmt_misc bpf ('B') handler test ---------------------------------
 # The struct_ops bpf objects are compiled against the running kernel's BTF.
 # CLANG/BPFTOOL/VMLINUX_BTF are set above next to the toolchain check;
tools/testing/selftests/exec/config +3 -0
index ea359a929ae82..2b7563a234112 100644
@@ -4,9 +4,12 @@ CONFIG_BINFMT_MISC=y
 CONFIG_BINFMT_MISC_BPF=y
 CONFIG_BPF_JIT=y
 CONFIG_BPF_SYSCALL=y
+CONFIG_CHECKPOINT_RESTORE=y
 CONFIG_DEBUG_INFO=y
 CONFIG_DEBUG_INFO_BTF=y
 CONFIG_DEBUG_INFO_DWARF4=y
 CONFIG_OVERLAY_FS=y
+CONFIG_PERF_EVENTS=y
 CONFIG_TMPFS=y
+CONFIG_USERFAULTFD=y
 CONFIG_USER_NS=y
tools/testing/selftests/exec/update-lock-fault.c new file +547 -0

547 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#8 lore raw

RFC PATCH 8/19 selftests/exec: test exec with a shared signal table

In reply to Christian Brauner

Test that exec gives a task that shares its signal table with another process a private one:

- handlers the processes shared are reset in the new image

- an ignored signal stays ignored in the new image

- the other process keeps all of its handlers

- a signal the other process ignores right after vfork() returned isn't ignored in the new image

The task is created with CLONE_SIGHAND but without CLONE_THREAD so it isn't taken care of by de_thread(). For the last one the parent runs in a realtime scheduling class on the cpu of the task so that it gets to ignore the signal as soon as it's woken up.

---
 tools/testing/selftests/exec/.gitignore        |   1 +
 tools/testing/selftests/exec/Makefile          |   2 +
 tools/testing/selftests/exec/unshare-sighand.c | 236 +++++++++++++++++++++++++
 3 files changed, 239 insertions(+)
tools/testing/selftests/exec/.gitignore +1 -0
index 4613c68537395..b27f4db42f87b 100644
@@ -16,6 +16,7 @@ null-argv
 !load_address.c
 /recursion-depth
 /set-exec
+/unshare-sighand
 /update-lock-fault
 xxxxxxxx*
 pipe
tools/testing/selftests/exec/Makefile +2 -0
index 3756a250f9591..70f090a5f7648 100644
@@ -21,6 +21,7 @@ TEST_GEN_PROGS += recursion-depth
 TEST_GEN_PROGS += null-argv
 TEST_GEN_PROGS += check-exec
 TEST_GEN_PROGS += update-lock-fault
+TEST_GEN_PROGS += unshare-sighand
 
 # binfmt_misc must not be reachable as an exec source or as a stacking layer,
 # or an 'F' entry can pin the instance that owns it. Unprivileged, no bpf.
@@ -117,6 +118,7 @@ $(OUTPUT)/binfmt_misc_interplimit: CFLAGS += $(TOOLS_INCLUDES)
 $(OUTPUT)/binfmt_misc_interplimit: ../filesystems/utils.c
 
 $(OUTPUT)/update-lock-fault: LDLIBS += -lpthread
+$(OUTPUT)/unshare-sighand: LDLIBS += -lpthread
 
 # --- binfmt_misc bpf ('B') handler test ---------------------------------
 # The struct_ops bpf objects are compiled against the running kernel's BTF.
tools/testing/selftests/exec/unshare-sighand.c new file +236 -0

236 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#9 lore raw

RFC PATCH 9/19 lsm: add security_bprm_revalidate_files()

In reply to Christian Brauner

SELinux and AppArmor revalidate the controlling terminal and the inherited files during exec when the security context changes. Files the new credentials aren't allowed to use are replaced with the null device or closed and a controlling terminal they aren't allowed to use is dropped. Currently, they do this from the bprm_committing_creds hook which begin_new_exec() calls with exec_update_lock held.

Closing a file calls into the filesystem's ->flush() method and that may block for a long time. For the same reason commit e780259b54e6 ("exec:
do_close_on_exec() before taking exec_update_lock") moved the closing of close-on-exec files in front of exec_update_lock.

Add a new hook that is called right after the close-on-exec files have been closed. At that point we're past the point of no return, all other threads are gone and the file descriptor table isn't shared anymore. So nobody but the task itself can install new files or acquire a new controlling terminal until the new credentials are committed. And nothing between the new hook and the bprm_committing_creds hook touches the file descriptor table.

The hook has no users yet. SELinux and AppArmor are switched over separately. Note that bpf lsm programs can attach to it like to any other LSM hook.

Fixes 6650527444da ("proc: protect ptrace_may_access() with exec_update_lock (part 1)")
---
 fs/exec.c                     |  3 +++
 include/linux/lsm_hook_defs.h |  1 +
 include/linux/security.h      |  5 +++++
 security/security.c           | 27 ++++++++++++++++++++++++---
 4 files changed, 33 insertions(+), 3 deletions(-)
fs/exec.c +3 -0
index 87b78fce609de..855437c352137 100644
@@ -1203,6 +1203,9 @@ int begin_new_exec(struct linux_binprm * bprm)
 	 */
 	close_cloexec_files(me->files);
 
+	/* Let LSMs revoke inherited files the new creds may not use. */
+	security_bprm_revalidate_files(bprm);
+
 	/*
 	 * Must be called _before_ exec_mmap() as bprm->mm is
 	 * not visible until then. Doing it here also ensures
include/linux/lsm_hook_defs.h +1 -0
index 87d9d06710cb2..c1bb7501d530d 100644
@@ -52,6 +52,7 @@ LSM_HOOK(int, 0, vm_enough_memory, struct mm_struct *mm, long pages)
 LSM_HOOK(int, 0, bprm_creds_for_exec, struct linux_binprm *bprm)
 LSM_HOOK(int, 0, bprm_creds_from_file, struct linux_binprm *bprm, const struct file *file)
 LSM_HOOK(int, 0, bprm_check_security, struct linux_binprm *bprm)
+LSM_HOOK(void, LSM_RET_VOID, bprm_revalidate_files, const struct linux_binprm *bprm)
 LSM_HOOK(void, LSM_RET_VOID, bprm_committing_creds, const struct linux_binprm *bprm)
 LSM_HOOK(void, LSM_RET_VOID, bprm_committed_creds, const struct linux_binprm *bprm)
 LSM_HOOK(int, 0, fs_context_submount, struct fs_context *fc, struct super_block *reference)
include/linux/security.h +5 -0
index 40831fab54709..e1a85b2f7005e 100644
@@ -360,6 +360,7 @@ int security_vm_enough_memory_mm(struct mm_struct *mm, long pages);
 int security_bprm_creds_for_exec(struct linux_binprm *bprm);
 int security_bprm_creds_from_file(struct linux_binprm *bprm, const struct file *file);
 int security_bprm_check(struct linux_binprm *bprm);
+void security_bprm_revalidate_files(const struct linux_binprm *bprm);
 void security_bprm_committing_creds(const struct linux_binprm *bprm);
 void security_bprm_committed_creds(const struct linux_binprm *bprm);
 int security_fs_context_submount(struct fs_context *fc, struct super_block *reference);
@@ -753,6 +754,10 @@ static inline int security_bprm_check(struct linux_binprm *bprm)
 	return 0;
 }
 
+static inline void security_bprm_revalidate_files(const struct linux_binprm *bprm)
+{
+}
+
 static inline void security_bprm_committing_creds(const struct linux_binprm *bprm)
 {
 }
security/security.c +24 -3
index 4727b8347fc4e..f340880ce77ff 100644
@@ -834,6 +834,25 @@ int security_bprm_check(struct linux_binprm *bprm)
 	return call_int_hook(bprm_check_security, bprm);
 }
 
+/**
+ * security_bprm_revalidate_files() - Revalidate open files during exec()
+ * @bprm: binary program information
+ *
+ * Revalidate access to the controlling tty and the open file descriptors of a
+ * process being transformed by an execve operation, based on the old
+ * credentials pointed to by @current->cred and the information set in
+ * @bprm->cred by the bprm_creds_for_exec hook.  Files to which access will no
+ * longer be granted may be closed or replaced.  @bprm points to the
+ * linux_binprm structure.  This is called after the point of no return, once
+ * the file descriptor table has been unshared and close-on-exec files have been
+ * closed, but before exec_update_lock is taken, as closing a file may block in
+ * the filesystem.
+ */
+void security_bprm_revalidate_files(const struct linux_binprm *bprm)
+{
+	call_void_hook(bprm_revalidate_files, bprm);
+}
+
 /**
  * security_bprm_committing_creds() - Install creds for a process during exec()
  * @bprm: binary program information
@@ -842,9 +861,11 @@ int security_bprm_check(struct linux_binprm *bprm)
  * transformed by an execve operation, based on the old credentials pointed to
  * by @current->cred and the information set in @bprm->cred by the
  * bprm_creds_for_exec hook.  @bprm points to the linux_binprm structure.  This
- * hook is a good place to perform state changes on the process such as closing
- * open file descriptors to which access will no longer be granted when the
- * attributes are changed.  This is called immediately before commit_creds().
+ * hook is a good place to perform state changes on the process such as
+ * resetting resource limits.  It is called with exec_update_lock held so it
+ * should not block on a filesystem.  In particular, it must not close files.
+ * Use the bprm_revalidate_files hook for that.  This is called immediately
+ * before commit_creds().
  */
 void security_bprm_committing_creds(const struct linux_binprm *bprm)
 {
Signature · 1 line
2.53.0
author maintainer
#10 lore raw

RFC PATCH 10/19 bpf: mark bprm_revalidate_files as sleepable

In reply to Christian Brauner

The bprm_revalidate_files hook is called from begin_new_exec() right after the close-on-exec files have been closed. It only exists so that an LSM can revoke inherited files before exec_update_lock is taken as that may block on the filesystem. So it's always called from sleepable context.

Add it to sleepable_lsm_hooks so that sleepable bpf lsm programs can attach to it. All the other bprm hooks are sleepable already.

---
 kernel/bpf/bpf_lsm.c | 1 +
 1 file changed, 1 insertion(+)
kernel/bpf/bpf_lsm.c +1 -0
index 468e63dbd922d..df6ee6e3674dd 100644
@@ -324,6 +324,7 @@ BTF_ID(func, bpf_lsm_bprm_committed_creds)
 BTF_ID(func, bpf_lsm_bprm_committing_creds)
 BTF_ID(func, bpf_lsm_bprm_creds_for_exec)
 BTF_ID(func, bpf_lsm_bprm_creds_from_file)
+BTF_ID(func, bpf_lsm_bprm_revalidate_files)
 BTF_ID(func, bpf_lsm_capget)
 BTF_ID(func, bpf_lsm_capset)
 BTF_ID(func, bpf_lsm_cred_prepare)
Signature · 1 line
2.53.0
author maintainer
#11 lore raw

RFC PATCH 11/19 selinux: revalidate inherited files before taking exec_update_lock

In reply to Christian Brauner

When an exec transitions to a new SID flush_unauthorized_files() revalidates the controlling terminal and the inherited files against the new SID. Files the new SID isn't allowed to use are replaced with the null device. This is done from selinux_bprm_committing_creds() which runs with exec_update_lock held for writing.

Replacing a file closes the old one and so calls its ->flush() method which can block waiting on the filesystem. So a hung filesystem blocks everyone who needs the exec_update_lock of that task. And a FUSE server that looks at the task it serves the flush request for deadlocks:

exec FUSE server
begin_new_exec()

    exec_mmap()
      down_write(exec_update_lock)
    security_bprm_committing_creds()
      flush_unauthorized_files()
        replace_fd()
          filp_close()
            fuse_flush()
                                       do_task_stat()
                                         down_read(exec_update_lock)

With a FUSE server that reads /proc/<pid>/stat of the task that sent the flush request the exec hangs until the server is killed:

task:se-target state:S pid:143

  Call Trace:
   __schedule+0x53e/0x13f0
   schedule+0x36/0x100
   request_wait_answer+0x1a9/0x320
   fuse_chan_send+0x110/0x250
   fuse_flush+0x1af/0x1f0
   filp_flush+0x33/0x90
   filp_close+0x12/0x30
   do_dup2+0xbf/0x1b0
   replace_fd+0x7e/0xd0
   selinux_bprm_committing_creds+0x1a7/0x2d0
   security_bprm_committing_creds+0x1e/0x30
   begin_new_exec+0x6dc/0xf90
   load_elf_binary+0x12a/0x1990
   bprm_execve+0x39d/0x870
   do_execveat_common.isra.0+0x165/0x180
   __x64_sys_execve+0x38/0x50
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

task:se-fuse state:D pid:142

  Call Trace:
   __schedule+0x53e/0x13f0
   schedule+0x36/0x100
   schedule_preempt_disabled+0x11/0x20
   rwsem_down_read_slowpath+0x186/0x5f0
   down_read_killable+0x78/0x1b0
   do_task_stat+0x87/0x10c0
   proc_single_show+0x67/0xe0
   seq_read_iter+0x11c/0x480
   seq_read+0x127/0x1c0
   vfs_read+0xd8/0x4a0
   ksys_read+0x7c/0x110
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

The flush is a forced request so the exec can't even be killed while it waits for the reply.

This is the same problem that commit e780259b54e6 ("exec:
do_close_on_exec() before taking exec_update_lock") fixed for close-on-exec files.

Fix this by moving the revalidation into the new bprm_revalidate_files hook which is called before exec_update_lock is taken.

Fixes 6650527444da ("proc: protect ptrace_may_access() with exec_update_lock (part 1)")
---
 security/selinux/hooks.c | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)
security/selinux/hooks.c +15 -3
index 4ec9ec723cacc..71ea94f663772 100644
@@ -2529,6 +2529,20 @@ static inline void flush_unauthorized_files(const struct cred *cred,
 		fput(devnull);
 }
 
+/*
+ * Close files for which the new task SID is not authorized. Called before
+ * exec_update_lock is taken as closing files may block in the filesystem.
+ */
+static void selinux_bprm_revalidate_files(const struct linux_binprm *bprm)
+{
+	const struct cred_security_struct *new_crsec = selinux_cred(bprm->cred);
+
+	if (new_crsec->sid == new_crsec->osid)
+		return;
+
+	flush_unauthorized_files(bprm->cred, current->files);
+}
+
 /*
  * Prepare a process for imminent new credential changes due to exec
  */
@@ -2542,9 +2556,6 @@ static void selinux_bprm_committing_creds(const struct linux_binprm *bprm)
 	if (new_crsec->sid == new_crsec->osid)
 		return;
 
-	/* Close files for which the new task SID is not authorized. */
-	flush_unauthorized_files(bprm->cred, current->files);
-
 	/* Always clear parent death signal on SID transitions. */
 	current->pdeath_signal = 0;
 
@@ -7690,6 +7701,7 @@ static struct security_hook_list selinux_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(netlink_send, selinux_netlink_send),
 
 	LSM_HOOK_INIT(bprm_creds_for_exec, selinux_bprm_creds_for_exec),
+	LSM_HOOK_INIT(bprm_revalidate_files, selinux_bprm_revalidate_files),
 	LSM_HOOK_INIT(bprm_committing_creds, selinux_bprm_committing_creds),
 	LSM_HOOK_INIT(bprm_committed_creds, selinux_bprm_committed_creds),
 
Signature · 1 line
2.53.0
author maintainer
#13 lore raw

RFC PATCH 12/19 apparmor: revalidate inherited files before taking exec_update_lock

In reply to Christian Brauner

When an exec changes the profile aa_inherit_files() revalidates the controlling terminal and the inherited files against the new label. Everything the new label isn't allowed to use is taken away from the task. This is done from apparmor_bprm_committing_creds() which runs with exec_update_lock held for writing.

Taking a file away closes it and so calls its ->flush() method which can block waiting on the filesystem. So a hung filesystem blocks everyone who needs the exec_update_lock of that task. And a FUSE server that looks at the task it serves the flush request for deadlocks:

exec FUSE server
begin_new_exec()

    exec_mmap()
      down_write(exec_update_lock)
    security_bprm_committing_creds()
      aa_inherit_files()
        replace_fd()
          filp_close()
            fuse_flush()
                                       do_task_stat()
                                         down_read(exec_update_lock)

With a FUSE server that reads /proc/<pid>/stat of the task that sent the flush request the exec hangs until the server is killed:

task:aa-target state:S pid:98

  Call Trace:
   __schedule+0x53e/0x13f0
   schedule+0x36/0x100
   request_wait_answer+0x1a9/0x320
   fuse_chan_send+0x110/0x250
   fuse_flush+0x1af/0x1f0
   filp_flush+0x33/0x90
   filp_close+0x12/0x30
   aa_inherit_files+0x191/0x2a0
   apparmor_bprm_committing_creds+0x61/0x90
   security_bprm_committing_creds+0x19/0x30
   begin_new_exec+0x6dc/0xf90
   load_elf_binary+0x12a/0x1990
   bprm_execve+0x39d/0x870
   do_execveat_common.isra.0+0x165/0x180
   __x64_sys_execve+0x38/0x50
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

task:aa-fuse state:D pid:97

  Call Trace:
   __schedule+0x53e/0x13f0
   schedule+0x36/0x100
   schedule_preempt_disabled+0x11/0x20
   rwsem_down_read_slowpath+0x186/0x5f0
   down_read_killable+0x78/0x1b0
   do_task_stat+0x87/0x10c0
   proc_single_show+0x67/0xe0
   seq_read_iter+0x11c/0x480
   seq_read+0x127/0x1c0
   vfs_read+0xd8/0x4a0
   ksys_read+0x7c/0x110
   do_syscall_64+0x110/0x600
   entry_SYSCALL_64_after_hwframe+0x77/0x7f

The flush is a forced request so the exec can't even be killed while it waits for the reply.

This is the same problem that commit e780259b54e6 ("exec:
do_close_on_exec() before taking exec_update_lock") fixed for close-on-exec files.

Fix this by moving the revalidation into the new bprm_revalidate_files hook which is called before exec_update_lock is taken.

Fixes 6650527444da ("proc: protect ptrace_may_access() with exec_update_lock (part 1)")
---
 security/apparmor/lsm.c | 23 +++++++++++++++++++++--
 1 file changed, 21 insertions(+), 2 deletions(-)
security/apparmor/lsm.c +21 -2
index eaebc3c60c5af..e40619b0f4ba9 100644
@@ -951,10 +951,13 @@ static int apparmor_setprocattr(const char *name, void *value,
 }
 
 /**
- * apparmor_bprm_committing_creds - do task cleanup on committing new creds
+ * apparmor_bprm_revalidate_files - revalidate inherited files on exec
  * @bprm: binprm for the exec  (NOT NULL)
+ *
+ * Called before exec_update_lock is taken as closing files may block in
+ * the filesystem.
  */
-static void apparmor_bprm_committing_creds(const struct linux_binprm *bprm)
+static void apparmor_bprm_revalidate_files(const struct linux_binprm *bprm)
 {
 	struct aa_label *label = aa_current_raw_label();
 	struct aa_label *new_label = cred_label(bprm->cred);
@@ -965,6 +968,21 @@ static void apparmor_bprm_committing_creds(const struct linux_binprm *bprm)
 		return;
 
 	aa_inherit_files(bprm->cred, current->files);
+}
+
+/**
+ * apparmor_bprm_committing_creds - do task cleanup on committing new creds
+ * @bprm: binprm for the exec  (NOT NULL)
+ */
+static void apparmor_bprm_committing_creds(const struct linux_binprm *bprm)
+{
+	struct aa_label *label = aa_current_raw_label();
+	struct aa_label *new_label = cred_label(bprm->cred);
+
+	/* bail out if unconfined or not changing profile */
+	if ((new_label->proxy == label->proxy) ||
+	    (unconfined(new_label)))
+		return;
 
 	current->pdeath_signal = 0;
 
@@ -1860,6 +1878,7 @@ static struct security_hook_list apparmor_hooks[] __ro_after_init = {
 	LSM_HOOK_INIT(cred_transfer, apparmor_cred_transfer),
 
 	LSM_HOOK_INIT(bprm_creds_for_exec, apparmor_bprm_creds_for_exec),
+	LSM_HOOK_INIT(bprm_revalidate_files, apparmor_bprm_revalidate_files),
 	LSM_HOOK_INIT(bprm_committing_creds, apparmor_bprm_committing_creds),
 	LSM_HOOK_INIT(bprm_committed_creds, apparmor_bprm_committed_creds),
 
Signature · 1 line
2.53.0
author maintainer
#14 lore raw

RFC PATCH 13/19 exec: drop exec_update_lock after the credentials are committed

In reply to Christian Brauner

exec_update_lock makes sure that nobody who takes it can see the new mm together with the old credentials. It is taken in exec_mmap() and currently held until setup_new_exec().

When it was added in commit eea9673250db ("exec: Add exec_update_mutex to replace cred_guard_mutex") it was dropped at the end of install_exec_creds(), right after the new credentials were committed and the LSMs had been told about it. Back then the personality and the mmap layout were set up before the credentials were committed. They only ended up between commit_creds() and the unlock when commit df9e4d2c4a53 ("exec: Move most of setup_new_exec into flush_old_exec") moved the credential commit into flush_old_exec() and left the unlock in setup_new_exec().

Once the mm, the exec state and the credentials are switched and perf_event_exit_task() has run every reader is checked against the new credentials. But we still do a bunch of work with exec_update_lock held:

- security_bprm_committed_creds() which is a sleepable hook for bpf lsm programs

- installing the execfd which may have to grow the file descriptor table

- the binfmt setting the personality

- arch_pick_mmap_layout() and arch_setup_new_exec()

So drop it right after perf_event_exit_task(). The LSM hooks don't move relative to commit_creds() and cred_guard_mutex is still held until setup_new_exec() so nothing changes for ptrace.

While at it, fix the comments that still point to setup_new_exec(). It's begin_new_exec() that commits the new credentials, changes whether the task is dumpable and calls perf_event_exit_task().

---
 fs/exec.c            | 39 ++++++++++++++++++++++++---------------
 kernel/events/core.c |  2 +-
 2 files changed, 25 insertions(+), 16 deletions(-)
fs/exec.c +24 -15
index 855437c352137..7b261b0a5f33c 100644
@@ -837,8 +837,10 @@ EXPORT_SYMBOL(read_code);
 /*
  * Maps the mm_struct mm into the current task struct.
  * On success, this function returns with exec_update_lock
- * held for writing. The replaced address space is stashed in
- * bprm->old_mm for setup_new_exec() to release outside the lock.
+ * held for writing. begin_new_exec() drops it once the new
+ * credentials are committed. The replaced address space is
+ * stashed in bprm->old_mm for setup_new_exec() to release
+ * outside the exec locks.
  */
 static int exec_mmap(struct linux_binprm *bprm)
 {
@@ -1191,8 +1193,8 @@ int begin_new_exec(struct linux_binprm * bprm)
 
 	/*
 	 * We have to apply CLOEXEC before we change whether the process is
-	 * dumpable (in setup_new_exec) to avoid a race with a process in userspace
-	 * trying to access the should-be-closed file descriptors of a process
+	 * dumpable to avoid a race with a process in userspace trying to
+	 * access the should-be-closed file descriptors of a process
 	 * undergoing exec(2).
 	 *
 	 * This can block on filesystem ->flush() and ->release() handlers,
@@ -1232,7 +1234,7 @@ int begin_new_exec(struct linux_binprm * bprm)
 
 	retval = exec_task_namespaces();
 	if (retval)
-		goto out_unlock;
+		goto out_unlock_exec_update;
 
 	me->flags &= ~(PF_RANDOMIZE | PF_FORKNOEXEC |
 					PF_NOFREEZE | PF_NO_SETAFFINITY);
@@ -1303,7 +1305,7 @@ int begin_new_exec(struct linux_binprm * bprm)
 
 	retval = set_cred_ucounts(bprm->cred);
 	if (retval < 0)
-		goto out_unlock;
+		goto out_unlock_exec_update;
 
 	/*
 	 * install the new credentials for this executable
@@ -1321,6 +1323,10 @@ int begin_new_exec(struct linux_binprm * bprm)
 	 */
 	if (task_exec_state_get_dumpable(me) != TASK_DUMPABLE_OWNER)
 		perf_event_exit_task(me);
+
+	/* The mm, exec state and creds are switched. Let readers back in. */
+	up_write(&me->signal->exec_update_lock);
+
 	/*
 	 * cred_guard_mutex must be held at least to this point to prevent
 	 * ptrace_attach() from altering our determination of the task's
@@ -1339,17 +1345,20 @@ int begin_new_exec(struct linux_binprm * bprm)
 		if (retval < 0) {
 			/* The reference was not consumed. */
 			fput(executable);
-			goto out_unlock;
+			goto out_unlock_cred_guard;
 		}
 		bprm->execfd = retval;
 	}
 	return 0;
 
-out_unlock:
-	up_write(&me->signal->exec_update_lock);
-	if (!bprm->cred)
-		mutex_unlock(&me->signal->cred_guard_mutex);
+out_unlock_cred_guard:
+	/* free_bprm() only unlocks cred_guard_mutex if bprm->cred is set. */
+	mutex_unlock(&me->signal->cred_guard_mutex);
+	return retval;
 
+out_unlock_exec_update:
+	/* bprm->cred is still set so free_bprm() unlocks cred_guard_mutex. */
+	up_write(&me->signal->exec_update_lock);
 out:
 	return retval;
 }
@@ -1391,7 +1400,6 @@ void setup_new_exec(struct linux_binprm * bprm)
 	 * some architectures like powerpc
 	 */
 	me->mm->task_size = TASK_SIZE;
-	up_write(&me->signal->exec_update_lock);
 	mutex_unlock(&me->signal->cred_guard_mutex);
 
 	/* The exec locks are dropped: release the old address space now. */
@@ -1414,9 +1422,10 @@ EXPORT_SYMBOL(finalize_exec);
 
 /*
  * Prepare credentials and lock ->cred_guard_mutex.
- * setup_new_exec() commits the new creds and drops the lock.
- * Or, if exec fails before, free_bprm() should release ->cred
- * and unlock.
+ * begin_new_exec() commits the new creds and setup_new_exec()
+ * drops the lock. If exec fails before the creds are committed
+ * free_bprm() releases ->cred and unlocks. If it fails after
+ * that begin_new_exec() unlocks.
  */
 static int prepare_bprm_creds(struct linux_binprm *bprm)
 {
kernel/events/core.c +1 -1
index 5f648e00ae661..10612214e89cd 100644
@@ -14871,7 +14871,7 @@ static void perf_event_exit_task_context(struct task_struct *task, bool exit)
  * When a task exits, feed back event values to parent events.
  *
  * Can be called with exec_update_lock held when called from
- * setup_new_exec().
+ * begin_new_exec().
  */
 void perf_event_exit_task(struct task_struct *task)
 {
Signature · 1 line
2.53.0
author maintainer
#15 lore raw

RFC PATCH 14/19 exec: switch time namespace after dropping exec_update_lock

In reply to Christian Brauner

If the task has unshared its time namespace then exec moves it into the new time namespace as it's getting a new mm. That allocates a new nsproxy, may take the timens offset mutex and the mmap lock of the new mm to switch the vdso data and may drop the last reference to the old nsproxy. Currently, all of that happens with exec_update_lock held.

The time namespace switch isn't tied to the credentials changing. So do it after exec_update_lock has been dropped. It still happens before the vdso is mapped. Call it after security_bprm_committed_creds() so there's no failure between committing the credentials and telling the LSMs about it.

---
 fs/exec.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
fs/exec.c +5 -4
index 7b261b0a5f33c..6120310f3fbab 100644
@@ -1232,10 +1232,6 @@ int begin_new_exec(struct linux_binprm * bprm)
 
 	bprm->mm = NULL;
 
-	retval = exec_task_namespaces();
-	if (retval)
-		goto out_unlock_exec_update;
-
 	me->flags &= ~(PF_RANDOMIZE | PF_FORKNOEXEC |
 					PF_NOFREEZE | PF_NO_SETAFFINITY);
 	flush_thread();
@@ -1334,6 +1330,11 @@ int begin_new_exec(struct linux_binprm * bprm)
 	 */
 	security_bprm_committed_creds(bprm);
 
+	/* Switch time namespace now that the task has a new mm. */
+	retval = exec_task_namespaces();
+	if (retval)
+		goto out_unlock_cred_guard;
+
 	/* Pass the opened binary to the interpreter. */
 	if (bprm->have_execfd) {
 		struct file *executable = bprm->executable;
Signature · 1 line
2.53.0
author maintainer
#16 lore raw

RFC PATCH 15/19 exec: don't take the mmap lock of the old mm

In reply to Christian Brauner

exec_mmap() takes the mmap lock of the old mm for reading while it switches the task over to the new mm. And it does that with exec_update_lock held for writing.

That lock was only ever needed for coredumps. The coredump code used to take the mmap lock for writing and then killed every task using the mm. So exec had to check for a coredump in progress under the mmap lock before it left the mm. Commit 7e3c4fb7fc19 ("exec: Check for a pending fatal signal instead of core_state") replaced that check with mmap_read_lock_killable(). And since commit 0258b5fd7c71 ("coredump:
Limit coredumps to a single thread group") a coredump doesn't kill anything outside of its own thread-group and doesn't take the mmap lock to find tasks anymore. An exec in the same thread-group is serialized against the coredump in de_thread().

Nothing else relies on the mmap lock to keep a task from leaving its mm.

exit_mm() takes the mmap lock for the same historical reason. The next patch removes that one.

---
 fs/exec.c | 14 --------------
 1 file changed, 14 deletions(-)
fs/exec.c +0 -14
index 6120310f3fbab..78046ed839646 100644
@@ -864,19 +864,6 @@ static int exec_mmap(struct linux_binprm *bprm)
 	if (ret)
 		return ret;
 
-	if (old_mm) {
-		/*
-		 * If there is a pending fatal signal perhaps a signal
-		 * whose default action is to create a coredump get
-		 * out and die instead of going through with the exec.
-		 */
-		ret = mmap_read_lock_killable(old_mm);
-		if (ret) {
-			up_write(&tsk->signal->exec_update_lock);
-			return ret;
-		}
-	}
-
 	task_lock(tsk);
 	membarrier_exec_mmap(mm);
 
@@ -903,7 +890,6 @@ static int exec_mmap(struct linux_binprm *bprm)
 	task_unlock(tsk);
 	lru_gen_use_mm(mm);
 	if (old_mm) {
-		mmap_read_unlock(old_mm);
 		BUG_ON(active_mm != old_mm);
 		/* Defer teardown to setup_new_exec(), outside the exec locks. */
 		bprm->old_mm = old_mm;
Signature · 1 line
2.53.0
author maintainer
#17 lore raw

RFC PATCH 16/19 exit: don't take the mmap lock in exit_mm()

In reply to Christian Brauner

exit_mm() takes the mmap lock for reading around clearing current->mm. That goes back to 2003 (cf. [1]). A coredump took the lock for writing and counted every thread that had an mm in mm->core_waiters. An exiting thread had to look at core_waiters and clear its mm without the dumping thread getting in between.

Commit 92307383082d ("coredump: Don't perform any cleanups before dumping core") moved that check into coredump_task_exit() which runs before exit_mm(). And commit 0258b5fd7c71 ("coredump: Limit coredumps to a single thread group") moved core_state into signal_struct and the check under siglock. Since then the lock in exit_mm() doesn't protect anything a coredump looks at.

So don't take it.

While at it, drop the comment that calls task_lock() more a memory barrier than a real lock. It's the only lock that's left around clearing current->mm.

[1]: https://git.kernel.org/pub/scm/linux/kernel/git/history/history.git/commit/?id=99365bd4725d431255ff4bdd51fb3dca60c47322

---
 kernel/exit.c | 3 ---
 1 file changed, 3 deletions(-)
kernel/exit.c +0 -3
index d5e7bc2af804a..38de318a07aaa 100644
@@ -559,10 +559,8 @@ static void exit_mm(void)
 
 	sched_cache_exit_mm(current);
 
-	mmap_read_lock(mm);
 	mmgrab_lazy_tlb(mm);
 	BUG_ON(mm != current->active_mm);
-	/* more a memory barrier than a real lock */
 	task_lock(current);
 	/*
 	 * When a thread stops operating on an address space, the loop
@@ -581,7 +579,6 @@ static void exit_mm(void)
 	enter_lazy_tlb(mm, current);
 	local_irq_enable();
 	task_unlock(current);
-	mmap_read_unlock(mm);
 	mm_update_next_owner(mm);
 	mmput(mm);
 	if (test_thread_flag(TIF_MEMDIE))
Signature · 1 line
2.53.0
author maintainer
#18 lore raw

RFC PATCH 17/19 proc: look up map_files vma without exec_update_lock held

In reply to Christian Brauner

Since commit 6255da28d4bb ("proc: protect ptrace_may_access() with exec_update_lock (FD links)") the links in /proc/<pid>/map_files are resolved with exec_update_lock of the task held. To find the file map_files_get_link() looks up the vma and for that it waits for the mmap lock of the mm.

So whoever reads such a link makes an exec of the task wait for the mmap lock of its old mm although exec_mmap() doesn't take that lock anymore. And everyone else who wants to look at the task queues up behind the exec.

The lock is only needed for the access check and to get at the mm the check was made for. So only do that with the lock held and look up the vma afterwards.

The links don't go through call_proc_get_link() anymore so they don't need ->proc_get_link().

---
 fs/proc/base.c | 68 ++++++++++++++++++++++++++++++++++++++++++++--------------
 1 file changed, 52 insertions(+), 16 deletions(-)
fs/proc/base.c +52 -16
index 7685660c36241..b28bd6c57e1d8 100644
@@ -2228,18 +2228,40 @@ static const struct dentry_operations tid_map_files_dentry_operations = {
 	.d_delete	= pid_delete_dentry,
 };
 
-static int map_files_get_link(struct dentry *dentry, struct path *path,
-			      struct task_struct *task)
+/* Check the access and pin the mm with exec_update_lock held. */
+static struct mm_struct *map_files_mm(struct inode *inode)
+{
+	struct task_struct *task __free(put_task) = NULL;
+	struct mm_struct *mm;
+	int err;
+
+	task = get_proc_task(inode);
+	if (!task)
+		return ERR_PTR(-ENOENT);
+
+	err = down_read_killable(&task->signal->exec_update_lock);
+	if (err)
+		return ERR_PTR(err);
+	if (ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS))
+		mm = get_task_mm(task) ?: ERR_PTR(-ENOENT);
+	else
+		mm = ERR_PTR(-EACCES);
+	up_read(&task->signal->exec_update_lock);
+	return mm;
+}
+
+/* The vma lookup waits for the mmap lock so do it without exec_update_lock. */
+static int map_files_get_link(struct dentry *dentry, struct inode *inode,
+			      struct path *path)
 {
 	unsigned long vm_start, vm_end;
 	struct vm_area_struct *vma;
 	struct mm_struct *mm;
 	int rc;
 
-	rc = -ENOENT;
-	mm = get_task_mm(task);
-	if (!mm)
-		goto out;
+	mm = map_files_mm(inode);
+	if (IS_ERR(mm))
+		return PTR_ERR(mm);
 
 	rc = dname_to_vma_addr(dentry, &vm_start, &vm_end);
 	if (rc)
@@ -2260,7 +2282,6 @@ static int map_files_get_link(struct dentry *dentry, struct path *path,
 
 out_mmput:
 	mmput(mm);
-out:
 	return rc;
 }
 
@@ -2280,17 +2301,36 @@ proc_map_files_get_link(struct dentry *dentry,
 			struct inode *inode,
 		        struct delayed_call *done)
 {
+	struct path path;
+	int error;
+
 	if (!checkpoint_restore_ns_capable(&init_user_ns))
 		return ERR_PTR(-EPERM);
 
-	return proc_pid_get_link(dentry, inode, done);
+	if (!dentry)
+		return ERR_PTR(-ECHILD);
+	error = map_files_get_link(dentry, inode, &path);
+	if (!error)
+		error = nd_jump_link(&path);
+	return ERR_PTR(error);
+}
+
+static int proc_map_files_readlink(struct dentry *dentry, char __user *buffer,
+				   int buflen)
+{
+	struct path path;
+	int error;
+
+	error = map_files_get_link(dentry, d_inode(dentry), &path);
+	if (!error) {
+		error = do_proc_readlink(&path, buffer, buflen);
+		path_put(&path);
+	}
+	return error;
 }
 
-/*
- * Identical to proc_pid_link_inode_operations except for get_link()
- */
 static const struct inode_operations proc_map_files_link_inode_operations = {
-	.readlink	= proc_pid_readlink,
+	.readlink	= proc_map_files_readlink,
 	.get_link	= proc_map_files_get_link,
 	.setattr	= proc_nochmod_setattr,
 };
@@ -2300,7 +2340,6 @@ proc_map_files_instantiate(struct dentry *dentry,
 			   struct task_struct *task, const void *ptr)
 {
 	fmode_t mode = (fmode_t)(unsigned long)ptr;
-	struct proc_inode *ei;
 	struct inode *inode;
 
 	inode = proc_pid_make_inode(dentry->d_sb, task, S_IFLNK |
@@ -2309,9 +2348,6 @@ proc_map_files_instantiate(struct dentry *dentry,
 	if (!inode)
 		return ERR_PTR(-ENOENT);
 
-	ei = PROC_I(inode);
-	ei->op.proc_get_link = map_files_get_link;
-
 	inode->i_op = &proc_map_files_link_inode_operations;
 	inode->i_size = 64;
 
Signature · 1 line
2.53.0
author maintainer
#20 lore raw

RFC PATCH 18/19 vfork: wake up the parent once the child has left the mm

In reply to Christian Brauner

A task that called vfork() sleeps until the child has released the mm in mm_release(). But exec_mmap() releases the old mm, then waits for exec_update_lock and only then switches to the new mm. And exit_mm() releases the mm and only then drops it. So the parent is woken up while the child is still on its mm.

It wasn't meant to be that way. When mm_release() was added in 2.2 it was called after the task had been switched away from the mm. exec only moved it in front of the switch in 2.5.56 because deactivate_mm() and the write to the child tid address need the old mm (cf. [1]).

The release has to stay where it is as it can sleep in a page fault for as long as userspace likes. So take the wakeup out of mm_release(). Wake up the parent in exec_mmap() once the task has switched to its new mm and in exit_mm() once it has dropped the mm.

While at it, fix the comment above mm_release(). It hasn't been called after the mm was removed from the task since 2.5.56.

---
 fs/exec.c                |  3 ++-
 include/linux/sched/mm.h |  4 +++-
 kernel/exit.c            |  7 ++++++-
 kernel/fork.c            | 24 ++++++++++++++----------
 4 files changed, 25 insertions(+), 13 deletions(-)
fs/exec.c +2 -1
index 78046ed839646..4d3f78ea0b0e6 100644
@@ -854,7 +854,6 @@ static int exec_mmap(struct linux_binprm *bprm)
 	if (!exec_state)
 		return -ENOMEM;
 
-	/* Notify parent that we're no longer interested in the old VM */
 	tsk = current;
 	old_mm = current->mm;
 	/* Clean up futexes and release the mm */
@@ -897,6 +896,8 @@ static int exec_mmap(struct linux_binprm *bprm)
 		mmdrop_lazy_tlb(active_mm);
 	}
 	futex_exec_done(tsk);
+	/* We've left the old mm so a vfork() parent can run again. */
+	complete_vfork_done(tsk);
 	return 0;
 }
 
include/linux/sched/mm.h +3 -1
index d7c6a942aa7e0..2adfba6217133 100644
@@ -158,9 +158,11 @@ extern struct mm_struct *mm_access(struct task_struct *task, unsigned int mode);
 
 /*
  * Remove the current tasks stale references to the old mm_struct on exit() and
- * exec(). Cleans up futexes as well.
+ * exec(). Cleans up futexes as well. A parent that sleeps in vfork() is only
+ * woken up by complete_vfork_done() once the task has left the mm.
  */
 extern void mm_exit_exec_release(struct task_struct *, struct mm_struct *);
+void complete_vfork_done(struct task_struct *tsk);
 
 #ifdef CONFIG_MEMCG
 extern void mm_update_next_owner(struct mm_struct *mm);
kernel/exit.c +6 -1
index 38de318a07aaa..6120f0dc3b17d 100644
@@ -554,8 +554,11 @@ static void exit_mm(void)
 	struct mm_struct *mm = current->mm;
 
 	mm_exit_exec_release(current, mm);
-	if (!mm)
+	if (!mm) {
+		/* kthread_stop() waits for this. */
+		complete_vfork_done(current);
 		return;
+	}
 
 	sched_cache_exit_mm(current);
 
@@ -579,6 +582,8 @@ static void exit_mm(void)
 	enter_lazy_tlb(mm, current);
 	local_irq_enable();
 	task_unlock(current);
+	/* We've left the mm so a vfork() parent can run again. */
+	complete_vfork_done(current);
 	mm_update_next_owner(mm);
 	mmput(mm);
 	if (test_thread_flag(TIF_MEMDIE))
kernel/fork.c +14 -10
index 5efceb8d58a78..f63133b9e6faf 100644
@@ -1428,10 +1428,21 @@ struct mm_struct *mm_access(struct task_struct *task, unsigned int mode)
 	return mm;
 }
 
-static void complete_vfork_done(struct task_struct *tsk)
+/**
+ * complete_vfork_done - wake up whoever waits for @tsk in vfork()
+ * @tsk: task that execs or exits
+ *
+ * A parent that sleeps in vfork() must not run before the child is off its
+ * mm. So this is called once @tsk has switched to its new mm in exec or has
+ * dropped its mm in exit. kthread_stop() uses this completion as well.
+ */
+void complete_vfork_done(struct task_struct *tsk)
 {
 	struct completion *vfork;
 
+	if (!tsk->vfork_done)
+		return;
+
 	task_lock(tsk);
 	vfork = tsk->vfork_done;
 	if (likely(vfork)) {
@@ -1465,8 +1476,8 @@ static int wait_for_vfork_done(struct task_struct *child,
  * mmput is called whenever we stop holding onto a mm_struct,
  * error success whatever.
  *
- * mm_release is called after a mm_struct has been removed
- * from the current process.
+ * mm_release is called when the current process is about to
+ * leave a mm_struct in exec or in exit. It's still on it.
  *
  * This difference is important for error handling, when we
  * only half set up a mm_struct for a new process and need to restore
@@ -1498,13 +1509,6 @@ static void mm_release(struct task_struct *tsk, struct mm_struct *mm)
 		}
 		tsk->clear_child_tid = NULL;
 	}
-
-	/*
-	 * All done, finally we can wake up parent and return this mm to him.
-	 * Also kthread_stop() uses this completion for synchronization.
-	 */
-	if (tsk->vfork_done)
-		complete_vfork_done(tsk);
 }
 
 void mm_exit_exec_release(struct task_struct *tsk, struct mm_struct *mm)
Signature · 1 line
2.53.0
author maintainer
#22 lore raw

RFC PATCH 19/19 selftests/exec: test when a vfork() parent is woken up

In reply to Christian Brauner

Test that a task which called vfork() only runs again once the child has left the mm:

- when the child execs

- when the child is killed in the middle of the exec

- when the child exits

A parent that is woken up too early only has a few instructions to catch the child on the mm. So the parent runs in a realtime scheduling class on the cpu of the child and preempts it as soon as it's woken up. That takes a kernel with preemption. The tests are skipped without it and without the right to use a realtime class.

To kill the child between the release of the old mm and the switch to the new one it has to wait for exec_update_lock there. So there are more readers of its /proc/<pid>/stat than the cpu they share can run and some of them are preempted with the lock held.

---
 tools/testing/selftests/exec/.gitignore |   1 +
 tools/testing/selftests/exec/Makefile   |   1 +
 tools/testing/selftests/exec/vfork-mm.c | 363 ++++++++++++++++++++++++++++++++
 3 files changed, 365 insertions(+)
tools/testing/selftests/exec/.gitignore +1 -0
index b27f4db42f87b..24f8f80543df1 100644
@@ -18,6 +18,7 @@ null-argv
 /set-exec
 /unshare-sighand
 /update-lock-fault
+/vfork-mm
 xxxxxxxx*
 pipe
 S_I*.test
tools/testing/selftests/exec/Makefile +1 -0
index 70f090a5f7648..7d61203d6547b 100644
@@ -22,6 +22,7 @@ TEST_GEN_PROGS += null-argv
 TEST_GEN_PROGS += check-exec
 TEST_GEN_PROGS += update-lock-fault
 TEST_GEN_PROGS += unshare-sighand
+TEST_GEN_PROGS += vfork-mm
 
 # binfmt_misc must not be reachable as an exec source or as a stacking layer,
 # or an 'F' entry can pin the instance that owns it. Unprivileged, no bpf.
tools/testing/selftests/exec/vfork-mm.c new file +363 -0

363 lines not on this page · raw message

Signature · 1 line
2.53.0
#19 lore raw

Re: [PATCH RFC 17/19] proc: look up map_files vma without exec_update_lock held

In reply to Christian Brauner
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] proc: separate __free() declaration and initialization in map_files_mm() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] proc: separate __free() declaration and initialization in map_files_mm()
--

commit 6e8b44b478838f53cfc44f13f68cf03b45a869ce
Author: Christian Brauner <[email protected]>

proc: look up map_files vma without exec_update_lock held

This commit restricts holding exec_update_lock during /proc/<pid>/map_files symlink resolution to the access check and mm pinning in map_files_mm(), performing the VMA lookup after releasing the lock.

Quoted 8 lines
fs/proc/base.c +0 -0
index 7685660c36241..b28bd6c57e1d8 100644
@@ -2228,18 +2228,40 @@ static const struct dentry_operations tid_map_files_dentry_operations = {
 	.d_delete	= pid_delete_dentry,
 };
 

fs/proc/base.c static const struct dentry_operations tid_map_files_dentry_operations = { · line 2238

Quoted 10 lines
fs/proc/base.c +8 -2
-static int map_files_get_link(struct dentry *dentry, struct path *path,
-			      struct task_struct *task)
+/* Check the access and pin the mm with exec_update_lock held. */
+static struct mm_struct *map_files_mm(struct inode *inode)
+{
+	struct task_struct *task __free(put_task) = NULL;
+	struct mm_struct *mm;
+	int err;
+
+	task = get_proc_task(inode);

[Severity: Low]
This isn't a bug, but per the cleanup.h convention, task can be defined and initialized with get_proc_task(inode) in a single statement rather than being initialized to NULL and assigned right after.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=17
#23 lore raw
In reply to Christian Brauner
Sashiko has finished reviewing this 19-patch series:

Sashiko has finished reviewing this 19-patch series:

- Patches 1-16, 18, and 19: no issues found.
- Patch 17 ("proc: look up map_files vma without exec_update_lock..."):
1 potential issue (1 Low)

A detailed review has been sent as a separate reply to patch 17.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]
#21 lore raw

Re: [PATCH RFC 18/19] vfork: wake up the parent once the child has left the mm

In reply to Christian Brauner
TL;DR: Commit message only: it cites "[1]" for the 2.5.56 change but has no matching link; the review asks for the history.git URL to be added.
Quoted 1 line

vfork: wake up the parent once the child has left the mm

TL;DR: Commit message only: it cites "[1]" for the 2.5.56 change but has no matching link; the review asks for the history.git URL to be added.

Quoted 18 lines

vfork: wake up the parent once the child has left the mm

A task that called vfork() sleeps until the child has released the mm in mm_release(). But exec_mmap() releases the old mm, then waits for exec_update_lock and only then switches to the new mm. And exit_mm() releases the mm and only then drops it. So the parent is woken up while the child is still on its mm.

It wasn't meant to be that way. When mm_release() was added in 2.2 it was called after the task had been switched away from the mm. exec only moved it in front of the switch in 2.5.56 because deactivate_mm() and the write to the child tid address need the old mm (cf. [1]).

The release has to stay where it is as it can sleep in a page fault for as long as userspace likes. So take the wakeup out of mm_release(). Wake up the parent in exec_mmap() once the task has switched to its new mm and in exit_mm() once it has dropped the mm.

Quoted 4 lines

While at it, fix the comment above mm_release(). It hasn't been called after the mm was removed from the task since 2.5.56.

This isn't a bug, but the changelog cites "(cf. [1])" for the 2.5.56 change that moved mm_release() in front of the mm switch, and there is no "[1]: https://..." line or Link: tag anywhere in the message.

The previous commit in the series, d0c33c04297e ("exit: don't take the mmap lock in exit_mm()"), uses the same "(cf. [1])" form and does end with a "[1]: https://git.kernel.org/pub/scm/linux/kernel/git/history/history.git/..."
line.

Could the history.git link for the 2.5.56 change be added here as well?

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45508356147

#12 lore raw

Re: [PATCH RFC 11/19] selinux: revalidate inherited files before taking exec_update_lock

In reply to Christian Brauner
TL;DR: Moving flush_unauthorized_files() earlier changes the comm logged in SELinux AVC denials to the pre-exec name instead of the new program's; asks whether that is intended and, if so, to note…
Quoted 1 line

selinux: revalidate inherited files before taking exec_update_lock

TL;DR: Moving flush_unauthorized_files() earlier changes the comm logged in SELinux AVC denials to the pre-exec name instead of the new program's; asks whether that is intended and, if so, to note it in the commit message.

Quoted 3 lines
security/selinux/hooks.c +0 -0

[ ... ]

security/selinux/hooks.c static inline void flush_unauthorized_files(const struct cred *cred, · line 2544

Quoted 13 lines
security/selinux/hooks.c +13 -0
+/*
+ * Close files for which the new task SID is not authorized. Called before
+ * exec_update_lock is taken as closing files may block in the filesystem.
+ */
+static void selinux_bprm_revalidate_files(const struct linux_binprm *bprm)
+{
+	const struct cred_security_struct *new_crsec = selinux_cred(bprm->cred);
+
+	if (new_crsec->sid == new_crsec->osid)
+		return;
+
+	flush_unauthorized_files(bprm->cred, current->files);
+}

Moving this call changes what the resulting AVC denial records contain. Denials from flush_unauthorized_files() go through match_file() -> file_has_perm() -> avc_has_perm() and are formatted by dump_common_audit_data(), which logs the program name from current->comm:

    audit_log_format(ab, " pid=%d comm=", task_tgid_nr(current));
    audit_log_untrustedstring(ab, get_task_comm(comm, current));

Previously this ran from selinux_bprm_committing_creds() in begin_new_exec(), after __set_task_comm(me, kbasename(bprm->filename), true), so the record carried the new program's comm together with the new scontext.

The new hook is called right after close_cloexec_files(), well before __set_task_comm(), so a denial for a revoked fd or controlling tty now reports the pre-exec comm (for a fork+exec, the parent's name such as "sh") while scontext is already the new domain.

Is this change in the logged comm intended? The commit message does not mention it. If it is acceptable, could it be noted in the changelog?

---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md

CI run summary: https://github.com/kernel-patches/bpf/actions/runs/45508356147