From 42a1acfd0e100035f71e7112935a115136d6b90c Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Tue, 21 Jan 2020 16:12:07 +0100 Subject: [PATCH] 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. --- tests/suites/test_suite_asn1parse.function | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/suites/test_suite_asn1parse.function b/tests/suites/test_suite_asn1parse.function index d747cc254..f07fd409d 100644 --- a/tests/suites/test_suite_asn1parse.function +++ b/tests/suites/test_suite_asn1parse.function @@ -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 ) {