简体   繁体   中英

How do i fix this buffer overflow issue?

I recently ran a code scan on a project i'm working on using HP fortify. It reported that I have a critical issue with ReadFile. I never pass an empty buffer. Any suggestions on how to fix the potential buffer overflow problem.

The Abstract

The function Read() in serialport.cpp might be able to write outside the bounds of allocated memory on line 225, which could corrupt data, cause the program to crash, or lead to the execution of malicious code.

DWORD serialport::Read(std::vector<char> & buffer)
{
    DWORD read = 0;
    int val = ReadFile(h, &buffer[0], buffer.size(), &read, NULL);

    if (val == 0)
    {
        LPCSTR ptr = "";
        PrintError(ptr);
    }

    buffer.resize(read);
    return read;
}

I never pass an empty buffer

But someone else may someday. You're making the mistake of evaluating the code inside the function with knowledge of what you do outside the function. That function can be passed an empty std::vector<char> & . Someday, it will be. Handle that case.

You never pass an empty buffer, but the code scanning tool doesn't know that. The ones I've worked with look only at individual functions, so it will assume the actual arguments can be anything.

If the buffer is empty, then &buffer[0] is undefined behavior. You've tried to create a pointer to memory that doesn't exist. That's probably what the code scanning tool is reacting to.

Even though &buffer[0] is an invalid pointer, you might expect nothing to go wrong because nothing will access it. But buffer[0] is itself an invalid access, even though you're not reading or writing to that element.

Although you might get away with using buffer.data() instead, I'd still be wary of it. It only seems to be defined for a non-empty array.

To fix the problem, ...

Option 1: Add assert(!buffer.empty()); to the beginning of the function.

Option 2: Get the pointer more carefully,

DWORD read = 0;
char trash;
void *pBuffer = buffer.empty() ? &trash : buffer.data();
int val = ReadFile(h, pBuffer, buffer.size(), &read, NULL);

Although the tool didn't complain, I'd also make sure that buffer.size() (a std::size_t ) fits into a DWORD, which might not be the case in a 64-bit build.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM