Skip to content

BUG: Refuse a header whose dimensions overflow the voxel count - #106

Open
hjmjohnson wants to merge 8 commits into
masterfrom
fix/nvox-overflow
Open

hjmjohnson wants to merge 8 commits into
masterfrom
fix/nvox-overflow

Conversation

@hjmjohnson

@hjmjohnson hjmjohnson commented Sep 24, 2026 •

Copy link
Copy Markdown
Member

Re-submission of #68. A NIFTI-1, NIFTI-2, or ASCII (.nia) header whose
dimensions overflow the voxel count or the volume size is now refused, so
callers such as ITK get NULL from nifti_image_read() for it instead of an
image with a wrapped nvox. Regression tests are included.

Base: master. Independent: nothing has to land before it. The two
test commits taken from #123 now live here, so #123 should drop them.

The NULL check that the -DFSLSTYLE=ON rejection tests need landed on master separately (75de25f).

Commits
  • BUG: Refuse a header whose dimensions overflow the voxel count (NIFTI-2
    library, both binary converters; the volume size is also checked
    against SIZE_MAX for 32-bit targets)
  • BUG: Guard the voxel count in the NIFTI-1 library too
  • BUG: Refuse an ASCII header whose dimensions overflow the voxel count
    (nifti_image_from_ascii() in both libraries; also stops the (int)
    cast of nifti_get_volsize() in nifti_read_ascii_image() from
    reading image bytes as extensions)
  • ENH: Cover the voxel-count and volume-size overflow guards
  • ENH: Cover the voxel-count guards in the NIFTI-1 library
  • ENH: Cover the ASCII header voxel-count and volume-size guards
  • BUG: Refuse an ASCII header whose ndim is outside 1..7 (an ndim of
    99 indexed past dim[8] in the tools)
  • ENH: Fail the overflow tests on sanitizer output, and allow 32-bit
    (on a 32-bit size_t the earlier overflow message is also accepted)
Deferred

Two more nvox loops remain in each library, and neither reads dimensions
from a file header:

  • nifti_update_dims_from_array() (dims the caller has set; reached from
    nifti_tool -cci)
  • update_nifti_image_for_brick_list() (brick count of a caller's brick
    list)

Two ASCII-reader problems that predate this change, found while reviewing it:

  • a dimension too large for int (nx = '99999999999') is undefined
    behavior in the parser, before the new guard runs;
  • num_ext is taken from the header text unchecked, and a mismatch
    reaches undefined behavior in nifti_tool.
Testing

Every guard was neutralized in turn; each mutant turns exactly its own
test red (12 mutants, 14 tests); the ndim tests fail with their fix
reverted. All 16 tests pass under ASan + UBSan and with gcc-16
-Wall -Wextra. The 32-bit expectations were checked by simulating the
CMake branch, not by a 32-bit build.

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

@hjmjohnson
hjmjohnson marked this pull request as ready for review September 24, 2026 12:17

@gdevenyi gdevenyi left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review by Google Carbon

Verdict: Request Changes

Guarding dim[] -> nvox and nvox * nbyper -> volume-size against signed/unsigned overflow in binary and .nia ASCII headers (and fixing nifti_read_ascii_image's 32-bit vsize truncation) closes a critical class of heap-overflow / OOM / bogus-extension bugs!

Four issues need to be addressed before merging:

  1. Merge conflict with master: Commit 1 (5f637af, moving #ifdef REJECT_COMPLEX below if (nim == NULL)) already landed on master as 75de25f. Drop 5f637af when rebasing onto master.
  2. 4 new CTests fail on 32-bit platforms (ILP32, SIZE_MAX == 2^32 - 1):
    • nia_volsize_trunc.nia (nx=65536, ny=65536, datatype=UINT8) has nvox = 2^32 > UINT32_MAX, so on 32-bit both nifti2_tool_nia_volsize_no_exts and nifti1_tool_nia_volsize_no_exts reject the header in nifti_image_from_ascii (nvox > SIZE_MAX) instead of printing num_ext = 0! Fix: Use e.g. nx='65536' ny='32768' datatype='2' (vsize = 2^31 = 2147483648), which fits in 32-bit size_t (<= UINT32_MAX) while still overflowing signed 32-bit int (INT32_MIN) in the old buggy int vsize code!
    • n1_volsize.nii and nia_volsize.nia (nvox = 4 * 32767^4 > 2^62 > UINT32_MAX) trip "dim[] overflows the voxel count" on 32-bit nifti1_tool (nim->nvox is size_t) instead of "dim[] and datatype overflow the volume size". Using e.g. nx=32767, ny=32767, nz=2, datatype=DT_FLOAT64 (8B) overflowed SIZE_MAX on 32-bit only at the nbyper step, or accept either overflow regex on 32-bit nifti1_tool.
  3. Unvalidated nim->ndim in nifti_image_from_ascii (nifti2_io.c:8941, nifti1_io.c:6809): Checks nim->dim[ii] <= 0 for ii = 1..7, whereas nim->ndim (nim->dim[0]) is only checked for <= 0 at line 8932 — an ASCII header with ndim = '99' passes right into downstream loops for (i = 1; i <= nim->ndim; i++) and reads past nim->dim[8]! Check if (nim->ndim <= 0 || nim->ndim > 7) as well.
  4. Add Sanitizer FAIL_REGULAR_EXPRESSION to the PASS_REGULAR_EXPRESSION CTests: In CTest, setting PASS_REGULAR_EXPRESSION ignores non-zero exit codes (including ASan/LSan/UBSan exit codes!) whenever stdout/stderr matches the pass regex.

Comment thread nifti2/nifti2_io.c Resolved
Comment thread nifti2/nifti2_io.c Resolved
Comment thread nifti2/CMakeLists.txt Resolved
Comment thread niftilib/testdata/nia_volsize.nia Resolved
@hjmjohnson

Copy link
Copy Markdown
Member Author

Force-push 465ced1..91fac29 is a plain rebase onto master: the first commit (null check before the REJECT_COMPLEX datatype read) already landed as 75de25f and was dropped; the other six commits are unchanged (range-diff all =).

@hjmjohnson

Copy link
Copy Markdown
Member Author

@gdevenyi all four review points are addressed: rebased (first force-push, rebase only), then two new commits (second push, content only): aa5d71a refuses an ASCII ndim outside 1..7, and 4d64760 adds FAIL_REGULAR_EXPRESSION "runtime error|Sanitizer|leaked in" to every pass-regex test in this PR and the 32-bit alternatives. Could you re-review?

Checks run locally
  • All 16 tests from this PR pass under clang ASan + UBSan (-fno-sanitize-recover=undefined) and under gcc-16 -Wall -Wextra.
  • The new ndim tests fail with the library change reverted.
  • A scratch CTest project confirms a fail regex wins over a matching pass regex.
  • The 32-bit branch was checked by forcing it on a 64-bit configure and reading the test properties; no 32-bit build was run.
  • The trunc fixture keeps 2^32 bytes: 2^31 does not reproduce the old int vsize bug (master reports num_ext = 0 for it).

@hjmjohnson
hjmjohnson requested a review from gdevenyi November 14, 2026 15:33
gdevenyi and others added 8 commits November 14, 2026 09:38
Both NIFTI-2 header converters multiplied the dimensions into nvox
unchecked. Seven NIFTI-1 dims of 32767 overflow int64_t, a NIFTI-2
header needs two (found with libFuzzer under UBSan):

    nifti2_io.c:4838: runtime error: signed integer overflow

The wrong nvox then feeds nifti_get_volsize(), an allocation size and
a read length. Both products, and the volume size against SIZE_MAX for
32-bit targets, are now checked first; an overflowing header is refused
with a message and nifti_image_read() returns NULL. No valid image is
affected.
nifti_convert_nhdr2nim() in niftilib has the same unchecked loop on the
same untrusted path: seven dims of 32767 give nvox -1073512449, which
becomes the allocation size. It now refuses the header:

    ** ERROR: nifti_convert_nhdr2nim: dim[] overflows the voxel count

nvox is a size_t here, so the bound is SIZE_MAX, and nifti_get_volsize()
is size_t * size_t to match. Every dim is raised to at least 1 before
the loop, so the dim[ii] > 0 test never rejects; it guards the division.
nifti_update_dims_from_array() and update_nifti_image_for_brick_list()
compute nvox from caller-set dims, not a file header, and are left as
they are.
nifti_image_from_ascii() multiplied nx..nw from a .nia file into nvox
unchecked (nifti2_io.c:8937: signed integer overflow; NIFTI-1 wraps
silently). Each dim must now be positive, each step and nvox * nbyper
are checked as in the binary converters, and the header is refused with
a message. nifti_image_to_ascii() writes only the dims up to ndim, the
rest default to 1, so nothing it writes is refused.

nifti_read_ascii_image() cast the volume size to int to find the bytes
left for extensions, so a 2^32 byte volume truncated to 0 and the image
was read as extensions. The size is now compared in its own type, and
extensions are read only when the volume fits in the file.
Four fixtures, because the guards are reached separately: a NIFTI-1 and
a NIFTI-2 header whose dimensions wrap nvox, and a NIFTI-1 and a NIFTI-2
header whose nvox fits while nvox * nbyper does not. Without the guards
the tool accepts all four; it reports a negative nvox for the two that
wrap the voxel count.

The two NIFTI-1 fixtures live in niftilib/testdata, where the NIFTI-1
library tests use them too.

The regex pins which refusal fired; an exit-code test would not tell
this rejection apart from any other error.
nifti_convert_nhdr2nim carries its own copy of the guards, so it needs
its own tests; reverting the NIFTI-1 half alone leaves the nifti2 tests
green and turns exactly these two red.
Four .nia fixtures, read by both nifti1_tool and nifti_tool: seven
dimensions of 32767 (the voxel count overflows), a dimension of 0, a
float64 volume whose nvox fits while nvox * nbyper does not, and a
65536 x 65536 uint8 volume followed by a valid extension block.  That
volume is 2^32 bytes, which an int cast truncates to 0, so without the
guard the tool reads the image bytes as an extension and reports
num_ext = 1.

The fixtures sit in niftilib/testdata, which is always built; the
NIFTI-2 tests point there.
nifti_image_from_ascii() rejected ndim <= 0 but not ndim > 7, so a .nia
header with ndim = '99' was accepted, and callers that loop to ndim
index past dim[8]:

    nifti_tool.c:6913: runtime error: index 8 out of bounds
    for type 'int64_t[8]'

The binary header converters already refuse that range; the ASCII
reader now does too, with a message, in both libraries. Both tools
run the new fixture.
These tests pass on a regular expression, which makes CTest ignore the
exit code, so a sanitizer report printed beside the expected message
would pass. Each now also fails on "runtime error", "Sanitizer", or
"leaked in".

With a 32-bit size_t the voxel count (NIFTI-1) or the volume size
(NIFTI-2) overflows before the check a test is aimed at, so the header
is refused with that earlier message. On 32-bit only, the four affected
tests also accept it; 64-bit expectations are unchanged.
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