Re: strncpy clarify result may not be null terminated

Alejandro Colomar
2023-11-09T23:49:18Z

[-- Attachment #1: Type: text/plain, Size: 1126 bytes --]

On Thu, Nov 09, 2023 at 10:11:10AM -0800, Paul Eggert wrote:
> On 2023-11-09 03:38, Alejandro Colomar wrote:
> > If you are consistent in checking the return value of strlcpy(3) and
> > reporting an error, it's the best standard alternative nowadays.
>
> Not necessarily. strlcpy is subject to denial-of-service attacks if the
> attacker has control of the source string and can attack by using long
> source strings. strncpy, as bad as it is, does not have this problem.

Interesting thing. I'd then just use strlen(3)+strcpy(3), avoiding
strncpy(3).

>
> Instead of this:
>
> if (strlcpy (dst, src, dstsize) == dstsize)
> return failure;
>
> applications that want want to copy a string into a small nonempty
> fixed-size buffer, failing if the string doesn't fit, should do something
> like this:
>
> if (strncpy (dst, src, dstsize)[dstsize - 1])
> return failure;
>
> This avoids the denial-of-service attack and is portable all the way back to
> K&R C.
>
> It's unfortunate that strlcpy was misdesigned but here we are.
>

--
<https://www.alejandro-colomar.es/>