[PATCH] crypto: starfive - Fix memory leak in starfive_aes_aead_do_one_req()

Zilin Guan posted 1 patch 1 week, 3 days ago
drivers/crypto/starfive/jh7110-aes.c | 9 +++++++--
1 file changed, 7 insertions(+), 2 deletions(-)
[PATCH] crypto: starfive - Fix memory leak in starfive_aes_aead_do_one_req()
Posted by Zilin Guan 1 week, 3 days ago
The starfive_aes_aead_do_one_req() function allocates rctx->adata with
kzalloc() but fails to free it if sg_copy_to_buffer() or
starfive_aes_hw_init() fails, which lead to memory leaks.

Since rctx->adata is unconditionally freed after the write_adata
operations, ensure consistent cleanup by freeing the allocation in these
earlier error paths as well.

Compile tested only. Issue found using a prototype static analysis tool
and code review.

Fixes: 7467147ef9bf ("crypto: starfive - Use dma for aes requests")
Signed-off-by: Zilin Guan <zilin@seu.edu.cn>
---
 drivers/crypto/starfive/jh7110-aes.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/drivers/crypto/starfive/jh7110-aes.c b/drivers/crypto/starfive/jh7110-aes.c
index 426b24889af8..01195664cc7c 100644
--- a/drivers/crypto/starfive/jh7110-aes.c
+++ b/drivers/crypto/starfive/jh7110-aes.c
@@ -669,8 +669,10 @@ static int starfive_aes_aead_do_one_req(struct crypto_engine *engine, void *areq
 			return -ENOMEM;
 
 		if (sg_copy_to_buffer(req->src, sg_nents_for_len(req->src, cryp->assoclen),
-				      rctx->adata, cryp->assoclen) != cryp->assoclen)
+				      rctx->adata, cryp->assoclen) != cryp->assoclen) {
+			kfree(rctx->adata);
 			return -EINVAL;
+		}
 	}
 
 	if (cryp->total_in)
@@ -681,8 +683,11 @@ static int starfive_aes_aead_do_one_req(struct crypto_engine *engine, void *areq
 	ctx->rctx = rctx;
 
 	ret = starfive_aes_hw_init(ctx);
-	if (ret)
+	if (ret) {
+		if (cryp->assoclen)
+			kfree(rctx->adata);
 		return ret;
+	}
 
 	if (!cryp->assoclen)
 		goto write_text;
-- 
2.34.1
Re: [PATCH] crypto: starfive - Fix memory leak in starfive_aes_aead_do_one_req()
Posted by Herbert Xu 2 days, 7 hours ago
On Thu, Jan 29, 2026 at 03:10:16PM +0000, Zilin Guan wrote:
> The starfive_aes_aead_do_one_req() function allocates rctx->adata with
> kzalloc() but fails to free it if sg_copy_to_buffer() or
> starfive_aes_hw_init() fails, which lead to memory leaks.
> 
> Since rctx->adata is unconditionally freed after the write_adata
> operations, ensure consistent cleanup by freeing the allocation in these
> earlier error paths as well.
> 
> Compile tested only. Issue found using a prototype static analysis tool
> and code review.
> 
> Fixes: 7467147ef9bf ("crypto: starfive - Use dma for aes requests")
> Signed-off-by: Zilin Guan <zilin@seu.edu.cn>
> ---
>  drivers/crypto/starfive/jh7110-aes.c | 9 +++++++--
>  1 file changed, 7 insertions(+), 2 deletions(-)

Patch applied.  Thanks.
-- 
Email: Herbert Xu <herbert@gondor.apana.org.au>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt