Skip to content

FieldBase.unpack pads a short read with rjust regardless of byte order, silently corrupting little-endian values #604

Description

@JarryShaw

FieldBase.unpack zero-pads a short read with rjust unconditionally. That is correct for a big-endian field and wrong for a little-endian one, where the padding lands in the low-order bytes and silently inflates the value.

Measured

pcapkit/corekit/fields/field.py:244:

value = struct.unpack(self.template, buffer[:length].rjust(length, b'\x00'))[0]

On origin/main (13a75dfcd), CPython 3.14.7, a UInt32Field given one octet where four are declared:

little  short read of 0x78 -> 2013265920   (expected 120)
big     short read of 0x78 -> 120          (expected 120)

0x78 becomes 0x78000000. No exception and no warning — the field returns a plausible integer that is wrong by seven orders of magnitude.

Why it matters

The short-read accommodation itself is deliberate (#431): a snapshot-truncated capture should still parse. The padding side, however, must follow the field's byte order — a truncated little-endian field has lost its high bytes, so the zeros belong on the right, not the left.

Classic PCAP files are little-endian on little-endian hosts, which is the common case, so this affects ordinary truncated captures rather than a crafted corner.

Reported effects beyond the wrong value

The #594 worker reports this as the confirmed root cause of the previously-noted unhandled MemoryError at pcapkit/protocols/protocol.py:1016 on dhcp_little_endian.pcapng truncated to 161 octets — an inflated length derived from a corrupted little-endian read is then used as an allocation size. That MemoryError had been observed twice before and attributed only to "the #431/#571 failure class"; this explains the mechanism. I have verified the value corruption above by direct execution but have not myself reproduced the MemoryError chain, so that link is reported rather than confirmed here.

It also reports ljust as the fix, verified safe against all 19 example captures and the relevant test files. Also not independently verified by me.

Notes

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions