From 321a08944b9f47a52d4f6f683e356f2bc215c3f8 Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Fri, 10 Jun 2022 20:13:33 +0200 Subject: [PATCH] Fix bug whereby 0 was written as 0200 rather than 020100 0200 is not just non-DER, it's completely invalid, since there has to be a sign bit. Signed-off-by: Gilles Peskine --- ChangeLog.d/asn1write-0-fix | 2 ++ library/asn1write.c | 5 +++++ tests/suites/test_suite_asn1write.data | 7 +++++-- 3 files changed, 12 insertions(+), 2 deletions(-) create mode 100644 ChangeLog.d/asn1write-0-fix diff --git a/ChangeLog.d/asn1write-0-fix b/ChangeLog.d/asn1write-0-fix new file mode 100644 index 000000000..2e01244f8 --- /dev/null +++ b/ChangeLog.d/asn1write-0-fix @@ -0,0 +1,2 @@ +Bugfix + * Fix mbedtls_asn1_write_mpi() writing an incorrect encoding of 0. diff --git a/library/asn1write.c b/library/asn1write.c index 2110052d5..053dbb669 100644 --- a/library/asn1write.c +++ b/library/asn1write.c @@ -133,6 +133,11 @@ int mbedtls_asn1_write_mpi( unsigned char **p, const unsigned char *start, const // len = mbedtls_mpi_size( X ); + /* DER represents 0 with a sign bit (0=nonnegative) and 7 value bits, not + * as 0 digits. We need to end up with 020100, not with 0200. */ + if( len == 0 ) + len = 1; + if( *p < start || (size_t)( *p - start ) < len ) return( MBEDTLS_ERR_ASN1_BUF_TOO_SMALL ); diff --git a/tests/suites/test_suite_asn1write.data b/tests/suites/test_suite_asn1write.data index f2c32ec81..6fc668f53 100644 --- a/tests/suites/test_suite_asn1write.data +++ b/tests/suites/test_suite_asn1write.data @@ -91,8 +91,11 @@ mbedtls_asn1_write_enum:0x12345678:"0A0412345678" ASN.1 Write enum 2147483647 mbedtls_asn1_write_enum:0x7fffffff:"0A047fffffff" -#ASN.1 Write mpi 0 -#mbedtls_asn1_write_mpi:"00":"020100" +ASN.1 Write mpi 0 (null) +mbedtls_asn1_write_mpi:"":"020100" + +ASN.1 Write mpi 0 (1 limb) +mbedtls_asn1_write_mpi:"00":"020100" ASN.1 Write mpi 1 mbedtls_asn1_write_mpi:"01":"020101"