Subject: Re: [PATCH v6 2/3] commit-graph: fix buffer read-overflow

From: SZEDER Gábor <[email-masked]>
Date: Wed, 20 Feb 2019 17:50:48 +0100

On Wed, Feb 20, 2019 at 03:55:58PM +0100, Ævar Arnfjörð Bjarmason wrote:
> > @@ -376,11 +377,15 @@ corrupt_graph_and_verify() {
> >  	data="${2:-\0}"
> >  	grepstr=$3
> >  	cd "$TRASH_DIRECTORY/full" &&
> > +	orig_size=$(wc -c < $objdir/info/commit-graph) &&
> > +	zero_pos=${4:-${orig_size}} &&
> >  	test_when_finished mv commit-graph-backup $objdir/info/commit-graph &&
> >  	cp $objdir/info/commit-graph commit-graph-backup &&
> >  	printf "$data" | dd of="$objdir/info/commit-graph" bs=1 seek="$pos" conv=notrunc &&
> > +	dd of="$objdir/info/commit-graph" bs=1 seek="$zero_pos" count=0 &&
> > +	dd if=/dev/zero of="$objdir/info/commit-graph" bs=1 seek="$zero_pos" count=$(($orig_size - $zero_pos)) &&
> 
> In the limited time I had to dig it starts failing at test 46, when
> count=0 is given. dd on NetBSD exits with 127 when given count=0 it
> seems.

So the first 'dd' is supposed to truncate the commit-graph file at
$zero_pos.  I don't think we need 'count=0' for that: in the absence
of the 'if=...' operand, 'dd' reads from standard input, which is
redirected from /dev/null in our test scripts, i.e. there is nothing
to read, and, consequently, there is nothing to write, either.

Though not strictly necessary, I would feel more comfortable if
'if=/dev/null' would be explicitly specified, and even more so with a
"# truncate at $zero_pos" comment above that command.

As to the second 'dd', I think we should not run it at all when count
would be zero, i.e. when $orig_size = $zero_pos, because in
combination with 'if=/dev/zero' it's asking for trouble.  According to
POSIX [1]:

  count=n
      Copy only n input blocks. If n is zero, it is unspecified
      whether no blocks or all blocks are copied.

Imagine a 'dd' that implements the second option: there are infinite
blocks in /dev/zero to copy!  OTOH, if an implementation chooses the
first option (e.g. the usual Linux 'dd' from coreutils), then both of
these 'dd' invocations will leave the commit-graph file as-is, so it
doesn't matter whether we run them or not.

[1] http://pubs.opengroup.org/onlinepubs/9699919799/utilities/dd.html