2010.07.08 16:25 "[Tiff] strlcpy vs strncpy", by Bob Friesenhahn

2010.07.10 11:04 "Re: [Tiff] strlcpy vs strncpy", by Albert Cahalan

On Thu, Jul 8, 2010 at 12:25 PM, Bob Friesenhahn

<bfriesen@simple.dallas.tx.us> wrote:

I see that libtiff is using strncpy() as a safer strcpy() and strncat() as a safer strcat(). strncpy() does include  Unfortunately, a significant design flaw which causes it still to be insecure unless additional care is taken. problem occurs when the string to be  The copied exactly matches the buffer size, in which case the string will lack null termination.

That isn't a design flaw. You could argue that strncpy is a badly chosen name perhaps. The intended use is for character arrays, such as the one in wtmp and utmp files, which are not really strings in the normal C sense. Note how strncpy also zero-fills the remainder of the array; this behavior only makes sense for the intended purpose.

So strncpy isn't intended to do what you likely want, but strlcpy really does have a design flaw. It truncates the string. This can cause a security problem. To deal with that you'd need to check length and compare... but if you're going to do that then you've already written as much code as you'd need to write for doing things the standard and portable way: memcpy. Yep, that's right, memcpy is in <string.h> for a reason.

GraphicsMagick is using strlcpy() and strlcat() for secure string copies. will be happy to contribute versions that I wrote myself  I

Many decent programmers have botched reimplementations of various str* and mem* functions. You might need two hands to count the number of tries it took to get strncpy right in the Linux kernel. Sun shipped a libc that got these functions wrong when crossing a page boundry. Well-optimized code often has failures with bytes 0x7f, 0x80, and/or 0xff.

You can expect a modern compiler and C library to cooperate to provide a regression-tested implementation of str* and mem* functions that takes full advantage of the hardware. (aware of cache lines, aliasing issues, special-purpose instructions, etc.) I strongly suggest using what the platform provides rather than writing your own.