Usage of strncpy in the kernel

Roland Illig <[email protected]>
Newsgroups gmane.os.netbsd.devel.kernel
Message-ID <[email protected]>
I stumbled across a few usages of strncpy in the kernel that looked
suspicious, for example in lm75.c:

> strlcpy(name, "... preferred name ...", sizeof(sc->sc_sensor.desc));
>
> if (prop_dictionary_get_string(sc->sc_prop, "s00", &desc))
> 	strncpy(name, desc, 64);
>
> strlcpy(sc->sc_sensor.desc, name, sizeof(sc->sc_sensor.desc));

In the first line, the sizeof expression looks like an obvious typo, as
it should normally be sizeof(name).

In the second line, the character array is overwritten with data that is
not guaranteed to be null-terminated.

In the third line, strlcpy expects a (null-terminated) string but
actually only gets a character array, which may lead to out-of-bounds
memory read.

When I looked for other places where strncpy is called, I found similar
code patterns, for example in pcagpio.c:

> char name[32];
> strncpy(name, spptr, 31);

This code tries to avoid overwriting the final character but leaves it
uninitialized, thereby failing to produce a properly null-terminated string.

These code snippets made me wonder whether strncpy should be banned from
kernel code, in order to force developers to think about properly
handling character arrays and strings.

Roland
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.