FORTIFY_SOURCE Semantics



The GNU Compiler Collection has a FORTIFY_SOURCE option that does automatic bounds checking of dangerous functions to prevent simple buffer overflows. The FORTIFY_SOURCE code will do static and dynamic checks on buffer sizes to prevent these buffer overflows.

Details

FORTIFY_SOURCE will do checks on the following functions:

memcpy, mempcpy, memmove, memset, strcpy, stpcpy, stncpy, strcat, strncat, sprintf, vsprintf, snprintf, vsnprintf, gets.

Here’s a simple example of how one of these checks work: gets(buffer) would be converted to __gets_chk(buffer, sizeof(buffer)), then __gets_chk would make sure that the input from the keyboard does not exceed sizeof(buffer).

There are two operating modes of FORTIFY_SOURCE, they are described well here:

The intended use in glibc is that by default no protection is done, when the above GCC 4.0+ and -D_FORTIFY_SOURCE=1 is used at optimization level 1 and above, security measures that shouldn't change behaviour of conforming programs are taken. With -D_FORTIFY_SOURCE=2 some more checking is added, but some conforming programs might fail. [1]

Here’s how you can check to make sure FORTIFY_SOURCE is working properly:

objdump -M intel -d YOUR_BINARY | grep _chk

0804832c <__printf_chk@plt>:
0804833c <__gets_chk@plt>:
8048429:	e8 0e ff ff ff       	call   804833c <__gets_chk@plt>
8048439:	e8 ee fe ff ff       	call   804832c <__printf_chk@plt>

Troubleshooting

If FORTIFY_SOURCE isn’t working, you may be trying to use FORTIFY_SOURCE without optimization turned on.

YOU MUST TURN ON OPTIMIZATION -01 OR GREATER FOR FORTIFY_SOURCE TO WORK.

Citations

[1] http://gcc.gnu.org/ml/gcc-patches/2004-09/msg02055.html