Skip to content

Commit 581a968

Browse files
authored
Merge pull request #10444 from philljj/fix_wc_export_int
wolfmath: check mpSz in wc_export_int.
2 parents b8bc480 + 5918eab commit 581a968

2 files changed

Lines changed: 14 additions & 2 deletions

File tree

tests/api/test_wolfmath.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,14 @@ int test_wc_export_int(void)
193193
ExpectIntEQ(wc_export_int(&mp, buf, &len, 0, WC_TYPE_HEX_STR), 0);
194194
/* hex version of 1234 is 04D2 and should be 4 digits + 1 null */
195195
ExpectIntEQ(len, 5);
196+
mp_clear(&mp);
197+
198+
/* test mp_int too large for export buf */
199+
len = sizeof(buf);
200+
ExpectIntEQ(mp_init(&mp), MP_OKAY);
201+
ExpectIntEQ(mp_set_bit(&mp, 257), 0);
202+
ExpectIntEQ(wc_export_int(&mp, buf, &len, keySz, WC_TYPE_UNSIGNED_BIN),
203+
WC_NO_ERR_TRACE(BUFFER_E));
196204

197205
mp_clear(&mp);
198206
#endif

wolfcrypt/src/wolfmath.c

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -253,14 +253,18 @@ int wc_export_int(mp_int* mp, byte* buf, word32* len, word32 keySz,
253253
else {
254254
/* for WC_TYPE_UNSIGNED_BIN keySz is used to zero pad.
255255
* The key size is always returned as the size */
256+
int mpSz = 0;
256257
if (*len < keySz) {
257258
*len = keySz;
258259
return BUFFER_E;
259260
}
260261
*len = keySz;
262+
mpSz = mp_unsigned_bin_size(mp);
263+
if (mpSz < 0 || (word32)mpSz > keySz) {
264+
return BUFFER_E;
265+
}
261266
XMEMSET(buf, 0, *len);
262-
err = mp_to_unsigned_bin(mp, buf +
263-
(keySz - (word32)mp_unsigned_bin_size(mp)));
267+
err = mp_to_unsigned_bin(mp, buf + (keySz - (word32)mpSz));
264268
}
265269

266270
return err;

0 commit comments

Comments
 (0)