[PATCH] virt: acrn: fix memory leak in acrn_dev_ioctl()

From: Zhou Qingyang
Date: Tue Jan 04 2022 - 03:53:31 EST


In acrn_dev_ioctl(), cpu_regs is not released or passed out on several
error paths which could lead to memory leak bug.

Fix this bug by adding kfree of cpu_regs on error paths.

This bug was found by a static analyzer.

Builds with CONFIG_ACRN_GUEST=y, CONFIG_ACRN_HSM=y show no new warnings,
and our static analyzer no longer warns about this code.

Fixes: 2ad2aaee1bc9 ("virt: acrn: Introduce an ioctl to set vCPU registers state")
Signed-off-by: Zhou Qingyang <zhou1615@xxxxxxx>
---
The analysis employs differential checking to identify inconsistent
security operations (e.g., checks or kfrees) between two code paths
and confirms that the inconsistent operations are not recovered in
the current function or the callers, so they constitute bugs.

Note that, as a bug found by static analysis, it can be a false
positive or hard to trigger. Multiple researchers have cross-reviewed
the bug.

drivers/virt/acrn/hsm.c | 24 ++++++++++++++++--------
1 file changed, 16 insertions(+), 8 deletions(-)

diff --git a/drivers/virt/acrn/hsm.c b/drivers/virt/acrn/hsm.c
index 5419794fccf1..1eb0a17aadde 100644
--- a/drivers/virt/acrn/hsm.c
+++ b/drivers/virt/acrn/hsm.c
@@ -182,21 +182,29 @@ static long acrn_dev_ioctl(struct file *filp, unsigned int cmd,
return PTR_ERR(cpu_regs);

for (i = 0; i < ARRAY_SIZE(cpu_regs->reserved); i++)
- if (cpu_regs->reserved[i])
- return -EINVAL;
+ if (cpu_regs->reserved[i]) {
+ kfree(cpu_regs);
+ return -EINVAL;
+ }

for (i = 0; i < ARRAY_SIZE(cpu_regs->vcpu_regs.reserved_32); i++)
- if (cpu_regs->vcpu_regs.reserved_32[i])
- return -EINVAL;
+ if (cpu_regs->vcpu_regs.reserved_32[i]) {
+ kfree(cpu_regs);
+ return -EINVAL;
+ }

for (i = 0; i < ARRAY_SIZE(cpu_regs->vcpu_regs.reserved_64); i++)
- if (cpu_regs->vcpu_regs.reserved_64[i])
- return -EINVAL;
+ if (cpu_regs->vcpu_regs.reserved_64[i]) {
+ kfree(cpu_regs);
+ return -EINVAL;
+ }

for (i = 0; i < ARRAY_SIZE(cpu_regs->vcpu_regs.gdt.reserved); i++)
if (cpu_regs->vcpu_regs.gdt.reserved[i] |
- cpu_regs->vcpu_regs.idt.reserved[i])
- return -EINVAL;
+ cpu_regs->vcpu_regs.idt.reserved[i]) {
+ kfree(cpu_regs);
+ return -EINVAL;
+ }

ret = hcall_set_vcpu_regs(vm->vmid, virt_to_phys(cpu_regs));
if (ret < 0)
--
2.25.1