As per the document https://www.redhat.com/en/blog/enhance-application-security-fortifysource, I see that D_FORTIFY_SOURCE
provides buffer overflow checks for the following functions: memcpy, mempcpy, memmove, strcpy,memset ...etc And my source code below has the usage of the function strcpy
and i try to compiler my code with -D_FORTIFY_SOURCE=1
where it has no effect in compilation.
test.c:-
// fortify_test.c
#include<stdio.h>
/* Commenting out or not using the string.h header will cause this
* program to use the unprotected strcpy function.
*/
//#include<string.h>
int main(int argc, char **argv) {
char buffer[5];
printf ("Buffer Contains: %s , Size Of Buffer is %d\n",
buffer,sizeof(buffer));
strcpy(buffer,argv[1]);
printf ("Buffer Contains: %s , Size Of Buffer is %d\n",
buffer,sizeof(buffer));
}
Compile command:- gcc -D_FORTIFY_SOURCE=1 -g -O2 test.c -o ftest
I am using checksec
(https://github.com/slimm609/checksec.sh/blob/master/checksec) tool to verify my created binary as follows:
./checksec --file=test
RELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILE
Full RELRO Canary found NX enabled PIE enabled No RPATH No RUNPATH 72) Symbols No 0 2 test
Am i missing something here?
When does D_FORTIFY_SOURCE=1
flag gets into effect?
Lets say my source code file dont have any function (memcpy, mempcpy, memmove, memset, strcpy ...etc
) usages and try to compile the code with D_FORTIFY_SOURCE=1
, Does gcc tries to FORTIFY my code?
All fortification logic is implemented in Glibc headers. Roughly they contain code which replaces standard APIs (like strcpy
) with their fortified analogs (like __strcpy_chk
):
$ cat /usr/include/string.h
...
#ifdef _FORTIFY_SOURCE
#define strcpy __strcpy_chk
#endif
...
You commented out string.h
so functions that are defined in this header could not be fortified.