Re: Stack growth direction to thwart buffer overflow attacks

From: Tony Nelson (
Date: 08/16/03

Date: Sat, 16 Aug 2003 13:05:20 -0400

In article <bhj6c4$onu$>, (Nick Maclaren) wrote:

> If you are writing decent code, you are replacing:
> if (strlen(source) > target_length-1) fail("overflow");
> strcpy(target,source);
> by:
> target[target_length-1] = '\0';
> strncpy(target,source,target_length);
> if (target[target_length-1] != '\0') fail("overflow");
> NOT a big improvement!

Surely not. I prefer to use:

    target[0] = 0;

strncat puts a NUL at the end of the string.

sizeof(target) will be wrong if target is a ptr, but then target_length
is hard to trust as well (either it's a constant that might not be
appropriate, or it's a parameter to trust -- darn C for making ptrs and
arrays exactly equivalent except for sometimes). Normally I fix these
problems by using a local buffer so I know what is going on.

I'm also a fan of fgets and its ilk. Even if I get the length wrong,
I've set a smaller limit than infinity, so an attack would have to fit
in a smaller space.

Well, acually I'm not a fan of the standard library at all, and I try to
avoid using it as it makes the code crappier and harder to write. It
took me a while to learn this.

> >>One of the common causes of problems is that a 'solution' eliminates
> >>enough of the easy cases so that lazy programmers stop even trying
> >>to do tackle the problem themselves. In turn, this means that the
> >>number of nasty cases increases. As it is common for 90% of the
> >>bugs to be easy, but 90% of the problems to be caused by hard bugs,
> >>this often REDUCES the overall reliability.
> >
> >We're talking about programmers who aren't even getting the easy cases
> >right. If the cost of preventing 100 easy cases is 10 more nasty cases,
> >that seems like a net win.

Programmers that turn nasty cases into hard solutions are a problem. I
prefer to use easy solutions, as above

We make progress a little bit at a time. If we say that everything must
be solved at once, we don't make progress at all.