[PATCH 04/11] virtio: pci: Check virtio common config size

Andrew Scull
2022-03-20T11:44:06Z

Check that the common config is at least as large as the struct it is
expected to contain. Only then is it safe to cast the pointer and be
safe from out-of-bounds accesses.

Signed-off-by: Andrew Scull <ascull@google.com>
---
drivers/virtio/virtio_pci_modern.c | 8 ++++++++
1 file changed, 8 insertions(+)

diff --git a/drivers/virtio/virtio_pci_modern.c b/drivers/virtio/virtio_pci_modern.c
index 60bdc53a6d..3403ff5cca 100644
--- a/drivers/virtio/virtio_pci_modern.c
+++ b/drivers/virtio/virtio_pci_modern.c
@@ -475,6 +475,7 @@ static int virtio_pci_probe(struct udevice *udev)
u16 subvendor;
u8 revision;
int common, notify, device;
+ u32 common_length;
int offset;

/* We only own devices >= 0x1040 and <= 0x107f: leave the rest. */
@@ -496,6 +497,13 @@ static int virtio_pci_probe(struct udevice *udev)
return -ENODEV;
}

+ offset = common + offsetof(struct virtio_pci_cap, length);
+ dm_pci_read_config32(udev, offset, &common_length);
+ if (common_length < sizeof(struct virtio_pci_common_cfg)) {
+ printf("(%s): virtio common config too small\n", udev->name);
+ return -EINVAL;
+ }
+
/* If common is there, notify should be too */
notify = virtio_pci_find_capability(udev, VIRTIO_PCI_CAP_NOTIFY_CFG);
if (!notify) {
--
2.35.1.894.gb6a874cedc-goog