Re: [PATCH] mm/mempolicy: fix copy_nodes_to_user() for odd inputs

From: Arnd Bergmann

Date: Tue Nov 17 2026 - 15:31:59 EST


On Tue, Nov 17, 2026, at 20:59, Gregory Price (Meta) wrote:
> What about the following:
>
> --- 1/2 mm/mempolicy: convert maxnode to a bit count in copy_nodes_to_user()
>
> Converts maxnode to a bit count on entry to copy_nodes_to_user() and
> get_nodes(), fixing the compat KASAN stack over-read and stack leak.
> Fixes e130242dc351, Cc stable.
>
>
> Subject: [PATCH 1/2] mm/mempolicy: convert maxnode to a bit count in
> copy_nodes_to_user()
>
> Whenever maxnode - 1 is a multiple of 32, compat_put_bitmap() reads one

'multiple of 64' I think

> more compat_ulong_t from the kernel nodemask than the caller asked for,
> and writes it past the end of the caller's bitmap.
>
> When the kernel nodemask ends there, that read goes past the on-stack
> nodemask_t in kernel_get_mempolicy(), and its low 32 bits are copied
> to userspace.
>
> With CONFIG_NODES_SHIFT=6, 64 possible nodes and a 32-bit caller
> passing maxnode=65:
>
> BUG: KASAN: stack-out-of-bounds in compat_put_bitmap+0x122/0x130
> Read of size 8 at addr ffff8880150d7ec0 by task mpoltest/241
> compat_put_bitmap+0x122/0x130
> copy_nodes_to_user+0x14a/0x250
> __ia32_sys_get_mempolicy+0x1b0/0x2b0
>
> Convert maxnode to a bit count once, on entry, and use only that in the
> rest of copy_nodes_to_user(), so the compat path gets the same size as
> the native one. Do the same in get_nodes().
>
> Fixes: e130242dc351 ("mm: simplify compat numa syscalls")

I like the renaming as a cleanup, though it does make it a little
harder to backport to stable kernels from context changes, maybe
it's better to do do the minimal fix first.

> mm/mempolicy.c | 4 +++-
> 1 file changed, 3 insertions(+), 1 deletion(-)
>
> diff --git a/mm/mempolicy.c b/mm/mempolicy.c
> index 390a31a99b4ff..cddca1db3d9a1 100644
> --- a/mm/mempolicy.c
> +++ b/mm/mempolicy.c
> @@ -1725,8 +1725,10 @@ static int copy_nodes_to_user(unsigned long
> __user *mask, unsigned long maxnode,
> unsigned int nbytes = BITS_TO_LONGS(nr_node_ids) * sizeof(long);
> bool compat = in_compat_syscall();
>
> - if (compat)
> + if (compat) {
> + copy = ALIGN(nbits, BITS_PER_COMPAT_LONG) / 8;
> nbytes = BITS_TO_COMPAT_LONGS(nr_node_ids) * sizeof(compat_long_t);
> + }

It fixes the bug, but I'd drop the nbytes= assignment here, as it
has no benefit: The only configurations where nbytes actually gets
a different value is for NODES_SHIFT<6, but as the on-stack
bitmask is still a 64-bit word here, the only difference is whether
the extra zeroes come from memset() or compat_put_bitmap().

I assume that when I introduced this bug, I simply confused which of
the two variables needed to be adjusted.

Arnd