From 9fd9794d109ffbd7f9ebed92f4a90dc429e1a1df Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Thu, 10 Oct 2019 19:27:53 +0200 Subject: [PATCH] mbedtls_asn1_get_int: explain the logic No behavior change. --- library/asn1parse.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/library/asn1parse.c b/library/asn1parse.c index 4764ca4cb..4f9d6aef3 100644 --- a/library/asn1parse.c +++ b/library/asn1parse.c @@ -149,14 +149,22 @@ int mbedtls_asn1_get_int( unsigned char **p, if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_INTEGER ) ) != 0 ) return( ret ); - if( len == 0 || ( **p & 0x80 ) != 0 ) + /* len==0 is malformed (0 must be represented as 020100). */ + if( len == 0 ) + return( MBEDTLS_ERR_ASN1_INVALID_LENGTH ); + /* This is a cryptography library. Reject negative integers. */ + if( ( **p & 0x80 ) != 0 ) return( MBEDTLS_ERR_ASN1_INVALID_LENGTH ); + /* Skip leading zeros. */ while( len > 0 && **p == 0 ) { ++( *p ); --len; } + + /* Reject integers that don't fit in an int. This code assumes that + * the int type has no padding bit. */ if( len > sizeof( int ) ) return( MBEDTLS_ERR_ASN1_INVALID_LENGTH );