[PATCH v2] string: Fix OOB read on generic strncmp

Florian Weimer fweimer@redhat.com
Fri Feb 24 10:58:04 GMT 2023

* Szabolcs Nagy:

> The 02/23/2023 15:15, Adhemerval Zanella Netto wrote:
>> Noah has brought to my attention that he tried to add similar tests,
>> but they were rejected by strncmp string must be null-terminated [1].
>> The working drafts for C standard I have access (n1256.pdf for C99 and 
>> n3047.pdf for c2x) do not say possibly null-terminated array (as some
>> stackoverflow answer state [2]) they refer only as array. So I tend
>> to follow Florian understanding that strncmp inputs should be NULL
>> terminated.
> c11 draft is n1570.pdf
> https://open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
> i dont understand what extension Florian is talking about.
> (i think that was about strcmp not strncmp)
> c11 and c23 are clear that strncmp args may *not* be null-terminated
> so i think we should be careful not to overread.

It's common to use strncmp as a starts-with predicate, like this:

  strncmp (s, "prefix", 5)

This requires that reading stops at the first null byte.  C11 wording
makes this kind of usage inadvisable because it treats the inputs as
arrays, and this means that mean that implementations could read past
the null byte.  But that doesn't match current programming practice.

The strnlen function has the same problem if you want to use it to limit
readhead, e.g. in sscanf to fix bug 17577.  (POSIX also speaks of an
array argument.)  In stdio-common/Xprintf_buffer_puts_1.c, we already
use it to avoid a similar performance glitch.  It's not the first such
uses, there is already a similar call (with similar rationale) in
string/strcasestr.c, and for wcsnlen in

I think we should support all these as extensions.  The alternative
would be to add new functions that stop reading after the first null
byte (particularly for the strnlen optimization).

Unfortunately, the last time I brought this up, the manual was updated
to double down on the array interpretation.  I think this was the

commit 2cc4b9cce51643ec299e97450ccde4deeecfb083
Author: Paul Eggert <eggert@cs.ucla.edu>
Date:   Fri Dec 4 08:27:14 2015 -0800

    Consistency about byte vs character in string.texi

I think that's just not the right direction for glibc.


More information about the Libc-alpha mailing list