From 30d7caeb15df2f2c90b69803dae26f20f9078f50 Mon Sep 17 00:00:00 2001 From: Stefan Hajnoczi Date: Mon, 24 May 2021 16:40:20 +0100 Subject: [PATCH] UPSTREAM: virtio-blk: limit seg_max to a safe value The struct virtio_blk_config seg_max value is read from the device and incremented by 2 to account for the request header and status byte descriptors added by the driver. In preparation for supporting untrusted virtio-blk devices, protect against integer overflow and limit the value to a safe maximum. Signed-off-by: Stefan Hajnoczi Link: https://lore.kernel.org/r/20210524154020.98195-1-stefanha@redhat.com Reviewed-by: Christoph Hellwig Signed-off-by: Michael S. Tsirkin (cherry picked from commit 63947b3434f475418b9677a393d025c0962c2cf8) Bug: 196772804 Signed-off-by: Keir Fraser Change-Id: Ia239cc17c912f05ed2bad08c5ae8a9b1326d3ae6 --- drivers/block/virtio_blk.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/drivers/block/virtio_blk.c b/drivers/block/virtio_blk.c index 018fb172a098..2670306a297d 100644 --- a/drivers/block/virtio_blk.c +++ b/drivers/block/virtio_blk.c @@ -21,6 +21,9 @@ #define VQ_NAME_LEN 16 #define MAX_DISCARD_SEGMENTS 256u +/* The maximum number of sg elements that fit into a virtqueue */ +#define VIRTIO_BLK_MAX_SG_ELEMS 32768 + static int major; static DEFINE_IDA(vd_index_ida); @@ -730,7 +733,10 @@ static int virtblk_probe(struct virtio_device *vdev) if (err || !sg_elems) sg_elems = 1; - /* We need an extra sg elements at head and tail. */ + /* Prevent integer overflows and honor max vq size */ + sg_elems = min_t(u32, sg_elems, VIRTIO_BLK_MAX_SG_ELEMS - 2); + + /* We need extra sg elements at head and tail. */ sg_elems += 2; vdev->priv = vblk = kmalloc(sizeof(*vblk), GFP_KERNEL); if (!vblk) {