libfuzzer heap overflow in malloc

109 Views Asked by At

I am trying out my hand at libfuzzer and I am facing 'heap overflow' at malloc. The code snippet is as follows

int LLVMFuzzerTestOneInput(
    const unsigned char * Data,
    size_t Size
) {
    initialize_state_before_fuzzing();

    size_t charOffset = 0;
    size_t testValueSize = 0;
    size_t arrayLength = 0;
    size_t arrayLength2 = 0;
    const size_t FIXED_BUFFER_SIZE = 4096;

    if (Size == 0)
      return 0;
    uint8_t *testValue_1 = malloc(Size);
    testValueSize = Size;
    for (size_t i = 0; i < testValueSize && charOffset < Size; i++) {
        testValue_1[i] = (uint8_t) Data[charOffset];
        charOffset++;
    }

The overflow happens when Data="" and Size = 7. My question is why does libfuzzer give data that is not equal to the size? How to avoid this?

Also, even if Data is NULL, why does malloc cause heap overflow?

1

There are 1 best solutions below

0
On BEST ANSWER

Based on your description, I think the key point where the error occurred is that you did not check if Data is NULL when executing function LLVMFuzzerTestOneInput and without guarantee sizeof(Data) / sizeof(Data[0]) >= size.

When you check if Data is NULL at execute function LLVMFuzzerTestOneInput before, and the value of size is suitable, at here such as Size = 7, the problem may be disappear.

You can call function LLVMFuzzerTestOneInput(Data, Size) only when Data is not equal to NULL and sizeof(Data) / sizeof(Data[0]) >= size.

like this:

...
...

    if ((Data != NULL) && (sizeof(Data) / sizeof(Data[0])) >= size)
    {
        LLVMFuzzerTestOneInput(Data, Size);
    }
    else
    {

          // something else that you want to do
    }
...
...

And check if testValue_1 is NULL that return value by malloc in LLVMFuzzerTestOneInput function.

Like this:

    uint8_t *testValue_1 = malloc(Size);
    if(testValue_1 == NULL)
    {
        printf("testValue_1 malloc failed, no space\n");
        exit(1);
    }

If possible, please provide additional information, such as code snippets and error messages