Exploitability of many buffer overflows23 can be mitigated by compiling a program with GCC using the option -fstack-protector.24
This option causes the GCC to insert a check for stack buffer overflows before function returns. If an attempt is made to exploit a buffer overflow vulnerability in the program, the application will be killed immediately. This reduces the risk of any unknown potential exploits to a denial-of-service.
Example of insecure code: bof.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define DESTLEN 8
int main(int argc, char** argv)
{
char dest[DESTLEN];
if (argc == 2)
{
printf(">>> Before the possible buffer over flow >>>\n");
strcpy(dest, argv[1]);
printf("<<< After the possible buffer over flow <<<\n");
}
else
{
fprintf(stderr,"Usage: %s ARG\n", argv[0]);
fprintf(stderr," Character length(ARG) < %i bytes\n", DESTLEN);
exit(1);
}
return 0;
}
The insecure program bof.c can be compiled without obvious warnings.
$ gcc -Wall bof.c -o bof $ ./bof '123456789' || echo error >>> Before the possible buffer over flow >>> <<< After the possible buffer over flow <<<
The output shows that the bof.c program compiled without using the option -fstack-protector creates an executable bof which executes an insecure buffer overflow code silently.
The insecure program bof.c can be compiled with the option -fstack-protector.
$ gcc -Wall -fstack-protector bof.c -o bof-ssp $ ./bof-ssp '123456789' || echo error >>> Before the possible buffer over flow >>> <<< After the possible buffer over flow <<< *** stack smashing detected ***: ./bof-ssp terminated ... [snipped] Aborted Error
The output shows that the bof.c program compiled with the option -fstack-protector creates an executable bof-ssp. When the executable bof-ssp is executed, it detects stack smashing and exits safely.
http://en.wikipedia.org/wiki/Buffer_overflow_protection
You may use the option -fstack-protector --param=ssp-buffer-size=4 instead to protect more functions with SSP. See /usr/share/doc/gcc-*/README.ssp.