sprintf buffer global data overflow - how to detec

2019-08-07 09:27发布

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?

4条回答
神经病院院长
2楼-- · 2019-08-07 09:48

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

查看更多
再贱就再见
3楼-- · 2019-08-07 09:51

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.

查看更多
欢心
4楼-- · 2019-08-07 09:58

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" ;
}
查看更多
做个烂人
5楼-- · 2019-08-07 10:04

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.
查看更多
登录 后发表回答