From eb90411381f94b77bb5d8c265163c6aa0f30ba2e Mon Sep 17 00:00:00 2001 From: "Gabriel A. Devenyi" Date: Sat, 15 Aug 2026 16:27:21 -0400 Subject: [PATCH] BUG: Free the previous filename when an ASCII header repeats the attribute nifti_image_from_ascii() walks the attributes of an ASCII header and assigns the two filename fields with nim->fname = nifti_strdup(rhs) ; nim->iname = nifti_strdup(rhs) ; Nothing stops a header from carrying header_filename or image_filename twice, and nothing rejects the repeat, so the second assignment drops the first string. The input comes from a file, so the leak is attacker-controlled in size and count: one copy per repetition. Direct leak of 5 byte(s) in 1 object(s) allocated from: #0 malloc #1 nifti_strdup nifti2_io.c:1301 #2 nifti_image_from_ascii nifti2_io.c:8874 Freeing before the assignment costs one call and keeps the last value, which is what the function already documented by overwriting. The fields are NULL until the first assignment, and free(NULL) is defined, so no other path changes. The same two lines exist in nifti1_io.c and are fixed there too. Found by fuzzing nifti_image_from_ascii() with clang's libFuzzer under AddressSanitizer. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_014m231RPDZPDbYDVxawxpjG --- nifti2/nifti2_io.c | 2 ++ niftilib/nifti1_io.c | 2 ++ 2 files changed, 4 insertions(+) diff --git a/nifti2/nifti2_io.c b/nifti2/nifti2_io.c index 58b20841..43a26f71 100644 --- a/nifti2/nifti2_io.c +++ b/nifti2/nifti2_io.c @@ -8826,9 +8826,11 @@ nifti_image *nifti_image_from_ascii( const char *str, int * bytes_read ) nim->nifti_type = NIFTI_FTYPE_NIFTI2_2 ; } else if( strcmp(lhs,"header_filename") == 0 ){ + free(nim->fname) ; /* the attribute may appear more than once */ nim->fname = nifti_strdup(rhs) ; } else if( strcmp(lhs,"image_filename") == 0 ){ + free(nim->iname) ; nim->iname = nifti_strdup(rhs) ; } else if( strcmp(lhs,"sto_xyz_matrix") == 0 ){ diff --git a/niftilib/nifti1_io.c b/niftilib/nifti1_io.c index 1992b188..0580c629 100644 --- a/niftilib/nifti1_io.c +++ b/niftilib/nifti1_io.c @@ -6706,9 +6706,11 @@ nifti_image *nifti_image_from_ascii( const char *str, int * bytes_read ) nim->nifti_type = NIFTI_FTYPE_ASCII ; } else if( strcmp(lhs,"header_filename") == 0 ){ + free(nim->fname) ; /* the attribute may appear more than once */ nim->fname = nifti_strdup(rhs) ; } else if( strcmp(lhs,"image_filename") == 0 ){ + free(nim->iname) ; nim->iname = nifti_strdup(rhs) ; } else if( strcmp(lhs,"sto_xyz_matrix") == 0 ){