uaccess: Refuse and warn on user accesses when current->mm is NULL
Subsystems (21)
v2 cover uaccess: Refuse and warn on user accesses when current->mm is NULL
Hi everyone,
This series comes out of a set of bugs that were found in KVM where the kernel can sometimes write to a random process's user memory[1]. Sean's KVM fixes for those have since been merged, e.g. commit 2520694e6048 ("KVM: Reject user accesses to guest memory if current->mm != kvm->mm"). They are still required with this series, as they also handle the case where the VM is destroyed from another process, which this series can't detect.
We hit one of the KVM bugs in production, and it was challenging to debug. This series makes such bugs, where the kernel is doing uaccess without an mm, much more obvious.
The beginning of this series includes fixes for similar bugs found through static analysis with Claude Opus 5.5.
The main change in v2 is where the new check lives. Following Arnd's suggestion[2], it is now in access_ok() itself, plus the masked user access paths and the unchecked __copy_{from,to}_user{,_inatomic}() accessors, instead of in each generic copy helper. This covers more (e.g. get_user(), put_user() and clear_user() on most architectures), and makes most new user access code get the check automatically. See "Changes in v2" below for the full list.
I've also taken the liberty of dropping the "RFC" label from this series. :)
The Cc list is wide because the fixes at the start of the series touch several subsystems: xtensa/nios2 (patch 1), btrfs (patch 2), BPF (patches 3 and 6), tracing (patches 4 and 7), perf (patch 5) and powerpc (patch 8). They're included because the new warning in patches 10-12 would otherwise fire on those paths. The core uaccess change is in patches 9-12.
== Introduction ==
Accessing user memory from a task that has no mm is always a bug. This can happen from a kernel thread that is not using kthread_use_mm(), or from a task that has already gone through exit_mm(), e.g. when the last reference to a file is dropped at exit and its release handler runs from exit_task_work(). For example, KVM's nVMX code could write to guest memory while a vCPU was being freed during VM destruction[1], and other drivers may have similar bugs.
Such an access does not reliably fail. The user portion of the address space belongs to whatever mm happens to be lazily loaded, if any. If the access faults, the fault handler refuses to handle it and the copy fails, but if the page is already mapped, the access silently reads or writes another task's memory.
== Fixes ==
Patches 1-8 fix or prepare places that would access user memory without an mm, or that would otherwise trigger the new warning:
- Patch 1 makes xtensa and nios2 implement 8-byte __get_user() and __put_user() with raw_copy_{from,to}_user(), so that the generic kernel nofault accessors, which use them on kernel addresses, don't hit the new check.
- Patch 2 fixes btrfs's io_uring encoded read completion, which copies to the submitter's user memory even when io_uring runs it canceled from a kworker, e.g. after the submitter exited. (The equivalent scsi_bsg fix from v1 has been merged.)
- Patch 3 makes the sleepable BPF user copy helpers fail when current->mm is NULL, e.g. for bpf_wq callbacks or lsm.s programs running from kernel threads or exiting tasks.
- Patches 4 and 5 make stack_trace_save_user() (ftrace's userstacktrace option) and get_perf_callchain() (bpf_get_task_stack() on the current task) use is_user_task(), so that they don't unwind the user stack of PID 1 before exec, usermode helpers before exec, or tasks that have gone through exit_mm().
- Patches 6-8 make the users of the user nofault helpers that run in whatever context they're attached to (BPF tracing helpers, probe events, event filters, synthetic events and powerpc's BHRB decoding) check for an mm themselves. A missing mm there isn't a kernel bug, so these must not trigger the new warning. Patch 9 documents that requirement in the nofault helpers; their other users run in process context, where a missing mm would be a bug, and now get the warning.
== The New WARN ==
The rest of the series makes user accesses WARN_ON_ONCE() and refuse the access when current->mm is NULL:
- Patch 10 adds the check to access_ok(): the generic version, and the arm64 and riscv ones. __access_ok() stays a plain range check, for callers like copy_from_user_nofault() that handle a missing mm themselves. This covers copy_{to,from}_user() where masked user access isn't used, user_access_begin() and everything built on it, and get_user(), put_user() and clear_user() on the architectures that use access_ok() for them.
- Patch 11 adds the check to the callers of mask_user_address() and masked_user_*_access_begin() (x86-64 and powerpc), which don't call access_ok(). There are about a dozen of them.
- Patch 12 adds the check to the unchecked accessors, __copy_{from,to}_user() and __copy_{from,to}_user_inatomic(), which rely on an access_ok() done beforehand, possibly from a different context. This is the path KVM's guest memory accessors took. I'm preparing a separate series that removes these accessors, as Arnd suggested, after which these checks can go away. I've uploaded a draft here[3].
With defconfig + KVM, patches 10-12 grow vmlinux by +11,702 B (+0.027%) on x86_64 and +65,428 B (+0.15%) on arm64. v1's last patch, which moved the warning out of line, is dropped: it would save ~25 KB of __bug_table on arm64 (but add ~4 KB of text, and ~3 KB overall on x86_64), at the cost of warning only once system-wide, and of fuzzers like syzkaller reporting every such bug as a warning in the same helper, instead of in its caller.
What's still not covered: x86's get_user()/put_user(), which do their own range check in assembly, a few architecture-specific paths that call __access_ok() directly (e.g. on alpha and sparc32), and arch code that calls __get_user()/__put_user() without access_ok(), mostly trap handlers for user-mode faults. I haven't found any of those that can run without an mm.
The check also cannot catch a valid mm that isn't the one the caller expects, e.g. when a file's release or ioctl handlers run in a different process than the one that created it. Code that keeps user addresses belonging to a specific mm still has to compare current->mm against that mm itself, as KVM now does[1].
== Performance ==
I measured the overhead of the new check with syscall microbenchmarks on a two-socket Haswell server (Xeon E5-2696 v3, PTI enabled). I compared v7.4-rc5 with and without this series. Each benchmark runs in a tight loop pinned to one CPU, 10 times. The numbers are the median kernel-mode cycles and instructions per operation, from perf stat -e cycles:k,instructions:k:
v7.4-rc5 + this series
benchmark cycles insns cycles insns
getppid() (no user access) 1293 266 -0.9% +0 read(/dev/zero, 1B) 1434 501 -1.0% +5 read(/dev/zero, 64B) 1442 509 -1.4% +5 pipe write + read, 8B 3165 1627 -1.2% +8 fstat() 1547 705 +1.7% +3 uname() 1439 484 +0.6% +3 getrusage() 1928 1283 -0.5% +3 rt_sigaction() 1348 492 +0.7% +7 poll(), 64 fds 6816 8000 +1.1% +11 readv(/dev/zero), 16 x 8B 1913 1921 +1.7% +100 signal delivery + sigreturn 7038 4329 -0.2% +21 pipe ping-pong, 2 tasks/CPU 14634 12985 -0.2% +19
The check adds about 3-5 instructions per user access (loading current->mm, testing it and a branch that isn't taken), so the readv() case, which makes 16+ small user accesses, adds about 100. I couldn't measure any change in cycles: the deltas range from -1.4% to +1.7%, with no consistent sign, and are within the run-to-run spread (0.3-5%). Wall time didn't change measurably either.
For comparison, I also measured making the x86 lazy TLB mode eager, i.e. making enter_lazy_tlb() switch to init_mm, so that a task without an mm couldn't reach any user mapping at all. I tested it with and without an exception for the idle task, and counted system-wide so that work done in the idle task and in kernel threads is included:
v7.4-rc5 eager eager,
benchmark cycles insns idle lazy
pipe ping-pong, 2 CPUs 28814 18794 +5.8%/+408 0.0%/+26 1us nanosleep() loop 13775 8616 +10.0%/+244 +3.5%/+51
Each time a CPU goes idle and wakes up, the eager switch costs about 200 instructions and 900-1400 cycles, even though with PTI the CR3 write on kernel entry is already paid. Keeping the idle task lazy recovers almost all of that. Switching to and from a kworker costs a similar amount per switch, but that was too small to resolve with a schedule_on_each_cpu() benchmark (under 1% of the ~180k cycles per operation). Without PTI, the eager switch would cost relatively more.
== Testing ==
Build-tested on x86_64 (defconfig + KVM, defconfig without IA32_EMULATION, and allnoconfig), i386 (defconfig), arm64 (defconfig and allnoconfig), riscv (defconfig), powerpc (ppc64_defconfig with KVM HV), arm (multi_v7_defconfig), s390 (defconfig) and loongarch (defconfig).
As in v1, I have a reproducer only for the bug that patch 3 fixes: a bpf_wq callback calling bpf_copy_from_user(), which triggers the new warning without the patch, and fails with -EFAULT with it. I ran it on v1; the code in patch 3 hasn't changed since. The other fixes are only build-tested. Let me know if you'd like to see reproducers for them.
I've been fuzzing this version with syzkaller on x86_64 (syzbot's upstream KASAN config, nested VMX enabled) for about four days in total, before and after rebasing onto v7.4-rc5 (over 35 million programs). syzkaller hasn't triggered the new warning, i.e. it hasn't found any other path that accesses user memory without an mm, despite the check now being in access_ok().
== Changes in v2 ==
- Move the check into access_ok(), the masked user access paths and the unchecked accessors, instead of the generic copy helpers, which also covers user_access_begin() without a separate check (Arnd).
- Instead of making the user nofault helpers fail quietly without an mm, check for it in their callers that can run in any context (BPF, tracing, powerpc BHRB decoding), and document the requirement, so the remaining process-context users still warn (Arnd).
- Drop the scsi_bsg fix, which has been merged as
commit 2b2bb55990cf ("scsi: bsg: Don't copy sense data to user memory when canceled").
- Add Jens's Reviewed-by to "btrfs: Don't copy encoded read data to user memory when canceled".
- Add "xtensa, nios2: Don't use __copy_{from,to}_user() in __{get,put}_user()" (reported by the BPF CI AI review[4]).
- Fix the examples in the changelog of "bpf: Fail sleepable user copy helpers when current->mm is NULL" (BPF CI AI review).
- Fix the Fixes: tag of "stacktrace: Don't unwind the user stack without an mm".
- Clarify the changelog of "perf/core: Don't unwind the user stack without an mm" (Peter).
- Drop "uaccess: Move the NULL mm warning out of line", which mostly saved __bug_table space on arm64, so that each offending call site warns, and is reported, separately.
- Rebase onto v7.4-rc5.
v1: https://lore.kernel.org/all/[email protected]/
Please let me know what you think. Thank you!
[1] https://lore.kernel.org/kvm/[email protected]
[2] https://lore.kernel.org/lkml/[email protected]/
[3] https://github.com/48ca/linux/tree/no-unchecked-uaccess
[4] https://lore.kernel.org/lkml/b9959bd7711dee7a83a07b012b5967980d178c95eae90adeebebcb6040fc526f@mail.kernel.org/
James Houghton (12):
xtensa, nios2: Don't use __copy_{from,to}_user() in __{get,put}_user()
btrfs: Don't copy encoded read data to user memory when canceled
bpf: Fail sleepable user copy helpers when current->mm is NULL
stacktrace: Don't unwind the user stack without an mm perf/core: Don't unwind the user stack without an mm
bpf: Don't read user memory without an mm in tracing helpers
tracing: Don't read user memory without an mm powerpc/perf: Don't read user memory without an mm in BHRB decoding
uaccess: Document that the user nofault helpers need an mm
uaccess: Refuse and warn in access_ok() when current->mm is NULL
uaccess: Refuse and warn on masked user accesses without an mm
uaccess: Refuse and warn on unchecked user accesses without an mm
arch/arm64/include/asm/uaccess.h | 7 ++++++ arch/nios2/include/asm/uaccess.h | 2 +- arch/powerpc/include/asm/futex.h | 4 ++++ arch/powerpc/lib/pmem.c | 2 ++ arch/powerpc/perf/core-book3s.c | 7 ++++++ arch/riscv/include/asm/uaccess.h | 3 ++- arch/x86/include/asm/uaccess_64.h | 6 ++++++ arch/x86/lib/usercopy_64.c | 2 ++ arch/xtensa/include/asm/uaccess.h | 4 ++-- fs/btrfs/ioctl.c | 10 +++++++++ include/asm-generic/access_ok.h | 10 ++++++++- include/linux/uaccess.h | 34 ++++++++++++++++++++++++------ include/linux/uaccess_mm.h | 33 +++++++++++++++++++++++++++++ kernel/bpf/helpers.c | 28 ++++++++++++++++++++---- kernel/events/callchain.c | 12 +++++++---- kernel/stacktrace.c | 8 +++++-- kernel/trace/bpf_trace.c | 28 +++++++++++++++++++++--- kernel/trace/trace_events_filter.c | 8 +++++++ kernel/trace/trace_events_synth.c | 15 ++++++++++--- kernel/trace/trace_probe_kernel.h | 16 +++++++++++++- lib/iov_iter.c | 3 +++ lib/strncpy_from_user.c | 3 +++ lib/strnlen_user.c | 3 +++ mm/maccess.c | 16 ++++++++++++++ 24 files changed, 235 insertions(+), 29 deletions(-) create mode 100644 include/linux/uaccess_mm.h
base-commit: fe6ff8d5d675c01793b9f051d16055dd4aa75244
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v2 1/12 xtensa, nios2: Don't use __copy_{from,to}_user() in __{get,put}_user()
Architectures that don't define __get_kernel_nofault() or arch_get_kernel_nofault() use the generic fallback in include/linux/uaccess.h, which accesses *kernel* addresses with __get_user() and __put_user(). That relies on __get_user() and __put_user() being raw accessors, i.e. plain fixup-protected loads and stores with no extra checks that only make sense for user memory.
xtensa and nios2 use this fallback, but don't quite meet that: on xtensa, 8-byte __get_user() and __put_user() are implemented with __copy_from_user() and __copy_to_user(), and on nios2, __put_user() of any size other than 1, 2 or 4 bytes (i.e. 8-byte puts) uses __copy_to_user(). __copy_{from,to}_user() do more than a plain copy: they inject failures with CONFIG_FAULT_INJECTION_USERCOPY, check the kernel object size with CONFIG_HARDENED_USERCOPY, and, with a later patch in this series, refuse and warn on user accesses when current->mm is NULL.
As neither architecture selects HAVE_EFFICIENT_UNALIGNED_ACCESS, copy_from_kernel_nofault() and copy_to_kernel_nofault() use 8-byte accesses when both pointers are 8-byte aligned, so kernel nofault accesses (used e.g. by d_path() and print_worker_info()) end up in __copy_{from,to}_user() on kernel addresses. With the NULL mm check, copy_from_kernel_nofault() would then fail on valid kernel memory when called from kernel threads.
Use raw_copy_{from,to}_user() instead, as asm-generic's __get_user_fn()/__put_user_fn() do, and as nios2 already does for 8-byte gets (__get_user_8()). This only drops the extra checks and KASAN/KCSAN instrumentation for 8-byte accesses, making them consistent with the 1, 2 and 4-byte cases, which are plain inline asm.
The fallback itself is fine and is still needed: it's used by alpha, arc, csky, hexagon, microblaze, nios2, openrisc, sh, sparc and xtensa. Of those, only xtensa and nios2 have __get_user()/__put_user() that aren't raw. The others use either asm-generic's, which call raw_copy_{from,to}_user(), or inline asm for all sizes. The remaining architectures (arm, arm64, loongarch, m68k, mips, parisc, powerpc, riscv, s390, um and x86) define their own __get_kernel_nofault() or arch_get_kernel_nofault(), which don't use __get_user()/__put_user() or __copy_{from,to}_user().
--- arch/nios2/include/asm/uaccess.h | 2 +- arch/xtensa/include/asm/uaccess.h | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-)
arch/nios2/include/asm/uaccess.h +1 -1
@@ -161,7 +161,7 @@ do { \default : \/* XXX: This looks wrong... */ \ __pu_err =0 ; \ -if (__copy_to_user (__pu_ptr, &(__pu_val), \ +if (raw_copy_to_user (__pu_ptr, &(__pu_val), \sizeof (*__pu_ptr))) \ __pu_err = -EFAULT ; \break ; \
arch/xtensa/include/asm/uaccess.h +2 -2
@@ -76,7 +76,7 @@ do { \case 4 :__put_user_asm (x, ptr, retval,4 ,"s32i" , __cb);break ; \case 8 : { \ __typeof__(*ptr) __v64 = x; \ - retval =__copy_to_user (ptr, &__v64,8 ) ? -EFAULT :0 ; \ + retval =raw_copy_to_user (ptr, &__v64,8 ) ? -EFAULT :0 ; \break ; \ } \default :__put_user_bad (); \
@@ -176,7 +176,7 @@ do { \case 4 :__get_user_asm (x, ptr, retval,4 ,"l32i" , __cb);break ;\case 8 : { \u64 __x; \ -if (unlikely (__copy_from_user (&__x, ptr,8 ))) { \ +if (unlikely (raw_copy_from_user (&__x, ptr,8 ))) { \ retval = -EFAULT ; \ (x) = (__typeof__ (*(ptr )))0 ; \ }else { \
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
Re: [PATCH v2 01/12] xtensa, nios2: Don't use __copy_{from,to}_user() in __{get,put}_user()
Quoted 40 lines · James Houghton
Architectures that don't define
__get_kernel_nofault()orarch_get_kernel_nofault()use the generic fallback ininclude/linux/uaccess.h, which accesses *kernel* addresses with__get_user()and__put_user(). That relies on__get_user()and__put_user()being raw accessors, i.e. plain fixup-protected loads and stores with no extra checks that only make sense for user memory.xtensa and nios2 use this fallback, but don't quite meet that: on xtensa, 8-byte
__get_user()and__put_user()are implemented with__copy_from_user()and__copy_to_user(), and on nios2,__put_user()of any size other than 1, 2 or 4 bytes (i.e. 8-byte puts) uses__copy_to_user(). __copy_{from,to}_user() do more than a plain copy: they inject failures withCONFIG_FAULT_INJECTION_USERCOPY, check the kernel object size withCONFIG_HARDENED_USERCOPY, and, with a later patch in this series, refuse and warn on user accesses whencurrent->mmis NULL.As neither architecture selects
HAVE_EFFICIENT_UNALIGNED_ACCESS,copy_from_kernel_nofault()andcopy_to_kernel_nofault()use 8-byte accesses when both pointers are 8-byte aligned, so kernel nofault accesses (used e.g. byd_path()andprint_worker_info()) end up in __copy_{from,to}_user() on kernel addresses. With the NULL mm check,copy_from_kernel_nofault()would then fail on valid kernel memory when called from kernel threads.Use raw_copy_{from,to}_user() instead, as asm-generic's __get_user_fn()/__put_user_fn() do, and as nios2 already does for 8-byte gets (
__get_user_8()). This only drops the extra checks and KASAN/KCSAN instrumentation for 8-byte accesses, making them consistent with the 1, 2 and 4-byte cases, which are plain inline asm.The fallback itself is fine and is still needed: it's used by alpha, arc, csky, hexagon, microblaze, nios2, openrisc, sh, sparc and xtensa. Of those, only xtensa and nios2 have __get_user()/__put_user() that aren't raw. The others use either asm-generic's, which call raw_copy_{from,to}_user(), or inline asm for all sizes. The remaining architectures (arm, arm64, loongarch, m68k, mips, parisc, powerpc, riscv, s390, um and x86) define their own
__get_kernel_nofault()orarch_get_kernel_nofault(), which don't use __get_user()/__put_user() or __copy_{from,to}_user().
Quoted 1 line
Signed-off-by James Houghton <[email protected]>
PATCH v2 2/12 btrfs: Don't copy encoded read data to user memory when canceled
In reply to James Houghtonbtrfs_uring_read_finished() copies the data of an io_uring encoded read to the submitter's buffers with copy_page_to_iter(). It runs as io_uring task work, but io_uring may also run it with tw.cancel set from other contexts when the submitting task can't run it: from a kworker when the submitting task has exited (io_tctx_fallback_work()), or from io_cancel_local_task_work() when a DEFER_TASKRUN ring is torn down.
In a kworker, current->mm is NULL, and the copy does not reliably fail:
the user half of the address space belongs to whatever mm happens to be lazily loaded, if any, so the data may be written into an unrelated process.
Don't copy the data when the task work is canceled, and complete the command with -ECANCELED.
--- fs/btrfs/ioctl.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
fs/btrfs/ioctl.c +10 -0
@@ -4633,6 +4633,16 @@ static void btrfs_uring_read_finished(struct io_tw_req tw_req, io_tw_token_t tw) goto out; } +/* +* If the request is being canceled, e.g. because the submitting task +* has exited, this may run from a kworker or in a different task, so +* don't copy the data to the submitter's buffers. +*/ +if (unlikely (tw.cancel)) { + ret = -ECANCELED ; + goto out; + } +if (priv->compressed) { index =0 ; page_offset =0 ;
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v2 3/12 bpf: Fail sleepable user copy helpers when current->mm is NULL
In reply to James HoughtonSleepable BPF programs can run on behalf of a kernel thread, or of a task that has already gone through exit_mm(). For example, bpf_wq callbacks always run from a kworker, bpf_task_work callbacks queued late enough run from exit_task_work(), lsm.s programs may be attached to hooks reached from kernel threads or from exit_task_work() (e.g. bpf_lsm_inode_free_security() when the final __fput() of an unlinked file runs from delayed_fput() or from exit_task_work(), or bpf_lsm_bprm_check_security() during a usermode helper's kernel_execve()), and fentry.s programs may be attached to error-injectable functions called from kernel threads (e.g. btrfs_should_cancel_balance() from the btrfs-balance kthread).
In such contexts, bpf_copy_from_user(), bpf_copy_from_user_str() and bpf_copy_from_user{,_str}_dynptr() (when reading from the current task) call copy_from_user() or strncpy_from_user() without an mm. That access does not reliably fail: the user half of the address space belongs to whatever mm happens to be lazily loaded, if any, so the program may read another task's memory.
As there is no user memory to read from in this case, fail with -EFAULT without attempting the access.
---
Tested with a small bpf_wq reproducer: a SEC("syscall") program arms a bpf_wq whose callback (which runs in a kworker) calls bpf_copy_from_user() on an address in the loader. With the uaccess check from later in this series but without this patch, that triggers the new WARN from bpf_copy_from_user(); with this patch, the helper returns -EFAULT without warning. I can turn this into a selftest under tools/testing/selftests/bpf if that's useful.
--- kernel/bpf/helpers.c | 11 +++++++++-- kernel/trace/bpf_trace.c | 4 ++++ 2 files changed, 13 insertions(+), 2 deletions(-)
kernel/bpf/helpers.c +9 -2
@@ -660,7 +660,11 @@ const struct bpf_func_proto bpf_event_output_data_proto = { BPF_CALL_3(bpf_copy_from_user, void *, dst, u32, size, const void __user *, user_ptr) { -int ret =copy_from_user (dst, user_ptr, size); +int ret = -EFAULT ; + +/* Sleepable programs may run without an mm, e.g. on kernel threads. */ +if (likely (current->mm)) + ret =copy_from_user (dst, user_ptr, size);if (unlikely (ret)) {memset (dst,0 , size);
@@ -3726,7 +3730,10 @@ __bpf_kfunc int bpf_copy_from_user_str(void *dst, u32 dst__sz, const void __userif (unlikely (!dst__sz))return 0 ; - ret =strncpy_from_user (dst, unsafe_ptr__ign, dst__sz -1 ); +if (unlikely (!current->mm)) + ret = -EFAULT ; +else + ret =strncpy_from_user (dst, unsafe_ptr__ign, dst__sz -1 );if (ret <0 ) {if (flags &BPF_F_PAD_ZEROS )memset ((char *)dst,0 , dst__sz);
kernel/trace/bpf_trace.c +4 -0
@@ -3594,6 +3594,8 @@ static __always_inline int copy_user_data_sleepable(void *dst, const void *unsafint ret;if (!tsk) {/* Read from the current task */ +if (unlikely (!current->mm)) +return -EFAULT ; ret =copy_from_user (dst, (const void __user *)unsafe_src, size);if (ret)return -EFAULT ;
@@ -3628,6 +3630,8 @@ static __always_inline int copy_user_str_sleepable(void *dst, const void *unsafeif (tsk) { ret =copy_remote_vm_str (tsk, (unsigned long )unsafe_src, dst, size,0 ); + }else if (unlikely (!current->mm)) { + ret = -EFAULT ; }else { ret =strncpy_from_user (dst, (const void __user *)unsafe_src, size -1 );/* strncpy_from_user does not guarantee NUL termination */
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
Re: [PATCH v2 03/12] bpf: Fail sleepable user copy helpers when current->mm is NULL
Quoted 19 lines · James Houghton
Sleepable BPF programs can run on behalf of a kernel thread, or of a task that has already gone through
exit_mm(). For example,bpf_wqcallbacks always run from a kworker,bpf_task_workcallbacks queued late enough run fromexit_task_work(), lsm.s programs may be attached to hooks reached from kernel threads or fromexit_task_work()(e.g.bpf_lsm_inode_free_security()when the final__fput()of an unlinked file runs fromdelayed_fput()or fromexit_task_work(), orbpf_lsm_bprm_check_security()during a usermode helper'skernel_execve()), and fentry.s programs may be attached to error-injectable functions called from kernel threads (e.g.btrfs_should_cancel_balance()from the btrfs-balance kthread).In such contexts,
bpf_copy_from_user(),bpf_copy_from_user_str()and bpf_copy_from_user{,_str}_dynptr() (when reading from the current task) callcopy_from_user()orstrncpy_from_user()without an mm. That access does not reliably fail: the user half of the address space belongs to whatever mm happens to be lazily loaded, if any, so the program may read another task's memory.
Quoted 7 lines
As there is no user memory to read from in this case, fail with
-EFAULTwithout attempting the access.Fixes 07be4c4a3e7a ("bpf: Add bpf_copy_from_user() helper.")Fixes 65ab5ac4df01 ("bpf: Add bpf_copy_from_user_str kfunc")Fixes a498ee7576de ("bpf: Implement dynptr copy kfuncs")Signed-off-by James Houghton <[email protected]>
PATCH v2 4/12 stacktrace: Don't unwind the user stack without an mm
In reply to James Houghtonstack_trace_save_user() only refuses to unwind the user stack of tasks with PF_KTHREAD set. It used to check for !current->mm, but commit 7e8e6816c649 ("stacktrace: Use PF_KTHREAD to check for kernel threads") switched to PF_KTHREAD, as kernel threads can temporarily use a user mm. However, that doesn't cover all tasks without an mm:
- A user task that has already gone through exit_mm(), e.g. when an event fires from exit_files(), exit_task_work() or the final context switch in do_exit().
- PID 1 before it execs init, and usermode helper children before they exec, which are created with user_mode_thread() and don't have PF_KTHREAD set. E.g. booting with trace_options=userstacktrace and an event enabled with trace_event= unwinds PID 1's "user stack" during initcalls.
With the ftrace userstacktrace option enabled, the architecture unwinders then read the user stack without an mm. That access does not reliably fail: the user half of the address space belongs to whatever mm happens to be lazily loaded, if any, so the unwinder may read another task's memory.
Use is_user_task() instead, which also checks current->mm, as perf already does for the same reason since commit 76ed27608f7d ("perf:
sched: Fix perf crash with new is_user_task() helper"). This also stops unwinding the user stack of PF_USER_WORKER threads, which never run in user space, matching perf.
--- kernel/stacktrace.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
kernel/stacktrace.c +6 -2
@@ -228,8 +228,12 @@ unsigned int stack_trace_save_user(unsigned long *store, unsigned int size) .size = size, }; -/* Trace user stack if not a kernel thread */ -if (current->flags &PF_KTHREAD ) +/* +* Trace user stack only if this is a user task that still has an mm, +* i.e. not a kernel thread or user worker, and not a task that has +* already gone through exit_mm(). +*/ +if (!is_user_task (current))return 0 ;arch_stack_walk_user (consume_entry, &c,task_pt_regs (current));
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v2 5/12 perf/core: Don't unwind the user stack without an mm
In reply to James Houghtonget_perf_callchain() only checks is_user_task(current) when the regs it is given aren't user mode regs. That's fine for perf events: a task's own events are torn down by perf_event_exit_task() before exit_mm(), and samples from CPU-wide events go through perf_callchain(), which already skips the user callchain if current isn't a user task with an mm.
However, BPF's bpf_get_task_stack() (and bpf_get_task_stack_sleepable()) call get_perf_callchain() directly, passing task_pt_regs(current) when called on the current task. Those are user mode regs for a user task even after it has gone through exit_mm(), e.g. when the helper is called from a program attached to exit_files() or to the dying task's final sched_switch.
perf_callchain_user() then unwinds the user stack without an mm. That access does not reliably fail: the user half of the address space belongs to whatever mm happens to be lazily loaded, if any, so the unwinder may read another task's memory. This affects e.g. arm64, riscv, loongarch and csky, whose perf_callchain_user() doesn't check current->mm itself.
Check is_user_task(current) regardless of the regs' mode.
--- kernel/events/callchain.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
kernel/events/callchain.c +8 -4
@@ -245,11 +245,15 @@ get_perf_callchain(struct pt_regs *regs, bool kernel, bool user, }if (user && !crosstask) { -if (!user_mode (regs)) { -if (!is_user_task (current)) - goto exit_put; +/* +* Even if @regs are user mode regs, e.g. task_pt_regs(current) +* passed in by bpf_get_task_stack(), current may already have +* gone through exit_mm(). +*/ +if (!is_user_task (current)) + goto exit_put; +if (!user_mode (regs)) regs =task_pt_regs (current); - }if (defer_cookie) {/*
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
Re: [PATCH v2 05/12] perf/core: Don't unwind the user stack without an mm
Quoted 20 lines · James Houghton
get_perf_callchain()only checksis_user_task(current)when the regs it is given aren't user mode regs. That's fine for perf events: a task's own events are torn down byperf_event_exit_task()beforeexit_mm(), and samples from CPU-wide events go throughperf_callchain(), which already skips the user callchain if current isn't a user task with an mm.However, BPF's
bpf_get_task_stack()(andbpf_get_task_stack_sleepable()) callget_perf_callchain()directly, passingtask_pt_regs(current)when called on the current task. Those are user mode regs for a user task even after it has gone throughexit_mm(), e.g. when the helper is called from a program attached toexit_files()or to the dying task's finalsched_switch.
perf_callchain_user()then unwinds the user stack without an mm. That access does not reliably fail: the user half of the address space belongs to whatever mm happens to be lazily loaded, if any, so the unwinder may read another task's memory. This affects e.g. arm64, riscv, loongarch and csky, whoseperf_callchain_user()doesn't checkcurrent->mmitself.
Quoted 4 lines
Check
is_user_task(current)regardless of the regs' mode.Fixes fa28dcb82a38 ("bpf: Introduce helper bpf_get_task_stack()")Signed-off-by James Houghton <[email protected]>
PATCH v2 6/12 bpf: Don't read user memory without an mm in tracing helpers
In reply to James HoughtonBPF tracing programs run in whatever context the function, tracepoint or event they are attached to happens to run in, including kernel threads and tasks that have already gone through exit_mm(). There is no user memory to access there, so the helpers that access the current task's user memory without faulting should simply fail:
bpf_probe_read_user{,_str}(), bpf_probe_write_user(), bpf_probe_read_user{,_str}_dynptr(), and the user string arguments ("%s" or "%pus") of the bpf_bprintf_prepare() users, e.g. bpf_trace_printk() and bpf_snprintf().
They currently call the user nofault helpers regardless. Without an mm, those don't reliably fail: the user half of the address space belongs to whatever mm happens to be lazily loaded, if any, so the program may read another task's memory. (On x86, copy_from_user_nofault() already refuses this, as nmi_uaccess_okay() returns false when current->mm is not the loaded mm, but strncpy_from_user_nofault() doesn't.)
Check for a NULL current->mm in these helpers, and fail as if the access had faulted. bpf_probe_write_user() already refuses to run in kernel threads and exiting tasks; also refuse it without an mm, which covers PID 1 and usermode helpers before they exec, as these don't have PF_KTHREAD set.
A NULL mm here isn't a kernel bug, as the program doesn't choose the context it runs in, so this also keeps these helpers from triggering the warning that a later patch in this series adds to the uaccess helpers.
These helpers have read user memory without checking for an mm since they were added: bpf_probe_read_user{,_str}() in
commit 6ae08ae3dea2 ("bpf: Add probe_read_{user, kernel} and probe_read_{user, kernel}_str helpers"), the user string arguments of bpf_trace_printk() (since moved to bpf_bprintf_prepare()) in commit b2a5212fb634 ("bpf: Restrict bpf_trace_printk()'s %s usage and add %pks, %pus specifier"), and the user dynptr kfuncs in commit a498ee7576de ("bpf: Implement dynptr copy kfuncs"). bpf_probe_write_user() only became reachable without an mm with commit 753550eb0ce1 ("fork: Explicitly set PF_KTHREAD"), which stopped init and usermode helpers from inheriting PF_KTHREAD.
--- kernel/bpf/helpers.c | 17 +++++++++++++++-- kernel/trace/bpf_trace.c | 24 +++++++++++++++++++++--- 2 files changed, 36 insertions(+), 5 deletions(-)
kernel/bpf/helpers.c +15 -2
@@ -784,6 +784,19 @@ const struct bpf_func_proto bpf_this_cpu_ptr_proto = { .arg1_type = ARG_PTR_TO_PERCPU_BTF_ID, }; +static int bpf_trace_copy_user_string (char *buf,void __user *user_ptr, +size_t bufsz) +{ +/* +* BPF programs may run in any context, including kernel threads and +* exiting tasks, which have no user memory to read. That's not a +* kernel bug, so fail before the user copy helpers warn about it. +*/ +if (unlikely (!current->mm)) +return -EFAULT ; +return strncpy_from_user_nofault (buf, user_ptr, bufsz); +} +static int bpf_trace_copy_string (char *buf,void *unsafe_ptr,char fmt_ptype,size_t bufsz) {
@@ -795,13 +808,13 @@ static int bpf_trace_copy_string(char *buf, void *unsafe_ptr, char fmt_ptype,case 's' :#ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE if ((unsigned long )unsafe_ptr <TASK_SIZE ) -return strncpy_from_user_nofault (buf, user_ptr, bufsz); +return bpf_trace_copy_user_string (buf, user_ptr, bufsz); fallthrough;#endif case 'k' :return strncpy_from_kernel_nofault (buf, unsafe_ptr, bufsz);case 'u' : -return strncpy_from_user_nofault (buf, user_ptr, bufsz); +return bpf_trace_copy_user_string (buf, user_ptr, bufsz); }return -EINVAL ;
kernel/trace/bpf_trace.c +21 -3
@@ -204,7 +204,15 @@ bpf_probe_read_user_common(void *dst, u32 size, const void __user *unsafe_ptr) {int ret; - ret =copy_from_user_nofault (dst, unsafe_ptr, size); +/* +* Tracing programs may run in any context, including kernel threads +* and exiting tasks, which have no user memory to read. That's not a +* kernel bug, so fail before the user copy helpers warn about it. +*/ +if (unlikely (!current->mm)) + ret = -EFAULT ; +else + ret =copy_from_user_nofault (dst, unsafe_ptr, size);if (unlikely (ret <0 ))memset (dst,0 , size);return ret;
@@ -241,7 +249,11 @@ bpf_probe_read_user_str_common(void *dst, u32 size,* and keys a hash map with it, then semantically identical strings can * occupy multiple entries in the map. */ - ret =strncpy_from_user_nofault (dst, unsafe_ptr, size); +/* No user memory without an mm, see bpf_probe_read_user_common(). */ +if (unlikely (!current->mm)) + ret = -EFAULT ; +else + ret =strncpy_from_user_nofault (dst, unsafe_ptr, size);if (unlikely (ret <0 ))memset (dst,0 , size);return ret;
@@ -368,7 +380,7 @@ BPF_CALL_3(bpf_probe_write_user, void __user *, unsafe_ptr, const void *, src,* required to prevent the use of temporary mm. */ -if (unlikely (in_interrupt () || +if (unlikely (in_interrupt () || !current->mm || current->flags & (PF_KTHREAD |PF_EXITING )))return -EPERM ;if (unlikely (!nmi_uaccess_okay ()))
@@ -3585,6 +3597,9 @@ static __always_inline int __bpf_dynptr_copy(const struct bpf_dynptr *dptr, u64 static __always_inline int copy_user_data_nofault(void *dst, const void *unsafe_src,u32 size,struct task_struct *tsk) { +/* No user memory without an mm, see bpf_probe_read_user_common(). */ +if (unlikely (!current->mm)) +return -EFAULT ;return copy_from_user_nofault (dst, (const void __user *)unsafe_src, size); }
@@ -3617,6 +3632,9 @@ static __always_inline int copy_kernel_data_nofault(void *dst, const void *unsaf static __always_inline int copy_user_str_nofault(void *dst, const void *unsafe_src,u32 size,struct task_struct *tsk) { +/* No user memory without an mm, see bpf_probe_read_user_common(). */ +if (unlikely (!current->mm)) +return -EFAULT ;return strncpy_from_user_nofault (dst, (const void __user *)unsafe_src, size); }
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
Re: [PATCH v2 06/12] bpf: Don't read user memory without an mm in tracing helpers
kernel/trace/bpf_trace.c bpf_probe_read_user_common(void *dst, u32 size, const void __user *unsafe_ptr) · line 215
Quoted 9 lines · James Houghton
kernel/trace/bpf_trace.c +9
-0+/* +* Tracing programs may run in any context, including kernel threads +* and exiting tasks, which have no user memory to read. That's not a +* kernel bug, so fail before the user copy helpers warn about it. +*/ +if (unlikely (!current->mm)) + ret = -EFAULT ; +else + ret =copy_from_user_nofault (dst, unsafe_ptr, size);
The nofault helpers exist for callers that run in any context. v1 had the check inside the helpers. That was the right place. Nack to v2.
pw-bot: cr
Arnd Bergmann
maintainerRe: [PATCH v2 06/12] bpf: Don't read user memory without an mm in tracing helpers
Quoted 14 lines · Alexei Starovoitov
kernel/trace/bpf_trace.c bpf_probe_read_user_common(void *dst, u32 size, const void __user *unsafe_ptr) · line 215
Quoted 9 lines · James Houghton
kernel/trace/bpf_trace.c +9
-0+/* +* Tracing programs may run in any context, including kernel threads +* and exiting tasks, which have no user memory to read. That's not a +* kernel bug, so fail before the user copy helpers warn about it. +*/ +if (unlikely (!current->mm)) + ret = -EFAULT ; +else + ret =copy_from_user_nofault (dst, unsafe_ptr, size);The nofault helpers exist for callers that run in any context. v1 had the check inside the helpers. That was the right place. Nack to v2.
Looking through it all again, I agree with this now, as it simplifies the rules. If {copy_from,strncpy_from,strnlen}_user_nofault() silently fail on !current->mm, a couple of patches in this series are no longer needed, and James has checked the remaining users for correctness.
Arnd
PATCH v2 7/12 tracing: Don't read user memory without an mm
In reply to James HoughtonProbe events (kprobe, eprobe and fprobe events) fetching user memory, event filters on user space strings (filter_pred_pchar_user()) and synthetic events with user space string fields can fire in any context, including kernel threads and tasks that have already gone through exit_mm(). There is no user memory to access there, so these accesses should simply fail.
They currently call the user nofault helpers regardless. Without an mm, those don't reliably fail: the user half of the address space belongs to whatever mm happens to be lazily loaded, if any, so the event may record another task's memory.
Check for a NULL current->mm before these accesses, and fail as if the access had faulted.
A NULL mm here isn't a kernel bug, as these events don't choose the context they fire in, so this also keeps them from triggering the warning that a later patch in this series adds to the uaccess helpers.
Each of these has read user memory without checking for an mm since it was added: user memory fetches in probe events in commit e65f7ae7f4da ("tracing/probe: Support user-space dereference") and commit 88903c464321 ("tracing/probe: Add ustring type for user-space string"), user space strings in event filters in commit 77360f9bbc7e ("tracing:
Add test for user space strings when filtering on string pointers"), and user space strings in synthetic events in commit 0934ae9977c2 ("tracing: Fix reading strings from synthetic events").
--- kernel/trace/trace_events_filter.c | 8 ++++++++ kernel/trace/trace_events_synth.c | 15 ++++++++++++--- kernel/trace/trace_probe_kernel.h | 16 +++++++++++++++- 3 files changed, 35 insertions(+), 4 deletions(-)
kernel/trace/trace_events_filter.c +8 -0
@@ -832,6 +832,14 @@ static __always_inline char *test_ustring(char *str) ubuf =this_cpu_ptr (ustring_per_cpu); kstr = ubuf->buffer; +/* +* Events may fire in any context, including kernel threads and exiting +* tasks, which have no user memory to read. That's not a kernel bug, +* so fail before the user copy helpers warn about it. +*/ +if (unlikely (!current->mm)) +return NULL ; +/* user space address? */ ustr = (char __user *)str;if (strncpy_from_user_nofault (kstr, ustr,USTRING_BUF_SIZE ) <0 )
kernel/trace/trace_events_synth.c +12 -3
@@ -449,9 +449,18 @@ static unsigned int trace_string(struct synth_trace_event *entry, str_field = (char *)&entry->fields[*n_u64].as_u64;#ifdef CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE -if ((unsigned long )str_val <TASK_SIZE ) - ret =strncpy_from_user_nofault (str_field, (const void __user *)str_val,STR_VAR_LEN_MAX ); - else +if ((unsigned long )str_val <TASK_SIZE ) { +/* +* Synthetic events may fire in any context, including +* kernel threads, which have no user memory to read. +*/ +if (unlikely (!current->mm)) + ret = -EFAULT ; +else + ret =strncpy_from_user_nofault (str_field, + (const void __user *)str_val, +STR_VAR_LEN_MAX ); + } else#endif ret =strncpy_from_kernel_nofault (str_field, str_val,STR_VAR_LEN_MAX );
kernel/trace/trace_probe_kernel.h +15 -1
@@ -14,6 +14,13 @@ fetch_store_strlen_user(unsigned long addr) {const void __user *uaddr = (__force const void __user *)addr; +/* +* Probes may fire in any context, including kernel threads and exiting +* tasks, which have no user memory to read. That's not a kernel bug, +* so fail (like a fault would) before the user copy helpers warn. +*/ +if (unlikely (!current->mm)) +return 0 ;return strnlen_user_nofault (uaddr,MAX_STRING_SIZE ); }
@@ -61,7 +68,11 @@ fetch_store_string_user(unsigned long addr, void *dest, void *base) __dest =get_loc_data (dest, base); - ret =strncpy_from_user_nofault (__dest, uaddr, maxlen); +/* No user memory without an mm, see fetch_store_strlen_user(). */ +if (unlikely (!current->mm)) + ret = -EFAULT ; +else + ret =strncpy_from_user_nofault (__dest, uaddr, maxlen);set_data_loc (ret, dest, __dest, base);return ret;
@@ -103,6 +114,9 @@ probe_mem_read_user(void *dest, void *src, size_t size) {const void __user *uaddr = (__force const void __user *)src; +/* No user memory without an mm, see fetch_store_strlen_user(). */ +if (unlikely (!current->mm)) +return -EFAULT ;return copy_from_user_nofault (dest, uaddr, size); }
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
Re: [PATCH v2 07/12] tracing: Don't read user memory without an mm
Quoted 28 lines · James Houghton
Probe events (kprobe, eprobe and fprobe events) fetching user memory, event filters on user space strings (
filter_pred_pchar_user()) and synthetic events with user space string fields can fire in any context, including kernel threads and tasks that have already gone throughexit_mm(). There is no user memory to access there, so these accesses should simply fail.They currently call the user nofault helpers regardless. Without an mm, those don't reliably fail: the user half of the address space belongs to whatever mm happens to be lazily loaded, if any, so the event may record another task's memory.
Check for a NULL
current->mmbefore these accesses, and fail as if the access had faulted.A NULL mm here isn't a kernel bug, as these events don't choose the context they fire in, so this also keeps them from triggering the warning that a later patch in this series adds to the uaccess helpers.
Each of these has read user memory without checking for an mm since it was added: user memory fetches in probe events in commit
e65f7ae7f4da("tracing/probe: Support user-space dereference") and commit88903c464321("tracing/probe: Add ustring type for user-space string"), user space strings in event filters in commit77360f9bbc7e("tracing:
Add test for user space strings when filtering on string pointers"), and user space strings in synthetic events in commit0934ae9977c2("tracing: Fix reading strings from synthetic events").
Quoted 8 lines
Fixes e65f7ae7f4da ("tracing/probe: Support user-space dereference")Fixes 88903c464321 ("tracing/probe: Add ustring type for user-spacestring")
Fixes 77360f9bbc7e ("tracing: Add test for user space strings whenfiltering on string pointers")
Fixes 0934ae9977c2 ("tracing: Fix reading strings from syntheticevents")
Signed-off-by James Houghton <[email protected]>
Steven Rostedt
maintainerRe: [PATCH v2 07/12] tracing: Don't read user memory without an mm
In reply to James HoughtonQuoted 7 lines · On Wed, 2 Dec 2026 02:39:14 +0000 James Houghton <[email protected]> wrote:
#ifdef
CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACEkernel/trace/trace_events_synth.c +3
-3-if ((unsigned long )str_val <TASK_SIZE ) - ret =strncpy_from_user_nofault (str_field, (const void __user *)str_val,STR_VAR_LEN_MAX ); -else +if ((unsigned long )str_val <TASK_SIZE ) { +/* +* Synthetic events may fire in any context, including
kernel/trace/trace_events_synth.c static unsigned int trace_string(struct synth_trace_event *entry, · line 464
Quoted 10 lines
kernel/trace/trace_events_synth.c +9
-0+* kernel threads, which have no user memory to read. +*/ +if (unlikely (!current->mm)) + ret = -EFAULT ; +else + ret =strncpy_from_user_nofault (str_field, + (const void __user *)str_val, +STR_VAR_LEN_MAX ); + } else#endif
Instead of adding all these crazy checks, and then we need to play whack-a-mole when we add a new one that triggers the warning, can't you add a helper function for this?
strncpy_from_user_trace_nofault()?
Where it can be used by places that do not care if there's an current->mm or not.
If you are reading user space for tracing purposes, it may be done from a kernel thread too, and that's not a bug. It should simply return -EFAULT.
-- Steve
PATCH v2 8/12 powerpc/perf: Don't read user memory without an mm in BHRB decoding
In reply to James Houghtonpower_pmu_bhrb_to() reads the branch instruction at a user address to compute the branch target of a BHRB entry. It runs from the PMU interrupt.
The BHRB is cleared when a task is scheduled in, but not when a task exits, so between exit_mm() and its final schedule, an exiting task can still have its own user branches in the BHRB. On ISA v3.1, which only records user branches, they stay there for the rest of the exit; on older processors, the kernel's own branches push them out after a while. If a CPU-wide event with a branch stack samples the task in that window, e.g. during exit_files() or exit_task_work(), power_pmu_bhrb_to() reads one of those user addresses with current->mm == NULL. (The task's own events are already gone, as perf_event_exit_task() runs before exit_mm().)
This doesn't read another task's memory: the mm that is still loaded is the exiting task's own, so the read either faults, if exit_mmap() has already torn it down, or returns the right instruction, if another thread still uses the mm. But a later patch in this series makes the uaccess helpers warn when current->mm is NULL, and this path can be reached by anyone allowed to open CPU-wide events (CAP_PERFMON, or a low enough perf_event_paranoid), so it must not get there.
Check for a NULL current->mm first, and treat it like a failed read.
--- arch/powerpc/perf/core-book3s.c | 7 +++++++ 1 file changed, 7 insertions(+)
arch/powerpc/perf/core-book3s.c +7 -0
@@ -471,6 +471,13 @@ static __u64 power_pmu_bhrb_to(u64 addr)return branch_target (&instr); } +/* +* The PMU interrupt may hit a task without an mm, e.g. a kernel +* thread, which has no user memory to read. +*/ +if (!current->mm) +return 0 ; +/* Userspace: need copy instruction here then translate it */ if (copy_from_user_nofault (&instr, (unsigned int __user *)addr,sizeof (instr)))
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v2 9/12 uaccess: Document that the user nofault helpers need an mm
In reply to James HoughtonThe callers of the user nofault helpers (copy_{from,to}_user_nofault(), strncpy_from_user_nofault() and strnlen_user_nofault()) that may run in any context now check for a NULL current->mm themselves (see the previous patches). Document that requirement, so that new callers do too.
The remaining callers don't need to, as a NULL mm would be a bug there. The next patch makes the uaccess helpers warn in that case.
- btrfs's tree search ioctl, and vread_iter() through copy_page_to_iter_nofault(), run in process context. They use the nofault helpers only because they can't take page faults there.
- KVM's steal time update already returns early when current->mm is not the VM's mm.
- riscv's and powerpc's dumping of user instructions on faults, and the Freescale PCI machine check handler, only access user memory when the faulting context is in user mode.
- The architectures' perf_callchain_user(), e.g. powerpc's, which is only called by get_perf_callchain(), and only for a user task with an mm.
--- mm/maccess.c | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)
mm/maccess.c +16 -0
@@ -116,6 +116,10 @@ long strncpy_from_kernel_nofault(char *dst, const void *unsafe_addr, long count)* * Safely read from user address @src to the buffer at @dst. If a kernel fault * happens, handle that and return -EFAULT. +* +* The current task must have an mm. Callers that may run without one, e.g. +* tracing helpers that can run in kernel threads, must check current->mm +* themselves first. */ long copy_from_user_nofault (void *dst,const void __user *src,size_t size) {
@@ -145,6 +149,10 @@ EXPORT_SYMBOL_GPL(copy_from_user_nofault);* * Safely write to address @dst from the buffer at @src. If a kernel fault * happens, handle that and return -EFAULT. +* +* The current task must have an mm. Callers that may run without one, e.g. +* tracing helpers that can run in kernel threads, must check current->mm +* themselves first. */ long copy_to_user_nofault (void __user *dst,const void *src,size_t size) {
@@ -179,6 +187,10 @@ EXPORT_SYMBOL_GPL(copy_to_user_nofault);* * If @count is smaller than the length of the string, copies @count-1 bytes, * sets the last byte of @dst buffer to NUL and returns @count. +* +* The current task must have an mm. Callers that may run without one, e.g. +* tracing helpers that can run in kernel threads, must check current->mm +* themselves first. */ long strncpy_from_user_nofault (char *dst,const void __user *unsafe_addr,long count)
@@ -217,6 +229,10 @@ long strncpy_from_user_nofault(char *dst, const void __user *unsafe_addr,* * Unlike strnlen_user, this can be used from IRQ handler etc. because * it disables pagefaults. +* +* The current task must have an mm. Callers that may run without one, e.g. +* tracing helpers that can run in kernel threads, must check current->mm +* themselves first. */ long strnlen_user_nofault (const void __user *unsafe_addr,long count) {
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
PATCH v2 10/12 uaccess: Refuse and warn in access_ok() when current->mm is NULL
In reply to James HoughtonAccessing user memory from a task that has no mm is always a bug. This can happen from a kernel thread that is not using kthread_use_mm(), or from a task that has already gone through exit_mm() (e.g. when the last reference to a file is dropped from task_work at exit). KVM has had bugs of exactly this kind, and other drivers may have them too.
Such an access does not reliably fail. The user portion of the address space belongs to whatever mm happens to be lazily loaded, if any. If the access faults, the fault handler refuses to handle it and the copy fails, but if the page is already mapped, the access silently reads or writes another task's memory.
Almost every user access calls access_ok() first, so make access_ok() refuse the access, and warn, when current->mm is NULL. Callers already handle access_ok() failing as an inaccessible user range, so no access to user memory takes place. Add uaccess_without_mm() for this, in a new <linux/uaccess_mm.h> that <asm-generic/access_ok.h> and the x86 and arm64 <asm/uaccess.h> headers include. That way, the generic access_ok(), the arm64 and riscv versions and the other inline functions in <asm/uaccess.h> can use it, even in files that include <asm/uaccess.h> without, or before, <linux/uaccess.h>.
This covers copy_{to,from}_user() where masked user access isn't used, user_access_begin() and everything built on it (unsafe_*() accesses, check_zeroed_user(), strncpy_from_user(), strnlen_user() and scoped user accesses without masking), and get_user(), put_user() and clear_user() on the architectures that use access_ok() for them. x86's clear_user() calls __access_ok() directly, as access_ok() isn't defined yet where it is, so add the check to it explicitly.
__access_ok() stays a pure range check, as it is used by callers that may legitimately run without an mm and handle that themselves, e.g. copy_from_user_nofault() and x86's copy_from_user_nmi(), which both fail when nmi_uaccess_okay() is false.
The callers of the user nofault helpers that may legitimately run without an mm check for it first (see the previous patches), so they don't trigger the warning, e.g. through copy_to_user_nofault().
Not covered yet are the masked user access paths, which don't call access_ok(), and the unchecked accessors such as __copy_from_user(), which expect the caller to have called access_ok() earlier, possibly from a different context. The next patches add the check to those. Also not covered are x86's get_user() and put_user(), which do their own range check in assembly, and the few other architecture-specific paths that call __access_ok() directly, e.g. on alpha and sparc32.
These checks are only meant for user addresses, so they don't affect kernel addresses: e.g. the generic kernel nofault accessors don't use access_ok(), so copy_from_kernel_nofault() keeps working from tasks without an mm.
--- arch/arm64/include/asm/uaccess.h | 4 ++++ arch/riscv/include/asm/uaccess.h | 3 ++- arch/x86/include/asm/uaccess_64.h | 4 ++++ include/asm-generic/access_ok.h | 10 +++++++++- include/linux/uaccess.h | 1 + include/linux/uaccess_mm.h | 33 +++++++++++++++++++++++++++++++ 6 files changed, 53 insertions(+), 2 deletions(-) create mode 100644 include/linux/uaccess_mm.h
arch/arm64/include/asm/uaccess.h +4 -0
@@ -17,6 +17,7 @@#include <linux/bitops.h> #include <linux/kasan-checks.h> #include <linux/string.h> +#include <linux/uaccess_mm.h> #include <asm/asm-extable.h> #include <asm/cpufeature.h>
@@ -37,6 +38,9 @@ static inline int __access_ok(const void __user *ptr, unsigned long size);*/ static inline int access_ok (const void __user *addr,unsigned long size) { +if (uaccess_without_mm ()) +return 0 ; +/* * Asynchronous I/O running in a kernel thread does not have the * TIF_TAGGED_ADDR flag of the process owning the mm, so always untag
arch/riscv/include/asm/uaccess.h +2 -1
@@ -39,7 +39,8 @@ static inline unsigned long __untagged_addr_remote(struct mm_struct *mm, unsigne (__force __typeof__(addr))__untagged_addr_remote(mm, __addr); \ }) -#define access_ok (addr, size) likely(__access_ok(untagged_addr(addr), size)) +#define access_ok (addr, size) \ + (!uaccess_without_mm() && likely(__access_ok(untagged_addr(addr), size)))#else #define untagged_addr (addr) (addr)#endif
arch/x86/include/asm/uaccess_64.h +4 -0
@@ -8,6 +8,7 @@#include <linux/compiler.h> #include <linux/lockdep.h> #include <linux/kasan-checks.h> +#include <linux/uaccess_mm.h> #include <asm/alternative.h> #include <asm/cpufeatures.h> #include <asm/page.h>
@@ -203,6 +204,9 @@ static __always_inline __must_check unsigned long __clear_user(void __user *addrstatic __always_inline unsigned long clear_user (void __user *to,unsigned long n) { +/* access_ok() isn't defined yet here, so check for an mm explicitly. */ +if (uaccess_without_mm ()) +return n;if (__access_ok (to, n))return __clear_user (to, n);return n;
include/asm-generic/access_ok.h +9 -1
@@ -2,6 +2,8 @@#ifndef __ASM_GENERIC_ACCESS_OK_H__#define __ASM_GENERIC_ACCESS_OK_H__ +#include <linux/uaccess_mm.h> +/* * Checking whether a pointer is valid for user space access. * These definitions work on most architectures, but overrides can
@@ -41,8 +43,14 @@ static inline int __access_ok(const void __user *ptr, unsigned long size) }#endif +/* +* access_ok() also refuses, and warns about, any user access from a task +* without an mm, see uaccess_without_mm() in <linux/uaccess_mm.h>. +* __access_ok() is only a range check. +*/ #ifndef access_ok -#define access_ok (addr, size) likely(__access_ok(addr, size)) +#define access_ok (addr, size) \ + (!uaccess_without_mm() && likely(__access_ok(addr, size)))#endif #endif
include/linux/uaccess.h +1 -0
@@ -9,6 +9,7 @@#include <linux/nospec.h> #include <linux/sched.h> #include <linux/ucopysize.h> +#include <linux/uaccess_mm.h> #include <asm/uaccess.h>
include/linux/uaccess_mm.h new file +33 -0
@@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef __LINUX_UACCESS_MM_H__ +#define __LINUX_UACCESS_MM_H__ + +#include <linux/bug.h> +#include <linux/sched.h> + +/* +* Return true, and warn, if the current task has no mm, in which case user +* memory must not be accessed. +* +* Accessing user memory without an mm (e.g. from a kernel thread that is not +* using kthread_use_mm(), or from a task that has already gone through +* exit_mm()) is always a bug: the user portion of the address space belongs to +* whatever mm happens to be lazily loaded, if any, so the access could +* silently hit another task's memory. +* +* Note that this only catches a missing mm. It cannot catch a valid mm that +* isn't the one the caller expects, e.g. when a file's release or ioctl +* handlers run in a different process than the one that created it. Code +* that keeps user addresses belonging to a specific mm must check +* current->mm against that mm itself (see e.g. KVM's kvm->mm checks). +* +* This is in its own header, rather than in <linux/uaccess.h>, so that +* <asm/uaccess.h> can use it in inline functions (e.g. through access_ok()) +* even when it is included before <linux/uaccess.h>. +*/ +static __always_inline bool uaccess_without_mm(void) +{ +return WARN_ON_ONCE (!current->mm); +} + +#endif /* __LINUX_UACCESS_MM_H__ */
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
[email protected]
AI reviewRe: [PATCH v2 10/12] uaccess: Refuse and warn in access_ok() when current->mm is NULL
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] perf: arm_brbe: false WARN and broken filtering in filter_branch_privilege() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] perf: arm_brbe: false WARN and broken filtering in filter_branch_privilege()
--
commit c51cfe7734b475135fde7076d5f8a8f55775551a
Author: James Houghton <[email protected]>
uaccess: Refuse and warn in access_ok() when current->mm is NULL
This commit adds uaccess_without_mm() and updates access_ok() (and x86's clear_user()) to warn and fail when current->mm is NULL.
Quoted 13 lines
arch/arm64/include/asm/uaccess.h +1
-0@@ -17,6 +17,7 @@#include <linux/bitops.h> #include <linux/kasan-checks.h> #include <linux/string.h> +#include <linux/uaccess_mm.h> #include <asm/asm-extable.h> #include <asm/cpufeature.h>
arch/arm64/include/asm/uaccess.h static inline int __access_ok(const void __user *ptr, unsigned long size); · line 42
Quoted 5 lines
arch/arm64/include/asm/uaccess.h +2
-0@@ -37,6 +38,9 @@ static inline int __access_ok(const void __user *ptr, unsigned long size);*/ static inline int access_ok (const void __user *addr,unsigned long size) { +if (uaccess_without_mm ()) +return 0 ;
[Severity: Medium]
Does this cause a false WARN_ON_ONCE(!current->mm) and break branch privilege filtering in arm_brbe's filter_branch_privilege() when a PMU interrupt fires while current->mm is NULL?
From the PMU hardirq handler (armv8pmu_handle_irq() -> read_branch_records() -> brbe_read_filtered_entries() -> filter_branch_record()), filter_branch_privilege() uses access_ok() purely to classify branch record addresses without accessing user memory:
drivers/perf/arm_brbe.c:filter_branch_privilege() {
bool from_user = access_ok((void __user *)(unsigned long)entry->from, 4);
bool to_user = access_ok((void __user *)(unsigned long)entry->to, 4);
...
if (from_user == to_user)
return ((entry->priv == PERF_BR_PRIV_KERNEL) && !exclude_kernel) ||
((entry->priv == PERF_BR_PRIV_USER) &&
(branch_sample_type & PERF_SAMPLE_BRANCH_USER));
...
if (exclude_kernel) {
if (!from_user)
entry->from = 0;
if (!to_user)
entry->to = 0;
}
}When a PMU overflow interrupt hits the idle task or a kernel thread during CPU-wide branch-stack profiling, current->mm is NULL. Both access_ok() calls warn and return 0, so from_user == to_user evaluates to true even for cross-EL branch records, skipping the address zeroing of excluded user or kernel addresses.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
PATCH v2 11/12 uaccess: Refuse and warn on masked user accesses without an mm
In reply to James HoughtonWith masked user access (x86-64 and powerpc), mask_user_address() and masked_user_*_access_begin() take the place of access_ok(), so the NULL current->mm check that the previous patch added to access_ok() doesn't cover these paths.
Check for a NULL current->mm explicitly in their callers, and fail without attempting the access if there is none:
- _inline_copy_from_user(), i.e. copy_from_user().
- The generic copy_from_user_inatomic_nontemporal().
- copy_from_user_iter(), used by the user-backed iov_iters.
- strncpy_from_user() and strnlen_user().
- __scoped_user_access_begin(), i.e. scoped_user_*_access() and get_user_inline()/put_user_inline().
- x86's copy_from_user_inatomic_nontemporal() and copy_user_flushcache().
- powerpc's futex operations and copy_from_user_flushcache().
These are all the callers of the masking helpers. In the generic paths, the check is only needed when masking is used, as the other branch calls access_ok().
--- arch/powerpc/include/asm/futex.h | 4 ++++ arch/powerpc/lib/pmem.c | 2 ++ arch/x86/include/asm/uaccess_64.h | 2 ++ arch/x86/lib/usercopy_64.c | 2 ++ include/linux/uaccess.h | 16 ++++++++++++---- lib/iov_iter.c | 3 +++ lib/strncpy_from_user.c | 3 +++ lib/strnlen_user.c | 3 +++ 8 files changed, 31 insertions(+), 4 deletions(-)
arch/powerpc/include/asm/futex.h +4 -0
@@ -33,6 +33,8 @@ static inline int arch_futex_atomic_op_inuser(int op, int oparg, int *oval, {int oldval =0 , ret; +if (uaccess_without_mm ()) +return -EFAULT ; uaddr =masked_user_access_begin (uaddr);switch (op) {
@@ -68,6 +70,8 @@ futex_atomic_cmpxchg_inatomic(u32 *uval, u32 __user *uaddr,int ret =0 ;u32 prev; +if (uaccess_without_mm ()) +return -EFAULT ; uaddr =masked_user_access_begin (uaddr); __asm__ __volatile__ (
arch/powerpc/lib/pmem.c +2 -0
@@ -71,6 +71,8 @@ size_t copy_from_user_flushcache(void *dest, const void __user *src, {unsigned long not_copied, start = (unsigned long ) dest; +if (uaccess_without_mm ()) +return size; src =mask_user_address (src); not_copied =__copy_from_user (dest, src, size);clean_pmem_range (start, start + size);
arch/x86/include/asm/uaccess_64.h +2 -0
@@ -158,6 +158,8 @@ copy_from_user_inatomic_nontemporal(void *dst, const void __user *src, {long ret;kasan_check_write (dst, size); +if (uaccess_without_mm ()) +return size; src =mask_user_address (src);stac (); ret =copy_to_nontemporal (dst, (__force const void *)src, size);
arch/x86/lib/usercopy_64.c +2 -0
@@ -48,6 +48,8 @@ size_t copy_user_flushcache(void *dst, const void __user *src, size_t size)unsigned long flushed, dest = (unsigned long ) dst;unsigned long rc; +if (uaccess_without_mm ()) +return size; src =masked_user_access_begin (src); rc =copy_to_nontemporal (dst, (__force const void *)src, size);user_access_end ();
include/linux/uaccess.h +12 -4
@@ -170,9 +170,12 @@ _inline_copy_from_user(void *to, const void __user *from, unsigned long n)might_fault ();if (should_fail_usercopy ()) goto fail; -if (can_do_masked_user_access ()) +if (can_do_masked_user_access ()) { +/* Masking doesn't go through access_ok(), so check here. */ +if (uaccess_without_mm ()) + goto fail; from =mask_user_address (from); -else { + }else {if (!access_ok (from, n)) goto fail;/*
@@ -331,11 +334,14 @@ static inline __must_check unsigned long copy_from_user_inatomic_nontemporal(void *to, const void __user *from, unsigned long n) { -if (can_do_masked_user_access ()) +if (can_do_masked_user_access ()) { +if (uaccess_without_mm ()) +return n; from =mask_user_address (from); -else + }else {if (!access_ok (from, n))return n; + }return __copy_from_user_inatomic (to, from, n); }
@@ -751,6 +757,8 @@ static __always_inline void __scoped_user_rw_access_end(const void *p)typeof (uptr) __retptr; \ \if (can_do_masked_user_access ()) { \ +if (uaccess_without_mm ()) \ + goto elbl; \ __retptr = masked_user_##mode##_access_begin(uptr); \ } else { \ __retptr = uptr; \
lib/iov_iter.c +3 -0
@@ -50,6 +50,9 @@ size_t copy_from_user_iter(void __user *iter_from, size_t progress,if (should_fail_usercopy ())return len;if (can_do_masked_user_access ()) { +/* Masking doesn't go through access_ok(), so check here. */ +if (uaccess_without_mm ()) +return res; iter_from =mask_user_address (iter_from); }else {if (!access_ok (iter_from, len))
lib/strncpy_from_user.c +3 -0
@@ -126,6 +126,9 @@ long strncpy_from_user(char *dst, const char __user *src, long count)if (can_do_masked_user_access ()) {long retval; +/* Masking doesn't go through access_ok(), so check here. */ +if (uaccess_without_mm ()) +return -EFAULT ; src =masked_user_read_access_begin (src); retval =do_strncpy_from_user (dst, src, count, count);user_read_access_end ();
lib/strnlen_user.c +3 -0
@@ -99,6 +99,9 @@ long strnlen_user(const char __user *str, long count)if (can_do_masked_user_access ()) {long retval; +/* Masking doesn't go through access_ok(), so check here. */ +if (uaccess_without_mm ()) +return 0 ; str =masked_user_read_access_begin (str); retval =do_strnlen_user (str, count, count);user_read_access_end ();
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
Re: [PATCH v2 11/12] uaccess: Refuse and warn on masked user accesses without an mm
Quoted 4 lines · On Wed, 2 Dec 2026 02:39:18 +0000 James Houghton <[email protected]> wrote:
With masked user access (x86-64 and powerpc),
mask_user_address()and masked_user_*_access_begin() take the place ofaccess_ok(), so the NULLcurrent->mmcheck that the previous patch added toaccess_ok()doesn't cover these paths.
Ugg...
This adds a conditional branch to hot code paths that are pretty much carefully arranged to not contain one.
The WARN_ON_ONCE() also add inline bloat (more so on some architectures than others).
(The same is true for the previous patch.)
Adding tests to the unusual call paths is one thing, but not to the normal paths which always run in the context of a system call for a normal user process.
David
Quoted 178 lines
Check for a NULL
current->mmexplicitly in their callers, and fail without attempting the access if there is none:-
_inline_copy_from_user(), i.e.copy_from_user().
- The genericcopy_from_user_inatomic_nontemporal().
-copy_from_user_iter(), used by the user-backediov_iters.
-strncpy_from_user()andstrnlen_user().
-__scoped_user_access_begin(), i.e. scoped_user_*_access() and get_user_inline()/put_user_inline().
- x86'scopy_from_user_inatomic_nontemporal()andcopy_user_flushcache().
- powerpc's futex operations andcopy_from_user_flushcache().These are all the callers of the masking helpers. In the generic paths, the check is only needed when masking is used, as the other branch calls
access_ok().Signed-off-by James Houghton <[email protected]>--- arch/powerpc/include/asm/futex.h | 4 ++++ arch/powerpc/lib/pmem.c | 2 ++ arch/x86/include/asm/uaccess_64.h | 2 ++ arch/x86/lib/usercopy_64.c | 2 ++ include/linux/uaccess.h | 16 ++++++++++++---- lib/iov_iter.c | 3 +++ lib/strncpy_from_user.c | 3 +++ lib/strnlen_user.c | 3 +++ 8 files changed, 31 insertions(+), 4 deletions(-)arch/powerpc/include/asm/futex.h +4
-0@@ -33,6 +33,8 @@ static inline int arch_futex_atomic_op_inuser(int op, int oparg, int *oval, {int oldval =0 , ret; +if (uaccess_without_mm ()) +return -EFAULT ; uaddr =masked_user_access_begin (uaddr);switch (op) {@@ -68,6 +70,8 @@ futex_atomic_cmpxchg_inatomic(u32 *uval, u32 __user *uaddr,int ret =0 ;u32 prev; +if (uaccess_without_mm ()) +return -EFAULT ; uaddr =masked_user_access_begin (uaddr); __asm__ __volatile__ (arch/powerpc/lib/pmem.c +2
-0@@ -71,6 +71,8 @@ size_t copy_from_user_flushcache(void *dest, const void __user *src, {unsigned long not_copied, start = (unsigned long ) dest; +if (uaccess_without_mm ()) +return size; src =mask_user_address (src); not_copied =__copy_from_user (dest, src, size);clean_pmem_range (start, start + size);arch/x86/include/asm/uaccess_64.h +2
-0@@ -158,6 +158,8 @@ copy_from_user_inatomic_nontemporal(void *dst, const void __user *src, {long ret;kasan_check_write (dst, size); +if (uaccess_without_mm ()) +return size; src =mask_user_address (src);stac (); ret =copy_to_nontemporal (dst, (__force const void *)src, size);arch/x86/lib/usercopy_64.c +2
-0@@ -48,6 +48,8 @@ size_t copy_user_flushcache(void *dst, const void __user *src, size_t size)unsigned long flushed, dest = (unsigned long ) dst;unsigned long rc; +if (uaccess_without_mm ()) +return size; src =masked_user_access_begin (src); rc =copy_to_nontemporal (dst, (__force const void *)src, size);user_access_end ();include/linux/uaccess.h +12
-4@@ -170,9 +170,12 @@ _inline_copy_from_user(void *to, const void __user *from, unsigned long n)might_fault ();if (should_fail_usercopy ()) goto fail; -if (can_do_masked_user_access ()) +if (can_do_masked_user_access ()) { +/* Masking doesn't go through access_ok(), so check here. */ +if (uaccess_without_mm ()) + goto fail; from =mask_user_address (from); -else { + }else {if (!access_ok (from, n)) goto fail;/* @@ -331,11 +334,14 @@ static inline __must_check unsigned long copy_from_user_inatomic_nontemporal(void *to, const void __user *from, unsigned long n) { -if (can_do_masked_user_access ()) +if (can_do_masked_user_access ()) { +if (uaccess_without_mm ()) +return n; from =mask_user_address (from); -else + }else {if (!access_ok (from, n))return n; + }return __copy_from_user_inatomic (to, from, n); }@@ -751,6 +757,8 @@ static __always_inline void __scoped_user_rw_access_end(const void *p)typeof (uptr) __retptr; \ \if (can_do_masked_user_access ()) { \ +if (uaccess_without_mm ()) \ + goto elbl; \ __retptr = masked_user_##mode##_access_begin(uptr); \ } else { \ __retptr = uptr; \lib/iov_iter.c +3
-0@@ -50,6 +50,9 @@ size_t copy_from_user_iter(void __user *iter_from, size_t progress,if (should_fail_usercopy ())return len;if (can_do_masked_user_access ()) { +/* Masking doesn't go through access_ok(), so check here. */ +if (uaccess_without_mm ()) +return res; iter_from =mask_user_address (iter_from); }else {if (!access_ok (iter_from, len))lib/strncpy_from_user.c +3
-0@@ -126,6 +126,9 @@ long strncpy_from_user(char *dst, const char __user *src, long count)if (can_do_masked_user_access ()) {long retval; +/* Masking doesn't go through access_ok(), so check here. */ +if (uaccess_without_mm ()) +return -EFAULT ; src =masked_user_read_access_begin (src); retval =do_strncpy_from_user (dst, src, count, count);user_read_access_end ();lib/strnlen_user.c +3
-0@@ -99,6 +99,9 @@ long strnlen_user(const char __user *str, long count)if (can_do_masked_user_access ()) {long retval; +/* Masking doesn't go through access_ok(), so check here. */ +if (uaccess_without_mm ()) +return 0 ; str =masked_user_read_access_begin (str); retval =do_strnlen_user (str, count, count);user_read_access_end ();
PATCH v2 12/12 uaccess: Refuse and warn on unchecked user accesses without an mm
In reply to James Houghton__copy_{from,to}_user() and __copy_{from,to}_user_inatomic() don't call access_ok(): they rely on the caller having called it earlier. That earlier check may have happened in a different context, e.g. KVM checks a guest's memory slots when they are set up, and then accesses them through __copy_{from,to}_user() from whichever task happens to run the vCPU, or to tear down the VM. So the check in access_ok() doesn't cover these accesses.
Add uaccess_should_fail(), which combines the NULL current->mm check with the existing should_fail_usercopy() fault injection, and use it in place of should_fail_usercopy() in __copy_{from,to}_user() and __copy_to_user_inatomic(). __copy_from_user_inatomic() never called should_fail_usercopy(), so only add the NULL mm check there, rather than start injecting failures that some of its callers don't expect, e.g. __wp_page_copy_user() warns if the copy fails twice.
arm64's copy_from_user_flushcache() also relies on an earlier access_ok(), so add the check to it as well.
Ideally, the remaining users of these unchecked accessors would be converted to the checked ones, which would make these checks unnecessary, but that can be done separately.
The callers of copy_from_user_nofault() that may run without an mm check for it first (see "uaccess: Document that the user nofault helpers need an mm"), and the generic user stack unwinding entry points (perf_callchain(), get_perf_callchain() and stack_trace_save_user()) only unwind the user stack of a user task with an mm, so neither is affected by the check in __copy_from_user_inatomic().
--- arch/arm64/include/asm/uaccess.h | 3 +++ include/linux/uaccess.h | 17 ++++++++++++++--- 2 files changed, 17 insertions(+), 3 deletions(-)
arch/arm64/include/asm/uaccess.h +3 -0
@@ -484,6 +484,9 @@ extern unsigned long __must_check __copy_user_flushcache(void *to, const void __static inline size_t copy_from_user_flushcache (void *dst,const void __user *src,size_t size) {kasan_check_write (dst, size); +/* Like __copy_from_user(), this relies on an earlier access_ok(). */ +if (uaccess_without_mm ()) +return size;return __copy_user_flushcache (dst,__uaccess_mask_ptr (src), size); }#endif
include/linux/uaccess.h +14 -3
@@ -11,6 +11,15 @@#include <linux/ucopysize.h> #include <linux/uaccess_mm.h> +/* +* Return true if a user copy must not be attempted, either because the +* current task has no mm, or because a failure is being injected. +*/ +static __always_inline bool uaccess_should_fail(void) +{ +return uaccess_without_mm () ||should_fail_usercopy (); +} +#include <asm/uaccess.h> /*
@@ -101,6 +110,8 @@ __copy_from_user_inatomic(void *to, const void __user *from, unsigned long n) {unsigned long res; +if (uaccess_without_mm ()) +return n;instrument_copy_from_user_before (to, from, n);check_object_size (to, n, false); res =raw_copy_from_user (to, from, n);
@@ -115,7 +126,7 @@ __copy_from_user(void *to, const void __user *from, unsigned long n)might_fault ();instrument_copy_from_user_before (to, from, n); -if (should_fail_usercopy ()) +if (uaccess_should_fail ())return n;check_object_size (to, n, false); res =raw_copy_from_user (to, from, n);
@@ -139,7 +150,7 @@ __copy_from_user(void *to, const void __user *from, unsigned long n)static __always_inline __must_check unsigned long __copy_to_user_inatomic (void __user *to,const void *from,unsigned long n) { -if (should_fail_usercopy ()) +if (uaccess_should_fail ())return n;instrument_copy_to_user (to, from, n);check_object_size (from, n, true);
@@ -150,7 +161,7 @@ static __always_inline __must_check unsigned long __copy_to_user(void __user *to, const void *from, unsigned long n) {might_fault (); -if (should_fail_usercopy ()) +if (uaccess_should_fail ())return n;instrument_copy_to_user (to, from, n);check_object_size (from, n, true);
Signature · 1 line
2.56.1.911.g883d8bcb20-goog
[email protected]
AI reviewSashiko has finished reviewing this 12-patch series:
Sashiko has finished reviewing this 12-patch series:
- Patches 1-9, 11, and 12: no issues found.
- Patch 10 ("uaccess: Refuse and warn in access_ok() when current..."):
1 potential issue (1 Medium)
A detailed review has been sent as a separate reply to patch 10.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]