Secure Coding mailing list archives

strncpy (was: Re: New Microsoft Security Tool for developers)


From: "David A. Wheeler" <dwheeler () ida org>
Date: Wed, 17 Dec 2003 01:23:31 +0000




Dana Epp wrote:

It will copy UP TO len bytes from src to the dest. If the length of 
src is
only 4 bytes, it will only copy 4 bytes to dest, and nullify the rest 
of the
buffer of dest. As such, there is no information disclosure issues 
with this

call as you describe the threat.





Crispin Cowan wrote:


I cannot find supporting documentation for the claim "and nullify the 
rest of the buffer of dest". IIRC, strncpy will copy a null byte from 
src to dst, but it does not nullify the rest of dst. 



This "excess nul'ing" is extremely perverse behavior... but it's true.
This is clearly stated in Kernighan and Ritchie second edition
[Kernighan 1988, page 249], and this behavior is clearly documented in
the man pages for Linux, FreeBSD, and Solaris.  I don't have the formal
standards handy but I believe they say the same.  (The fact that
few have the formal standards handy, but every user of C has K&R handy, 
is probably

a good argument that K&R is the "real" standard anyway... but I digress...).



This semantics is screwed up. It is also defined standard. Thus 
leading to long flame wars about whether 'tis nobler in the mind to 
suffer the slings and arrows of crappy APIs, or to take up better APIs 
against a sea of standards documents, and by opposing, end them 
[Hamlet, sort of :]



Unfortunately, changing the semantics now would be extremely hazardous, 
since if I
problem CORRECTLY relies on the standard behavior and you introduce a 
change,

you might introduce a security problem.

For statically-allocated buffers I'm a big fan of strlcpy/strlcat, 
originally from OpenBSD
but now in other places such as Solaris.  I would very much like to see 
a push to
add these to the C standard library (in string.h).  Having a few simple 
library calls that
are easier to use securely would be far more helpful than the "just 
never make a mistake"
message that's far easier to do in theory than in practice. 
Statically-allocated buffers
have their own problems (attackers may be able to exploit the fact that 
the buffer can't
be expanded), but those are often harder to exploit than buffer overflow 
attacks.


There doesn't seem to be as obvious a winner
for dynamically-allocated buffers in C (C++ has std:string).
Viega/Messier's SafeStr is a good candidate.

--- David A. Wheeler










Current thread: