Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tools and methods to identify/prevent static buffer overruns

Are there any tools or methods that can identify buffer overruns in statically defined arrays (ie. char[1234] rather than malloc(1234))?

I spent most of yesterday tracking down crashes and odd behaviour which ultimately turned out to be caused by the following line:

// ensure string is nul terminated due to stupid snprintf
error_msg[error_msg_len] = '\0';

This index obviously caused writing beyond the bounds of the array. This lead to the clobbering of a pointer variable, leading to unexpected behaviour with that pointer later on.

The three things that come to mind that could help alleviate such problems are:

  1. Code review

    This wasn't done, but I'm working on that.

  2. valgrind

    I often use valgrind during development to detect memory problems but it does not deal with static arrays. In the above instance it only showed me the symptoms such as the invalid free() of the clobbered pointer.

  3. -fstack-protector-all

    In the past I have used -fstack-protector-all to detect overruns like the above but for some odd reason it didn't flag anything in this instance.

So can anyone offer any ideas on how I could identify such overruns? Either by improving on the above list or something completely new.

EDIT: Some of the answers so far have mentioned commercial products that are fairly expensive. At this stage I don't think I could convince the powers that be to buy such a tool so I'd like to restrict tools to cheap/free. Yes, you get what you pay for but some improvement is better than none.

like image 513
Burhan Ali Avatar asked Feb 14 '26 18:02

Burhan Ali


2 Answers

Static analyzer tools are able to detect some buffer overflows.

For example with this code:

char bla[1024];
int i;

for (i = 0; i <= 1024; i++)
    bla[i] = 0;

Here is what PC-Lint / flexelint reports:

tst.c 9 Warning 661: Possible access of out-of-bounds pointer (1 beyond end of data) by operator '[' [Reference: file tst.c: lines 8, 9]

like image 156
ouah Avatar answered Feb 16 '26 07:02

ouah


Have you tried the experimental Valgrind tool "SGCheck: an experimental stack and global array overrun detector" as opposed to the default "memcheck" tool?

http://valgrind.org/docs/manual/sg-manual.html

I haven't tried it myself but it appears to cover some of the types of bugs you are interested in.

Obviously, Valgrind does dynamic rather than static analysis which is a whole other discussion in itself.

like image 21
Sam Elstob Avatar answered Feb 16 '26 06:02

Sam Elstob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!