__virtnet_get_hw_stats() only checks that each record of the statistics
reply starts within the reply buffer, while virtnet_fill_stats() reads
the whole payload of the record's type, so a record near the end of the
buffer can make the driver read past it and report the heap bytes
through ethtool -S and the per-queue netlink statistics.

Fix this by reserving zeroed space of the largest ctx->size[] after the
reply, so the buffer can hold any type of payload.

Records of an unexpected size are still parsed, since every record
starts within the reply and cannot cause out-of-bounds reads, and
rejecting them with checks per type was judged costly to maintain [1].

Claude Opus 5.5 was used to audit the driver and draft this patch. To
reproduce, the virtio-net device in QEMU was modified to offer device
statistics and to end its reply with a truncated receive record. On an
unmodified kernel, KASAN reports:

  BUG: KASAN: slab-out-of-bounds in virtnet_fill_stats+0x66d/0xf20
  Read of size 8 at addr ffff8880036f5940 by task ethtool_stats/159
  Call Trace:
   virtnet_fill_stats+0x66d/0xf20
   virtnet_get_hw_stats+0x5d6/0x7c0
   virtnet_get_ethtool_stats+0x11b/0x920
   ethtool_get_stats+0x150/0x1f0
   dev_ethtool+0xaaa/0x1be0
  Allocated by task 159:
   __kmalloc_noprof+0x1b7/0x4a0
   virtnet_get_hw_stats+0x25e/0x7c0
  The buggy address is located 8 bytes to the right of
   allocated 56-byte region [ffff8880036f5900, ffff8880036f5938)

With this patch, the same reply triggers no KASAN report. The
drivers/net/stats.py selftest passes when the device answers with
well-formed records.

Reported-by: Michael Bommarito <[email protected]>
Link: 
https://lore.kernel.org/all/[email protected]/
 [1]
Reported-by: Jakub Kicinski <[email protected]>
Link: https://lore.kernel.org/all/[email protected]/
Fixes: 941168f8b40e ("virtio_net: support device stats")
Cc: [email protected]
Signed-off-by: Lianjie Wang <[email protected]>
---
v3:
- New patch.

 drivers/net/virtio_net.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/drivers/net/virtio_net.c b/drivers/net/virtio_net.c
index 498014773242..b9b6c915b6f3 100644
--- a/drivers/net/virtio_net.c
+++ b/drivers/net/virtio_net.c
@@ -5071,7 +5071,13 @@ static int virtnet_get_hw_stats(struct virtnet_info *vi,
        if (!req)
                return -ENOMEM;
 
-       reply = kzalloc(res_size, GFP_KERNEL);
+       /* virtnet_fill_stats() parses the whole payload of a record's type,
+        * so reserve zeroed space after the reply to hold any payload.
+        */
+       reply = kzalloc(res_size + max3(ctx->size[VIRTNET_Q_TYPE_RX],
+                                       ctx->size[VIRTNET_Q_TYPE_TX],
+                                       ctx->size[VIRTNET_Q_TYPE_CQ]),
+                       GFP_KERNEL);
        if (!reply) {
                kfree(req);
                return -ENOMEM;
-- 
2.56.1


Reply via email to