Thread (11 messages) 11 messages, 3 authors, 2022-12-23
STALE1287d

[PATCH] lib/mpi: Fix buffer overrun when SG is too long

From: Herbert Xu <herbert@gondor.apana.org.au>
Date: 2022-12-20 07:25:47
Also in: keyrings, linux-crypto, linux-integrity, lkml
Subsystem: library code, the rest · Maintainers: Andrew Morton, Linus Torvalds

On Mon, Dec 19, 2022 at 09:49:29AM +0100, Roberto Sassu wrote:
do you have any news on this bug?
Thanks for the reminder.  Could you please try this patch?

---8<---
The helper mpi_read_raw_from_sgl ignores the second parameter
nbytes when reading the SG list and may overrun its own buffer
because it only allocates enough memory according to nbytes.

Fixes: 2d4d1eea540b ("lib/mpi: Add mpi sgl helpers")
Reported-by: Roberto Sassu <redacted>
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>
diff --git a/lib/mpi/mpicoder.c b/lib/mpi/mpicoder.c
index 39c4c6731094..6bffc68c1a5a 100644
--- a/lib/mpi/mpicoder.c
+++ b/lib/mpi/mpicoder.c
@@ -494,17 +494,15 @@ MPI mpi_read_raw_from_sgl(struct scatterlist *sgl, unsigned int nbytes)
 	val->sign = 0;
 	val->nlimbs = nlimbs;
 
-	if (nbytes == 0)
-		return val;
-
 	j = nlimbs - 1;
 	a = 0;
 	z = BYTES_PER_MPI_LIMB - nbytes % BYTES_PER_MPI_LIMB;
 	z %= BYTES_PER_MPI_LIMB;
 
-	while (sg_miter_next(&miter)) {
+	while (nbytes && sg_miter_next(&miter)) {
 		buff = miter.addr;
-		len = miter.length;
+		len = min_t(unsigned, miter.length, nbytes);
+		nbytes -= len;
 
 		for (x = 0; x < len; x++) {
 			a <<= 8;
-- 
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
Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help