Skip to content

BUG: Check dim[0] before using it to index dim[] in the NIFTI-2 converter - #105

Open
hjmjohnson wants to merge 1 commit into
masterfrom
fix/n2-dim0-range
Open

hjmjohnson wants to merge 1 commit into
masterfrom
fix/n2-dim0-range

Conversation

@hjmjohnson

Copy link
Copy Markdown
Member

Re-submission of #64, 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: Check dim[0] before using it to index dim[] in the NIFTI-2 converter

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

…rter

nifti_convert_n2hdr2nim() uses nhdr.dim[0], the number of dimensions,
as a loop bound over the eight-element dim[] array:

    for( ii=2 ; ii <= nhdr.dim[0] ; ii++ )        ...
    for( ii=nhdr.dim[0]+1 ; ii <= 7 ; ii++ )      ...
    for( ii=1 ; ii <= nhdr.dim[0] ; ii++ )        ...

It never checks that dim[0] is in [0,7].  The NIFTI-1 converter gets
that check for free, because need_nhdr_swap() rejects a dim[0] outside
[1,7] in either byte order, but the NIFTI-2 path decides swapping from
sizeof_hdr and reaches the loops with whatever the file said.

A NIFTI-2 header with a large negative dim[0] therefore starts the
second loop at a wild negative index, reads far outside the header and
segfaults.  This is not confined to the header API: nifti_image_read()
gets there for any file with a valid 540 byte NIFTI-2 header, so a
604 byte file crashes nifti_tool:

    $ nifti_tool -disp_nim -infiles bad_n2_dim0.nii
    nifti2_io.c:5079: runtime error: index -6727636073941130588 out of
        bounds for type 'int64_t[8]'
    AddressSanitizer: SEGV ... in nifti_convert_n2hdr2nim

dim[0] is now range checked in the same place, and in the same style,
as the dim[1] check just below it.  Zero stays acceptable, as it is on
the NIFTI-1 side.  Valid headers are unaffected: dim[0] outside [0,7]
has no meaning in either format.

Found by fuzzing nifti_convert_n2hdr2nim() with clang's libFuzzer under
AddressSanitizer.

(cherry picked from commit 5e32002)
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