From 09c0a2364b9603936bf4e56e839ea7d10dcc120a Mon Sep 17 00:00:00 2001 From: Gilles Peskine Date: Mon, 4 Mar 2019 15:00:06 +0100 Subject: [PATCH] mbedtls_asn1_store_named_data: clarify val allocation behavior Document how mbedtls_asn1_store_named_data allocates val.p in the new or modified entry. Change the behavior to be more regular, always setting the new length to val_len. This does not affect the previous documented behavior since this aspect was not documented. This does not affect current usage in Mbed TLS's X.509 module where calls with the same OID always use the same size for the associated value. --- include/mbedtls/asn1write.h | 8 ++++++-- library/asn1write.c | 20 ++++++++++++++------ 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/include/mbedtls/asn1write.h b/include/mbedtls/asn1write.h index 8ecab4e2dd..982414626e 100644 --- a/include/mbedtls/asn1write.h +++ b/include/mbedtls/asn1write.h @@ -334,9 +334,13 @@ int mbedtls_asn1_write_octet_string( unsigned char **p, unsigned char *start, * through (will be updated in case of a new entry). * \param oid The OID to look for. * \param oid_len The size of the OID. - * \param val The data to store (can be \c NULL if you want to fill - * it by hand). + * \param val The associated data to store. If this is \c NULL, + * no data is copied to the new or existing buffer. * \param val_len The minimum length of the data buffer needed. + * If this is 0, do not allocate a buffer for the associated + * data. + * If the OID was already present, enlarge, shrink or free + * the existing buffer to fit \p val_len. * * \return A pointer to the new / existing entry on success. * \return \c NULL if if there was a memory allocation error. diff --git a/library/asn1write.c b/library/asn1write.c index 98c6766725..a138d0b75c 100644 --- a/library/asn1write.c +++ b/library/asn1write.c @@ -432,18 +432,26 @@ mbedtls_asn1_named_data *mbedtls_asn1_store_named_data( memcpy( cur->oid.p, oid, oid_len ); cur->val.len = val_len; - cur->val.p = mbedtls_calloc( 1, val_len ); - if( cur->val.p == NULL ) + if( val_len != 0 ) { - mbedtls_free( cur->oid.p ); - mbedtls_free( cur ); - return( NULL ); + cur->val.p = mbedtls_calloc( 1, val_len ); + if( cur->val.p == NULL ) + { + mbedtls_free( cur->oid.p ); + mbedtls_free( cur ); + return( NULL ); + } } cur->next = *head; *head = cur; } - else if( cur->val.len < val_len ) + else if( val_len == 0 ) + { + mbedtls_free( cur->val.p ); + cur->val.p = NULL; + } + else if( cur->val.len != val_len ) { /* * Enlarge existing value buffer if needed