get_len_step: Fix end-of-buffer calculation when buffer_size==0

Fix get_len_step when buffer_size==0. The intent of this test is to
ensure (via static or runtime buffer overflow analysis) that
mbedtls_asn1_get_len does not attempt to access beyond the end of the
buffer. When buffer_size is 0 (reached from get_len when parsing a
1-byte buffer), the buffer is buf[1..1] because allocating a 0-byte
buffer might yield a null pointer rather than a valid pointer. In this
case the end of the buffer is p==buf+1, not buf+buffer_size which is
buf+0.

The test passed because calling mbedtls_asn1_get_len(&p,end,...) with
end < p happens to work, but this is not guaranteed.
This commit is contained in:
Gilles Peskine 2020-01-21 16:12:07 +01:00
parent a2bdcb9e3a
commit 42a1acfd0e

View File

@ -121,6 +121,7 @@ int get_len_step( const data_t *input, size_t buffer_size,
{
unsigned char *buf = NULL;
unsigned char *p = NULL;
unsigned char *end;
size_t parsed_length;
int ret;
@ -130,7 +131,8 @@ int get_len_step( const data_t *input, size_t buffer_size,
if( buffer_size == 0 )
{
ASSERT_ALLOC( buf, 1 );
p = buf + 1;
end = buf + 1;
p = end;
}
else
{
@ -145,9 +147,10 @@ int get_len_step( const data_t *input, size_t buffer_size,
memcpy( buf, input->x, buffer_size );
}
p = buf;
end = buf + buffer_size;
}
ret = mbedtls_asn1_get_len( &p, buf + buffer_size, &parsed_length );
ret = mbedtls_asn1_get_len( &p, end, &parsed_length );
if( buffer_size >= input->len + actual_length )
{