From 98831c25d4609f7018217504cf2d6748cf0404cf Mon Sep 17 00:00:00 2001 From: jordan Date: Fri, 8 May 2026 15:26:57 -0500 Subject: [PATCH] wolfmath: check mpSz in wc_export_int. --- tests/api/test_wolfmath.c | 8 ++++++++ wolfcrypt/src/wolfmath.c | 8 ++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/tests/api/test_wolfmath.c b/tests/api/test_wolfmath.c index 4c86856dd4..1e4b622727 100644 --- a/tests/api/test_wolfmath.c +++ b/tests/api/test_wolfmath.c @@ -193,6 +193,14 @@ int test_wc_export_int(void) ExpectIntEQ(wc_export_int(&mp, buf, &len, 0, WC_TYPE_HEX_STR), 0); /* hex version of 1234 is 04D2 and should be 4 digits + 1 null */ ExpectIntEQ(len, 5); + mp_clear(&mp); + + /* test mp_int too large for export buf */ + len = sizeof(buf); + ExpectIntEQ(mp_init(&mp), MP_OKAY); + ExpectIntEQ(mp_set_bit(&mp, 257), 0); + ExpectIntEQ(wc_export_int(&mp, buf, &len, 0, WC_TYPE_UNSIGNED_BIN), + WC_NO_ERR_TRACE(BUFFER_E)); mp_clear(&mp); #endif diff --git a/wolfcrypt/src/wolfmath.c b/wolfcrypt/src/wolfmath.c index 20258001b9..60cd6b965d 100644 --- a/wolfcrypt/src/wolfmath.c +++ b/wolfcrypt/src/wolfmath.c @@ -253,14 +253,18 @@ int wc_export_int(mp_int* mp, byte* buf, word32* len, word32 keySz, else { /* for WC_TYPE_UNSIGNED_BIN keySz is used to zero pad. * The key size is always returned as the size */ + word32 mpSz = 0; if (*len < keySz) { *len = keySz; return BUFFER_E; } *len = keySz; + mpSz = (word32)mp_unsigned_bin_size(mp); + if (mpSz > keySz) { + return BUFFER_E; + } XMEMSET(buf, 0, *len); - err = mp_to_unsigned_bin(mp, buf + - (keySz - (word32)mp_unsigned_bin_size(mp))); + err = mp_to_unsigned_bin(mp, buf + (keySz - mpSz)); } return err;