/GS - Enable Security Checks (Windows CE 5.0)
/GS is the default build flag for device compilers.
/GS attempts to detect direct buffer overruns into the return address. When a buffer overruns overwrites the return address, it provides an opportunity to exploit code that does not enforce buffer size restrictions.
You can inject security checks into compiled code by enforcing buffer size restrictions.
Buffer overruns are more easily exploited on machines, such as x86, with calling conventions that pass the return address of function calls on the stack. When a function is compiled with /GS, the compiler identifies functions that might be subject to buffer overrun problems and inserts a security cookie on the stack before the return address. If, on function exit, the security cookie has changed, then the compiler reports an error and terminates the process.
The security cookie can be an issue when /GS is used to compile an EXE or DLL that does not use one of the default CRT entrypoints. The issue can occur because /GS requires CRT startup code, and the CRT function _cinit resets the expected value of the security cookie. If you have a function that is compiled with /GS (and thus has the security cookie) that in turn calls _cinit, the _cinit function changes the expected security cookie value and causes your program to falsely detect a buffer overrun.
To avoid this issue:
- Do not use arrays or _alloca in any functions that call (or end up calling) _cinit.
- Let the CRT initialize normally with a default entrypoint, such as WinMainCRTStartup or _DllMainCRTStartup.
/GS does not protect against all buffer overrun security attacks. For example, buffer overrun attacks are still possible by overwriting into the parameters area.
Even if you use /GS, you should strive to write secure code. That is, make sure that your code has no buffer overruns. /GS might protect your application from buffer overruns that do remain in your code.
Example
This sample overruns a buffer. It will display a message box and terminate the process when built with /GS.
#include <cstring>
// Vulnerable function
void vulnerable(const char *str)
{
char buffer[10];
strcpy(buffer, str); // overrun buffer !!!
}
int main()
{
// declare buffer that is bigger than expected
char large_buffer[] = "This string is longer than 10 characters!!!";
vulnerable(large_buffer);
}
See Also
Send Feedback on this topic to the authors