virtnet_get_hw_stats() allocates the reply buffer of the device statistics command with kmalloc(), and __virtnet_get_hw_stats() parses the whole buffer. When the device writes less than the buffer holds, stale heap bytes are reported as counters through ethtool -S and the per-queue netlink statistics.
Allocate the buffer with kzalloc(), so that the counters the device didn't write are zeroed. An unwritten record header then has size 0, so reject it when walking on that header to avoid an infinite loop. The used length cannot replace the zeroing here, since the device can also report a larger value than it wrote. 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 leave the counters of a receive record unwritten. On an unmodified kernel, ethtool -S reported kernel pointers as rx0 counters. With this patch, the counters are zeroed, and a reply with missing records or a record of size 0 is rejected. 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]/ 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 | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/drivers/net/virtio_net.c b/drivers/net/virtio_net.c index 57d7a98ecb57..498014773242 100644 --- a/drivers/net/virtio_net.c +++ b/drivers/net/virtio_net.c @@ -4994,6 +4994,9 @@ static int __virtnet_get_hw_stats(struct virtnet_info *vi, for (p = reply; p - reply < res_size; p += le16_to_cpu(hdr->size)) { hdr = p; + if (!hdr->size) + return -EINVAL; + qid = le16_to_cpu(hdr->vq_index); /* The vqs of the queue pairs beyond curr_queue_pairs lie * between last_vq and the control vq. @@ -5068,7 +5071,7 @@ static int virtnet_get_hw_stats(struct virtnet_info *vi, if (!req) return -ENOMEM; - reply = kmalloc(res_size, GFP_KERNEL); + reply = kzalloc(res_size, GFP_KERNEL); if (!reply) { kfree(req); return -ENOMEM; -- 2.56.1
