Vulnerability Development mailing list archives

Re: Secure coding in C (was Re: Administrivia #4883)


From: imp () VILLAGE ORG (Warner Losh)
Date: Fri, 21 Jan 2000 12:53:20 -0700


In message <20000121183139.28098.qmail () nwcst282 netaddress usa net> Brock Tellier writes:
: Maybe this is minutia since it's already proven that the man page is at least
: unclear, if not outright wrong, but.. Why wouldn't they say "If n=0, no null
: byte will be written" or "if n=0, no changes to the string will be made" if
: that was indeed the case.  Why they say "space available", I think they mean
: "bytes in the character buffer which have not yet been used in the current
: snprintf".  The reason I still agree with my interperetation is because I can
: see (though don't agree with) the reasoning behind this.  The idea of not
: writing the null byte if space is not available is to prevent the last byte of
: the string you'd snprinted from being overwritten.  It's a protection against
: having your data munged which assumes, from a security standpoint, that you
: know what you're doing with that string later on in the program.

I guess we don't agree.  I've seen lots of things written like this
because someone thought it was clearer than syaing "if n == 0...".

In any event, I don't care what the man page says.  If strcpy said
that it might not terminate the string, it would still be hopelessly
broken.

From the last publicly available ANSI C 9x draft standard:
       7.19.6.5  The snprintf function
...
       [#2]  The snprintf function is equivalent to fprintf, except
       that the output is  written  into  an  array  (specified  by
       argument  s) rather than to a stream.  If n is zero, nothing
       is written, and s may be a null pointer.  Otherwise,  output
       characters  beyond the n-1st are discarded rather than being
       written to the array, and a null character is written at the
       end  of  the characters actually written into the array.  If
       copying  takes  place  between  objects  that  overlap,  the
       behavior is undefined.

I can easily see how this could be abstracted down to "if there is
space available" by a tech writer that wasn't used to being precise
enough.  Given that Solaris 8 didn't change how snprintf worked, but
did change the manual to be closer to the above is another reason that
I think my reading is correct.

Warner


Current thread: