From d48761317c985f99a4829ed7d28450706aee8ad4 Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Tue, 8 Jun 2021 18:32:34 +0200 Subject: [PATCH] mbedtls_mpi_read_string: make an empty bignum for an empty string In mbedtls_mpi_read_string, if the string is empty, return an empty bignum rather than a bignum with one limb with the value 0. Both representations are correct, so this is not, in principle, a user-visible change. The change does leak however through mbedtls_mpi_write_string in base 16 (but not in other bases), as it writes a bignum with 0 limbs as "" but a bignum with the value 0 and at least one limb as "00". This change makes it possible to construct an empty bignum through mbedtls_mpi_read_string, which is especially useful to construct test cases (a common use of mbedtls_mpi_read_string, as most formats use in production encode numbers in binary, to be read with mbedtls_mpi_read_binary or mbedtls_mpi_read_binary_le). Signed-off-by: Gilles Peskine --- library/bignum.c | 6 ++++++ tests/suites/test_suite_mpi.data | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/library/bignum.c b/library/bignum.c index 748490066..208d50873 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -512,6 +512,12 @@ int mbedtls_mpi_read_string( mbedtls_mpi *X, int radix, const char *s ) mbedtls_mpi_init( &T ); + if( s[0] == 0 ) + { + mbedtls_mpi_free( X ); + return( 0 ); + } + if( s[0] == '-' ) { ++s; diff --git a/tests/suites/test_suite_mpi.data b/tests/suites/test_suite_mpi.data index da227ad87..2460d3fa3 100644 --- a/tests/suites/test_suite_mpi.data +++ b/tests/suites/test_suite_mpi.data @@ -68,13 +68,13 @@ Test mpi_read_write_string #7 mpi_read_write_string:10:"56125680981752282334141896320372489490613963693556392520816017892111350604111697682705498319512049040516698827829292076808006940873974979584527073481012636016353913462376755556720019831187364993587901952757307830896531678727717924":16:"0941379d00fed1491fe15df284dfde4a142f68aa8d412023195cee66883e6290ffe703f4ea5963bf212713cee46b107c09182b5edcd955adac418bf4918e2889af48e1099d513830cec85c26ac1e158b52620e33ba8692f893efbb2f958b4424":200:0:0 Test mpi_read_write_string #8 (Empty MPI hex -> hex) -mpi_read_write_string:16:"":16:"00":4:0:0 +mpi_read_write_string:16:"":16:"":4:0:0 Test mpi_read_write_string #9 (Empty MPI hex -> dec) mpi_read_write_string:16:"":10:"0":4:0:0 Test mpi_read_write_string #8 (Empty MPI dec -> hex) -mpi_read_write_string:10:"":16:"00":4:0:0 +mpi_read_write_string:10:"":16:"":4:0:0 Test mpi_read_write_string #9 (Empty MPI dec -> dec) mpi_read_write_string:10:"":10:"0":4:0:0