tech-kern archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Usage of strncpy in the kernel



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



Home | Main Index | Thread Index | Old Index