Re: [PATCH] genetlink: Prevent memory leak when krealloc fail

From: Kamil Duljas
Date: Sat Nov 18 2023 - 08:28:15 EST


Yes, you're right. I did not think about it. So if we have a static
pointer that may be resued, should not restore the pointer as at the
beginning?
static unsigned long *mc_groups = &mc_group_start;

At this moment we don't know how much memory is allocated. What do you
think about this?

> new_groups = krealloc(mc_groups, nlen,
> GFP_KERNEL);
> - if (!new_groups)
> + if (!new_groups) {
> + kfree(mc_groups);
> + mc_groups = &mc_group_start;
> return -ENOMEM;
> + }


sob., 18 lis 2023 o 13:02 Florian Westphal <fw@xxxxxxxxx> napisał(a):
>
> Kamil Duljas <kamil.duljas@xxxxxxxxx> wrote:
> > genl_allocate_reserve_groups() allocs new memory in while loop
> > but if krealloc fail, the memory allocated by kzalloc is not freed.
> > It seems allocated memory is unnecessary when the function
> > returns -ENOMEM
>
> Why should it be free'd? mc_groups is not a local variable.
>
> > new_groups = krealloc(mc_groups, nlen,
> > GFP_KERNEL);
> > - if (!new_groups)
> > + if (!new_groups) {
> > + kfree(mc_groups);
> > return -ENOMEM;
> > + }
>
> How did you test this? AFAICS this results in use-after-free for every
> access to mc_groups after this error path is taken.
>
> Existing code looks correct, we can't grow mc_groups and return an
> error.



--
Pozdrawiam,
Kamil Duljas