Skip to content

BUG: Do not use sscanf's output when sscanf matched nothing - #115

Open
hjmjohnson wants to merge 1 commit into
masterfrom
fix/ascii-scan-failure
Open

hjmjohnson wants to merge 1 commit into
masterfrom
fix/ascii-scan-failure

Conversation

@hjmjohnson

Copy link
Copy Markdown
Member

Re-submission of #67, reverted from master on 2026-09-24 so it can be
reviewed before merging. Content is unchanged from the original.

Base: master. Independent: nothing has to land before it.

Commits
  • BUG: Do not use sscanf's output when sscanf matched nothing

Ordering for all the re-submitted work is tracked in #84.

nifti_image_from_ascii() scans its input three times with

    ii = sscanf( str+spos , "%1023s%n" , lhs , &nn ) ; spos += nn ;
    if( ii == 0 || strcmp(lhs,"<nifti_image") != 0 ) return NULL ;

Two things are wrong with that pair of lines.  sscanf() returns EOF,
not 0, when the input ends before anything is matched, so ii == 0 does
not detect the failure; and nn is added to spos before ii is looked
at, so the position advances by an indeterminate amount.

For a string holding nothing but whitespace the first scan returns
EOF, the test passes, and strcmp() reads the uninitialized 1024 byte
stack buffer.  MemorySanitizer:

    WARNING: MemorySanitizer: use-of-uninitialized-value
        #0 nifti_image_from_ascii nifti2_io.c:8836

All three now test for the one successful conversion and only then
advance spos, which is what the surrounding code assumed.  The two
inside the loop cannot fail today, because whitespace is skipped and
end of string is checked before each, and the in-tree readers gate on
has_ascii_header(), so the first is reached only through a direct call
to this published function.  The same three lines exist in
nifti1_io.c and are corrected there too.

Found by fuzzing nifti_image_from_ascii() with libFuzzer under
MemorySanitizer.

(cherry picked from commit 70fa3a6)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants