x509: trailing bytes in DER: fix bug
Fix bug in mbedtls_x509_crt_parse that caused trailing extra data in the
buffer after DER certificates to be included in the raw representation. #377
diff --git a/ChangeLog b/ChangeLog
index e9b6790..ed32f0b 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -11,6 +11,8 @@
* Fix issue in Makefile that prevented building using armar. #386
* Fix memory leak that occured only when ECJPAKE was enabled and ECDHE and
ECDSA was disabled in config.h . The leak didn't occur by default.
+ * Fix bug in mbedtls_x509_crt_parse that caused trailing extra data in the
+ buffer after DER certificates to be included in the raw representation.
Changes
* On ARM platforms, when compiling with -O0 with GCC, Clang or armcc5,
diff --git a/library/x509_crt.c b/library/x509_crt.c
index 6dc5ad3..a1ce254 100644
--- a/library/x509_crt.c
+++ b/library/x509_crt.c
@@ -680,14 +680,9 @@
if( crt == NULL || buf == NULL )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
- p = mbedtls_calloc( 1, len = buflen );
- if( p == NULL )
- return( MBEDTLS_ERR_X509_ALLOC_FAILED );
-
- memcpy( p, buf, buflen );
-
- crt->raw.p = p;
- crt->raw.len = len;
+ // Use the original buffer until we figure out actual length
+ p = (unsigned char*) buf;
+ len = buflen;
end = p + len;
/*
@@ -711,6 +706,18 @@
}
crt_end = p + len;
+ // Create and populate a new buffer for the raw field
+ crt->raw.len = crt_end - buf;
+ crt->raw.p = p = mbedtls_calloc( 1, crt->raw.len );
+ if( p == NULL )
+ return( MBEDTLS_ERR_X509_ALLOC_FAILED );
+
+ memcpy( p, buf, crt->raw.len );
+
+ // Direct pointers to the new buffer
+ p += crt->raw.len - len;
+ end = crt_end = p + len;
+
/*
* TBSCertificate ::= SEQUENCE {
*/