[PATCH] mtd: Fix potential UAF for mtdswap_dev pointers

From: Ma Ke
Date: Mon Feb 24 2025 - 08:33:10 EST


In the mtdswap_init(), if the allocations fail, the error handling
path frees d->page_buf, d->eb_data, d->revmap and d->page_data without
setting these pointers to NULL. This could lead to UAF if subsequent
error handling or device reset operations attempt to release these
pointers again.

Set d->page_buf, d->eb_data, d->revmap and d->page_data to NULL
immediately after freeing them to prevent misuse. Release immediately
and set to NULL, adhering to the 'release implies invalid' defensive
programming principle.

Found by code review.

Cc: stable@xxxxxxxxxxxxxxx
Fixes: a32159024620 ("mtd: Add mtdswap block driver")
Signed-off-by: Ma Ke <make24@xxxxxxxxxxx>
---
drivers/mtd/mtdswap.c | 4 ++++
1 file changed, 4 insertions(+)

diff --git a/drivers/mtd/mtdswap.c b/drivers/mtd/mtdswap.c
index 680366616da2..b315dab2a914 100644
--- a/drivers/mtd/mtdswap.c
+++ b/drivers/mtd/mtdswap.c
@@ -1318,12 +1318,16 @@ static int mtdswap_init(struct mtdswap_dev *d, unsigned int eblocks,

oob_buf_fail:
kfree(d->page_buf);
+ d->page_buf = NULL;
page_buf_fail:
vfree(d->eb_data);
+ d->eb_data = NULL;
eb_data_fail:
vfree(d->revmap);
+ d->revmap = NULL;
revmap_fail:
vfree(d->page_data);
+ d->page_data = NULL;
page_data_fail:
printk(KERN_ERR "%s: init failed (%d)\n", MTDSWAP_PREFIX, ret);
return ret;
--
2.25.1