[PATCH] bzip2recover: Use snprintf to build the output file name

Mark Wielaard mark@klomp.org
Tue Jun 30 09:50:15 GMT 2026


Hi Naveed,

On Fri, Jun 26, 2026 at 09:58:00PM +0530, Naveed Khan via Bzip2-devel wrote:
> The per-block output file name is built in outFileName[BZ_MAX_FILENAME]
> with sprintf(split, "rec%5d", wrBlock+1).  split is an interior pointer
> into outFileName, past any leading directory component of the input file
> name, so the bytes written here come right after attacker-influenced
> path data.
> 
> The write is currently safe only by way of two non-local invariants: the
> input file name is rejected up front once strlen(argv[1]) reaches
> BZ_MAX_FILENAME-20, and the number of blocks is limited by
> BZ_MAX_HANDLED_BLOCKS so the formatted value stays at five digits.  The
> comment on BZ_MAX_HANDLED_BLOCKS explicitly invites raising it, which
> would silently eat into that 20 byte margin.

As far as I know BZ_MAX_HANDLED_BLOCKS is really enough for
everybody. At least I haven't heard of anybody raising it (which of
course would involve a recompile, since it is a compile time
constant). But point taken.

> Bound the write with snprintf() using the space left after the directory
> prefix (BZ_MAX_FILENAME - ofs) so it can no longer overrun outFileName
> regardless of those invariants.  This also removes the deprecated
> sprintf(), which recent compilers flag under -Wdeprecated-declarations.
> 
> For valid input the result is unchanged: the "rec%5d" prefix always fits,
> so snprintf() writes exactly the same bytes.

This is also https://sourceware.org/bugzilla/show_bug.cgi?id=29280
Which contains the exact same fix, but doesn't have the extensive comment.

> ---
> diff --git a/bzip2recover.c b/bzip2recover.c
> index 8c79a90..e6c0a99 100644
> --- a/bzip2recover.c
> +++ b/bzip2recover.c
> @@ -490,7 +490,7 @@ Int32 main ( Int32 argc, Char** argv )
>  	 }
>  	 /* Now split points to the start of the basename. */
>           ofs  = split - outFileName;
> -         sprintf (split, "rec%5d", wrBlock+1);
> +         snprintf (split, BZ_MAX_FILENAME - ofs, "rec%5d", wrBlock+1);
>           for (p = split; *p != 0; p++) if (*p == ' ') *p = '0';
>           strcat (outFileName, inFileName + ofs);

Looks good. Committed with a reference to the above bug.

Thanks,

Mark


More information about the Bzip2-devel mailing list