2022-06-28 05:12:53

by Schspa Shi

[permalink] [raw]
Subject: [PATCH] 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.

Signed-off-by: Schspa Shi <[email protected]>
---
drivers/vfio/vfio.c | 1 +
1 file changed, 1 insertion(+)

diff --git a/drivers/vfio/vfio.c b/drivers/vfio/vfio.c
index 61e71c1154be..a0fb93866f61 100644
--- a/drivers/vfio/vfio.c
+++ b/drivers/vfio/vfio.c
@@ -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);
}
--
2.29.0


2022-06-28 08:21:07

by Cornelia Huck

[permalink] [raw]
Subject: Re: [PATCH] vfio: Fix double free for caps->buf

On Tue, Jun 28 2022, Schspa Shi <[email protected]> wrote:

> 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.

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

>
> Signed-off-by: Schspa Shi <[email protected]>
> ---
> drivers/vfio/vfio.c | 1 +
> 1 file changed, 1 insertion(+)
>
> diff --git a/drivers/vfio/vfio.c b/drivers/vfio/vfio.c
> index 61e71c1154be..a0fb93866f61 100644
> --- a/drivers/vfio/vfio.c
> +++ b/drivers/vfio/vfio.c
> @@ -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.

> caps->size = 0;
> return ERR_PTR(-ENOMEM);
> }