GCC how to detect stack buffer overflow

Michael D picture Michael D · Sep 30, 2013 · Viewed 13.4k times · Source

Since there is an option -fstack-protector-strong in gcc to detect stack smashing. However, it can not always detect stack buffer overflow. For the first function func, when I input a 10 char more string, the program does not always crash. My question is where there is a way to detect stack buffer overflow.

void func()
{
    char array[10];
    gets(array);
}

void func2()
{
    char buffer[10];
    int n = sprintf(buffer, "%s", "abcdefghpapeas");
    printf("aaaa [%d], [%s]\n", n, buffer);
}

int main ()
{
   func();
   func2();
}

Answer

Aaron Digulla picture Aaron Digulla · Sep 30, 2013

Overflows on the stack are either hard to detect or very expensive to detect - chose your poison.

In a nutshell, when you have this:

 char a,b;
 char *ptr=&a;
 ptr[1] = 0;

then this is technically legal: There is space allocated on the stack which belongs to the function. It's just very dangerous.

So the solution might be to add a gap between a and b and fill that with a pattern. But, well, some people actually write code as above. So your compiler needs to detect that.

Alternatively, we could create a bit-map of all bytes that your code has really allocated and then instrument all the code to check against this map. Very safe, pretty slow, bloats your memory usage. On the positive side, there are tools to help with this (like Valgrind).

See where I'm going?

Conclusion: In C, there is no good way to automatically detect many memory problems because the language and the API is often too sloppy. The solution is to move code into helper functions that check their parameters rigorously, always to the right thing and have good unit test coverage.

Always use snprintf() versions of functions if you have a choice. If old code uses the unsafe versions, change it.