sprintf buffer global data overflow - how to detect it, Windows

安稳与你 提交于 2019-12-11 07:37:31

问题


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?


回答1:


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.



回答2:


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" ;
}



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/22684670/sprintf-buffer-global-data-overflow-how-to-detect-it-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!