Re: [PATCH] mm/mempolicy: limit compat bitmap reads to the source nodemask

From: Arnd Bergmann

Date: Tue Nov 17 2026 - 08:52:27 EST


On Tue, Nov 17, 2026, at 13:44, Arnd Bergmann wrote:
> On Tue, Nov 17, 2026, at 11:19, Gregory Price (Meta) wrote:
>> A 32-bit get_mempolicy() call can read past the kernel's stack nodemask.
>> With 64 possible nodes and maxnode=65, copy_nodes_to_user() computes an
>> eight-byte copy, but compat_put_bitmap() reads two native words.
>
> I don't quite follow the explanation yet:
>
> if maxnode=65, shouldn't that result in copying 16 bytes on x86-64
> and 12 bytes on compat mode?
>
> It looks like compat mode adjusts the wrong variable and we should
> be doing this instead:
>
> diff --git a/mm/mempolicy.c b/mm/mempolicy.c
> index 6d662a9a8c74..f9a7be9f4432 100644
> --- a/mm/mempolicy.c
> +++ b/mm/mempolicy.c
> @@ -1749,12 +1749,12 @@ static int get_nodes(nodemask_t *nodes, const
> unsigned long __user *nmask,
> static int copy_nodes_to_user(unsigned long __user *mask, unsigned
> long maxnode,
> nodemask_t *nodes)
> {
> - unsigned long copy = ALIGN(maxnode-1, 64) / 8;
> + unsigned long copy = ALIGN(maxnode-1, BITS_PER_LONG) / 8;

I guess this would be an ABI change for 32-bit userspace asking for
maxnum that results in an odd number of 32-bit words. The man
page documents this as "The value specified by maxnode is always
rounded to a multiple of sizeof(unsigned long)*8", while the
code here has always rounded it up to a multiple of 64 in
both native (no longer supported on 32-bit) and compat syscalls.

numactl (1) always uses 128 or 2048 bit masks and won't notice
it either way, so we can possibly change the ABI here and
do what the man page says, or keep the current behavior and update
the man page.

It looks like the other part of the problem is the off-by-one
error: the "ALIGN(maxnode-1, 64) / 8" rounds down maxnode=65
to copy=8 which is the same as nbytes, but the compat_put_bitmap()
treats it as a 65-bit map that needs 96 bytes.

This means we have a related bug on native syscalls as well:
asking for a 65 bit mask in mempolicy only returns 8 bytes
without clearing the next word like it would for a 66 bit mask.
If we just fix the off-by-one and keep the 64 bit alignment
(with a manpage update), the version below be should be sufficient.

Arnd

--- a/mm/mempolicy.c
+++ b/mm/mempolicy.c
@@ -1749,13 +1749,10 @@ static int get_nodes(nodemask_t *nodes, const unsigned long __user *nmask,
static int copy_nodes_to_user(unsigned long __user *mask, unsigned long maxnode,
nodemask_t *nodes)
{
- unsigned long copy = ALIGN(maxnode-1, 64) / 8;
+ unsigned long copy = ALIGN(maxnode, 64) / 8;
unsigned int nbytes = BITS_TO_LONGS(nr_node_ids) * sizeof(long);
bool compat = in_compat_syscall();

- if (compat)
- nbytes = BITS_TO_COMPAT_LONGS(nr_node_ids) * sizeof(compat_long_t);
-
if (copy > nbytes) {
if (copy > PAGE_SIZE)
return -EINVAL;