Skip to contentSkip to conversation

Block layer patches

GIT PULL Applied Kevin Wolf 2 participants 8 messages Dec 1 Block layer

lore
Share & tools
lore
author
#1 lore raw

[PULL 5/6] block/dmg-lzfse: reject truncated LZFSE decodes

In reply to Kevin Wolf

From: Julio Faracco <[email protected]>

dmg_uncompress_lzfse_do() treated any non-zero lzfse_decode_buffer() return as success. A crafted DMG can declare a larger chunk output size than its LZFSE stream decodes to, so the uninitialized tail of uncompressed_chunk is handed to the guest as sector data -- a heap disclosure.

Fix this by requiring out_size == avail_out: if lzfse_decode_buffer() returns less than avail_out the decode was truncated and the chunk is rejected with an error. When the return value equals avail_out the stream may also have been oversized (destination too small), but that ambiguity is harmless -- the guest never sees stale data either way.

zlib and bzip2 chunk paths already enforce exact output size; LZFSE did not.

Fixes: CVE-2026-116483
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/4662

Message-ID: <[email protected]>

---
 block/dmg-lzfse.c | 15 ++++++++++-----
 1 file changed, 10 insertions(+), 5 deletions(-)
block/dmg-lzfse.c +10 -5
index 4ea0b9b20da..61b6d567c17 100644
@@ -37,12 +37,17 @@ static int dmg_uncompress_lzfse_do(char *next_in, unsigned int avail_in,
                                           (uint8_t *) next_in, avail_in,
                                           NULL);
 
-    /* We need to decode the single chunk only. */
-    /* So, out_size == avail_out is not an error here. */
-    if (out_size > 0) {
-        return out_size;
+    /*
+     * lzfse_decode_buffer() returns the number of bytes written to the
+     * destination buffer, or the destination capacity if the buffer is
+     * too small.  Reject any decode that did not fill the full chunk:
+     * a truncated decode would expose the uninitialized tail of the
+     * uncompressed_chunk buffer to the guest.
+     */
+    if (out_size < avail_out) {
+        return -1;
     }
-    return -1;
+    return out_size;
 }
 
 __attribute__((constructor))
Signature · 1 line
2.56.1
author
#2 lore raw

[PULL 2/6] tests/qemu-iotest: Add test for qcow2 image with empty reftable

In reply to Kevin Wolf

From: Peter Maydell <[email protected]>

This test creates a qcow2 image, manually zeroes out its entire reftable, and then runs 'qemu-img amend -o refcount_bits=64" on it. This used to cause qemu-img to crash; now we will report that the image can't be opened because it's corrupted.

Message-ID: <[email protected]>

---
 tests/qemu-iotests/315     | 59 ++++++++++++++++++++++++++++++++++++++
 tests/qemu-iotests/315.out |  9 ++++++
 2 files changed, 68 insertions(+)
 create mode 100755 tests/qemu-iotests/315
 create mode 100644 tests/qemu-iotests/315.out
tests/qemu-iotests/315 new file +59 -0
new file mode 100755
index 00000000000..ff1a22bddd5
@@ -0,0 +1,59 @@
+#!/usr/bin/env bash
+# group: rw auto quick
+#
+# Test handling of corrupt qcow2 file with all-zeroes reftable
+#
+# Copyright (c) 2026 Linaro Ltd
+#
+# SPDX-License-Identifier: GPL-2.0-or-later
+
+seq=`basename $0`
+echo "QA output created by $seq"
+
+status=1        # failure is the default!
+
+_cleanup()
+{
+    _cleanup_test_img
+}
+trap "_cleanup; exit \$status" 0 1 2 3 15
+
+# get standard environment, filters and checks
+. ./common.rc
+. ./common.filter
+
+# This tests qcow2-specific low-level functionality
+_supported_fmt qcow2
+_supported_proto file
+_supported_os Linux
+# We are going to check changing refcount_bits from 16 to 64,
+# so anything else is not supported
+_unsupported_imgopts 'refcount_bits=\([^1]\|.\([^6]\|$\)\)'
+
+echo
+echo "=== Testing empty refcount table ==="
+echo
+
+# Create an image, then modify it to zero out the entire reftable.
+# Check that this corrupted image doesn't cause qemu-img amend to crash.
+
+_make_test_img -o 'refcount_bits=16' 64K
+
+reftable_ofs=$(peek_file_be "$TEST_IMG" 48 8)
+reftable_clusters=$(peek_file_be "$TEST_IMG" 56 4)
+cluster_bits=$(peek_file_be "$TEST_IMG" 20 4)
+# Cluster size is (1 << cluster_bits). Zero out the data starting
+# at reftable_ofs for (cluster_size * reftable_clusters) bytes.
+reftable_size=$(((1 << cluster_bits) * reftable_clusters))
+
+dd "of=$TEST_IMG" "bs=1" "seek=$reftable_ofs" "count=$reftable_size" if=/dev/zero conv=notrunc >&/dev/null
+
+# This should complain that the image is corrupt
+$QEMU_IMG amend -f qcow2 -o refcount_bits=64 "$TEST_IMG" 2>&1
+
+# success, all done
+echo
+echo '*** done'
+rm -f $seq.full
+status=0
+
tests/qemu-iotests/315.out new file +9 -0
new file mode 100644
index 00000000000..91b718df5ca
@@ -0,0 +1,9 @@
+QA output created by 315
+
+=== Testing empty refcount table ===
+
+Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=65536
+qcow2: Marking image as corrupt: first refblock is empty; further corruption events will be suppressed
+qemu-img: Image is corrupt (first refblock is empty)
+
+*** done
Signature · 1 line
2.56.1
author
#3 lore raw

[PULL 3/6] block: Restore fast path for non-serialising requests

In reply to Kevin Wolf

Commit 0bd5a1b3d60c added a bdrv_wait_serialising_requests_locked() call without the fast path for bs->serialising_in_flight == 0, which was present in the bdrv_wait_serialising_requests() it replaced (removed in cf4f672c11d6). This causes performance regressions when there are no serialising requests in flight: Instead of just comparing the counter, this now has to iterate through the whole list of tracked requests.

Add the fast path back in bdrv_wait_serialising_requests_locked().

Now that all users of bs->serialising_in_flight hold the mutex, more changes could be made (e.g. it doesn't have to be atomic any more, or it could be changed to keep a separate list of serialising requests), but given how late we're in the release cycle, this is left for another day.

Fixes 0bd5a1b3d60c ('block: Fix corruption from broken RMW atomicity')

Message-ID: <[email protected]>

---
 block/io.c | 4 ++++
 1 file changed, 4 insertions(+)
block/io.c +4 -0
index e4568d4d244..5e2734e540a 100644
@@ -703,6 +703,10 @@ bdrv_wait_serialising_requests_locked(BdrvTrackedRequest *self)
 {
     BdrvTrackedRequest *req;
 
+    if (!qatomic_read(&self->bs->serialising_in_flight)) {
+        return;
+    }
+
     while ((req = bdrv_find_conflicting_request(self))) {
         /*
          * If this request is the active owner of the data blocks it accesses,
Signature · 1 line
2.56.1
author
#4 lore raw

[PULL 6/6] tests/qemu-iotests: cover the dmg LZFSE truncated-decode fix

In reply to Kevin Wolf

From: Julio Faracco <[email protected]>

Add a regression test for the LZFSE truncated-decode heap disclosure. It builds a minimal DMG (koly trailer, plist, BLKX block, LZFSE data fork) whose chunk declares two sectors of output while its LZFSE stream only decodes to one, and checks that reading the chunk now fails with an Input/output error instead of leaking stale heap bytes.

A valid single-sector DMG is verified first with qemu-io; if the 'dmg-lzfse module is missing' error occurs, the test is skipped. Any other failure is treated as a regression.

Message-ID: <[email protected]>

[kwolf: Fixed up pylint errors]
---
 tests/qemu-iotests/tests/dmg-lzfse-short     | 141 +++++++++++++++++++
 tests/qemu-iotests/tests/dmg-lzfse-short.out |   2 +
 2 files changed, 143 insertions(+)
 create mode 100755 tests/qemu-iotests/tests/dmg-lzfse-short
 create mode 100644 tests/qemu-iotests/tests/dmg-lzfse-short.out
tests/qemu-iotests/tests/dmg-lzfse-short new file +141 -0
new file mode 100755
index 00000000000..691f83f04b1
@@ -0,0 +1,141 @@
+#!/usr/bin/env python3
+# group: rw quick
+#
+# Regression test for the dmg LZFSE short-decode heap disclosure.
+#
+# Copyright (C) 2026 Red Hat, Inc.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+# A crafted DMG can declare a chunk output size larger than its LZFSE
+# stream actually produces.  dmg_uncompress_lzfse_do() used to accept
+# such a short decode and hand the untouched tail of the (unzeroed)
+# uncompressed chunk buffer to the guest -- a heap disclosure.  Reading
+# such a chunk must now fail with an I/O error instead.
+
+import base64
+import struct
+
+import iotests
+
+ULFO = 0x80000007  # LZFSE compressed block type
+SECTOR = 512
+
+
+def lzfse_uncompressed_stream(payload: bytes) -> bytes:
+    """A valid LZFSE stream: one uncompressed block + end-of-stream marker."""
+    return (b'bvx-' + struct.pack('<I', len(payload))  # uncompressed block
+            + payload
+            + b'bvx$')                                   # end of stream
+
+
+def build_dmg(stream: bytes, decl_sectors: int, total_sectors: int) -> bytes:
+    """
+    Build a minimal DMG with a single LZFSE chunk.  The chunk declares
+    decl_sectors sectors of output; when that exceeds what 'stream'
+    decodes to, the decoded output is truncated.
+    """
+    data_fork = stream
+
+    # BLKX ("mish") block: 204-byte header followed by one 40-byte entry.
+    mish = bytearray(204)
+    struct.pack_into('>I', mish, 0x00, 0x6d697368)        # 'mish' magic
+    struct.pack_into('>I', mish, 0x04, 1)                 # version
+    struct.pack_into('>Q', mish, 0x08, 0)                 # first sector number
+    struct.pack_into('>Q', mish, 0x10, total_sectors)     # sector count
+    struct.pack_into('>Q', mish, 0x18, 0)                 # data fork offset
+
+    entry = bytearray(40)
+    struct.pack_into('>I', entry, 0x00, ULFO)             # entry type
+    struct.pack_into('>Q', entry, 0x08, 0)                # sector number
+    struct.pack_into('>Q', entry, 0x10, decl_sectors)     # sector count
+    struct.pack_into('>Q', entry, 0x18, 0)                # compressed offset
+    struct.pack_into('>Q', entry, 0x20, len(data_fork))   # compressed length
+    mish += entry
+
+    xml = (b'<plist><dict><data>'
+           + base64.b64encode(bytes(mish))
+           + b'</data></dict></plist>')
+
+    buf = bytearray()
+    buf += data_fork
+    xml_off = len(buf)
+    buf += xml
+    koly_off = len(buf)
+
+    # UDIF trailer ("koly" block), 512 bytes, big-endian.
+    koly = bytearray(512)
+    struct.pack_into('>4s', koly, 0x000, b'koly')         # signature
+    struct.pack_into('>I',  koly, 0x004, 4)               # version
+    struct.pack_into('>I',  koly, 0x008, 512)             # header size
+    struct.pack_into('>Q',  koly, 0x018, 0)               # DataForkOffset
+    struct.pack_into('>Q',  koly, 0x020, len(data_fork))  # DataForkLength
+    struct.pack_into('>Q',  koly, 0x028, 0)               # RsrcForkOffset
+    struct.pack_into('>Q',  koly, 0x030, 0)               # RsrcForkLength
+    struct.pack_into('>Q',  koly, 0x0d8, xml_off)         # XMLOffset
+    struct.pack_into('>Q',  koly, 0x0e0, len(xml))        # XMLLength
+    struct.pack_into('>q',  koly, 0x1ec, total_sectors)   # SectorCount
+    buf += koly
+
+    assert koly_off == len(buf) - 512
+    return bytes(buf)
+
+
+def main() -> None:
+    payload = b'\xab' * SECTOR
+
+    with iotests.FilePath('good.dmg') as good_path, \
+         iotests.FilePath('evil.dmg') as evil_path:
+
+        # A well-formed single-sector chunk must be readable.  Skip only
+        # when QEMU was built without the LZFSE module; treat any other
+        # failure as a real regression.
+        good = build_dmg(lzfse_uncompressed_stream(payload),
+                         decl_sectors=1, total_sectors=1)
+        with open(good_path, 'wb') as f:
+            f.write(good)
+
+        res = iotests.qemu_io('-f', 'dmg', '-r', '-c', 'read -P 0xab 0 512',
+                              good_path, check=False)
+        if res.returncode != 0:
+            if 'dmg-lzfse module is missing' in res.stdout:
+                iotests.notrun('LZFSE decompression not available')
+            iotests.log('FAIL: valid LZFSE chunk failed to read')
+            iotests.log(res.stdout)
+            return
+        iotests.log('valid LZFSE chunk reads: ok')
+
+        # Same 512-byte stream, but the chunk claims two sectors (1024 bytes).
+        # The decoded output is truncated and must be rejected with an I/O
+        # error.
+        evil = build_dmg(lzfse_uncompressed_stream(payload),
+                         decl_sectors=2, total_sectors=2)
+        with open(evil_path, 'wb') as f:
+            f.write(evil)
+
+        res = iotests.qemu_io('-f', 'dmg', '-r', '-c', 'read 0 1024',
+                              evil_path, check=False)
+        if res.returncode == 0:
+            iotests.log('FAIL: truncated LZFSE decode was accepted')
+            return
+        if 'Input/output error' not in res.stdout:
+            iotests.log('FAIL: unexpected error reading truncated LZFSE chunk')
+            iotests.log(res.stdout)
+            return
+        iotests.log('truncated LZFSE decode rejected: ok')
+
+
+iotests.script_main(main, supported_fmts=['dmg'],
+                    supported_protocols=['file'],
+                    supported_platforms=['linux'])
tests/qemu-iotests/tests/dmg-lzfse-short.out new file +2 -0
new file mode 100644
index 00000000000..03014a6d28a
@@ -0,0 +1,2 @@
+valid LZFSE chunk reads: ok
+truncated LZFSE decode rejected: ok
Signature · 1 line
2.56.1
author
#5 lore raw

[PULL 4/6] block/vhdx-log: Fix loop index type in vhdx_log_flush_desc()

In reply to Kevin Wolf

From: Peter Maydell <[email protected]>

In vhdx_log_flush_desc(), the when the log descriptor is a zero descriptor it has a 64-bit "zero_length" field telling us how many bytes of zeroes we should be writing. However, the 'i' variable we use as a loop index when we're actually writing out the zeroes is only of "int" type, so we will mishandle the descriptor if it specifies a large number of bytes.

Fix the type mismatch; since we're touching it anyway, restrict the variable to the minimum necessary scope (the loop).

Note that although this bug could cause us to spin in this loop performing disk writes for 2^31 iterations, the image could equally well ask us to do that directly, since the file format permits a valid log descriptor to specify a very large length. This is at most "guest self-DoS"; management applications should be imposing CPU and memory caps when they validate untrusted images.

Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/4019

Reported-by Tristan <https://gitlab.com/TristanInSec>
Fixes 0a43a1b5d7c33 ("block: vhdx - log parsing, replay, and flush support")

Message-ID: <[email protected]>

---
 block/vhdx-log.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
block/vhdx-log.c +1 -2
index 5c20468e1e6..6f2996ee3b8 100644
@@ -427,7 +427,6 @@ vhdx_log_flush_desc(BlockDriverState *bs, VHDXLogDescriptor *desc,
     uint32_t offset = 0;
     void *buffer = NULL;
     uint64_t count = 1;
-    int i;
 
     buffer = qemu_blockalign(bs, VHDX_LOG_SECTOR_SIZE);
 
@@ -473,7 +472,7 @@ vhdx_log_flush_desc(BlockDriverState *bs, VHDXLogDescriptor *desc,
     file_offset = desc->file_offset;
 
     /* count is only > 1 if we are writing zeroes */
-    for (i = 0; i < count; i++) {
+    for (uint64_t i = 0; i < count; i++) {
         ret = bdrv_pwrite_sync(bs->file, file_offset, VHDX_LOG_SECTOR_SIZE,
                                buffer, 0);
         if (ret < 0) {
Signature · 1 line
2.56.1

Kevin Wolf

author
#0 lore raw

The following changes since commit fae886567b48c672977acde6b775dd7e2d2121c1:

Merge tag 'hw-misc-20261130' of https://github.com/philmd/qemu into staging (2026-11-30 14:02:58 -0800)

are available in the Git repository at:

https://repo.or.cz/qemu/kevin.git tags/for-upstream

for you to fetch changes up to c06e442945b8c70b2369d1442fe2f4dc84b20a78:

tests/qemu-iotests: cover the dmg LZFSE truncated-decode fix (2026-12-01 15:03:28 +0100)

----------------------------------------------------------------
Block layer patches

- Fix performance regression for non-serialising requests
- qcow2, vhdx, dmg: Image validation fixes

----------------------------------------------------------------
Julio Faracco (2):
block/dmg-lzfse: reject truncated LZFSE decodes tests/qemu-iotests: cover the dmg LZFSE truncated-decode fix

Kevin Wolf (1):
block: Restore fast path for non-serialising requests

Peter Maydell (3):
block/qcow2: Detect corrupt images where first refcount block is empty tests/qemu-iotest: Add test for qcow2 image with empty reftable block/vhdx-log: Fix loop index type in vhdx_log_flush_desc()

 block/dmg-lzfse.c                            |  15 ++-
 block/io.c                                   |   4 +
 block/qcow2-refcount.c                       |  15 +++
 block/vhdx-log.c                             |   3 +-
 tests/qemu-iotests/315                       |  59 +++++++++++
 tests/qemu-iotests/315.out                   |   9 ++
 tests/qemu-iotests/tests/dmg-lzfse-short     | 141 +++++++++++++++++++++++++++
 tests/qemu-iotests/tests/dmg-lzfse-short.out |   2 +
 8 files changed, 241 insertions(+), 7 deletions(-)
 create mode 100755 tests/qemu-iotests/315
 create mode 100644 tests/qemu-iotests/315.out
 create mode 100755 tests/qemu-iotests/tests/dmg-lzfse-short
 create mode 100644 tests/qemu-iotests/tests/dmg-lzfse-short.out
author
#6 lore raw

[PULL 1/6] block/qcow2: Detect corrupt images where first refcount block is empty

From: Peter Maydell <[email protected]>

In a QCOW2 image, the header is always cluster zero, and so that cluster must have a non-zero refcount. This means that an image where the first entry in the refcount table is zero, or where it points to a refblock which is empty, must be corrupt. Detect this in alloc_refblock().

This fixes a bug where 'qemu-img amend -o refcount_bits=...' would crash on a corrupted image where the entire refcount table was empty. The crash happened because walk_over_reftable() would return with new_reftable_size == 0 and new_reftable == NULL. qcow2_change_refcount_table() updated s->refcount_table and s->refcount_table_size with these bogus values, and update_max_refcount_table_index() would crash trying to dereference NULL[UINT_MAX]. We add a defensive assertion here that the new refcount table isn't zero-sized; this can't be reached because it only happens in the corruption case that we now detect.

Fixes 791c9a004efbcff ("qcow2: Add function for refcount order amendment")

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3690

Reported-by a1gxer

Message-ID: <[email protected]>

---
 block/qcow2-refcount.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
block/qcow2-refcount.c +15 -0
index df7f6d2f234..2102386147a 100644
@@ -3139,6 +3139,14 @@ alloc_refblock(BlockDriverState *bs, uint64_t **reftable,
     BDRVQcow2State *s = bs->opaque;
     int64_t offset;
 
+    if (reftable_index == 0 && refblock_empty) {
+        /* The header is in cluster 0 so it must have a non-zero refcount */
+        qcow2_signal_corruption(bs, true, -1, -1,
+                                "first refblock is empty");
+        error_setg(errp, "Image is corrupt (first refblock is empty)");
+        return -EIO;
+    }
+
     if (!refblock_empty && reftable_index >= *reftable_size) {
         uint64_t *new_reftable;
         uint64_t new_reftable_size;
@@ -3451,6 +3459,13 @@ int qcow2_change_refcount_order(BlockDriverState *bs, int refcount_order,
         }
     } while (new_allocation);
 
+    /*
+     * This can only happen if the reftable is all zeroes, but the header is
+     * in cluster 0 and must have a non-zero refcount, and we check that in
+     * alloc_refblock().
+     */
+    assert(new_reftable_size != 0);
+
     /* Second, write the new refblocks */
     ret = walk_over_reftable(bs, &new_reftable, &new_reftable_index,
                              &new_reftable_size, new_refblock,
Signature · 1 line
2.56.1
#7 lore raw
In reply to Kevin Wolf
Quoted 10 lines · Kevin Wolf

The following changes since commit fae886567b48c672977acde6b775dd7e2d2121c1:

   Merge tag 'hw-misc-20261130' ofhttps://github.com/philmd/qemu into staging (2026-11-30 14:02:58 -0800)

are available in the Git repository at:

https://repo.or.cz/qemu/kevin.git tags/for-upstream

for you to fetch changes up to c06e442945b8c70b2369d1442fe2f4dc84b20a78:

Quoted 7 lines
   tests/qemu-iotests: cover the dmg LZFSE truncated-decode fix (2026-12-01 15:03:28 +0100)

----------------------------------------------------------------
Block layer patches

- Fix performance regression for non-serialising requests
- qcow2, vhdx, dmg: Image validation fixes

Applied, thanks.

r~