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

2010.07.11 08:18 "Re: [Tiff] strlcpy vs strncpy", by Albert Cahalan

On Sat, Jul 10, 2010 at 9:39 AM, Bob Friesenhahn

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

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.

I tend to agree except for the fact that strlcpy() does absolutely assure null termination, even if the programmer made an error.

Uh oh. You have failed to consider the case of a zero-sized buffer. If your strlcpy overflows with a NUL byte, then it may corrupt a function pointer. If it doesn't, but you rely on getting a NUL byte, your app code may leak data by read-overflowing as the 0-byte "string" gets copied elsewhere.

GraphicsMagick-1.3.12 has two strlcpy implementations that I could find. Both use assert for this case, which is not what strlcpy is supposed to do. Also you are either paying the cost of compiling code with assertions enabled or you are running without them and being subject to having things possibly depend on input that an attacker might control.

If compiled without assertions, your strlcpy seems to turn into strcpy when size is 0. You underflow from 0 to 0xffffffff or 0xffffffffffffffff for the right side of the (length < size-1) comparison.