Re: [syzbot] [bpf?] KASAN: slab-use-after-free Read in do_check

From: Luis Gerhorst
Date: Wed Jun 11 2025 - 10:15:09 EST


Eduard Zingerman <eddyz87@xxxxxxxxx> writes:

> Accessed memory is freed at an error path in push_stack():
>
> static struct bpf_verifier_state *push_stack(...)
> {
> ...
> err:
> free_verifier_state(env->cur_state, true); // <-- KASAN points here
> ...
> }
>
> And is accessed after being freed here:
>
> static int do_check(struct bpf_verifier_env *env)
> {
> ...
> err = do_check_insn(env, &do_print_state);
> KASAN --> if (state->speculative && error_recoverable_with_nospec(err)) ...
> ...
> }
>
> [...]
>
> Either 'state = env->cur_state' is needed after 'do_check_insn()' or
> error path should not free env->cur_state (seems logical).

Sorry, this was my error from [1]. Thanks for the pointer.

Yes, I think the former makes sense (with the respective `state &&`
added to the if).

The latter might also be possible, but I guess it would require more
significant changes.

state->speculative does not make sense if the error path of push_stack()
ran. In that case, `state->speculative &&
error_recoverable_with_nospec(err)` as a whole should already never
evaluate to true (because all cases where push_stack() fails also return
a non-recoverable error -ENOMEM/-EFAULT).

Alternatively to adding `state = env->cur_state` and `state &&`, turning
the check around would avoid the use-after-free. However, I think your
idea is better because it is more explicit compared to this:

if (error_recoverable_with_nospec(err) && state->speculative) ...

Does this make sense to you? If yes I can send the fix later today.

I will also check that all other paths calling free_verifier_state() are
sane. So far it looks good.

The later

if (state->speculative && cur_aux(env)->nospec_result) {

should already be fine, because !env->cur_state should imply that the
previous if raises the error.

[1] https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/commit/?id=d6f1c85f22534d2d9fea9b32645da19c91ebe7d2