* [PATCH 1/4] nbd: Refactor structured payload interpretation
2026-11-13 22:34 [PATCH for-11.2 0/4] Another NBD CVE fix: incomplete read Eric Blake
@ 2026-11-13 22:34 ` Eric Blake
2026-11-17 18:06 ` Stefan Hajnoczi
2026-11-13 22:34 ` [PATCH 2/4] nbd: Pass back offset/length for all structured read replies Eric Blake
` (2 subsequent siblings)
3 siblings, 1 reply; 12+ messages in thread
From: Eric Blake @ 2026-11-13 22:34 UTC (permalink / raw)
To: qemu-devel
Cc: qemu-block, qemu-stable, bea1e, Vladimir Sementsov-Ogievskiy,
Kevin Wolf, Hanna Reitz
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.
Signed-off-by: Eric Blake <eblake@redhat.com>
---
block/nbd.c | 18 +++++++++++++++---
1 file changed, 15 insertions(+), 3 deletions(-)
diff --git a/block/nbd.c b/block/nbd.c
index e5e16722ba2..052469b3547 100644
--- a/block/nbd.c
+++ b/block/nbd.c
@@ -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,
--
2.56.0
^ permalink raw reply related [flat|nested] 12+ messages in thread* Re: [PATCH 1/4] nbd: Refactor structured payload interpretation
2026-11-13 22:34 ` [PATCH 1/4] nbd: Refactor structured payload interpretation Eric Blake
@ 2026-11-17 18:06 ` Stefan Hajnoczi
0 siblings, 0 replies; 12+ messages in thread
From: Stefan Hajnoczi @ 2026-11-17 18:06 UTC (permalink / raw)
To: Eric Blake
Cc: qemu-devel, qemu-block, qemu-stable, bea1e,
Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz
On Fri, Nov 13, 2026 at 04:34:49PM -0600, Eric Blake wrote:
> 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.
>
> Signed-off-by: Eric Blake <eblake@redhat.com>
> ---
> block/nbd.c | 18 +++++++++++++++---
> 1 file changed, 15 insertions(+), 3 deletions(-)
Reviewed-by: Stefan Hajnoczi <stefanha@redhat.com>
^ permalink raw reply [flat|nested] 12+ messages in thread
* [PATCH 2/4] nbd: Pass back offset/length for all structured read replies
2026-11-13 22:34 [PATCH for-11.2 0/4] Another NBD CVE fix: incomplete read Eric Blake
2026-11-13 22:34 ` [PATCH 1/4] nbd: Refactor structured payload interpretation Eric Blake
@ 2026-11-13 22:34 ` Eric Blake
2026-11-17 18:06 ` Stefan Hajnoczi
2026-11-13 22:34 ` [PATCH 3/4] nbd/client: Don't leak uninitialized memory on malicious server Eric Blake
2026-11-13 22:34 ` [PATCH 4/4] nbd: Add iotest exposing previous CVE fix Eric Blake
3 siblings, 1 reply; 12+ messages in thread
From: Eric Blake @ 2026-11-13 22:34 UTC (permalink / raw)
To: qemu-devel
Cc: qemu-block, qemu-stable, bea1e, Vladimir Sementsov-Ogievskiy,
Kevin Wolf, Hanna Reitz
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.
Signed-off-by: Eric Blake <eblake@redhat.com>
---
block/nbd.c | 45 +++++++++++++++++++++++++++++++++++----------
1 file changed, 35 insertions(+), 10 deletions(-)
diff --git a/block/nbd.c b/block/nbd.c
index 052469b3547..d873892c197 100644
--- a/block/nbd.c
+++ b/block/nbd.c
@@ -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--;
--
2.56.0
^ permalink raw reply related [flat|nested] 12+ messages in thread* Re: [PATCH 2/4] nbd: Pass back offset/length for all structured read replies
2026-11-13 22:34 ` [PATCH 2/4] nbd: Pass back offset/length for all structured read replies Eric Blake
@ 2026-11-17 18:06 ` Stefan Hajnoczi
0 siblings, 0 replies; 12+ messages in thread
From: Stefan Hajnoczi @ 2026-11-17 18:06 UTC (permalink / raw)
To: Eric Blake
Cc: qemu-devel, qemu-block, qemu-stable, bea1e,
Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz
On Fri, Nov 13, 2026 at 04:34:50PM -0600, Eric Blake wrote:
> 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.
>
> Signed-off-by: Eric Blake <eblake@redhat.com>
> ---
> block/nbd.c | 45 +++++++++++++++++++++++++++++++++++----------
> 1 file changed, 35 insertions(+), 10 deletions(-)
Reviewed-by: Stefan Hajnoczi <stefanha@redhat.com>
^ permalink raw reply [flat|nested] 12+ messages in thread
* [PATCH 3/4] nbd/client: Don't leak uninitialized memory on malicious server
2026-11-13 22:34 [PATCH for-11.2 0/4] Another NBD CVE fix: incomplete read Eric Blake
2026-11-13 22:34 ` [PATCH 1/4] nbd: Refactor structured payload interpretation Eric Blake
2026-11-13 22:34 ` [PATCH 2/4] nbd: Pass back offset/length for all structured read replies Eric Blake
@ 2026-11-13 22:34 ` Eric Blake
2026-11-17 18:06 ` Stefan Hajnoczi
2026-11-13 22:34 ` [PATCH 4/4] nbd: Add iotest exposing previous CVE fix Eric Blake
3 siblings, 1 reply; 12+ messages in thread
From: Eric Blake @ 2026-11-13 22:34 UTC (permalink / raw)
To: qemu-devel
Cc: qemu-block, qemu-stable, bea1e, Vladimir Sementsov-Ogievskiy,
Kevin Wolf, Hanna Reitz
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.
Reported-by: Feifan Qian <bea1e@proton.me>
Fixes: CVE-2026-126657
Fixes: https://gitlab.com/qemu-project/qemu/-/work_items/3815
Fixes: f140e300 ("nbd: Minimal structured read for client", v2.11.0)
CC: qemu-stable@nongnu.org
Signed-off-by: Eric Blake <eblake@redhat.com>
---
block/nbd.c | 24 +++++++++++++++++++++++-
1 file changed, 23 insertions(+), 1 deletion(-)
diff --git a/block/nbd.c b/block/nbd.c
index d873892c197..fb4295bb235 100644
--- a/block/nbd.c
+++ b/block/nbd.c
@@ -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;
--
2.56.0
^ permalink raw reply related [flat|nested] 12+ messages in thread* Re: [PATCH 3/4] nbd/client: Don't leak uninitialized memory on malicious server
2026-11-13 22:34 ` [PATCH 3/4] nbd/client: Don't leak uninitialized memory on malicious server Eric Blake
@ 2026-11-17 18:06 ` Stefan Hajnoczi
0 siblings, 0 replies; 12+ messages in thread
From: Stefan Hajnoczi @ 2026-11-17 18:06 UTC (permalink / raw)
To: Eric Blake
Cc: qemu-devel, qemu-block, qemu-stable, bea1e,
Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz
On Fri, Nov 13, 2026 at 04:34:51PM -0600, Eric Blake wrote:
> 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.
>
> Reported-by: Feifan Qian <bea1e@proton.me>
> Fixes: CVE-2026-126657
> Fixes: https://gitlab.com/qemu-project/qemu/-/work_items/3815
> Fixes: f140e300 ("nbd: Minimal structured read for client", v2.11.0)
> CC: qemu-stable@nongnu.org
> Signed-off-by: Eric Blake <eblake@redhat.com>
> ---
> block/nbd.c | 24 +++++++++++++++++++++++-
> 1 file changed, 23 insertions(+), 1 deletion(-)
Reviewed-by: Stefan Hajnoczi <stefanha@redhat.com>
^ permalink raw reply [flat|nested] 12+ messages in thread
* [PATCH 4/4] nbd: Add iotest exposing previous CVE fix
2026-11-13 22:34 [PATCH for-11.2 0/4] Another NBD CVE fix: incomplete read Eric Blake
` (2 preceding siblings ...)
2026-11-13 22:34 ` [PATCH 3/4] nbd/client: Don't leak uninitialized memory on malicious server Eric Blake
@ 2026-11-13 22:34 ` Eric Blake
2026-11-17 18:06 ` Stefan Hajnoczi
3 siblings, 1 reply; 12+ messages in thread
From: Eric Blake @ 2026-11-13 22:34 UTC (permalink / raw)
To: qemu-devel
Cc: qemu-block, qemu-stable, bea1e, Vladimir Sementsov-Ogievskiy,
Kevin Wolf, Hanna Reitz
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.
Reported-by: Feifan Qian <bea1e@proton.me>
Based-on: https://gitlab.com/qemu-project/qemu/-/work_items/3815
AI-used-for: tests
Signed-off-by: Eric Blake <eblake@redhat.com>
---
.../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
diff --git a/tests/qemu-iotests/tests/nbd-structured-read-gaps b/tests/qemu-iotests/tests/nbd-structured-read-gaps
new file mode 100755
index 00000000000..9f8b3b8b20b
--- /dev/null
+++ b/tests/qemu-iotests/tests/nbd-structured-read-gaps
@@ -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"])
diff --git a/tests/qemu-iotests/tests/nbd-structured-read-gaps.out b/tests/qemu-iotests/tests/nbd-structured-read-gaps.out
new file mode 100644
index 00000000000..ae1213e6f86
--- /dev/null
+++ b/tests/qemu-iotests/tests/nbd-structured-read-gaps.out
@@ -0,0 +1,5 @@
+.
+----------------------------------------------------------------------
+Ran 1 tests
+
+OK
--
2.56.0
^ permalink raw reply related [flat|nested] 12+ messages in thread* Re: [PATCH 4/4] nbd: Add iotest exposing previous CVE fix
2026-11-13 22:34 ` [PATCH 4/4] nbd: Add iotest exposing previous CVE fix Eric Blake
@ 2026-11-17 18:06 ` Stefan Hajnoczi
2026-11-17 20:07 ` Eric Blake
0 siblings, 1 reply; 12+ messages in thread
From: Stefan Hajnoczi @ 2026-11-17 18:06 UTC (permalink / raw)
To: Eric Blake
Cc: qemu-devel, qemu-block, qemu-stable, bea1e,
Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz
On Fri, Nov 13, 2026 at 04:34:52PM -0600, Eric Blake wrote:
> 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.
>
> Reported-by: Feifan Qian <bea1e@proton.me>
> Based-on: https://gitlab.com/qemu-project/qemu/-/work_items/3815
> AI-used-for: tests
QEMU's current AI policy forbids AI-generated code.
> Signed-off-by: Eric Blake <eblake@redhat.com>
> ---
> .../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
>
> diff --git a/tests/qemu-iotests/tests/nbd-structured-read-gaps b/tests/qemu-iotests/tests/nbd-structured-read-gaps
> new file mode 100755
> index 00000000000..9f8b3b8b20b
> --- /dev/null
> +++ b/tests/qemu-iotests/tests/nbd-structured-read-gaps
> @@ -0,0 +1,215 @@
> +#!/usr/bin/env python3
> +# group: rw quick
Does this run in CI without the "auto" group?
^ permalink raw reply [flat|nested] 12+ messages in thread
* Re: [PATCH 4/4] nbd: Add iotest exposing previous CVE fix
2026-11-17 18:06 ` Stefan Hajnoczi
@ 2026-11-17 20:07 ` Eric Blake
2026-11-17 20:51 ` Philippe Mathieu-Daudé
0 siblings, 1 reply; 12+ messages in thread
From: Eric Blake @ 2026-11-17 20:07 UTC (permalink / raw)
To: Stefan Hajnoczi
Cc: qemu-devel, qemu-block, qemu-stable, bea1e,
Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz
On Tue, Nov 17, 2026 at 01:06:01PM -0500, Stefan Hajnoczi wrote:
> On Fri, Nov 13, 2026 at 04:34:52PM -0600, Eric Blake wrote:
> > 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.
> >
> > Reported-by: Feifan Qian <bea1e@proton.me>
> > 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).
>
> > Signed-off-by: Eric Blake <eblake@redhat.com>
> > ---
> > .../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
> >
> > diff --git a/tests/qemu-iotests/tests/nbd-structured-read-gaps b/tests/qemu-iotests/tests/nbd-structured-read-gaps
> > new file mode 100755
> > index 00000000000..9f8b3b8b20b
> > --- /dev/null
> > +++ b/tests/qemu-iotests/tests/nbd-structured-read-gaps
> > @@ -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.
--
Eric Blake, Principal Software Engineer
Red Hat, Inc.
Virtualization: qemu.org | libguestfs.org
^ permalink raw reply [flat|nested] 12+ messages in thread
* Re: [PATCH 4/4] nbd: Add iotest exposing previous CVE fix
2026-11-17 20:07 ` Eric Blake
@ 2026-11-17 20:51 ` Philippe Mathieu-Daudé
2026-11-17 22:03 ` Stefan Hajnoczi
0 siblings, 1 reply; 12+ messages in thread
From: Philippe Mathieu-Daudé @ 2026-11-17 20:51 UTC (permalink / raw)
To: Eric Blake, Stefan Hajnoczi
Cc: qemu-devel, qemu-block, qemu-stable, bea1e,
Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz
On 17/11/26 21:07, Eric Blake wrote:
> On Tue, Nov 17, 2026 at 01:06:01PM -0500, Stefan Hajnoczi wrote:
>> On Fri, Nov 13, 2026 at 04:34:52PM -0600, Eric Blake wrote:
>>> 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.
>>>
>>> Reported-by: Feifan Qian <bea1e@proton.me>
>>> 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/20260930085433.830743-1-pbonzini@redhat.com/)
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.
> 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).
^ permalink raw reply [flat|nested] 12+ messages in thread
* Re: [PATCH 4/4] nbd: Add iotest exposing previous CVE fix
2026-11-17 20:51 ` Philippe Mathieu-Daudé
@ 2026-11-17 22:03 ` Stefan Hajnoczi
0 siblings, 0 replies; 12+ messages in thread
From: Stefan Hajnoczi @ 2026-11-17 22:03 UTC (permalink / raw)
To: Philippe Mathieu-Daudé
Cc: Eric Blake, qemu-devel, qemu-block, qemu-stable, bea1e,
Vladimir Sementsov-Ogievskiy, Kevin Wolf, Hanna Reitz
On Tue, Nov 17, 2026 at 09:51:12PM +0100, Philippe Mathieu-Daudé wrote:
> On 17/11/26 21:07, Eric Blake wrote:
> > On Tue, Nov 17, 2026 at 01:06:01PM -0500, Stefan Hajnoczi wrote:
> > > On Fri, Nov 13, 2026 at 04:34:52PM -0600, Eric Blake wrote:
> > > > 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.
> > > >
> > > > Reported-by: Feifan Qian <bea1e@proton.me>
> > > > 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/20260930085433.830743-1-pbonzini@redhat.com/)
> 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
^ permalink raw reply [flat|nested] 12+ messages in thread