Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
f06417f
AVRO-4299: [perl] Validate available bytes before allocating for leng…
iemejia Jul 11, 2026
e51a7b1
AVRO-4299: [perl] Avoid explicit return undef in _bytes_remaining
iemejia Jul 11, 2026
92df248
AVRO-4299: [perl] Reject negative lengths; restore position robustly;…
iemejia Jul 11, 2026
98aaeb6
AVRO-4299: [perl] Compare collection size via division to avoid overflow
iemejia Jul 11, 2026
fa8332b
AVRO-4299: [perl] Reject short reads and negative skip lengths
iemejia Jul 11, 2026
9a4cf0a
AVRO-4299: [perl] Skip bytes relative to the current position
iemejia Jul 12, 2026
25ab8ab
AVRO-4299: [perl] Validate and relatively-skip bytes/fixed/block fields
iemejia Jul 12, 2026
8af98be
AVRO-4299: [perl] Reject a negative block size in skip_block
iemejia Jul 12, 2026
fce9c6a
AVRO-4299: [perl] Fix skip_block call signature for array/map skipping
iemejia Jul 12, 2026
ddca5b5
AVRO-4299: [perl] Cap zero-byte collection element allocation
iemejia Jul 12, 2026
384ef7e
AVRO-4299: [perl] Test INT64_MIN block count is bounded
iemejia Jul 12, 2026
f46ed3d
AVRO-4299: [perl] Apply structural cap to zero-byte collections; fix …
iemejia Jul 12, 2026
d53c40e
AVRO-4299: [perl] Validate available bytes before skipping a fixed
iemejia Jul 12, 2026
929db90
AVRO-4299: [perl] Force the availability check on seek-based skip paths
iemejia Jul 12, 2026
f2b4562
AVRO-4299: [perl] Count decoded map entries for cumulative caps
iemejia Jul 12, 2026
985cfa8
AVRO-4299: [perl] Bounds-check union and enum indices
iemejia Jul 12, 2026
afe56c5
AVRO-4299: [perl] Reject overlong varints in unsigned_varint
iemejia Jul 12, 2026
b3666f6
AVRO-4299: [perl] Treat a short read as a parse error in unsigned_varint
iemejia Jul 12, 2026
1778a63
AVRO-4299: [perl] Bound byte-sized skip blocks; reject negative decod…
iemejia Jul 13, 2026
58989e7
AVRO-4299: [perl] Descriptive skip_union out-of-range message
iemejia Jul 13, 2026
f83a2bf
AVRO-4299: [perl] Fix test comments: union index is a zig-zag int
iemejia Jul 13, 2026
fc5509a
AVRO-4299: [perl] Pin default limit in the huge-null-array test
iemejia Jul 13, 2026
8d8a8e4
AVRO-4299: [perl] skip_block size-vs-count check; make tests env-inde…
iemejia Jul 13, 2026
8c79c31
AVRO-4299: [perl] Correct zero-byte element test comment
iemejia Jul 13, 2026
d77e8b8
AVRO-4299: [perl] Bound zero-byte collection elements per datum, not …
iemejia Aug 6, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 121 additions & 2 deletions lang/perl/lib/Avro/BinaryDecoder.pm
Original file line number Diff line number Diff line change
Expand Up @@ -124,18 +124,130 @@ sub skip_bytes {
my $class = shift;
my $reader = pop;
my $size = decode_long($class, undef, undef, $reader);
$reader->seek($size, 0);
if ($size < 0) {
throw Avro::Schema::Error::Parse(
"Invalid negative bytes/string length: $size");
}
# Skip forward by $size bytes relative to the current position
# (SEEK_CUR); whence 0 (SEEK_SET) would incorrectly seek to the
# absolute offset $size.
$reader->seek($size, 1);
return;

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 25ab8ab: skip_bytes now calls _ensure_available before skipping (mirroring decode_bytes), so a declared length that exceeds the remaining bytes is rejected on a size-reporting reader instead of silently seeking past EOF, and a failed seek is treated as fatal.

While here I fixed the same absolute-vs-relative seek bug in two related paths that shared it: skip_fixed used seek(size, 0) (SEEK_SET) — now SEEK_CUR — and skip_block's negative-count branch ignored the block-size long, did an absolute seek of a negative offset, and re-looped on the same count (an infinite loop); it now reads the block size and skips it relatively. Added tests for skipping fixed/bytes writer fields absent from the reader schema and for rejecting an oversized skipped bytes length. Full suite (386 tests) and perlcritic pass.

}

sub decode_bytes {
my $class = shift;
my $reader = pop;
my $size = decode_long($class, undef, undef, $reader);
$reader->read(my $buf, $size);
if ($size < 0) {
throw Avro::Schema::Error::Parse(
"Invalid negative bytes/string length: $size");
}
_ensure_available($reader, $size);
my $nread = $reader->read(my $buf, $size);
if (!defined $nread || $nread != $size) {
# A short read means the input is truncated; failing here avoids
# returning an under-sized buffer and misaligning the decoder.
throw Avro::Schema::Error::Parse(
"Expected $size bytes but read " . (defined $nread ? $nread : 0));
}
return $buf;
}

## Reject a declared length that exceeds the bytes actually remaining before
## allocating for it, to guard against an out-of-memory attack from a malicious
## or truncated input. Only enforced for larger reads and when the reader can
## report its size via seek/tell; smaller reads and non-seekable readers fall
## through to a direct read.
use constant _MAX_UNCHECKED_READ => 1024 * 1024;

## Number of bytes still available to read, or undef when the reader cannot
## report its size. Used to reject a declared length or collection block count
## that exceeds the data actually available before allocating for it. Readers
## that do not support seeking to the end (e.g. a streaming decompressor) return
## undef, so the check is simply skipped for them.
sub _bytes_remaining {
my ($reader) = @_;
my $current = eval { $reader->tell };
return if !defined $current || $current < 0;

# Attempt to seek to the end. Readers that cannot (e.g. a streaming
# decompressor) leave the position unchanged; skip the check for them.
my $moved = eval { $reader->seek(0, 2) }; # SEEK_END
return if !$moved;

# We are now at the end. Record the end offset, then ALWAYS restore the
# original position. A restore failure leaves the reader corrupted for
# subsequent decoding, so treat it as fatal rather than continuing.
my $end = eval { $reader->tell };
unless (eval { $reader->seek($current, 0) }) { # SEEK_SET
throw Avro::Schema::Error::Parse(
"Failed to restore reader position after size check");
}
return if !defined $end || $end < 0;
return $end - $current;
}
Comment on lines +222 to +242

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 92df248: _bytes_remaining now always restores the original position after seeking to the end (even if reading the end offset fails) and treats a restore failure as fatal, so the reader is never silently left at EOF.


sub _ensure_available {
my ($reader, $size) = @_;
return if $size <= _MAX_UNCHECKED_READ;
my $remaining = _bytes_remaining($reader);
return unless defined $remaining;
Comment on lines +244 to +252

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 929db90: _ensure_available() now takes a $force flag that bypasses the <= 1 MiB fast path, so seek-based skip paths can always validate the bytes remaining while decode_bytes keeps the small-read fast path.

if ($size > $remaining) {
throw Avro::Schema::Error::Parse(
"Cannot read $size bytes, only $remaining remaining");
}
return;
}

## Minimum number of bytes a single value of the given schema can occupy on the
## wire. Used to reject an array/map block count that could not be backed by the
## bytes remaining. A type that can encode to zero bytes (null) returns 0, which
## disables the collection check for it (so an array of nulls is not falsely
## rejected).
sub _min_bytes_per_element {
my ($schema, $visited) = @_;
$visited ||= {};
my $type = $schema->type;
return 0 if $type eq 'null';
return 4 if $type eq 'float';
return 8 if $type eq 'double';
return $schema->size if $type eq 'fixed';
if ($type eq 'record' || $type eq 'error') {
my $id = "$schema"; # stringified reference as identity
return 0 if $visited->{$id};
$visited->{$id} = 1;
my $total = 0;
for my $field (@{ $schema->fields }) {
$total += _min_bytes_per_element($field->{type}, $visited);
}
delete $visited->{$id};
return $total;
}
# boolean, int, long, bytes, string, enum, union, array, map: >= 1 byte
# (a union encodes at least a 1-byte branch index).
return 1;
}

## Reject a collection (array or map) block whose declared element count could
## not be backed by the bytes actually remaining, before iterating. Skipped when
## the per-element minimum is zero or when the reader cannot report how many
## bytes remain.
sub _ensure_collection_available {
my ($reader, $count, $min_bytes) = @_;
return if $count <= 0 || $min_bytes <= 0;
my $remaining = _bytes_remaining($reader);
return unless defined $remaining;
# Compare via integer division rather than multiplying, so $count * $min_bytes
# cannot overflow/wrap (notably on 32-bit builds) and defeat the check.
if ($count > int($remaining / $min_bytes)) {
throw Avro::Schema::Error::Parse(
"Collection claims $count elements with at least $min_bytes bytes each, "
. "but only $remaining bytes are available");
}
Comment on lines +332 to +337

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in f46ed3d: _ensure_collection_available now applies the structural cap to every collection (including zero-byte elements) before the tighter zero-byte item cap, so raising MAX_COLLECTION_ITEMS above MAX_COLLECTION_STRUCTURAL can't bypass the structural guard.

return;
}

sub skip_string { &skip_bytes }
sub decode_string {
my $class = shift;
Expand Down Expand Up @@ -251,13 +363,15 @@ sub decode_array {
my @array;
my $writer_items = $writer_schema->items;
my $reader_items = $reader_schema->items;
my $min_bytes = _min_bytes_per_element($writer_items);
while ($block_count) {
my $block_size;
if ($block_count < 0) {
$block_count = -$block_count;
$block_size = decode_long($class, @_);
## XXX we can skip with $reader_schema?
Comment on lines 524 to 531

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed — decode_array now rejects a negative per-block byte-size.

}
_ensure_collection_available($reader, $block_count, $min_bytes);
for (1..$block_count) {
push @array, $class->decode(
writer_schema => $writer_items,
Expand Down Expand Up @@ -296,13 +410,18 @@ sub decode_map {
my $block_count = decode_long($class, @_);
my $writer_values = $writer_schema->values;
my $reader_values = $reader_schema->values;
# A map key is a non-empty string (decode_map rejects empty keys below), so
# its minimum on-wire size is 2 bytes: a 1-byte length prefix plus at least
# 1 byte of key data, in addition to the value.
my $min_bytes = 2 + _min_bytes_per_element($writer_values);
while ($block_count) {
my $block_size;
if ($block_count < 0) {
$block_count = -$block_count;
$block_size = decode_long($class, @_);
## XXX we can skip with $reader_schema?
Comment on lines 583 to 590

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed — decode_map now rejects a negative per-block byte-size, consistent with decode_array and skip_block.

}
_ensure_collection_available($reader, $block_count, $min_bytes);
for (1..$block_count) {
my $key = decode_string($class, @_);
unless (defined $key && length $key) {
Comment on lines +592 to 596

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Same — for (1..$block_count) in decode_map is the foreach-range form, which Perl iterates lazily without materializing the list (confirmed: no RSS growth for 200M). The count is also bounded by ensure_collection_available before the loop.

Expand Down
97 changes: 97 additions & 0 deletions lang/perl/t/03_bin_decode.t
Original file line number Diff line number Diff line change
Expand Up @@ -255,4 +255,101 @@ EOP
is $dec->{one}[0], 1.0, "kind of dumb test";
}

## A bytes/string value declares a length prefix; a malicious or truncated
## input can declare far more bytes than actually exist. On a seekable reader
## that is rejected before allocating for it.
{
my $bytes_schema = Avro::Schema->parse(q({ "type": "bytes" }));

## A length prefix declaring 100 MiB, with no payload following it.
my $enc = '';
Avro::BinaryEncoder->encode(
schema => Avro::Schema->parse(q({ "type": "long" })),
data => 100 * 1024 * 1024,
emit_cb => sub { $enc .= ${ $_[0] } },
);
open my $reader, '<', \$enc or die "Can't open memory file: $!";
throws_ok {
Avro::BinaryDecoder->decode(
writer_schema => $bytes_schema,
reader_schema => $bytes_schema,
reader => $reader,
);
} qr/Cannot read/, "oversized bytes length is rejected before allocating";

## A well-formed value above the check threshold whose data is present
## still decodes.
my $payload = 'x' x (2 * 1024 * 1024);
my $enc2 = '';
Avro::BinaryEncoder->encode(
schema => $bytes_schema,
data => $payload,
emit_cb => sub { $enc2 .= ${ $_[0] } },
);
open my $reader2, '<', \$enc2 or die "Can't open memory file: $!";
my $dec = Avro::BinaryDecoder->decode(
writer_schema => $bytes_schema,
reader_schema => $bytes_schema,
reader => $reader2,
);
is $dec, $payload, "within-limit bytes value still decodes";
}

## An array/map block declares an element count; a malicious or truncated input
## can declare far more elements than the remaining bytes could hold. The count
## is validated against the bytes remaining before iterating, using the minimum
## on-wire size of the element schema (so 0-byte elements like null are not
## falsely rejected).
sub encode_long {
my ($value) = @_;
my $enc = '';
Avro::BinaryEncoder->encode(
schema => Avro::Schema->parse(q({ "type": "long" })),
data => $value,
emit_cb => sub { $enc .= ${ $_[0] } },
);
return $enc;
}

{
my $array_schema = Avro::Schema->parse(q({ "type": "array", "items": "long" }));
my $enc = encode_long(1_000_000); # 1,000,000 longs, no element data
open my $reader, '<', \$enc or die "Can't open memory file: $!";
throws_ok {
Avro::BinaryDecoder->decode(
writer_schema => $array_schema,
reader_schema => $array_schema,
reader => $reader,
);
} qr/Collection claims/, "oversized array count is rejected before iterating";
}

{
my $map_schema = Avro::Schema->parse(q({ "type": "map", "values": "long" }));
my $enc = encode_long(1_000_000);
open my $reader, '<', \$enc or die "Can't open memory file: $!";
throws_ok {
Avro::BinaryDecoder->decode(
writer_schema => $map_schema,
reader_schema => $map_schema,
reader => $reader,
);
} qr/Collection claims/, "oversized map count is rejected before iterating";
}

{
## An array of nulls: null elements occupy zero bytes, so a large count is
## legitimate and must not be rejected.
my $array_schema = Avro::Schema->parse(q({ "type": "array", "items": "null" }));
my $count = 100_000;
my $enc = encode_long($count) . encode_long(0); # one block + end marker
open my $reader, '<', \$enc or die "Can't open memory file: $!";
my $dec = Avro::BinaryDecoder->decode(
writer_schema => $array_schema,
reader_schema => $array_schema,
reader => $reader,
);
is scalar(@$dec), $count, "array of nulls is not falsely rejected";
}

done_testing;
Loading