Skip to contentSkip to conversation

Another NBD CVE fix: incomplete read

PATCH In review Eric Blake 3 participants 15 messages Nov 13 – Nov 19 Block layer

lore
Share & tools
lore

Eric Blake

author
#0 lore raw

cover Another NBD CVE fix: incomplete read

https://gitlab.com/qemu-project/qemu/-/work_items/3815

This one is a bug with QEMU as NBD client leaking qemu heap data under the influence from a malicious server. Not as dramatic as the denial-of-service attacks that my two CVE fixes earlier this week (those were both assertion failures on QEMU as NBD server to a malicious client), but the data exfiltration may make other attacks on QEMU easier to pull off. As before, the ability to insist on TLS and perform x509 cert checks reduces the risk when you restrict NBD connections to assumed-safe servers.

Eric Blake (4):
nbd: Refactor structured payload interpretation
nbd: Pass back offset/length for all structured read replies nbd/client: Don't leak uninitialized memory on malicious server
nbd: Add iotest exposing previous CVE fix

 block/nbd.c                                   |  87 +++++--
 .../tests/nbd-structured-read-gaps            | 215 ++++++++++++++++++
 .../tests/nbd-structured-read-gaps.out        |   5 +
 3 files changed, 293 insertions(+), 14 deletions(-)
 create mode 100755 tests/qemu-iotests/tests/nbd-structured-read-gaps
 create mode 100644 tests/qemu-iotests/tests/nbd-structured-read-gaps.out
Signature · 1 line
2.56.0
author
#1 lore raw

PATCH 1/4 nbd: Refactor structured payload interpretation

An upcoming patch wants to reuse the payload of a structured reply chunk in further code for additional safety checks on the server's response. It will be easiest if the initial parse converts the payload from network order into host order along the way, so that I don't introduce subtle endian-specific bugs in that upcoming code. A quick audit shows that none of the current callers of payload_advance*() were reading a memory location within the payload after its initial parse.

---
 block/nbd.c | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)
block/nbd.c +15 -3
index e5e16722ba2..052469b3547 100644
@@ -578,24 +578,36 @@ err:
     return rc;
 }
 
+/* Consume a field of payload, while swapping it in place to host-endian. */
 static inline uint16_t payload_advance16(uint8_t **payload)
 {
+    uint16_t value = lduw_be_p(*payload);
+    stw_he_p(*payload, value);
     *payload += 2;
-    return lduw_be_p(*payload - 2);
+    return value;
 }
 
 static inline uint32_t payload_advance32(uint8_t **payload)
 {
+    uint32_t value = ldl_be_p(*payload);
+    stl_he_p(*payload, value);
     *payload += 4;
-    return ldl_be_p(*payload - 4);
+    return value;
 }
 
 static inline uint64_t payload_advance64(uint8_t **payload)
 {
+    uint64_t value = ldq_be_p(*payload);
+    stq_he_p(*payload, value);
     *payload += 8;
-    return ldq_be_p(*payload - 8);
+    return value;
 }
 
+/*
+ * nbd_parse_offset_hole_payload:
+ * Parse a chunk for NBD_REPLY_TYPE_OFFSET_HOLE, updating payload in
+ * place to a host-endian description of the region described.
+ */
 static int nbd_parse_offset_hole_payload(BDRVNBDState *s,
                                          NBDStructuredReplyChunk *chunk,
                                          uint8_t *payload, uint64_t orig_offset,
Signature · 1 line
2.56.0
Reviewed-by on v1 1/4
#2 lore raw

Re: [PATCH 1/4] nbd: Refactor structured payload interpretation

Quoted 9 lines · Eric Blake

An upcoming patch wants to reuse the payload of a structured reply chunk in further code for additional safety checks on the server's response. It will be easiest if the initial parse converts the payload from network order into host order along the way, so that I don't introduce subtle endian-specific bugs in that upcoming code. A quick audit shows that none of the current callers of payload_advance*() were reading a memory location within the payload after its initial parse.

Quoted 4 lines
---
 block/nbd.c | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)
author
#3 lore raw

PATCH 2/4 nbd: Pass back offset/length for all structured read replies

In reply to Eric Blake

The NBD spec allows a server that has negotiated structured replies to respond in any order among its various reply chunks. Although most known servers happen to give replies in sequential order, QEMU must be prepared for a server that intentionally returns out-of-order read chunks (a malicious server could exploit that in an effort to attempt to convince QEMU to expose uninitialized memory to a guest that is using the NBD client as storage). Although this patch does not actually add any new validation of the server's response chunks, it does make it easier for the next patch to do so by providing a centralized location in the code. Now, in nbd_co_receive_cmdread_reply(), payload contains a host-endian offset+length after either the nbd_co_receive_one_chunk for OFFSET_DATA or the nbd_parse_offset_hole_payload() for OFFSET_HOLE.

---
 block/nbd.c | 45 +++++++++++++++++++++++++++++++++++----------
 1 file changed, 35 insertions(+), 10 deletions(-)
block/nbd.c +35 -10
index 052469b3547..d873892c197 100644
@@ -786,9 +786,17 @@ static int nbd_parse_error_payload(NBDStructuredReplyChunk *chunk,
     return 0;
 }
 
+/*
+ * nbd_co_receive_offset_data_payload:
+ * Helper to nbd_co_do_receive_one_chunk when server replies with
+ * structured reply to NBD_CMD_READ with an OFFSET_DATA chunk. On
+ * success, synthesize an NBDStructuredReadHole into @payload
+ * describing the same region that was populated into @qiov.
+ */
 static int coroutine_fn
 nbd_co_receive_offset_data_payload(BDRVNBDState *s, uint64_t orig_offset,
-                                   QEMUIOVector *qiov, Error **errp)
+                                   QEMUIOVector *qiov, void **payload,
+                                   Error **errp)
 {
     QEMUIOVector sub_qiov;
     uint64_t offset;
@@ -797,6 +805,7 @@ nbd_co_receive_offset_data_payload(BDRVNBDState *s, uint64_t orig_offset,
     NBDStructuredReplyChunk *chunk = &s->reply.structured;
 
     assert(nbd_reply_is_structured(&s->reply));
+    assert(payload);
 
     /* The NBD spec requires at least one byte of payload */
     if (chunk->length <= sizeof(offset)) {
@@ -826,6 +835,18 @@ nbd_co_receive_offset_data_payload(BDRVNBDState *s, uint64_t orig_offset,
     ret = qio_channel_readv_all(s->ioc, sub_qiov.iov, sub_qiov.niov, errp);
     qemu_iovec_destroy(&sub_qiov);
 
+    if (ret == 0) {
+        /*
+         * Give the caller a struct describing the same region we
+         * populated here, to allow for easier followup accounting
+         * between data and hole reads.
+         */
+        NBDStructuredReadHole *synth = g_new(NBDStructuredReadHole, 1);
+        synth->offset = offset;
+        synth->length = data_size;
+        *payload = synth;
+    }
+
     return ret < 0 ? -EIO : 0;
 }
 
@@ -867,18 +888,21 @@ static coroutine_fn int nbd_co_receive_structured_payload(
 
 /*
  * nbd_co_do_receive_one_chunk
+ * @qiov is non-NULL for NBD_CMD_READ, NULL for all other commands.
  * for simple reply:
  *   set request_ret to received reply error
- *   if qiov is not NULL: read payload to @qiov
+ *   if qiov is not NULL: read data to @qiov
+ *   either way, @payload stays NULL
  * for structured reply chunk:
- *   if error chunk: read payload, set @request_ret, do not set @payload
- *   else if offset_data chunk: read payload data to @qiov, do not set @payload
- *   else: read payload to @payload
+ *   if error chunk: read chunk payload, set @request_ret, @payload is NULL
+ *   else if offset_data chunk and @qiov: read data to @qiov, allocate
+ *     @payload as NBDStructuredReadHole describing region just populated
+ *   else: read payload to @payload; caller checks size and contents
  *
- * If function fails, @errp contains corresponding error message, and the
- * connection with the server is suspect.  If it returns 0, then the
- * transaction succeeded (although @request_ret may be a negative errno
- * corresponding to the server's error reply), and errp is unchanged.
+ * If function fails, @errp contains corresponding error message, @payload
+ * is NULL, and the connection with the server is suspect.  If it returns 0,
+ * then the transaction succeeded (although @request_ret may be a negative
+ * errno corresponding to the server's error reply), and errp is unchanged.
  */
 static coroutine_fn int nbd_co_do_receive_one_chunk(
         BDRVNBDState *s, uint64_t cookie, bool only_structured,
@@ -945,7 +969,7 @@ static coroutine_fn int nbd_co_do_receive_one_chunk(
 
         return nbd_co_receive_offset_data_payload(
                 s, nbd_request_by_cookie(s, cookie, &error_abort)->offset,
-                qiov, errp);
+                qiov, payload, errp);
     }
 
     if (nbd_reply_type_is_error(chunk->type)) {
@@ -1093,6 +1117,7 @@ static bool coroutine_fn nbd_reply_chunk_iter_receive(BDRVNBDState *s,
     return true;
 
 break_loop:
+    assert(payload == NULL || *payload == NULL);
     qemu_mutex_lock(&s->requests_lock);
     nbd_request_by_cookie(s, cookie, &error_abort)->coroutine = NULL;
     s->in_flight--;
Signature · 1 line
2.56.0
Reviewed-by on v1 2/4
#4 lore raw

Re: [PATCH 2/4] nbd: Pass back offset/length for all structured read replies

Quoted 14 lines · Eric Blake

The NBD spec allows a server that has negotiated structured replies to respond in any order among its various reply chunks. Although most known servers happen to give replies in sequential order, QEMU must be prepared for a server that intentionally returns out-of-order read chunks (a malicious server could exploit that in an effort to attempt to convince QEMU to expose uninitialized memory to a guest that is using the NBD client as storage). Although this patch does not actually add any new validation of the server's response chunks, it does make it easier for the next patch to do so by providing a centralized location in the code. Now, in nbd_co_receive_cmdread_reply(), payload contains a host-endian offset+length after either the nbd_co_receive_one_chunk for OFFSET_DATA or the nbd_parse_offset_hole_payload() for OFFSET_HOLE.

Quoted 4 lines
---
 block/nbd.c | 45 +++++++++++++++++++++++++++++++++++----------
 1 file changed, 35 insertions(+), 10 deletions(-)
author
#5 lore raw

PATCH 3/4 nbd/client: Don't leak uninitialized memory on malicious server

In reply to Eric Blake

The NBD spec permits servers to send out-of-order replies for a structured read, which the client must re-assemble into the final buffer of its NBD_CMD_READ request. The standard states a server must send chunks covering the entire region, but leaves the burden on the client for double-checking whether a server actually sent sufficient reply chunks. If the client never checks for a server omitting chunks, or even sending multiple chunks that re-write the same portion of the buffer, then the NBD spec says behavior is unspecified. But ever since we added structured reads to QEMU, the actual behavior is that we would end up silently leaking QEMU host heap contents into the guest's view, which the guest blindly assumes is legitimate data sent by the server. A proof of concept reported by Feifan Qian with the help of AI analysis demonstrated the ability to leak 0xa5 bytes from a qemu process with MALLOC_PERTURB_=165, which implies a malicious server can coerce QEMU into divulging other parts of its heap to a guest for exfiltration, where knowing unscrubbed heap contents may make further attacks against QEMU easier.

In terms of the security risk, a guest cannot detect when a server does a short reply, and may misbehave if successive reads of the same portion of the disk come back with different contents, based on changes to QEMU's heap between those reads, making it easy for an attacker to attempt to provoke a silent form of data corruption to guests, even though the server cannot control the actual sequence of guest reads or QEMU heap contents between those reads. And although modern computing tends to isolate heap contents to prevent cross-process leaks, it is feasible that a determined attacker could try to set up a scenario in a multi-tenant environment where a guest under attacker control using a disk backed by an NBD server supplied by the attacker could then exfiltrate unrelated information learned from other guests on the same host. As a mitigating factor, QEMU recommends that NBD client connections utilize TLS traffic and x509 certificates to avoid connecting to untrusted NBD servers. See also CVE-2022-0485 for a similar issue with clients being made more robust to a non-compliant server in libnbd.

It may be worth proposing a future enhancement to the NBD protocol to allow the client and server to negotiate an additional handshake guarantee that structured reads must occur in order (the client can detect a non-compliant server with less overhead, or even refuse to talk to a server that doesn't know the new protocol). But for now, tracking the highwater mark of what has been covered in the buffer, even if portions of the buffer get covered more than once, was sufficient to guarantee that data left uninitialized by the server is at least deterministic of showing as all zero in the guest's view.

Fixes CVE-2026-126657
Fixes f140e300 ("nbd: Minimal structured read for client", v2.11.0)
---
 block/nbd.c | 24 +++++++++++++++++++++++-
 1 file changed, 23 insertions(+), 1 deletion(-)
block/nbd.c +23 -1
index d873892c197..fb4295bb235 100644
@@ -1151,6 +1151,7 @@ nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t cookie,
     NBDReply reply;
     void *payload = NULL;
     Error *local_err = NULL;
+    uint64_t highwater = offset;
 
     NBD_FOREACH_REPLY_CHUNK(s, iter, cookie,
                             s->info.mode >= NBD_MODE_STRUCTURED,
@@ -1158,6 +1159,7 @@ nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t cookie,
     {
         int ret;
         NBDStructuredReplyChunk *chunk = &reply.structured;
+        NBDStructuredReadHole *slice = NULL;
 
         assert(nbd_reply_is_structured(&reply));
 
@@ -1165,8 +1167,9 @@ nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t cookie,
         case NBD_REPLY_TYPE_OFFSET_DATA:
             /*
              * special cased in nbd_co_receive_one_chunk, data is already
-             * in qiov
+             * in qiov, and payload is host-endian offset+length.
              */
+            slice = payload;
             break;
         case NBD_REPLY_TYPE_OFFSET_HOLE:
             ret = nbd_parse_offset_hole_payload(s, &reply.structured, payload,
@@ -1174,6 +1177,9 @@ nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t cookie,
             if (ret < 0) {
                 nbd_channel_error(s, ret);
                 nbd_iter_channel_error(&iter, ret, &local_err);
+            } else {
+                /* Successful parse swapped payload to host-endian. */
+                slice = payload;
             }
             break;
         default:
@@ -1187,10 +1193,26 @@ nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t cookie,
             }
         }
 
+        /* Initialize any region skipped by a malicious server. */
+        if (slice) {
+            if (slice->offset > highwater) {
+                qemu_iovec_memset(qiov, highwater - offset, 0,
+                                  slice->offset - highwater);
+            }
+            highwater = MAX(highwater, slice->offset + slice->length);
+        }
+
         g_free(payload);
         payload = NULL;
     }
 
+    /* Initialize any trailing region not touched by server. */
+    if (iter.only_structured && iter.ret == 0 &&
+        highwater < offset + qiov->size) {
+        qemu_iovec_memset(qiov, highwater - offset, 0,
+                          offset + qiov->size - highwater);
+    }
+
     error_propagate(errp, iter.err);
     *request_ret = iter.request_ret;
     return iter.ret;
Signature · 1 line
2.56.0
Reviewed-by on v1 3/4
#6 lore raw

Re: [PATCH 3/4] nbd/client: Don't leak uninitialized memory on malicious server

Quoted 52 lines · Eric Blake

The NBD spec permits servers to send out-of-order replies for a structured read, which the client must re-assemble into the final buffer of its NBD_CMD_READ request. The standard states a server must send chunks covering the entire region, but leaves the burden on the client for double-checking whether a server actually sent sufficient reply chunks. If the client never checks for a server omitting chunks, or even sending multiple chunks that re-write the same portion of the buffer, then the NBD spec says behavior is unspecified. But ever since we added structured reads to QEMU, the actual behavior is that we would end up silently leaking QEMU host heap contents into the guest's view, which the guest blindly assumes is legitimate data sent by the server. A proof of concept reported by Feifan Qian with the help of AI analysis demonstrated the ability to leak 0xa5 bytes from a qemu process with MALLOC_PERTURB_=165, which implies a malicious server can coerce QEMU into divulging other parts of its heap to a guest for exfiltration, where knowing unscrubbed heap contents may make further attacks against QEMU easier.

In terms of the security risk, a guest cannot detect when a server does a short reply, and may misbehave if successive reads of the same portion of the disk come back with different contents, based on changes to QEMU's heap between those reads, making it easy for an attacker to attempt to provoke a silent form of data corruption to guests, even though the server cannot control the actual sequence of guest reads or QEMU heap contents between those reads. And although modern computing tends to isolate heap contents to prevent cross-process leaks, it is feasible that a determined attacker could try to set up a scenario in a multi-tenant environment where a guest under attacker control using a disk backed by an NBD server supplied by the attacker could then exfiltrate unrelated information learned from other guests on the same host. As a mitigating factor, QEMU recommends that NBD client connections utilize TLS traffic and x509 certificates to avoid connecting to untrusted NBD servers. See also CVE-2022-0485 for a similar issue with clients being made more robust to a non-compliant server in libnbd.

It may be worth proposing a future enhancement to the NBD protocol to allow the client and server to negotiate an additional handshake guarantee that structured reads must occur in order (the client can detect a non-compliant server with less overhead, or even refuse to talk to a server that doesn't know the new protocol). But for now, tracking the highwater mark of what has been covered in the buffer, even if portions of the buffer get covered more than once, was sufficient to guarantee that data left uninitialized by the server is at least deterministic of showing as all zero in the guest's view.

Fixes CVE-2026-126657
Fixes f140e300 ("nbd: Minimal structured read for client", v2.11.0)
Quoted 3 lines
---
 block/nbd.c | 24 +++++++++++++++++++++++-
 1 file changed, 23 insertions(+), 1 deletion(-)
author
#7 lore raw

PATCH 4/4 nbd: Add iotest exposing previous CVE fix

In reply to Eric Blake

Feifan Qian posted a sample script generated with the help of AI that created a known-broken NBD server that intentionally replies to a structured read with only a subset of bytes, to expose the leak of heap data from qemu as an NBD client into an emulated IDE drive. Take the idea of that test, but simplify it into a qemu-io test (much lighter-weight NBD client, and easier access to see what bytes the NBD client code is passing on) that more closely resembles paradigms in my recent nbd-robustness iotest. Also, expand the test to cover multiple
scenarios: in addition to the original test demonstrating a prefix of 20 bytes with unwritten tail, I expanded it to cover out-of-order replies, a hole-only reply, and a completely empty reply.

Based-on: https://gitlab.com/qemu-project/qemu/-/work_items/3815
AI-used-for: tests

---
 .../tests/nbd-structured-read-gaps            | 215 ++++++++++++++++++
 .../tests/nbd-structured-read-gaps.out        |   5 +
 2 files changed, 220 insertions(+)
 create mode 100755 tests/qemu-iotests/tests/nbd-structured-read-gaps
 create mode 100644 tests/qemu-iotests/tests/nbd-structured-read-gaps.out
tests/qemu-iotests/tests/nbd-structured-read-gaps new file +215 -0
new file mode 100755
index 00000000000..9f8b3b8b20b
@@ -0,0 +1,215 @@
+#!/usr/bin/env python3
+# group: rw quick
+#
+# Test that NBD client zero-initializes any regions omitted by a server
+# sending incomplete or out-of-order structured read replies.
+#
+# Copyright (C) 2026 Red Hat, Inc.
+#
+# SPDX-License-Identifier: GPL-2.0-or-later
+
+import os
+import socket
+import struct
+import threading
+import iotests
+
+NBD_INIT_MAGIC = 0x4E42444D41474943
+NBD_OPTS_MAGIC = 0x49484156454F5054
+NBD_REP_MAGIC = 0x0003E889045565A9
+NBD_REQUEST_MAGIC = 0x25609513
+NBD_STRUCTURED_REPLY_MAGIC = 0x668E33EF
+
+NBD_FLAG_FIXED_NEWSTYLE = 1 << 0
+NBD_FLAG_NO_ZEROES = 1 << 1
+NBD_FLAG_HAS_FLAGS = 1 << 0
+
+NBD_OPT_ABORT = 2
+NBD_OPT_GO = 7
+NBD_OPT_STRUCTURED_REPLY = 8
+
+NBD_REP_ACK = 1
+NBD_REP_INFO = 3
+NBD_REP_ERR_UNSUP = (1 << 31) | 1
+NBD_INFO_EXPORT = 0
+
+NBD_CMD_READ = 0
+NBD_CMD_DISC = 2
+
+NBD_REPLY_FLAG_DONE = 1 << 0
+NBD_REPLY_TYPE_NONE = 0
+NBD_REPLY_TYPE_OFFSET_DATA = 1
+NBD_REPLY_TYPE_OFFSET_HOLE = 2
+
+
+def recvall(conn, size):
+    data = bytearray()
+    while len(data) < size:
+        chunk = conn.recv(size - len(data))
+        if not chunk:
+            raise EOFError("unexpected EOF")
+        data.extend(chunk)
+    return bytes(data)
+
+
+def send_option_reply(conn, option, reply_type, payload=b""):
+    conn.sendall(struct.pack(">QII", NBD_REP_MAGIC, option, reply_type))
+    conn.sendall(struct.pack(">I", len(payload)) + payload)
+
+
+def send_chunk(conn, flags, chunk_type, cookie, payload=b""):
+    hdr = struct.pack(">IHHQI", NBD_STRUCTURED_REPLY_MAGIC,
+                      flags, chunk_type, cookie, len(payload))
+    conn.sendall(hdr + payload)
+
+
+# Emulate a simple NBD server that only knows how to respond to 512-byte
+# structured reads from fixed offsets.
+class StructuredReadServer(threading.Thread):
+    def __init__(self, sock_path):
+        super().__init__(daemon=True)
+        self.sock_path = sock_path
+        self.ready = threading.Event()
+        self.error = None
+
+    def run(self):
+        try:
+            with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as srv:
+                srv.bind(self.sock_path)
+                srv.listen(1)
+                self.ready.set()
+                conn, _ = srv.accept()
+                with conn:
+                    conn.settimeout(10)
+                    self.negotiate(conn)
+                    self.transmission(conn)
+        except (OSError, EOFError, AssertionError, struct.error) as exc:
+            self.error = exc
+
+    def negotiate(self, conn):
+        conn.sendall(struct.pack(">QQH", NBD_INIT_MAGIC, NBD_OPTS_MAGIC,
+                                 NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES))
+        recvall(conn, 4)  # client flags
+
+        while True:
+            magic, option, length = struct.unpack(">QII", recvall(conn, 16))
+            assert magic == NBD_OPTS_MAGIC
+            if length:
+                recvall(conn, length)
+
+            if option == NBD_OPT_STRUCTURED_REPLY:
+                send_option_reply(conn, option, NBD_REP_ACK)
+            elif option == NBD_OPT_GO:
+                info = struct.pack(">HQH", NBD_INFO_EXPORT, 65536,
+                                   NBD_FLAG_HAS_FLAGS)
+                send_option_reply(conn, option, NBD_REP_INFO, info)
+                send_option_reply(conn, option, NBD_REP_ACK)
+                return
+            elif option == NBD_OPT_ABORT:
+                send_option_reply(conn, option, NBD_REP_ACK)
+                return
+            else:
+                send_option_reply(conn, option, NBD_REP_ERR_UNSUP)
+
+    def transmission(self, conn):
+        """Trigger several non-compliant server behaviors based on the
+        client's offset. A compliant server would supply all 512 bytes."""
+        while True:
+            try:
+                hdr = recvall(conn, 28)
+            except EOFError:
+                return
+            magic, _flags, cmd, cookie, offset, length = struct.unpack(
+                ">IHHQQI", hdr)
+            assert magic == NBD_REQUEST_MAGIC
+
+            if cmd == NBD_CMD_DISC:
+                return
+            assert cmd == NBD_CMD_READ and length == 512
+
+            if offset == 0:
+                # Case 1: Short prefix with FLAG_DONE
+                payload = struct.pack(">Q", offset) + b"QEMU_NBD_PREFIX_DATA"
+                send_chunk(conn, NBD_REPLY_FLAG_DONE,
+                           NBD_REPLY_TYPE_OFFSET_DATA, cookie, payload)
+            elif offset == 512:
+                # Case 2: Out-of-order chunks with gaps + NONE|DONE
+                send_chunk(conn, 0, NBD_REPLY_TYPE_OFFSET_DATA, cookie,
+                           struct.pack(">Q", 768) + (b"\x11" * 128))
+                send_chunk(conn, 0, NBD_REPLY_TYPE_OFFSET_DATA, cookie,
+                           struct.pack(">Q", 576) + (b"\x22" * 64))
+                send_chunk(conn, NBD_REPLY_FLAG_DONE,
+                           NBD_REPLY_TYPE_NONE, cookie)
+            elif offset == 1024:
+                # Case 3: Leading & trailing gaps around OFFSET_HOLE
+                send_chunk(conn, NBD_REPLY_FLAG_DONE,
+                           NBD_REPLY_TYPE_OFFSET_HOLE, cookie,
+                           struct.pack(">QI", 1280, 128))
+            elif offset == 1536:
+                # Case 4: Immediate NONE|DONE with zero chunks
+                send_chunk(conn, NBD_REPLY_FLAG_DONE,
+                           NBD_REPLY_TYPE_NONE, cookie)
+
+
+class TestNBDStructuredReadGaps(iotests.QMPTestCase):
+    def setUp(self):
+        self.sock_path = os.path.join(iotests.sock_dir, "nbd.sock")
+        self.server = StructuredReadServer(self.sock_path)
+        self.server.start()
+        self.assertTrue(self.server.ready.wait(5))
+
+    def tearDown(self):
+        self.server.join(timeout=5)
+        self.assertIsNone(self.server.error)
+        if os.path.exists(self.sock_path):
+            os.unlink(self.sock_path)
+
+    @staticmethod
+    def parse_read_v(out):
+        """Reconstruct raw bytes from `qemu-io -c 'read -v ...'` output."""
+        buf = bytearray()
+        for line in out.splitlines():
+            # Format: "00000000:  51 45 4d 55 ...  QEMU_NBD_PREFIX_"
+            if ":  " not in line:
+                continue
+            hex_col = line.split(":  ", 1)[1][:49]
+            buf.extend(int(b, 16) for b in hex_col.split())
+        return bytes(buf)
+
+    def test_incomplete_and_out_of_order_reads(self):
+        # Force heap perturbation so uninitialized bytes show up (if not
+        # already set in caller, this favors values of 0x5A in unused heap)
+        os.environ.setdefault("MALLOC_PERTURB_", "165")
+        nbd_uri = f"nbd+unix:///?socket={self.sock_path}"
+        out = iotests.qemu_io(
+            "-f", "raw",
+            "-c", "read -v 0 512",
+            "-c", "read -v 512 512",
+            "-c", "read -v 1024 512",
+            "-c", "read -v 1536 512",
+            nbd_uri
+        )
+        data = self.parse_read_v(out.stdout)
+        self.assertEqual(len(data), 2048)
+
+        # Case 1 [0..512): 20-byte prefix + 492 zeroed bytes
+        self.assertEqual(data[0:20], b"QEMU_NBD_PREFIX_DATA")
+        self.assertEqual(data[20:512], b"\x00" * 492)
+
+        # Case 2 [512..1024): 0x22 at [576..640), 0x11 at [768..896),
+        # zeroes elsewhere
+        self.assertEqual(data[512:576], b"\x00" * 64)
+        self.assertEqual(data[576:640], b"\x22" * 64)
+        self.assertEqual(data[640:768], b"\x00" * 128)
+        self.assertEqual(data[768:896], b"\x11" * 128)
+        self.assertEqual(data[896:1024], b"\x00" * 128)
+
+        # Case 3 [1024..1536): OFFSET_HOLE + leading/trailing gaps all zeroed
+        self.assertEqual(data[1024:1536], b"\x00" * 512)
+
+        # Case 4 [1536..2048): empty NONE|DONE all zeroed
+        self.assertEqual(data[1536:2048], b"\x00" * 512)
+
+
+if __name__ == "__main__":
+    iotests.main(supported_protocols=["nbd"])
tests/qemu-iotests/tests/nbd-structured-read-gaps.out new file +5 -0
new file mode 100644
index 00000000000..ae1213e6f86
@@ -0,0 +1,5 @@
+.
+----------------------------------------------------------------------
+Ran 1 tests
+
+OK
Signature · 1 line
2.56.0
#8 lore raw

Re: [PATCH 4/4] nbd: Add iotest exposing previous CVE fix

Quoted 12 lines · Eric Blake

Feifan Qian posted a sample script generated with the help of AI that created a known-broken NBD server that intentionally replies to a structured read with only a subset of bytes, to expose the leak of heap data from qemu as an NBD client into an emulated IDE drive. Take the idea of that test, but simplify it into a qemu-io test (much lighter-weight NBD client, and easier access to see what bytes the NBD client code is passing on) that more closely resembles paradigms in my recent nbd-robustness iotest. Also, expand the test to cover multiple
scenarios: in addition to the original test demonstrating a prefix of 20 bytes with unwritten tail, I expanded it to cover out-of-order replies, a hole-only reply, and a completely empty reply.

Quoted 3 lines

Based-on: https://gitlab.com/qemu-project/qemu/-/work_items/3815
AI-used-for: tests

QEMU's current AI policy forbids AI-generated code.

Quoted 14 lines
---
 .../tests/nbd-structured-read-gaps            | 215 ++++++++++++++++++
 .../tests/nbd-structured-read-gaps.out        |   5 +
 2 files changed, 220 insertions(+)
 create mode 100755 tests/qemu-iotests/tests/nbd-structured-read-gaps
 create mode 100644 tests/qemu-iotests/tests/nbd-structured-read-gaps.out
tests/qemu-iotests/tests/nbd-structured-read-gaps new file +0 -0
new file mode 100755
index 00000000000..9f8b3b8b20b

tests/qemu-iotests/tests/nbd-structured-read-gaps line 2

Quoted 2 lines
tests/qemu-iotests/tests/nbd-structured-read-gaps new file +2 -0
@@ -0,0 +1,215 @@
+#!/usr/bin/env python3
+# group: rw quick

Does this run in CI without the "auto" group?

author
#9 lore raw

Re: [PATCH 4/4] nbd: Add iotest exposing previous CVE fix

Quoted 13 lines · Stefan Hajnoczi
Quoted 12 lines · Eric Blake

Feifan Qian posted a sample script generated with the help of AI that created a known-broken NBD server that intentionally replies to a structured read with only a subset of bytes, to expose the leak of heap data from qemu as an NBD client into an emulated IDE drive. Take the idea of that test, but simplify it into a qemu-io test (much lighter-weight NBD client, and easier access to see what bytes the NBD client code is passing on) that more closely resembles paradigms in my recent nbd-robustness iotest. Also, expand the test to cover multiple
scenarios: in addition to the original test demonstrating a prefix of 20 bytes with unwritten tail, I expanded it to cover out-of-order replies, a hole-only reply, and a completely empty reply.

Quoted 5 lines
Quoted 3 lines

Based-on: https://gitlab.com/qemu-project/qemu/-/work_items/3815
AI-used-for: tests

QEMU's current AI policy forbids AI-generated code.

This tag is based on the ongoing discussion about AGENTS.md and code-provenance.rst:

https://lists.gnu.org/archive/html/qemu-devel/2026-09/msg09158.html
https://lists.gnu.org/archive/html/qemu-devel/2026-10/msg00110.html
(and elsewhere)

At present, as of commit 1915e810d, use of AI-assisted unit tests is still not approved for upstream. And it appears that I started writing this patch before that AGENTS.md change landed, because with that patch in place, my LLM should have tried harder to dissuade me from posting.

I agree that my starting point of Feifan's reproduction script, which already documented AI assistance, already puts this patch on shaky ground, no matter how much or little else I further did with an LLM while polishing it into a more complete test (while I can attest to understanding every line of this patch and am not blindly trusting AI output, I genuinely cannot state that the patch is free from AI influence, despite the differences between here and the original reproduction script on gitlab). Therefore, I agree that this patch cannot be applied until that discussion results in an upstream patch.

I don't know of any other easy way to prove that the CVE is fixed; nbdkit does not support out-of-order structured read replies, and intentionally writing a known-non-compliant NBD server is grunt work. In the past, when fixing NBD protocol corner cases in QEMU, I have resorted to including reproduction instructions that could not be easily automated into unit tests to instead occur as part of the commit message in the form of a quoted patch that could be applied to QEMU - certainly not as automatable, but still strengthens the power of the git log (see commit 6e280648, for an example), and something I am capable of doing without LLM assistance. For the sake of getting the CVE fix into the 11.2 release, I could repeat that framework:
amend patch 3/4 to call out more detailed instructions on how to patch QEMU into behaving as a triggering known-broken server, do a pull request on just 1-3, and omit patch 4/4 entirely (saving it for a future day when our LLM policy is relaxed).

Quoted 9 lines
Quoted 9 lines
---
 .../tests/nbd-structured-read-gaps            | 215 ++++++++++++++++++
 .../tests/nbd-structured-read-gaps.out        |   5 +
 2 files changed, 220 insertions(+)
 create mode 100755 tests/qemu-iotests/tests/nbd-structured-read-gaps
 create mode 100644 tests/qemu-iotests/tests/nbd-structured-read-gaps.out
Quoted 10 lines

tests/qemu-iotests/tests/nbd-structured-read-gaps line 2

Quoted 8 lines
tests/qemu-iotests/tests/nbd-structured-read-gaps new file +2 -0
new file mode 100755
index 00000000000..9f8b3b8b20b
@@ -0,0 +1,215 @@
+#!/usr/bin/env python3
+# group: rw quick

Does this run in CI without the "auto" group?

Huh. It looks like I based my template on a copy-and-paste of tests/qemu-nbd-snapshots (lacks "auto") rather than tests/nbd-commands or tests/nbd-robustness (include "auto"). I agree that "auto" makes sense here; the test completes in less than half a second. Not sure if that means qemu-nbd-snapshots should be updated as a separate patch.

But that doesn't matter for 11.2, since this patch needs to be excluded until LLM policy changes, and my proposed workaround does not affect the qemu-iotests directory at this time.

Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.
Virtualization:  qemu.org | libguestfs.org
#10 lore raw

Re: [PATCH 4/4] nbd: Add iotest exposing previous CVE fix

Quoted 14 lines · Eric Blake
Quoted 13 lines · Stefan Hajnoczi
Quoted 12 lines · Eric Blake

Feifan Qian posted a sample script generated with the help of AI that created a known-broken NBD server that intentionally replies to a structured read with only a subset of bytes, to expose the leak of heap data from qemu as an NBD client into an emulated IDE drive. Take the idea of that test, but simplify it into a qemu-io test (much lighter-weight NBD client, and easier access to see what bytes the NBD client code is passing on) that more closely resembles paradigms in my recent nbd-robustness iotest. Also, expand the test to cover multiple
scenarios: in addition to the original test demonstrating a prefix of 20 bytes with unwritten tail, I expanded it to cover out-of-order replies, a hole-only reply, and a completely empty reply.

Quoted 5 lines
Quoted 5 lines
Quoted 3 lines

Based-on: https://gitlab.com/qemu-project/qemu/-/work_items/3815
AI-used-for: tests

QEMU's current AI policy forbids AI-generated code.

OTOH nobody disagreed with latest policy sent by Paolo
(https://lore.kernel.org/qemu-devel/[email protected]/)
and Paolo said he'd get it merge during a community call (Tuesday, 5 or 6 weeks ago?) so personally I consider it accepted and being processed, only delayed. I hope this isn't a problem.

Quoted 38 lines

This tag is based on the ongoing discussion about AGENTS.md and code-provenance.rst:

https://lists.gnu.org/archive/html/qemu-devel/2026-09/msg09158.html
https://lists.gnu.org/archive/html/qemu-devel/2026-10/msg00110.html
(and elsewhere)

At present, as of commit 1915e810d, use of AI-assisted unit tests is still not approved for upstream. And it appears that I started writing this patch before that AGENTS.md change landed, because with that patch in place, my LLM should have tried harder to dissuade me from posting.

I agree that my starting point of Feifan's reproduction script, which already documented AI assistance, already puts this patch on shaky ground, no matter how much or little else I further did with an LLM while polishing it into a more complete test (while I can attest to understanding every line of this patch and am not blindly trusting AI output, I genuinely cannot state that the patch is free from AI influence, despite the differences between here and the original reproduction script on gitlab). Therefore, I agree that this patch cannot be applied until that discussion results in an upstream patch.

I don't know of any other easy way to prove that the CVE is fixed; nbdkit does not support out-of-order structured read replies, and intentionally writing a known-non-compliant NBD server is grunt work. In the past, when fixing NBD protocol corner cases in QEMU, I have resorted to including reproduction instructions that could not be easily automated into unit tests to instead occur as part of the commit message in the form of a quoted patch that could be applied to QEMU - certainly not as automatable, but still strengthens the power of the git log (see commit 6e280648, for an example), and something I am capable of doing without LLM assistance. For the sake of getting the CVE fix into the 11.2 release, I could repeat that framework:
amend patch 3/4 to call out more detailed instructions on how to patch QEMU into behaving as a triggering known-broken server, do a pull request on just 1-3, and omit patch 4/4 entirely (saving it for a future day when our LLM policy is relaxed).

#11 lore raw

Re: [PATCH 4/4] nbd: Add iotest exposing previous CVE fix

Quoted 19 lines · Philippe Mathieu-Daudé
Quoted 18 lines · Eric Blake
Quoted 17 lines · Stefan Hajnoczi
Quoted 15 lines · Eric Blake

Feifan Qian posted a sample script generated with the help of AI that created a known-broken NBD server that intentionally replies to a structured read with only a subset of bytes, to expose the leak of heap data from qemu as an NBD client into an emulated IDE drive. Take the idea of that test, but simplify it into a qemu-io test (much lighter-weight NBD client, and easier access to see what bytes the NBD client code is passing on) that more closely resembles paradigms in my recent nbd-robustness iotest. Also, expand the test to cover multiple
scenarios: in addition to the original test demonstrating a prefix of 20 bytes with unwritten tail, I expanded it to cover out-of-order replies, a hole-only reply, and a completely empty reply.

Based-on: https://gitlab.com/qemu-project/qemu/-/work_items/3815
AI-used-for: tests

Quoted 7 lines
Quoted 1 line
Quoted 1 line

QEMU's current AI policy forbids AI-generated code.

OTOH nobody disagreed with latest policy sent by Paolo
(https://lore.kernel.org/qemu-devel/[email protected]/)
and Paolo said he'd get it merge during a community call (Tuesday, 5 or 6 weeks ago?) so personally I consider it accepted and being processed, only delayed. I hope this isn't a problem.

The new policy is not in effect yet. There are maintainers who wanted to discuss it at QEMU Summit but we ran out of time, so it was deferred to the next KVM Community Call (November 24th).

If we merge this before there is a consensus, then we are overruling those who are not in agreement yet. I think it's too early.

Eric: is there a way to implement the tests in tests/qemu-iotests/nbd-fault-injector.py? At least that already contains the NBD server logic and it would just be a question of adding the specific server responses needed to exercise the block/nbd.c code paths.

Stefan

author
#12 lore raw

Re: [PATCH 4/4] nbd: Add iotest exposing previous CVE fix

Quoted 6 lines · Stefan Hajnoczi

The new policy is not in effect yet. There are maintainers who wanted to discuss it at QEMU Summit but we ran out of time, so it was deferred to the next KVM Community Call (November 24th).

If we merge this before there is a consensus, then we are overruling those who are not in agreement yet. I think it's too early.

Indeed, that's why I'm okay with not using patch 4 until the policy is actually upstream, whether that's on November 24th or after 11.2 is released.

Quoted 5 lines

Eric: is there a way to implement the tests in tests/qemu-iotests/nbd-fault-injector.py? At least that already contains the NBD server logic and it would just be a question of adding the specific server responses needed to exercise the block/nbd.c code paths.

I'll play with the idea. If I can get it working, it would be a bit stronger than my current approach of documenting a two-line hack patch to nbd/server.c that will trigger one instance of the behavior, in that it would be usable in a unit test rather than requiring the reader to take additional steps to do a one-off build.

Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.
Virtualization:  qemu.org | libguestfs.org
author
#13 lore raw

Re: [PATCH 4/4] nbd: Add iotest exposing previous CVE fix

Quoted 10 lines · Eric Blake
Quoted 4 lines

Eric: is there a way to implement the tests in tests/qemu-iotests/nbd-fault-injector.py? At least that already contains the NBD server logic and it would just be a question of adding the specific server responses needed to exercise the block/nbd.c code paths.

I'll play with the idea. If I can get it working, it would be a bit stronger than my current approach of documenting a two-line hack patch to nbd/server.c that will trigger one instance of the behavior, in that it would be usable in a unit test rather than requiring the reader to take additional steps to do a one-off build.

It turns out the bug is only triggered by structured replies, while nbd-fault-injector.py is currently only producing simple replies, so it is a bigger task to improve that file to the point of doing structured replies; and it is going to be faster for me to provide a one-off patch that makes a one-off build of QEMU non-compliant than to add features to a python script.

Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.
Virtualization:  qemu.org | libguestfs.org
author
#14 lore raw

Re: [PATCH 4/4] nbd: Add iotest exposing previous CVE fix

In reply to Eric Blake
Quoted 18 lines · Eric Blake

Feifan Qian posted a sample script generated with the help of AI that created a known-broken NBD server that intentionally replies to a structured read with only a subset of bytes, to expose the leak of heap data from qemu as an NBD client into an emulated IDE drive. Take the idea of that test, but simplify it into a qemu-io test (much lighter-weight NBD client, and easier access to see what bytes the NBD client code is passing on) that more closely resembles paradigms in my recent nbd-robustness iotest. Also, expand the test to cover multiple
scenarios: in addition to the original test demonstrating a prefix of 20 bytes with unwritten tail, I expanded it to cover out-of-order replies, a hole-only reply, and a completely empty reply.

Based-on: https://gitlab.com/qemu-project/qemu/-/work_items/3815
AI-used-for: tests

---

tests/qemu-iotests/tests/nbd-structured-read-gaps line 184

Quoted 7 lines
tests/qemu-iotests/tests/nbd-structured-read-gaps new file +7 -0
+
+    def test_incomplete_and_out_of_order_reads(self):
+        # Force heap perturbation so uninitialized bytes show up (if not
+        # already set in caller, this favors values of 0x5A in unused heap)
+        os.environ.setdefault("MALLOC_PERTURB_", "165")
+        nbd_uri = f"nbd+unix:///?socket={self.sock_path}"
+        out = iotests.qemu_io(

It turns out MALLOC_PERTURB_ does not help or hurt in this case; that's because qemu-io's read command is hardcoded to (re-)wipe memory buffers to 0xab before it calls blk_pread(). So setting MALLOC_PERTURB_=165 with the hopes of seeing 0x5a on fresh buffers and 0xa5 after free didn't change anything (the wipe to 0xab happens unconditionally in qemu-io), I'll drop it from this patch.

Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.
Virtualization:  qemu.org | libguestfs.org