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

bpf: Reject negative offsets for ALU ops

When verifying BPF programs, the check_alu_op() function validates
instructions with ALU operations. The 'offset' field in these
instructions is a signed 16-bit integer.

The existing check 'insn->off > 1' was intended to ensure the offset is
either 0, or 1 for BPF_MOD/BPF_DIV. However, because 'insn->off' is
signed, this check incorrectly accepts all negative values (e.g., -1).

This commit tightens the validation by changing the condition to
'(insn->off != 0 && insn->off != 1)'. This ensures that any value
other than the explicitly permitted 0 and 1 is rejected, hardening the
verifier against malformed BPF programs.

Co-developed-by: Shenghao Yuan <shenghaoyuan0928@163.com>
Signed-off-by: Shenghao Yuan <shenghaoyuan0928@163.com>
Co-developed-by: Tianci Cao <ziye@zju.edu.cn>
Signed-off-by: Tianci Cao <ziye@zju.edu.cn>
Signed-off-by: Yazhou Tang <tangyazhou518@outlook.com>
Acked-by: Yonghong Song <yonghong.song@linux.dev>
Fixes: ec0e2da95f72 ("bpf: Support new signed div/mod instructions.")
Link: https://lore.kernel.org/r/tencent_70D024BAE70A0A309A4781694C7B764B0608@qq.com
Signed-off-by: Alexei Starovoitov <ast@kernel.org>

authored by

Yazhou Tang and committed by
Alexei Starovoitov
55c0ced5 1bd3773a

+2 -2
+2 -2
kernel/bpf/verifier.c
··· 15804 15804 } else { /* all other ALU ops: and, sub, xor, add, ... */ 15805 15805 15806 15806 if (BPF_SRC(insn->code) == BPF_X) { 15807 - if (insn->imm != 0 || insn->off > 1 || 15807 + if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) || 15808 15808 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 15809 15809 verbose(env, "BPF_ALU uses reserved fields\n"); 15810 15810 return -EINVAL; ··· 15814 15814 if (err) 15815 15815 return err; 15816 15816 } else { 15817 - if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 15817 + if (insn->src_reg != BPF_REG_0 || (insn->off != 0 && insn->off != 1) || 15818 15818 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 15819 15819 verbose(env, "BPF_ALU uses reserved fields\n"); 15820 15820 return -EINVAL;