Re: stack access issue. Re: [syzbot] [bpf?] UBSAN: array-index-out-of-bounds in check_stack_range_initialized

From: Kaiming Huang
Date: Tue Mar 26 2024 - 17:11:27 EST


Hi there,

I went across this bug using my static analysis tool as well and was
glad to find this email thread.

My understanding is that the root cause of this bug has not been
identified yet given the previous discussion in this thread.

This is the line of code that has the issue.

stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];

Based on my analysis result, it is the part "slot_type[slot %
BPF_REG_SIZE]" may result in memory access with a negative index,
which should not be allowed. spi (as well as min_off, max_off, and
slot) is(are) supposed to be negative based on my understanding of the
workflow. But the index of slot_type is not supposed to be negative.

The slot_type is defined as below:

u8 slot_type[BPF_REG_SIZE]; //BPF_REG_SIZE is 8

So the type of slot_type is u8[8].

However, given "slot" can be negative, say -1. The result of slot %
BPF_REG_SIZE is -1. This might sound counter-intuitive as % always
gives positive results. But in C, % operation keeps the sign of
dividend (and thus that's why I'm not sure whether the fix will catch
this).

You can examine this by simply running this short piece of code. The
result of the modulo operation is -1 on my end, and that is the reason
that causes the OOB negative index, and this would be an off-by-one on
the u8[8].

#include <stdio.h>
#define BPF_REG_SIZE 8
int main() {
int i = -1;
unsigned int j = i % BPF_REG_SIZE;
printf("%d\n", j);
return 0;
}

A more severe scenario is when interpreting the j in the above example
as unsigned int, aka integer overflow/wrap-around, in that case, the
value of j will be 4,294,967,295. If it is the case, then it is a
classic OOB access on the u8[8].

Hopefully my illustration makes sense, please let me know if you see
any issues. Thanks.

Best regards,
Kaiming.