Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

bpf: Forget ranges when refining tnum after JSET

Syzbot reported a kernel warning due to a range invariant violation on
the following BPF program.

0: call bpf_get_netns_cookie
1: if r0 == 0 goto <exit>
2: if r0 & Oxffffffff goto <exit>

The issue is on the path where we fall through both jumps.

That path is unreachable at runtime: after insn 1, we know r0 != 0, but
with the sign extension on the jset, we would only fallthrough insn 2
if r0 == 0. Unfortunately, is_branch_taken() isn't currently able to
figure this out, so the verifier walks all branches. The verifier then
refines the register bounds using the second condition and we end
up with inconsistent bounds on this unreachable path:

1: if r0 == 0 goto <exit>
r0: u64=[0x1, 0xffffffffffffffff] var_off=(0, 0xffffffffffffffff)
2: if r0 & 0xffffffff goto <exit>
r0 before reg_bounds_sync: u64=[0x1, 0xffffffffffffffff] var_off=(0, 0)
r0 after reg_bounds_sync: u64=[0x1, 0] var_off=(0, 0)

Improving the range refinement for JSET to cover all cases is tricky. We
also don't expect many users to rely on JSET given LLVM doesn't generate
those instructions. So instead of improving the range refinement for
JSETs, Eduard suggested we forget the ranges whenever we're narrowing
tnums after a JSET. This patch implements that approach.

Reported-by: syzbot+c711ce17dd78e5d4fdcf@syzkaller.appspotmail.com
Suggested-by: Eduard Zingerman <eddyz87@gmail.com>
Acked-by: Yonghong Song <yonghong.song@linux.dev>
Acked-by: Eduard Zingerman <eddyz87@gmail.com>
Signed-off-by: Paul Chaignon <paul.chaignon@gmail.com>
Link: https://lore.kernel.org/r/9d4fd6432a095d281f815770608fdcd16028ce0b.1752171365.git.paul.chaignon@gmail.com
Signed-off-by: Alexei Starovoitov <ast@kernel.org>

authored by

Paul Chaignon and committed by
Alexei Starovoitov
6279846b 2b1fd82c

+4
+4
kernel/bpf/verifier.c
··· 16208 16208 if (!is_reg_const(reg2, is_jmp32)) 16209 16209 break; 16210 16210 val = reg_const_value(reg2, is_jmp32); 16211 + /* Forget the ranges before narrowing tnums, to avoid invariant 16212 + * violations if we're on a dead branch. 16213 + */ 16214 + __mark_reg_unbounded(reg1); 16211 16215 if (is_jmp32) { 16212 16216 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 16213 16217 reg1->var_off = tnum_with_subreg(reg1->var_off, t);