Add new function mbedtls_asn1_write_named_bitstring()
Add a new function mbedtls_asn1_write_named_bitstring() that removes
trailing 0s at the end of DER encoded bitstrings. The function is
implemented according to Hanno Becker's suggestions.
This commit also changes the functions x509write_crt_set_ns_cert_type
and crt_set_key_usage to call the new function as the use named
bitstrings instead of the regular bitstrings.
diff --git a/library/x509write_crt.c b/library/x509write_crt.c
index b1ef216..b6cb745 100644
--- a/library/x509write_crt.c
+++ b/library/x509write_crt.c
@@ -221,23 +221,36 @@
int mbedtls_x509write_crt_set_key_usage( mbedtls_x509write_cert *ctx,
unsigned int key_usage )
{
- unsigned char buf[4], ku;
+ unsigned char buf[5], ku[2];
unsigned char *c;
int ret;
+ const unsigned int allowed_bits = MBEDTLS_X509_KU_DIGITAL_SIGNATURE |
+ MBEDTLS_X509_KU_NON_REPUDIATION |
+ MBEDTLS_X509_KU_KEY_ENCIPHERMENT |
+ MBEDTLS_X509_KU_DATA_ENCIPHERMENT |
+ MBEDTLS_X509_KU_KEY_AGREEMENT |
+ MBEDTLS_X509_KU_KEY_CERT_SIGN |
+ MBEDTLS_X509_KU_CRL_SIGN |
+ MBEDTLS_X509_KU_ENCIPHER_ONLY |
+ MBEDTLS_X509_KU_DECIPHER_ONLY;
- /* We currently only support 7 bits, from 0x80 to 0x02 */
- if( ( key_usage & ~0xfe ) != 0 )
+ /* Check that nothing other than the allowed flags is set */
+ if( ( key_usage & ~allowed_bits ) != 0 )
return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE );
- c = buf + 4;
- ku = (unsigned char) key_usage;
+ c = buf + 5;
+ ku[0] = (unsigned char)( key_usage );
+ ku[1] = (unsigned char)( key_usage >> 8 );
+ ret = mbedtls_asn1_write_named_bitstring( &c, buf, ku, 9 );
- if( ( ret = mbedtls_asn1_write_bitstring( &c, buf, &ku, 7 ) ) != 4 )
+ if( ret < 0 )
return( ret );
+ else if( ret < 3 || ret > 5 )
+ return( MBEDTLS_ERR_X509_INVALID_FORMAT );
ret = mbedtls_x509write_crt_set_extension( ctx, MBEDTLS_OID_KEY_USAGE,
MBEDTLS_OID_SIZE( MBEDTLS_OID_KEY_USAGE ),
- 1, buf, 4 );
+ 1, c, (size_t)ret );
if( ret != 0 )
return( ret );
@@ -253,12 +266,13 @@
c = buf + 4;
- if( ( ret = mbedtls_asn1_write_bitstring( &c, buf, &ns_cert_type, 8 ) ) != 4 )
+ ret = mbedtls_asn1_write_named_bitstring( &c, buf, &ns_cert_type, 8 );
+ if( ret < 3 || ret > 4 )
return( ret );
ret = mbedtls_x509write_crt_set_extension( ctx, MBEDTLS_OID_NS_CERT_TYPE,
MBEDTLS_OID_SIZE( MBEDTLS_OID_NS_CERT_TYPE ),
- 0, buf, 4 );
+ 0, c, (size_t)ret );
if( ret != 0 )
return( ret );