Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
8 changes: 7 additions & 1 deletion archive/cpio.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
MAGIC = b"070701"
TRAILER = "TRAILER!!!"
_HEADER = 110 # 6-byte magic + 13 * 8-hex fields
_HEX_DIGITS = b"0123456789abcdefABCDEF"
# Fixed alignment keeps bytes reproducible across filesystems.
_BLOCK = 4096
# A newc name is a full path, so the kernel's initramfs unpacker bounds the namesize field by
Expand Down Expand Up @@ -81,7 +82,12 @@ def read(source: Source, start: int = 0) -> Iterator[Entry]:
raise ValueError(f"bad cpio magic at {off}: {source[off : off + 6]!r}")
# 13 8-hex fields: ino, mode, uid, gid, nlink, mtime, filesize, devmajor, devminor,
# rdevmajor, rdevminor, namesize, check.
f = [int(source[off + 6 + i * 8 : off + 6 + (i + 1) * 8], 16) for i in range(13)]
header = source[off + 6 : off + _HEADER]
# int() also accepts a sign, blanks and underscores. A negative filesize can point the next
# header offset back at this header, and the reader then loops forever.
if len(header) != _HEADER - 6 or header.strip(_HEX_DIGITS):
raise ValueError(f"bad cpio header at {off}: {header!r}")
f = [int(header[i * 8 : (i + 1) * 8], 16) for i in range(13)]
ino, mode, nlink, filesize, devmajor, devminor, namesize = (
f[0], f[1], f[4], f[6], f[7], f[8], f[11],
) # fmt: skip
Expand Down
9 changes: 9 additions & 0 deletions archive/cpio_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,15 @@ def test_reports_a_malformed_archive_as_the_input_error_it_is(self) -> None:
cpio.unpack(raw.fileno(), root / "dest")
self.assertIn("magic", str(raised.exception))

def test_a_negative_size_is_a_malformed_archive(self) -> None:
# The data of "demo" starts at offset 116. int() parses the filesize "-0000074" as -116, which
# would point the next header back at this one.
before = b"".join(b"%08X" % field for field in (0, stat.S_IFREG | 0o644, 0, 0, 1, 0))
after = b"".join(b"%08X" % field for field in (0, 0, 0, 0, 5, 0))
header = b"070701" + before + b"-0000074" + after + b"demo\0"
with self.assertRaisesRegex(ValueError, "bad cpio header at 0: .*-0000074"):
list(cpio.read(header))

def test_reports_what_actually_failed_when_an_entry_cannot_be_written(self) -> None:
with tempfile.TemporaryDirectory() as scratch:
root = Path(scratch)
Expand Down
Loading