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 - 18:06:38 EST


Hi there,

Please discard my previous email as I figured it may be beneficial to
rephrase some of the content in it for clarity.

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. min_off and max_off are supposed to be
negative based on my understanding of the
workflow. But the spi, slot, and the index of slot_type are 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, the bug may alter the "slot" to be negative, say -1. Then
this would cause 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
the dividend. The applied check checks whether access_size is
negative, I'm not sure whether the fix will catch
this sufficiently). Could the fix be potentially directly applied to
"slot" to ensure it is positive?

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 -1, which was reported by the Syzkaller.

#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, if possible, 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 this is the case, then it is a
classic OOB access on the u8[8]. I don't know whether this part is feasible.

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

Best regards,
Kaiming.