Skip to content

Commit c8ea9fc

Browse files
committed
lib/mpi: Fix karactx leak in mpi_powm
Sometimes mpi_powm will leak karactx because a memory allocation failure causes a bail-out that skips the freeing of karactx. This patch moves the freeing of karactx to the end of the function like everything else so that it can't be skipped. Reported-by: [email protected] Fixes: cdec9cb ("crypto: GnuPG based MPI lib - source files...") Cc: <[email protected]> Signed-off-by: Herbert Xu <[email protected]> Reviewed-by: Eric Biggers <[email protected]> Signed-off-by: Herbert Xu <[email protected]>
1 parent 7829a0c commit c8ea9fc

File tree

1 file changed

+2
-4
lines changed

1 file changed

+2
-4
lines changed

lib/mpi/mpi-pow.c

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
int mpi_powm(MPI res, MPI base, MPI exp, MPI mod)
3838
{
3939
mpi_ptr_t mp_marker = NULL, bp_marker = NULL, ep_marker = NULL;
40+
struct karatsuba_ctx karactx = {};
4041
mpi_ptr_t xp_marker = NULL;
4142
mpi_ptr_t tspace = NULL;
4243
mpi_ptr_t rp, ep, mp, bp;
@@ -163,13 +164,11 @@ int mpi_powm(MPI res, MPI base, MPI exp, MPI mod)
163164
int c;
164165
mpi_limb_t e;
165166
mpi_limb_t carry_limb;
166-
struct karatsuba_ctx karactx;
167167

168168
xp = xp_marker = mpi_alloc_limb_space(2 * (msize + 1));
169169
if (!xp)
170170
goto enomem;
171171

172-
memset(&karactx, 0, sizeof karactx);
173172
negative_result = (ep[0] & 1) && base->sign;
174173

175174
i = esize - 1;
@@ -294,8 +293,6 @@ int mpi_powm(MPI res, MPI base, MPI exp, MPI mod)
294293
if (mod_shift_cnt)
295294
mpihelp_rshift(rp, rp, rsize, mod_shift_cnt);
296295
MPN_NORMALIZE(rp, rsize);
297-
298-
mpihelp_release_karatsuba_ctx(&karactx);
299296
}
300297

301298
if (negative_result && rsize) {
@@ -312,6 +309,7 @@ int mpi_powm(MPI res, MPI base, MPI exp, MPI mod)
312309
leave:
313310
rc = 0;
314311
enomem:
312+
mpihelp_release_karatsuba_ctx(&karactx);
315313
if (assign_rp)
316314
mpi_assign_limb_space(res, rp, size);
317315
if (mp_marker)

0 commit comments

Comments
 (0)