From 97999131722b5a2a457b917fbbec1b8188856800 Mon Sep 17 00:00:00 2001 From: saeednourian82 Date: Wed, 2 Dec 2026 00:29:00 +0330 Subject: [PATCH 1/4] qcow2: Decode a qcow2 image into a sparse raw file First step of loading a spawn from a VM image (#23). The decoder is pure Python and handles deflate and zstd compressed clusters and zero clusters. Backing files, encryption, external data files and extended L2 entries are rejected with a clear error, since none of them can be represented in the sparse raw output this produces. Signed-off-by: saeednourian82 --- src/kerf/qcow2.py | 244 +++++++++++++++++++++++++++++++++++++++++ tests/test_qcow2.py | 256 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 500 insertions(+) create mode 100644 src/kerf/qcow2.py create mode 100644 tests/test_qcow2.py diff --git a/src/kerf/qcow2.py b/src/kerf/qcow2.py new file mode 100644 index 0000000..28000cf --- /dev/null +++ b/src/kerf/qcow2.py @@ -0,0 +1,244 @@ +# Copyright 2026 Multikernel Technologies, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +qcow2 image decoding. + +Pure Python, no external commands. See docs/interop/qcow2.rst in the +QEMU source tree for the format. +""" + +import struct +import importlib +import zlib +import os +from dataclasses import dataclass +from typing import BinaryIO, Optional, Tuple + +from .exceptions import KerfError + + +class Qcow2Error(KerfError): + """Raised when a qcow2 image is malformed or uses an unsupported feature.""" + + +QCOW2_MAGIC = b"QFI\xfb" + +# Header bytes 0-71, big endian: magic, version, backing_file_offset, +# backing_file_size, cluster_bits, size, crypt_method, l1_size, +# l1_table_offset, refcount_table_offset, refcount_table_clusters, +# nb_snapshots, snapshots_offset +_HEADER_V2 = struct.Struct(">4sIQIIQIIQQIIQ") +# Header bytes 72-103, version 3 only: incompatible_features, +# compatible_features, autoclear_features, refcount_order, header_length +_HEADER_V3 = struct.Struct(">QQQII") +_COMPRESSION_TYPE_OFFSET = 104 + +_MIN_CLUSTER_BITS = 9 +_MAX_CLUSTER_BITS = 21 # QEMU refuses clusters above 2 MiB +_MAX_L1_BYTES = 32 * 1024 * 1024 # QEMU's own limit + +INCOMPAT_CORRUPT = 1 << 1 +INCOMPAT_EXTERNAL_DATA = 1 << 2 +INCOMPAT_COMPRESSION_TYPE = 1 << 3 +INCOMPAT_EXTENDED_L2 = 1 << 4 +_KNOWN_INCOMPAT = 0x1F # dirty (bit 0) is fine, we never read refcounts + +COMPRESSION_DEFLATE = 0 +COMPRESSION_ZSTD = 1 + + +@dataclass(frozen=True) +class Qcow2Header: + """The fields of a qcow2 header that decoding needs.""" + version: int + cluster_bits: int + size: int + l1_size: int + l1_table_offset: int + compression_type: int + + @property + def cluster_size(self) -> int: + return 1 << self.cluster_bits + + +def parse_header(data: bytes, file_size: int) -> Qcow2Header: + """ + Parse and validate a qcow2 header. + + Args: + data: The start of the image, at least its first 512 bytes + file_size: Size of the whole image file, to bound the offsets + + Raises: + Qcow2Error: If the image is malformed or needs an unsupported feature + """ + if len(data) < _HEADER_V2.size: + raise Qcow2Error("file is too small to be a qcow2 image") + + (magic, version, backing_offset, _backing_size, cluster_bits, size, + crypt_method, l1_size, l1_offset, _refcount_offset, _refcount_clusters, + _nb_snapshots, _snapshots_offset) = _HEADER_V2.unpack_from(data) + + if magic != QCOW2_MAGIC: + raise Qcow2Error("not a qcow2 image (bad magic)") + if version not in (2, 3): + raise Qcow2Error(f"unsupported qcow2 version {version}") + if not _MIN_CLUSTER_BITS <= cluster_bits <= _MAX_CLUSTER_BITS: + raise Qcow2Error(f"invalid qcow2 cluster size (cluster_bits={cluster_bits})") + if backing_offset: + raise Qcow2Error("qcow2 backing files are not supported") + if crypt_method: + raise Qcow2Error("qcow2 encryption is not supported") + + compression = COMPRESSION_DEFLATE + if version == 3: + v3_end = _HEADER_V2.size + _HEADER_V3.size + if len(data) < v3_end: + raise Qcow2Error("truncated qcow2 version 3 header") + incompat, _compat, _autoclear, _refcount_order, header_length = ( + _HEADER_V3.unpack_from(data, _HEADER_V2.size)) + if header_length < v3_end or header_length % 8 or header_length > len(data): + raise Qcow2Error(f"invalid qcow2 header length {header_length}") + if incompat & ~_KNOWN_INCOMPAT: + raise Qcow2Error( + f"qcow2 image uses unknown incompatible features {incompat & ~_KNOWN_INCOMPAT:#x}") + if incompat & INCOMPAT_CORRUPT: + raise Qcow2Error("qcow2 image is marked corrupt") + if incompat & INCOMPAT_EXTERNAL_DATA: + raise Qcow2Error("qcow2 external data files are not supported") + if incompat & INCOMPAT_EXTENDED_L2: + raise Qcow2Error("qcow2 extended L2 entries are not supported") + if incompat & INCOMPAT_COMPRESSION_TYPE: + # The field only exists if header_length reaches past it + if header_length > _COMPRESSION_TYPE_OFFSET: + compression = data[_COMPRESSION_TYPE_OFFSET] + if compression != COMPRESSION_ZSTD: + raise Qcow2Error(f"unknown qcow2 compression type {compression}") + + cluster_size = 1 << cluster_bits + l2_entries = cluster_size // 8 + clusters = (size + cluster_size - 1) >> cluster_bits + l1_needed = (clusters + l2_entries - 1) // l2_entries + if l1_size < l1_needed or l1_size * 8 > _MAX_L1_BYTES: + raise Qcow2Error(f"invalid qcow2 L1 table size {l1_size}") + if l1_offset % cluster_size or l1_offset + l1_size * 8 > file_size: + raise Qcow2Error("qcow2 L1 table lies outside the file") + + return Qcow2Header(version, cluster_bits, size, l1_size, l1_offset, compression) + + + +_OFFSET_MASK = 0x00FFFFFFFFFFFE00 # bits 9-55 of an L1/L2 entry +_COMPRESSED = 1 << 62 +_ZERO_FLAG = 1 +_HEADER_READ = 4096 + + +def _zstd_decompress(data: bytes, limit: int) -> bytes: + """Decompress one zstd frame, ignoring whatever follows it.""" + try: + zstandard = importlib.import_module("zstandard") + except ImportError: + raise Qcow2Error( + "the Python module 'zstandard' is required to decompress this image" + ) from None + try: + return zstandard.ZstdDecompressor().decompressobj().decompress(data)[:limit] + except zstandard.ZstdError as err: + raise Qcow2Error(f"cannot decompress qcow2 zstd cluster: {err}") from err + + +def _decompress(header: Qcow2Header, data: bytes) -> bytes: + limit = header.cluster_size + if header.compression_type == COMPRESSION_ZSTD: + return _zstd_decompress(data, limit) + try: + # Raw deflate: qcow2 stores no zlib header + return zlib.decompressobj(-zlib.MAX_WBITS).decompress(data, limit) + except zlib.error as err: + raise Qcow2Error(f"cannot decompress qcow2 cluster: {err}") from err + + +def _read_table(src: BinaryIO, offset: int, count: int, header: Qcow2Header, file_size: int) -> Tuple[int, ...]: + """Read a table of 64-bit big endian entries (an L1 or L2 table).""" + if offset % header.cluster_size or offset + count * 8 > file_size: + raise Qcow2Error("qcow2 table lies outside the file") + src.seek(offset) + raw = src.read(count * 8) + if len(raw) != count * 8: + raise Qcow2Error("qcow2 table is truncated") + return struct.unpack(f">{count}Q", raw) + + +def _cluster_data(src: BinaryIO, header: Qcow2Header, entry: int, file_size: int) -> Optional[bytes]: + """Return the bytes of the cluster an L2 entry describes, None if all zeros.""" + cluster_size = header.cluster_size + if entry & _COMPRESSED: + shift = 62 - (header.cluster_bits - 8) + offset = entry & ((1 << shift) - 1) + extra_sectors = (entry >> shift) & ((1 << (header.cluster_bits - 8)) - 1) + size = min((extra_sectors + 1) * 512 - (offset & 511), file_size - offset) + if size <= 0: + raise Qcow2Error("qcow2 compressed cluster lies outside the file") + src.seek(offset) + data = _decompress(header, src.read(size)) + else: + if entry & _ZERO_FLAG: + return None + host = entry & _OFFSET_MASK + if not host: + return None # unallocated; no backing file, so it reads as zeros + if host % cluster_size or host + cluster_size > file_size: + raise Qcow2Error("qcow2 data cluster lies outside the file") + src.seek(host) + data = src.read(cluster_size) + return None if data.count(0) == len(data) else data + + +def convert_to_raw(source: str, dest: str) -> int: + """ + Decode a qcow2 image into a sparse raw disk image. + + Only clusters that hold data are written, so the output stays sparse. + + Returns: + The virtual size of the disk in bytes + + Raises: + Qcow2Error: If the image is malformed or uses an unsupported feature + """ + with open(source, "rb") as src: + file_size = os.fstat(src.fileno()).st_size + header = parse_header(src.read(_HEADER_READ), file_size) + l1_table = _read_table(src, header.l1_table_offset, header.l1_size, + header, file_size) + per_l2 = header.cluster_size // 8 + with open(dest, "wb") as out: + out.truncate(header.size) + for l1_index, l1_entry in enumerate(l1_table): + l2_offset = l1_entry & _OFFSET_MASK + if not l2_offset: + continue # no L2 table: every cluster below it is zeros + l2_table = _read_table(src, l2_offset, per_l2, header, file_size) + for l2_index, entry in enumerate(l2_table): + guest = (l1_index * per_l2 + l2_index) << header.cluster_bits + if guest >= header.size: + break + data = _cluster_data(src, header, entry, file_size) + if data: + out.seek(guest) + out.write(data[:header.size - guest]) + return header.size diff --git a/tests/test_qcow2.py b/tests/test_qcow2.py new file mode 100644 index 0000000..5382c55 --- /dev/null +++ b/tests/test_qcow2.py @@ -0,0 +1,256 @@ +# Copyright 2026 Multikernel Technologies, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Tests for qcow2 image decoding. +""" + +import struct +import zlib + +import pytest + +from kerf.qcow2 import ( + COMPRESSION_DEFLATE, + QCOW2_MAGIC, + Qcow2Error, + convert_to_raw, + parse_header, +) + +# First 112 bytes of `qemu-img create -f qcow2 demo.qcow2 1G` +REAL_HEADER = bytes.fromhex(""" + 514649fb 00000003 00000000 00000000 + 00000000 00000010 00000000 40000000 + 00000000 00000002 00000000 00030000 + 00000000 00010000 00000001 00000000 + 00000000 00000000 00000000 00000000 + 00000000 00000000 00000000 00000000 + 00000004 00000070 00000000 00000000 +""") +FILE_SIZE = 197120 # file length reported by qemu-img info + +CS = 1 << 16 +PATTERN = bytes(range(256)) * (CS // 256) +SIZE = 4 * CS + 100 # five clusters, the last one partial + + +def patched(offset, value, data=REAL_HEADER): + """Return the image bytes with value written at offset.""" + buf = bytearray(data) + buf[offset:offset + len(value)] = value + return bytes(buf) + + +def test_parses_real_header(): + header = parse_header(REAL_HEADER, FILE_SIZE) + assert header.version == 3 + assert header.cluster_bits == 16 + assert header.cluster_size == 65536 + assert header.size == 1 << 30 + assert header.l1_size == 2 + assert header.l1_table_offset == 0x30000 + assert header.compression_type == COMPRESSION_DEFLATE + + +def test_parses_version_2_header(): + header = parse_header(patched(7, b"\x02")[:72], FILE_SIZE) + assert header.version == 2 + assert header.compression_type == COMPRESSION_DEFLATE + + +@pytest.mark.parametrize("data, message", [ + (b"\0" * 10, "too small"), + (patched(0, b"XXXX"), "magic"), + (patched(7, b"\x04"), "version"), + (patched(23, b"\x08"), "cluster size"), + (patched(15, b"\x01"), "backing"), + (patched(35, b"\x01"), "encryption"), + (patched(79, b"\x02"), "corrupt"), + (patched(79, b"\x04"), "external data"), + (patched(79, b"\x10"), "extended L2"), + (patched(79, b"\x20"), "unknown incompatible"), + (patched(39, b"\x01"), "L1 table size"), +]) +def test_rejects_unsupported_or_malformed(data, message): + with pytest.raises(Qcow2Error, match=message): + parse_header(data, FILE_SIZE) + + +def test_rejects_l1_table_outside_file(): + with pytest.raises(Qcow2Error, match="L1 table lies"): + parse_header(REAL_HEADER, 100000) + + +def zstd_compress(data): + """Compress one cluster with zstd, skipping the test without the module.""" + zstandard = pytest.importorskip("zstandard") + return zstandard.ZstdCompressor().compress(data) + + +def build_qcow2(size, clusters, cluster_bits=16): + """ + Build a qcow2 image in memory. + + clusters maps a guest cluster index to (kind, payload), kind being + "data", "zero" (preallocated, flagged as zeros), "deflate" or "zstd" + (payload is compressed here), "compressed" (payload is stored as + given, to make corrupt images), "outside" (an offset beyond the end + of the file) or "misaligned" (an offset that is not cluster aligned). + """ + cs = 1 << cluster_bits + per_l2 = cs // 8 + l1_size = -(-(-(-size // cs)) // per_l2) + img = bytearray(2 * cs) # header cluster, then the L1 table + + def alloc(data): + offset = len(img) + img.extend(data.ljust(cs, b"\0")) + return offset + + l2_tables = {} + for index, (kind, payload) in sorted(clusters.items()): + table = l2_tables.setdefault(index // per_l2, [0] * per_l2) + slot = index % per_l2 + if kind == "data": + table[slot] = alloc(payload) + elif kind == "zero": + table[slot] = alloc(b"\xcd" * cs) | 1 # preallocated, reads as zeros + elif kind == "outside": + table[slot] = 1 << 40 # aligned, but far beyond the end of the file + elif kind == "misaligned": + table[slot] = cs + 512 # inside the file, not cluster aligned + else: + if kind == "deflate": + comp = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS) + payload = comp.compress(payload) + comp.flush() + elif kind == "zstd": + payload = zstd_compress(payload) + assert len(payload) <= cs + shift = 62 - (cluster_bits - 8) + extra = (len(payload) - 1) // 512 + table[slot] = alloc(payload) | (extra << shift) | (1 << 62) + + l1_table = [0] * l1_size + for l1_index, table in l2_tables.items(): + l1_table[l1_index] = alloc(struct.pack(f">{per_l2}Q", *table)) | (1 << 63) + struct.pack_into(f">{l1_size}Q", img, cs, *l1_table) + + header = struct.pack( + ">4sIQIIQIIQQIIQQQQII", + QCOW2_MAGIC, 3, 0, 0, cluster_bits, size, 0, l1_size, cs, + 0, 0, 0, 0, # refcount table offset/clusters, snapshots count/offset + 0, 0, 0, 4, 112, # feature bitmasks, refcount_order, header_length + ) + img[:len(header)] = header + if any(kind == "zstd" for kind, _ in clusters.values()): + struct.pack_into(">Q", img, 72, 1 << 3) # incompatible: compression type + img[104] = 1 # compression_type = zstd + return bytes(img) + + +def expected_raw(size, clusters, cluster_bits=16): + """Return the raw disk that build_qcow2 should decode to.""" + cs = 1 << cluster_bits + raw = bytearray(size) + for index, (kind, payload) in clusters.items(): + if kind in ("zero", "compressed", "outside", "misaligned"): + continue + start = index * cs + chunk = payload[:size - start] + raw[start:start + len(chunk)] = chunk + return bytes(raw) + + +def convert(tmp_path, image): + """Write image to disk and decode it, returning the size and the raw file.""" + src = tmp_path / "disk.qcow2" + src.write_bytes(image) + dst = tmp_path / "disk.raw" + return convert_to_raw(str(src), str(dst)), dst + + +@pytest.mark.parametrize("clusters", [ + {}, + {0: ("data", PATTERN)}, + {0: ("data", PATTERN), 3: ("data", PATTERN[::-1])}, + {4: ("data", PATTERN)}, # the partial last cluster + {1: ("deflate", PATTERN), 2: ("zero", b"")}, + {0: ("data", PATTERN), 1: ("deflate", PATTERN[::-1]), 4: ("deflate", PATTERN)}, +]) +def test_decodes_clusters(tmp_path, clusters): + size, dst = convert(tmp_path, build_qcow2(SIZE, clusters)) + assert size == SIZE + assert dst.read_bytes() == expected_raw(SIZE, clusters) + + +def test_second_l2_table(tmp_path): + # 512-byte clusters: one L2 table covers 64 of them, so cluster 70 + # is reached through the second L1 entry + pattern = bytes(range(256)) * 2 + clusters = {3: ("data", pattern), 70: ("data", pattern[::-1])} + image = build_qcow2(128 * 512, clusters, cluster_bits=9) + size, dst = convert(tmp_path, image) + assert size == 128 * 512 + assert dst.read_bytes() == expected_raw(128 * 512, clusters, cluster_bits=9) + + +def test_output_is_sparse(tmp_path): + size = 64 * CS + _, dst = convert(tmp_path, build_qcow2(size, {5: ("data", PATTERN)})) + assert dst.stat().st_size == size + assert dst.stat().st_blocks * 512 < size // 2 + + +def test_rejects_truncated_image(tmp_path): + image = build_qcow2(SIZE, {0: ("data", PATTERN)}) + with pytest.raises(Qcow2Error, match="outside the file"): + convert(tmp_path, image[:-1]) # cuts the last-written L2 table + + +def test_rejects_corrupt_compressed_cluster(tmp_path): + image = build_qcow2(SIZE, {1: ("compressed", b"\xff" * 100)}) + with pytest.raises(Qcow2Error, match="decompress"): + convert(tmp_path, image) + + +def test_zero_flag_wins_over_preallocated_data(tmp_path): + clusters = {1: ("zero", b""), 2: ("data", PATTERN)} + _, dst = convert(tmp_path, build_qcow2(SIZE, clusters)) + assert dst.read_bytes() == expected_raw(SIZE, clusters) + + +@pytest.mark.parametrize("kind", ["outside", "misaligned"]) +def test_rejects_bad_data_cluster_offset(tmp_path, kind): + with pytest.raises(Qcow2Error, match="data cluster lies outside"): + convert(tmp_path, build_qcow2(SIZE, {1: (kind, b"")})) + + +def test_decodes_zstd_clusters(tmp_path): + clusters = {0: ("zstd", PATTERN), 2: ("data", PATTERN[::-1]), + 3: ("zstd", PATTERN[::-1])} + size, dst = convert(tmp_path, build_qcow2(SIZE, clusters)) + assert size == SIZE + assert dst.read_bytes() == expected_raw(SIZE, clusters) + + +def test_zstd_needs_the_module(tmp_path, monkeypatch): + image = build_qcow2(SIZE, {1: ("zstd", PATTERN)}) + + def missing(name): + raise ImportError(name) + + monkeypatch.setattr("importlib.import_module", missing) + with pytest.raises(Qcow2Error, match="zstandard"): + convert(tmp_path, image) From bcfd3390fad5efd748abb1be7bf97c748711d2ea Mon Sep 17 00:00:00 2001 From: saeednourian82 Date: Wed, 2 Dec 2026 14:33:48 +0330 Subject: [PATCH 2/4] qcow2: reject truncated and oversized compressed clusters Raise Qcow2Error when a compressed cluster does not expand to exactly cluster_size, for both deflate and zstd, and add tests. Also update the copyright headers. --- src/kerf/qcow2.py | 33 +++++++++++++++++++++------- tests/test_qcow2.py | 52 ++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 76 insertions(+), 9 deletions(-) diff --git a/src/kerf/qcow2.py b/src/kerf/qcow2.py index 28000cf..ef7cba8 100644 --- a/src/kerf/qcow2.py +++ b/src/kerf/qcow2.py @@ -1,4 +1,4 @@ -# Copyright 2026 Multikernel Technologies, Inc. +# Copyright 2026 Saeed Nourian # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import struct import importlib +import io import zlib import os from dataclasses import dataclass @@ -156,20 +157,36 @@ def _zstd_decompress(data: bytes, limit: int) -> bytes: "the Python module 'zstandard' is required to decompress this image" ) from None try: - return zstandard.ZstdDecompressor().decompressobj().decompress(data)[:limit] + reader = zstandard.ZstdDecompressor().stream_reader( + io.BytesIO(data), read_across_frames=False + ) + # One byte past the limit, so an oversized frame is detectable + return reader.read(limit + 1) except zstandard.ZstdError as err: raise Qcow2Error(f"cannot decompress qcow2 zstd cluster: {err}") from err def _decompress(header: Qcow2Header, data: bytes) -> bytes: + """Decompress one compressed cluster, which must expand to a full cluster.""" limit = header.cluster_size if header.compression_type == COMPRESSION_ZSTD: - return _zstd_decompress(data, limit) - try: - # Raw deflate: qcow2 stores no zlib header - return zlib.decompressobj(-zlib.MAX_WBITS).decompress(data, limit) - except zlib.error as err: - raise Qcow2Error(f"cannot decompress qcow2 cluster: {err}") from err + out = _zstd_decompress(data, limit) + else: + try: + # Raw deflate: qcow2 stores no zlib header + inflater = zlib.decompressobj(-zlib.MAX_WBITS) + out = inflater.decompress(data, limit) + if len(out) == limit: + # One more byte of output means the cluster is oversized + out += inflater.decompress(inflater.unconsumed_tail, 1) + except zlib.error as err: + raise Qcow2Error(f"cannot decompress qcow2 cluster: {err}") from err + if len(out) != limit: + raise Qcow2Error( + f"qcow2 compressed cluster is truncated or corrupt " + f"(expected {limit} bytes, got {'more' if len(out) > limit else len(out)})" + ) + return out def _read_table(src: BinaryIO, offset: int, count: int, header: Qcow2Header, file_size: int) -> Tuple[int, ...]: diff --git a/tests/test_qcow2.py b/tests/test_qcow2.py index 5382c55..ae45779 100644 --- a/tests/test_qcow2.py +++ b/tests/test_qcow2.py @@ -1,4 +1,4 @@ -# Copyright 2026 Multikernel Technologies, Inc. +# Copyright 2026 Saeed Nourian # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ Tests for qcow2 image decoding. """ +import random import struct import zlib @@ -254,3 +255,52 @@ def missing(name): monkeypatch.setattr("importlib.import_module", missing) with pytest.raises(Qcow2Error, match="zstandard"): convert(tmp_path, image) + + +def deflate_compress(data): + """Compress data as raw deflate, the way qcow2 stores it.""" + comp = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS) + return comp.compress(data) + comp.flush() + + +# Compressible, but not so much that cutting the stream leaves nothing to decode +NOISY = bytes(random.Random(1).choices(b"abcdefgh", k=CS)) + + +@pytest.mark.parametrize("kind", ["deflate", "zstd"]) +def test_rejects_short_compressed_cluster(tmp_path, kind): + # A valid stream that expands to less than a full cluster + image = build_qcow2(SIZE, {1: (kind, PATTERN[:CS // 2])}) + with pytest.raises(Qcow2Error, match="truncated or corrupt"): + convert(tmp_path, image) + + +def test_rejects_truncated_deflate_cluster(tmp_path): + payload = deflate_compress(NOISY) + image = build_qcow2(SIZE, {1: ("compressed", payload[:len(payload) // 2])}) + with pytest.raises(Qcow2Error, match="truncated or corrupt"): + convert(tmp_path, image) + + +def test_rejects_truncated_zstd_cluster(tmp_path): + payload = zstd_compress(NOISY) + # Cluster 0 only makes build_qcow2 mark the image as zstd + clusters = {0: ("zstd", PATTERN), + 1: ("compressed", payload[:len(payload) // 2])} + with pytest.raises(Qcow2Error, match="truncated or corrupt"): + convert(tmp_path, build_qcow2(SIZE, clusters)) + + +def test_rejects_oversized_deflate_cluster(tmp_path): + # A valid stream that expands to two clusters + payload = deflate_compress(PATTERN * 2) + image = build_qcow2(SIZE, {1: ("compressed", payload)}) + with pytest.raises(Qcow2Error, match="truncated or corrupt"): + convert(tmp_path, image) + + +def test_rejects_oversized_zstd_cluster(tmp_path): + payload = zstd_compress(PATTERN * 2) + clusters = {0: ("zstd", PATTERN), 1: ("compressed", payload)} + with pytest.raises(Qcow2Error, match="truncated or corrupt"): + convert(tmp_path, build_qcow2(SIZE, clusters)) From 484f452c2bc04220eb5182d31c060065972dd547 Mon Sep 17 00:00:00 2001 From: saeednourian82 Date: Wed, 2 Dec 2026 14:41:47 +0330 Subject: [PATCH 3/4] qcow2: do not clobber the source or leave partial output on failure Refuse to convert an image onto itself, remove the output file when decoding fails, and ignore L1 entries that lie past the end of the disk. --- src/kerf/qcow2.py | 49 +++++++++++++++++++++++++++++++-------------- tests/test_qcow2.py | 29 +++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 15 deletions(-) diff --git a/src/kerf/qcow2.py b/src/kerf/qcow2.py index ef7cba8..cc15a70 100644 --- a/src/kerf/qcow2.py +++ b/src/kerf/qcow2.py @@ -20,6 +20,7 @@ """ import struct +import contextlib import importlib import io import zlib @@ -225,11 +226,35 @@ def _cluster_data(src: BinaryIO, header: Qcow2Header, entry: int, file_size: int return None if data.count(0) == len(data) else data +def _write_clusters(src: BinaryIO, out: BinaryIO, header: Qcow2Header, + l1_table: Tuple[int, ...], file_size: int) -> None: + """Write every data cluster of the image to its place in the raw file.""" + per_l2 = header.cluster_size // 8 + out.truncate(header.size) + for l1_index, l1_entry in enumerate(l1_table): + first_guest = (l1_index * per_l2) << header.cluster_bits + if first_guest >= header.size: + break # the rest of the L1 table lies past the end of the disk + l2_offset = l1_entry & _OFFSET_MASK + if not l2_offset: + continue # no L2 table: every cluster below it is zeros + l2_table = _read_table(src, l2_offset, per_l2, header, file_size) + for l2_index, entry in enumerate(l2_table): + guest = first_guest + (l2_index << header.cluster_bits) + if guest >= header.size: + break + data = _cluster_data(src, header, entry, file_size) + if data: + out.seek(guest) + out.write(data[:header.size - guest]) + + def convert_to_raw(source: str, dest: str) -> int: """ Decode a qcow2 image into a sparse raw disk image. Only clusters that hold data are written, so the output stays sparse. + If decoding fails, no output file is left behind. Returns: The virtual size of the disk in bytes @@ -237,25 +262,19 @@ def convert_to_raw(source: str, dest: str) -> int: Raises: Qcow2Error: If the image is malformed or uses an unsupported feature """ + if os.path.exists(dest) and os.path.samefile(source, dest): + raise Qcow2Error("source and destination are the same file") with open(source, "rb") as src: file_size = os.fstat(src.fileno()).st_size header = parse_header(src.read(_HEADER_READ), file_size) l1_table = _read_table(src, header.l1_table_offset, header.l1_size, header, file_size) - per_l2 = header.cluster_size // 8 with open(dest, "wb") as out: - out.truncate(header.size) - for l1_index, l1_entry in enumerate(l1_table): - l2_offset = l1_entry & _OFFSET_MASK - if not l2_offset: - continue # no L2 table: every cluster below it is zeros - l2_table = _read_table(src, l2_offset, per_l2, header, file_size) - for l2_index, entry in enumerate(l2_table): - guest = (l1_index * per_l2 + l2_index) << header.cluster_bits - if guest >= header.size: - break - data = _cluster_data(src, header, entry, file_size) - if data: - out.seek(guest) - out.write(data[:header.size - guest]) + try: + _write_clusters(src, out, header, l1_table, file_size) + except BaseException: + # Do not leave a partial image behind that looks like a valid disk + with contextlib.suppress(OSError): + os.unlink(dest) + raise return header.size diff --git a/tests/test_qcow2.py b/tests/test_qcow2.py index ae45779..0fbce9a 100644 --- a/tests/test_qcow2.py +++ b/tests/test_qcow2.py @@ -304,3 +304,32 @@ def test_rejects_oversized_zstd_cluster(tmp_path): clusters = {0: ("zstd", PATTERN), 1: ("compressed", payload)} with pytest.raises(Qcow2Error, match="truncated or corrupt"): convert(tmp_path, build_qcow2(SIZE, clusters)) + + +def test_rejects_same_source_and_destination(tmp_path): + image = build_qcow2(SIZE, {0: ("data", PATTERN)}) + path = tmp_path / "disk.qcow2" + path.write_bytes(image) + with pytest.raises(Qcow2Error, match="same file"): + convert_to_raw(str(path), str(path)) + assert path.read_bytes() == image # the source must survive untouched + + +def test_failed_conversion_leaves_no_output(tmp_path): + clusters = {0: ("data", PATTERN), 1: ("compressed", b"\xff" * 100)} + src = tmp_path / "disk.qcow2" + src.write_bytes(build_qcow2(SIZE, clusters)) + dst = tmp_path / "disk.raw" + with pytest.raises(Qcow2Error): + convert_to_raw(str(src), str(dst)) + assert not dst.exists() + + +def test_ignores_l1_entries_past_the_end_of_the_disk(tmp_path): + clusters = {0: ("data", PATTERN)} + image = bytearray(build_qcow2(SIZE, clusters)) + struct.pack_into(">I", image, 36, 2) # l1_size: one entry more than needed + struct.pack_into(">Q", image, CS + 8, (1 << 63) | (1 << 40)) # bogus L2 offset + size, dst = convert(tmp_path, bytes(image)) + assert size == SIZE + assert dst.read_bytes() == expected_raw(SIZE, clusters) From 71038cc14f447cf1bfe1e97870ec8dd7a0649f68 Mon Sep 17 00:00:00 2001 From: saeednourian82 Date: Fri, 4 Dec 2026 01:18:53 +0330 Subject: [PATCH 4/4] qcow2: decode into a temp file, then move it into place A failed conversion no longer touches a pre-existing dest. --- src/kerf/qcow2.py | 22 ++++++++++++++-------- tests/test_qcow2.py | 22 ++++++++++++++++++++++ 2 files changed, 36 insertions(+), 8 deletions(-) diff --git a/src/kerf/qcow2.py b/src/kerf/qcow2.py index cc15a70..846cf7e 100644 --- a/src/kerf/qcow2.py +++ b/src/kerf/qcow2.py @@ -25,6 +25,7 @@ import io import zlib import os +import secrets from dataclasses import dataclass from typing import BinaryIO, Optional, Tuple @@ -254,7 +255,8 @@ def convert_to_raw(source: str, dest: str) -> int: Decode a qcow2 image into a sparse raw disk image. Only clusters that hold data are written, so the output stays sparse. - If decoding fails, no output file is left behind. + The output is written to a temporary file and moved to dest on success, + so if decoding fails, dest is left exactly as it was. Returns: The virtual size of the disk in bytes @@ -269,12 +271,16 @@ def convert_to_raw(source: str, dest: str) -> int: header = parse_header(src.read(_HEADER_READ), file_size) l1_table = _read_table(src, header.l1_table_offset, header.l1_size, header, file_size) - with open(dest, "wb") as out: - try: + # Decode into a temporary file next to dest and move it into place on + # success, so a failure never touches a pre-existing dest + tmp_name = f"{dest}.{secrets.token_hex(8)}.tmp" + fd = os.open(tmp_name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666) + try: + with os.fdopen(fd, "wb") as out: _write_clusters(src, out, header, l1_table, file_size) - except BaseException: - # Do not leave a partial image behind that looks like a valid disk - with contextlib.suppress(OSError): - os.unlink(dest) - raise + os.replace(tmp_name, dest) + except BaseException: + with contextlib.suppress(OSError): + os.unlink(tmp_name) + raise return header.size diff --git a/tests/test_qcow2.py b/tests/test_qcow2.py index 0fbce9a..02e6cc7 100644 --- a/tests/test_qcow2.py +++ b/tests/test_qcow2.py @@ -333,3 +333,25 @@ def test_ignores_l1_entries_past_the_end_of_the_disk(tmp_path): size, dst = convert(tmp_path, bytes(image)) assert size == SIZE assert dst.read_bytes() == expected_raw(SIZE, clusters) + + +def test_failure_keeps_existing_destination(tmp_path): + clusters = {0: ("data", PATTERN), 1: ("compressed", b"\xff" * 100)} + src = tmp_path / "disk.qcow2" + src.write_bytes(build_qcow2(SIZE, clusters)) + dst = tmp_path / "disk.raw" + dst.write_bytes(b"precious") + with pytest.raises(Qcow2Error): + convert_to_raw(str(src), str(dst)) + assert dst.read_bytes() == b"precious" + # No temporary file is left behind either + assert sorted(p.name for p in tmp_path.iterdir()) == ["disk.qcow2", "disk.raw"] + + +def test_success_replaces_existing_destination(tmp_path): + clusters = {0: ("data", PATTERN)} + (tmp_path / "disk.raw").write_bytes(b"old contents that are longer than nothing") + size, dst = convert(tmp_path, build_qcow2(SIZE, clusters)) + assert size == SIZE + assert dst.read_bytes() == expected_raw(SIZE, clusters) + assert sorted(p.name for p in tmp_path.iterdir()) == ["disk.qcow2", "disk.raw"]