I am wondering if it's possible to detect this kind of buffer overflow somehow in Windows. Buffer is global ( not on stack ) so /RTC in Visual Studio 2008, VS2012 is not checking it. MinGW gcc also failed.

#include <stdio.h>
char buffer[2];
void main()
{
  sprintf(buffer,"12345");
}

My first thought was static analysis.

  1. VS2012 Code Analysis : nothing
  2. CppCheck: nothing
  3. PCLint Online: nothing ( http://www.gimpel-online.com/OnlineTesting.html )
  4. PVS-Studio: nothing

another solution is to use _s version.

#include <stdio.h>
char buffer[2];
void main()
{
  sprintf_s(buffer, sizeof(buffer), "12345");
}

but with code looking like that

#include <stdio.h>
char buffer[2];
void main()
{
  sprintf_s(buffer, 20, "12345");
}

there is still same problem of not detected buffer overrun.

Is is possible to use memory guard, canaries on global data ( like on stack ) as well or resolve this problem using better Static,Dynamic Analysis?

有帮助吗?

解决方案

I am a Cppcheck developer. Cppcheck should easily detect that. What Cppcheck version did you use? Latest Cppcheck version is 1.64.

Here is the expected output when cppcheck-1.64 is used:

danielm@HP-Z220-2CMT:~/cppcheck$ ./cppcheck a.c 
Checking a.c...
[a.c:5]: (error) Buffer is accessed out of bounds.

其他提示

As the question is tagged C++, the simple solution to avoid the issue altogether and not use the intrinsically unsafe C library at all, but rather use a std::ostringstream object.

#include <sstream>

std::ostringstream buffer ;

int main() 
{
    buffer << "12345" ;
}

Coverity's secure coding checker (SECURE_CODING) will catch this sort of bug. See this link.

You can use gflags that comes with Windows SDK:

http://msdn.microsoft.com/en-us/library/windows/hardware/ff543097%28v=vs.85%29.aspx

you register your app with gflags.exe:

 gflags /p /enable pheap-buggy.exe

and during program execution it will throw exceptions if you read/write outside array boundary, which can be caught in VS debugger.

But unfortunately gflags is for Windows Desktop, so it is of use only if you can build your app also for desktop - which actually makes development a lot easier.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top