String Handling
Secure Programming HOWTO contains very good
chapter about string handling problems. Here's only the basics:
- strncpy() doesn't necessarily NUL-terminate string requiring it to be
done explicitly. It also completely fills the rest of the destination
buffer with \0 characters, making it unnecessarily slow.
- strncat() was probably never meant to be a way to prevent buffer
overflows, it's behaviour is just too insane for that:
strncat(buf, "foo", sizeof(buf)-strlen(buf)-1);
Then
there's also people who are happily using strncat() by giving the full
buffer size in 3rd parameter. While that would sound logical, it's
completely wrong.
- snprintf() is pretty usable, unless you need it's return value which
has different semantics when buffer gets full. Either it returns -1 (old
semantics) or the full length as if it hadn't been truncated (C99).
- strlcpy(), strlcat(): Much better replacements to above by OpenBSD.
They're not currently included in most systems, but their implementation
is so small that you can easily include them with your own programs. But
these can still be used unsafely if the buffer size parameter is wrong
or if the programmer goes playing around with the buffer indirectly, by
eg. appending single characters and forgetting size checks (yes, I've
seen this in software that contained "secure" in it's name).
- Dynamically allocating the amount of wanted memory and then using
strcpy(), strcat(), sprintf() and direct accessing. This requires you to
be very careful with the string size calculations. I don't understand
why so many people think that's not a problem, they have this "If you
can't calculate the sizes correctly, you're stupid and you shouldn't be
coding at all" attitude. Why bother wasting time with that at all when
you could be doing more important things?
- Dynamically growing buffers, used by for example GLIB, vsftpd, qmail,
djbdns and Postfix. This is definitely the right way; string
manipulation is done through API which discourages - or even disallows -
direct buffer manipulation.