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 <werner.lewis@arm.com>
This commit is contained in:
Werner Lewis 2022-05-04 09:44:50 +01:00
parent 585a412129
commit 12ddae870c
3 changed files with 9 additions and 8 deletions

View file

@ -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 );

View file

@ -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

View file

@ -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,