Re: [PATCH v5] bpf: core: fix shift-out-of-bounds in ___bpf_prog_run

From: Edward Cree
Date: Tue Jun 15 2021 - 14:51:16 EST


On 15/06/2021 17:42, Kurt Manucredo wrote:
> Syzbot detects a shift-out-of-bounds in ___bpf_prog_run()
> kernel/bpf/core.c:1414:2.
>
> The shift-out-of-bounds happens when we have BPF_X. This means we have
> to go the same way we go when we want to avoid a divide-by-zero. We do
> it in do_misc_fixups().

Shifts by more than insn_bitness are legal in the eBPF ISA; they are
implementation-defined behaviour, rather than UB, and have been made
legal for performance reasons. Each of the JIT backends compiles the
eBPF shift operations to machine instructions which produce
implementation-defined results in such a case; the resulting contents
of the register may be arbitrary but program behaviour as a whole
remains defined.
Guard checks in the fast path (i.e. affecting JITted code) will thus
not be accepted.
The case of division by zero is not truly analogous, as division
instructions on many of the JIT-targeted architectures will raise a
machine exception / fault on division by zero, whereas (to the best of
my knowledge) none will do so on an out-of-bounds shift.
(That said, it would be possible to record from the verifier division
instructions in the program which are known never to be passed zero as
divisor, and eliding the fixup patch in those cases. However, the
extra complexity may not be worthwhile.)

As I understand it, the UBSAN report is coming from the eBPF interpreter,
which is the *slow path* and indeed on many production systems is
compiled out for hardening reasons (CONFIG_BPF_JIT_ALWAYS_ON).
Perhaps a better approach to the fix would be to change the interpreter
to compute "DST = DST << (SRC & 63);" (and similar for other shifts and
bitnesses), thus matching the behaviour of most chips' shift opcodes.
This would shut up UBSAN, without affecting JIT code generation.

-ed