[PATCH] nscd: nscd.h: fix off-by-one buffer overflow in init_traced_file

Adhemerval Zanella Netto adhemerval.zanella@linaro.org
Wed Oct 29 17:28:18 GMT 2025



On 29/10/25 11:16, Anton Moryakov wrote:
> Report of the static analyzer:
> Accessing an element of array 'file->dname' of size 1024 at nscd.h:111 can
> lead to a buffer overflow, since the index 'len' can have an out of range
> value 1024, as indicated by the conditional check at nscd.h:108.
> 
> Correct explained:
> The function init_traced_file copies the directory portion of a path into
> file->dname[PATH_MAX] (1024 bytes). It checks if (len > sizeof(file->dname))
> before copying, but this allows len == PATH_MAX to pass. In this case,
> memcpy writes 1024 bytes, and then a null terminator is written to
> file->dname[len], which is out of bounds (valid indices are 0..1023).
> 
> This off-by-one error can lead to a stack-based buffer overflow, potentially
> corrupting adjacent memory or causing undefined behavior.
> 
> Fix by changing the condition to 'if (len >= sizeof(file->dname)) abort();'
> to properly reject paths where the directory length equals PATH_MAX.

Wouldn't this path only taken if fname contains a '/', and thus 'dname - fname'
will always be less than sizeof (dname) - 1?

> 
> Signed-off-by: Anton V. Moryakov <ant.v.moryakov@gmail.com>
> ---
>  nscd/nscd.h | 2 +-
>  1 file changed, 1 insertion(+), 1 deletion(-)
> 
> diff --git a/nscd/nscd.h b/nscd/nscd.h
> index 1ea0f08bdf..eb833b8411 100644
> --- a/nscd/nscd.h
> +++ b/nscd/nscd.h
> @@ -105,7 +105,7 @@ init_traced_file(struct traced_file *file, const char *fname, int crinit)
>     if (dname != NULL)
>       {
>         size_t len = (size_t)(dname - fname);
> -       if (len > sizeof (file->dname))
> +       if (len >= sizeof (file->dname))
>  	 abort ();
>         memcpy (file->dname, file->fname, len);
>         file->dname[len] = '\0';



More information about the Libc-alpha mailing list