From 12ddae870cfe3ba33a457ed91937f3f16033bf24 Mon Sep 17 00:00:00 2001 From: Werner Lewis Date: Wed, 4 May 2022 09:44:50 +0100 Subject: [PATCH] Fix memcpy() UB in mbedtls_asn1_named_data() Removes a case in mbedtls_asn1_named_data() where memcpy() could be called with a null pointer and zero length. A test case is added for this code path, to catch the undefined behavior when running tests with UBSan. Signed-off-by: Werner Lewis --- library/asn1write.c | 2 +- tests/suites/test_suite_asn1write.data | 9 ++++++--- tests/suites/test_suite_asn1write.function | 6 ++---- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/library/asn1write.c b/library/asn1write.c index 3811ef27a..d45484146 100644 --- a/library/asn1write.c +++ b/library/asn1write.c @@ -472,7 +472,7 @@ mbedtls_asn1_named_data *mbedtls_asn1_store_named_data( cur->val.len = val_len; } - if( val != NULL ) + if( val != NULL && val_len != 0 ) memcpy( cur->val.p, val, val_len ); return( cur ); diff --git a/tests/suites/test_suite_asn1write.data b/tests/suites/test_suite_asn1write.data index 7f5f5360e..f844d4844 100644 --- a/tests/suites/test_suite_asn1write.data +++ b/tests/suites/test_suite_asn1write.data @@ -374,10 +374,13 @@ Store named data: found, larger data store_named_data_val_found:4:9 Store named data: new, val_len=0 -store_named_data_val_new:0 +store_named_data_val_new:0:1 + +Stored named data: new, val_len=0, val=NULL +store_named_data_val_new:0:0 Store named data: new, val_len=4 -store_named_data_val_new:4 +store_named_data_val_new:4:1 Store named data: new, val_len=4, val=NULL -store_named_data_val_new:-4 +store_named_data_val_new:4:0 diff --git a/tests/suites/test_suite_asn1write.function b/tests/suites/test_suite_asn1write.function index 882473905..597d6ac3c 100644 --- a/tests/suites/test_suite_asn1write.function +++ b/tests/suites/test_suite_asn1write.function @@ -431,7 +431,7 @@ exit: /* END_CASE */ /* BEGIN_CASE */ -void store_named_data_val_new( int new_len ) +void store_named_data_val_new( int new_len, int set_new_val ) { mbedtls_asn1_named_data *head = NULL; mbedtls_asn1_named_data *found = NULL; @@ -439,10 +439,8 @@ void store_named_data_val_new( int new_len ) size_t oid_len = strlen( (const char *) oid ); const unsigned char *new_val = (unsigned char *) "new value"; - if( new_len <= 0 ) + if( set_new_val == 0 ) new_val = NULL; - if( new_len < 0 ) - new_len = - new_len; found = mbedtls_asn1_store_named_data( &head, (const char *) oid, oid_len,