berry icon indicating copy to clipboard operation
berry copied to clipboard

Out-of-bound memory access in be_byteslib

Open Kosehai opened this issue 1 year ago • 1 comments

Due to a cast from size_t to int32 in buf_set and buf_get functions it is possible to supply a large number to access memory out-of-bounds from a bytes object.

Here is an example problematic function:

static void buf_set4_le(buf_impl* attr, size_t offset, uint32_t data)
{
    // Cast here is causeing the problem
    if ((int32_t)offset + 3 < attr->len) {
        attr->bufptr[offset] = data & 0xFF;
        attr->bufptr[offset+1] = (data >> 8) & 0xFF;
        attr->bufptr[offset+2] = (data >> 16) & 0xFF;
        attr->bufptr[offset+3] = data >> 24;
    }
}

Reproducing

Here is a berry code snippet that will cause a segmentation fault:

b=bytes()
b.set(32314545516,0,4) #This is being treated as a negative number bypassing the bounds check

Fixing

The issue can be rectified by checking that the provided offset is not negative.

Kosehai avatar May 22 '24 17:05 Kosehai

Nice finding. Maybe we should handle negative offset as starting from end, like in arrays. Thoughts?

s-hadinger avatar May 27 '24 20:05 s-hadinger

Fixed, awaiting approval before merging

s-hadinger avatar Jul 24 '24 09:07 s-hadinger