Skip to contentSkip to conversation

vfio: Fix double free for caps->buf

PATCH In review Schspa Shi 2 participants 2 messages Jun 28, 2022

Subsystems (2)
lore
Share & tools
lore

Schspa Shi

author
#0 lore raw

PATCH 1/1 vfio: Fix double free for caps->buf

There is a double free, if vfio_iommu_dma_avail_build_caps calls failed.

The following call path will call vfio_info_cap_add multiple times

vfio_iommu_type1_get_info

	if (!ret)
		ret = vfio_iommu_dma_avail_build_caps(iommu, &caps);

	if (!ret)
		ret = vfio_iommu_iova_build_caps(iommu, &caps);

If krealloc failed on vfio_info_cap_add, there will be a double free.

---
 drivers/vfio/vfio.c | 1 +
 1 file changed, 1 insertion(+)
drivers/vfio/vfio.c +1 -0
index 61e71c1154be..a0fb93866f61 100644
@@ -1812,6 +1812,7 @@ struct vfio_info_cap_header *vfio_info_cap_add(struct vfio_info_cap *caps,
 	buf = krealloc(caps->buf, caps->size + size, GFP_KERNEL);
 	if (!buf) {
 		kfree(caps->buf);
+		caps->buf = NULL;
 		caps->size = 0;
 		return ERR_PTR(-ENOMEM);
 	}
Signature · 1 line
2.29.0
#1 lore raw
Quoted 5 lines · Schspa Shi

There is a double free, if vfio_iommu_dma_avail_build_caps calls failed.

The following call path will call vfio_info_cap_add multiple times

Quoted 8 lines

vfio_iommu_type1_get_info

	if (!ret)
		ret = vfio_iommu_dma_avail_build_caps(iommu, &caps);

	if (!ret)
		ret = vfio_iommu_iova_build_caps(iommu, &caps);

If krealloc failed on vfio_info_cap_add, there will be a double free.

But it will only call it several times if the last call didn't fail, won't it?

Quoted 11 lines
---
 drivers/vfio/vfio.c | 1 +
 1 file changed, 1 insertion(+)
drivers/vfio/vfio.c +0 -0
index 61e71c1154be..a0fb93866f61 100644

drivers/vfio/vfio.c struct vfio_info_cap_header *vfio_info_cap_add(struct vfio_info_cap *caps, · line 1815

Quoted 4 lines
drivers/vfio/vfio.c +1 -0
@@ -1812,6 +1812,7 @@ struct vfio_info_cap_header *vfio_info_cap_add(struct vfio_info_cap *caps,
 	buf = krealloc(caps->buf, caps->size + size, GFP_KERNEL);
 	if (!buf) {
 		kfree(caps->buf);
+		caps->buf = NULL;

We could add this as some kind of hardening, I guess. Current callers all seem to deal with failure correctly.

Quoted 3 lines
drivers/vfio/vfio.c +0 -0
 		caps->size = 0;
 		return ERR_PTR(-ENOMEM);
 	}