Writing of X509v3 extensions supported

Standard extensions already in: basicConstraints, subjectKeyIdentifier
and authorityKeyIdentifier
diff --git a/include/polarssl/x509write.h b/include/polarssl/x509write.h
index 8600b42..af4d2a1 100644
--- a/include/polarssl/x509write.h
+++ b/include/polarssl/x509write.h
@@ -292,6 +292,60 @@
 void x509write_crt_set_md_alg( x509write_cert *ctx, md_type_t md_alg );
 
 /**
+ * \brief           Generic function to add to or replace an extension in the
+ *                  CRT
+ *
+ * \param ctx       CRT context to use
+ * \param oid       OID of the extension
+ * \param oid_len   length of the OID
+ * \param critical  if the extension is critical (per the RFC's definition)
+ * \param val       value of the extension OCTET STRING
+ * \param val_len   length of the value data
+ *
+ * \return          0 if successful, or a POLARSSL_ERR_X509WRITE_MALLOC_FAILED
+ */
+int x509write_crt_set_extension( x509write_cert *ctx,
+                                 const char *oid, size_t oid_len,
+                                 int critical,
+                                 const unsigned char *val, size_t val_len );
+
+/**
+ * \brief           Set the basicConstraints extension for a CRT
+ *
+ * \param ctx       CRT context to use
+ * \param is_ca     is this a CA certificate
+ * \param max_pathlen   maximum length of certificate chains below this
+ *                      certificate (only for CA certificates, -1 is
+ *                      inlimited)
+ *
+ * \return          0 if successful, or a POLARSSL_ERR_X509WRITE_MALLOC_FAILED
+ */
+int x509write_crt_set_basic_constraints( x509write_cert *ctx,
+                                         int is_ca, int max_pathlen );
+
+/**
+ * \brief           Set the subjectKeyIdentifier extension for a CRT
+ *                  Requires that x509write_crt_set_subject_key() has been
+ *                  called before
+ *
+ * \param ctx       CRT context to use
+ *
+ * \return          0 if successful, or a POLARSSL_ERR_X509WRITE_MALLOC_FAILED
+ */
+int x509write_crt_set_subject_key_identifier( x509write_cert *ctx );
+
+/**
+ * \brief           Set the authorityKeyIdentifier extension for a CRT
+ *                  Requires that x509write_crt_set_issuer_key() has been
+ *                  called before
+ *
+ * \param ctx       CRT context to use
+ *
+ * \return          0 if successful, or a POLARSSL_ERR_X509WRITE_MALLOC_FAILED
+ */
+int x509write_crt_set_authority_key_identifier( x509write_cert *ctx );
+
+/**
  * \brief           Free the contents of a CRT write context
  *
  * \param ctx       CRT context to free
diff --git a/library/x509write.c b/library/x509write.c
index 1428c67..c2af143 100644
--- a/library/x509write.c
+++ b/library/x509write.c
@@ -33,6 +33,8 @@
 #include "polarssl/md.h"
 #include "polarssl/oid.h"
 
+#include "polarssl/sha1.h"
+
 #if defined(POLARSSL_BASE64_C)
 #include "polarssl/base64.h"
 #endif
@@ -124,6 +126,27 @@
     return( ret );
 }
 
+/*
+ *  RSAPublicKey ::= SEQUENCE {
+ *      modulus           INTEGER,  -- n
+ *      publicExponent    INTEGER   -- e
+ *  }
+ */
+static int x509_write_rsa_pubkey( unsigned char **p, unsigned char *start,
+                                  rsa_context *rsa )
+{
+    int ret;
+    size_t len = 0;
+
+    ASN1_CHK_ADD( len, asn1_write_mpi( p, start, &rsa->E ) );
+    ASN1_CHK_ADD( len, asn1_write_mpi( p, start, &rsa->N ) );
+
+    ASN1_CHK_ADD( len, asn1_write_len( p, start, len ) );
+    ASN1_CHK_ADD( len, asn1_write_tag( p, start, ASN1_CONSTRUCTED | ASN1_SEQUENCE ) );
+
+    return( len );
+}
+
 void x509write_csr_init( x509_csr *ctx )
 {
     memset( ctx, 0, sizeof(x509_csr) );
@@ -165,14 +188,17 @@
     return x509write_string_to_names( &ctx->subject, subject_name );
 }
 
-int x509write_csr_set_extension( x509_csr *ctx,
-                                 const char *oid, size_t oid_len,
-                                 const unsigned char *val, size_t val_len )
+/* The first byte of the value in the asn1_named_data structure is reserved
+ * to store the critical boolean for us
+ */
+static int x509_set_extension( asn1_named_data **head,
+                               const char *oid, size_t oid_len,
+                               int critical,
+                               const unsigned char *val, size_t val_len )
 {
     asn1_named_data *cur;
 
-    if( ( cur = asn1_find_named_data( ctx->extensions, oid,
-                                      oid_len ) ) == NULL )
+    if( ( cur = asn1_find_named_data( *head, oid, oid_len ) ) == NULL )
     {
         cur = polarssl_malloc( sizeof(asn1_named_data) );
         if( cur == NULL )
@@ -188,8 +214,8 @@
             return( POLARSSL_ERR_X509WRITE_MALLOC_FAILED );
         }
 
-        cur->val.len = val_len;
-        cur->val.p = polarssl_malloc( val_len );
+        cur->val.len = val_len + 1;
+        cur->val.p = polarssl_malloc( val_len + 1 );
         if( cur->val.p == NULL )
         {
             polarssl_free( cur->oid.p );
@@ -199,16 +225,16 @@
 
         memcpy( cur->oid.p, oid, oid_len );
 
-        cur->next = ctx->extensions;
-        ctx->extensions = cur;
+        cur->next = *head;
+        *head = cur;
     }
 
-    if( cur->val.len != val_len )
+    if( cur->val.len != val_len + 1 )
     {
         polarssl_free( cur->val.p );
 
-        cur->val.len = val_len;
-        cur->val.p = polarssl_malloc( val_len );
+        cur->val.len = val_len + 1;
+        cur->val.p = polarssl_malloc( val_len + 1);
         if( cur->val.p == NULL )
         {
             polarssl_free( cur->oid.p );
@@ -217,11 +243,20 @@
         }
     }
 
-    memcpy( cur->val.p, val, val_len );
+    cur->val.p[0] = critical;
+    memcpy( cur->val.p + 1, val, val_len );
 
     return( 0 );
 }
 
+int x509write_csr_set_extension( x509_csr *ctx,
+                                 const char *oid, size_t oid_len,
+                                 const unsigned char *val, size_t val_len )
+{
+    return x509_set_extension( &ctx->extensions, oid, oid_len,
+                               0, val, val_len );
+}
+
 int x509write_csr_set_key_usage( x509_csr *ctx, unsigned char key_usage )
 {
     unsigned char buf[4];
@@ -350,6 +385,92 @@
     return( 0 );
 }
 
+int x509write_crt_set_extension( x509write_cert *ctx,
+                                 const char *oid, size_t oid_len,
+                                 int critical,
+                                 const unsigned char *val, size_t val_len )
+{
+    return x509_set_extension( &ctx->extensions, oid, oid_len,
+                               critical, val, val_len );
+}
+
+int x509write_crt_set_basic_constraints( x509write_cert *ctx,
+                                         int is_ca, int max_pathlen )
+{
+    int ret;
+    unsigned char buf[9];
+    unsigned char *c = buf + sizeof(buf);
+    size_t len = 0;
+
+    memset( buf, 0, sizeof(buf) );
+
+    if( is_ca && max_pathlen > 127 )
+        return( POLARSSL_ERR_X509WRITE_BAD_INPUT_DATA );
+
+    if( is_ca )
+    {
+        if( max_pathlen >= 0 )
+        {
+            ASN1_CHK_ADD( len, asn1_write_int( &c, buf, max_pathlen ) );
+        }
+        ASN1_CHK_ADD( len, asn1_write_bool( &c, buf, 1 ) );
+    }
+
+    ASN1_CHK_ADD( len, asn1_write_len( &c, buf, len ) );
+    ASN1_CHK_ADD( len, asn1_write_tag( &c, buf, ASN1_CONSTRUCTED | ASN1_SEQUENCE ) );
+
+    return x509write_crt_set_extension( ctx, OID_BASIC_CONSTRAINTS,
+                                        OID_SIZE( OID_BASIC_CONSTRAINTS ),
+                                        0, buf + sizeof(buf) - len, len );
+}
+
+int x509write_crt_set_subject_key_identifier( x509write_cert *ctx )
+{
+    int ret;
+    unsigned char buf[POLARSSL_MPI_MAX_SIZE * 2 + 20]; /* tag, length + 2xMPI */
+    unsigned char *c = buf + sizeof(buf);
+    size_t len = 0;
+
+    memset( buf, 0, sizeof(buf));
+    ASN1_CHK_ADD( len, x509_write_rsa_pubkey( &c, buf, ctx->subject_key ) );
+
+    sha1( buf + sizeof(buf) - len, len, buf + sizeof(buf) - 20 );
+    c = buf + sizeof(buf) - 20;
+    len = 20;
+
+    ASN1_CHK_ADD( len, asn1_write_len( &c, buf, len ) );
+    ASN1_CHK_ADD( len, asn1_write_tag( &c, buf, ASN1_OCTET_STRING ) );
+
+    return x509write_crt_set_extension( ctx, OID_SUBJECT_KEY_IDENTIFIER,
+                                        OID_SIZE( OID_SUBJECT_KEY_IDENTIFIER ),
+                                        0, buf + sizeof(buf) - len, len );
+}
+
+int x509write_crt_set_authority_key_identifier( x509write_cert *ctx )
+{
+    int ret;
+    unsigned char buf[POLARSSL_MPI_MAX_SIZE * 2 + 20]; /* tag, length + 2xMPI */
+    unsigned char *c = buf + sizeof(buf);
+    size_t len = 0;
+
+    memset( buf, 0, sizeof(buf));
+    ASN1_CHK_ADD( len, x509_write_rsa_pubkey( &c, buf, ctx->issuer_key ) );
+
+    sha1( buf + sizeof(buf) - len, len, buf + sizeof(buf) - 20 );
+    c = buf + sizeof(buf) - 20;
+    len = 20;
+
+    ASN1_CHK_ADD( len, asn1_write_len( &c, buf, len ) );
+    ASN1_CHK_ADD( len, asn1_write_tag( &c, buf, ASN1_CONTEXT_SPECIFIC | 0 ) );
+
+    ASN1_CHK_ADD( len, asn1_write_len( &c, buf, len ) );
+    ASN1_CHK_ADD( len, asn1_write_tag( &c, buf, ASN1_CONSTRUCTED | ASN1_SEQUENCE ) );
+
+    return x509write_crt_set_extension( ctx, OID_AUTHORITY_KEY_IDENTIFIER,
+                                   OID_SIZE( OID_AUTHORITY_KEY_IDENTIFIER ),
+                                   0, buf + sizeof(buf) - len, len );
+}
+
 int x509write_pubkey_der( rsa_context *rsa, unsigned char *buf, size_t size )
 {
     int ret;
@@ -358,17 +479,7 @@
 
     c = buf + size - 1;
 
-    /*
-    *  RSAPublicKey ::= SEQUENCE {
-    *      modulus           INTEGER,  -- n
-    *      publicExponent    INTEGER   -- e
-    *  }
-    */
-    ASN1_CHK_ADD( len, asn1_write_mpi( &c, buf, &rsa->E ) );
-    ASN1_CHK_ADD( len, asn1_write_mpi( &c, buf, &rsa->N ) );
-
-    ASN1_CHK_ADD( len, asn1_write_len( &c, buf, len ) );
-    ASN1_CHK_ADD( len, asn1_write_tag( &c, buf, ASN1_CONSTRUCTED | ASN1_SEQUENCE ) );
+    ASN1_CHK_ADD( len, x509_write_rsa_pubkey( &c, buf, rsa ) );
 
     if( c - buf < 1 )
         return( POLARSSL_ERR_ASN1_BUF_TOO_SMALL );
@@ -541,6 +652,59 @@
     return( len );
 }
 
+static int x509_write_extension( unsigned char **p, unsigned char *start,
+                                 asn1_named_data *ext )
+{
+    int ret;
+    size_t len = 0;
+
+    ASN1_CHK_ADD( len, asn1_write_raw_buffer( p, start, ext->val.p + 1,
+                                              ext->val.len - 1 ) );
+    ASN1_CHK_ADD( len, asn1_write_len( p, start, ext->val.len - 1 ) );
+    ASN1_CHK_ADD( len, asn1_write_tag( p, start, ASN1_OCTET_STRING ) );
+
+    if( ext->val.p[0] != 0 )
+    {
+        ASN1_CHK_ADD( len, asn1_write_bool( p, start, 1 ) );
+    }
+
+    ASN1_CHK_ADD( len, asn1_write_raw_buffer( p, start, ext->oid.p,
+                                              ext->oid.len ) );
+    ASN1_CHK_ADD( len, asn1_write_len( p, start, ext->oid.len ) );
+    ASN1_CHK_ADD( len, asn1_write_tag( p, start, ASN1_OID ) );
+
+    ASN1_CHK_ADD( len, asn1_write_len( p, start, len ) );
+    ASN1_CHK_ADD( len, asn1_write_tag( p, start, ASN1_CONSTRUCTED | ASN1_SEQUENCE ) );
+
+    return( len );
+}
+
+/*
+ * Extension  ::=  SEQUENCE  {
+ *     extnID      OBJECT IDENTIFIER,
+ *     critical    BOOLEAN DEFAULT FALSE,
+ *     extnValue   OCTET STRING
+ *                 -- contains the DER encoding of an ASN.1 value
+ *                 -- corresponding to the extension type identified
+ *                 -- by extnID
+ *     }
+ */
+static int x509_write_extensions( unsigned char **p, unsigned char *start,
+                                 asn1_named_data *first )
+{
+    int ret;
+    size_t len = 0;
+    asn1_named_data *cur_ext = first;
+
+    while( cur_ext != NULL )
+    {
+        ASN1_CHK_ADD( len, x509_write_extension( p, start, cur_ext ) );
+        cur_ext = cur_ext->next;
+    }
+
+    return( len );
+}
+
 int x509write_csr_der( x509_csr *ctx, unsigned char *buf, size_t size )
 {
     int ret;
@@ -551,31 +715,10 @@
     unsigned char tmp_buf[2048];
     size_t pub_len = 0, sig_len = 0;
     size_t len = 0;
-    asn1_named_data *cur_ext = ctx->extensions;
 
     c = tmp_buf + 2048 - 1;
 
-    while( cur_ext != NULL )
-    {
-        size_t ext_len = 0;
-
-        ASN1_CHK_ADD( ext_len, asn1_write_raw_buffer( &c, tmp_buf, cur_ext->val.p,
-                                                      cur_ext->val.len ) );
-        ASN1_CHK_ADD( ext_len, asn1_write_len( &c, tmp_buf, cur_ext->val.len ) );
-        ASN1_CHK_ADD( ext_len, asn1_write_tag( &c, tmp_buf, ASN1_OCTET_STRING ) );
-
-        ASN1_CHK_ADD( ext_len, asn1_write_raw_buffer( &c, tmp_buf, cur_ext->oid.p,
-                                                      cur_ext->oid.len ) );
-        ASN1_CHK_ADD( ext_len, asn1_write_len( &c, tmp_buf, cur_ext->oid.len ) );
-        ASN1_CHK_ADD( ext_len, asn1_write_tag( &c, tmp_buf, ASN1_OID ) );
-
-        ASN1_CHK_ADD( ext_len, asn1_write_len( &c, tmp_buf, ext_len ) );
-        ASN1_CHK_ADD( ext_len, asn1_write_tag( &c, tmp_buf, ASN1_CONSTRUCTED | ASN1_SEQUENCE ) );
-
-        cur_ext = cur_ext->next;
-
-        len += ext_len;
-    }
+    ASN1_CHK_ADD( len, x509_write_extensions( &c, tmp_buf, ctx->extensions ) );
 
     if( len )
     {
@@ -664,7 +807,6 @@
     unsigned char tmp_buf[2048];
     size_t sub_len = 0, pub_len = 0, sig_len = 0;
     size_t len = 0;
-    asn1_named_data *cur_ext = ctx->extensions;
 
     c = tmp_buf + 2048 - 1;
 
@@ -674,6 +816,14 @@
     if( ret != 0 )
         return( ret );
 
+    /*
+     *  Extensions  ::=  SEQUENCE SIZE (1..MAX) OF Extension
+     */
+    ASN1_CHK_ADD( len, x509_write_extensions( &c, tmp_buf, ctx->extensions ) );
+    ASN1_CHK_ADD( len, asn1_write_len( &c, tmp_buf, len ) );
+    ASN1_CHK_ADD( len, asn1_write_tag( &c, tmp_buf, ASN1_CONSTRUCTED | ASN1_SEQUENCE ) );
+    ASN1_CHK_ADD( len, asn1_write_len( &c, tmp_buf, len ) );
+    ASN1_CHK_ADD( len, asn1_write_tag( &c, tmp_buf, ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 3 ) );
 
     /*
      *  SubjectPublicKeyInfo  ::=  SEQUENCE  {
diff --git a/programs/x509/cert_write.c b/programs/x509/cert_write.c
index 59c49b2..7a811d4 100644
--- a/programs/x509/cert_write.c
+++ b/programs/x509/cert_write.c
@@ -63,6 +63,8 @@
 #define DFL_NOT_BEFORE          "20010101000000"
 #define DFL_NOT_AFTER           "20301231235959"
 #define DFL_SERIAL              "1"
+#define DFL_IS_CA               0
+#define DFL_MAX_PATHLEN         -1
 #define DFL_KEY_USAGE           0
 #define DFL_NS_CERT_TYPE        0
 
@@ -81,6 +83,8 @@
     char *not_before;           /* validity period not before           */
     char *not_after;            /* validity period not after            */
     char *serial;               /* serial number string                 */
+    int is_ca;                  /* is a CA certificate                  */
+    int max_pathlen;            /* maximum CA path length               */
     unsigned char key_usage;    /* key usage flags                      */
     unsigned char ns_cert_type; /* NS cert type                         */
 } opt;
@@ -122,6 +126,8 @@
     "    serial=%%s           default: 1\n"             \
     "    not_before=%%s       default: 20010101000000\n"\
     "    not_after=%%s        default: 20301231235959\n"\
+    "    is_ca=%%d            default: 0 (disabled)\n"  \
+    "    max_pathlen=%%d      default: -1 (none)\n"     \
     "    key_usage=%%s        default: (empty)\n"       \
     "                        Comma-separated-list of values:\n"     \
     "                          digital_signature\n"     \
@@ -180,6 +186,8 @@
     opt.not_before          = DFL_NOT_BEFORE;
     opt.not_after           = DFL_NOT_AFTER;
     opt.serial              = DFL_SERIAL;
+    opt.is_ca               = DFL_IS_CA;
+    opt.max_pathlen         = DFL_MAX_PATHLEN;
     opt.key_usage           = DFL_KEY_USAGE;
     opt.ns_cert_type        = DFL_NS_CERT_TYPE;
 
@@ -228,6 +236,18 @@
         {
             opt.serial = q;
         }
+        else if( strcmp( p, "is_ca" ) == 0 )
+        {
+            opt.is_ca = atoi( q );
+            if( opt.is_ca < 0 || opt.is_ca > 1 )
+                goto usage;
+        }
+        else if( strcmp( p, "max_pathlen" ) == 0 )
+        {
+            opt.max_pathlen = atoi( q );
+            if( opt.max_pathlen < -1 || opt.max_pathlen > 127 )
+                goto usage;
+        }
         else if( strcmp( p, "key_usage" ) == 0 )
         {
             while( q != NULL )
@@ -389,6 +409,52 @@
 
     printf( " ok\n" );
 
+    printf( "  . Adding the Basic Constraints extension ..." );
+    fflush( stdout );
+
+    ret = x509write_crt_set_basic_constraints( &crt, opt.is_ca,
+                                               opt.max_pathlen );
+    if( ret != 0 )
+    {
+#ifdef POLARSSL_ERROR_C
+        error_strerror( ret, buf, 1024 );
+#endif
+        printf( " failed\n  !  x509write_crt_set_basic_contraints returned -0x%02x - %s\n\n", -ret, buf );
+        goto exit;
+    }
+
+    printf( " ok\n" );
+
+    printf( "  . Adding the Subject Key Identifier ..." );
+    fflush( stdout );
+
+    ret = x509write_crt_set_subject_key_identifier( &crt );
+    if( ret != 0 )
+    {
+#ifdef POLARSSL_ERROR_C
+        error_strerror( ret, buf, 1024 );
+#endif
+        printf( " failed\n  !  x509write_crt_set_subject_key_identifier returned -0x%02x - %s\n\n", -ret, buf );
+        goto exit;
+    }
+
+    printf( " ok\n" );
+
+    printf( "  . Adding the Authority Key Identifier ..." );
+    fflush( stdout );
+
+    ret = x509write_crt_set_authority_key_identifier( &crt );
+    if( ret != 0 )
+    {
+#ifdef POLARSSL_ERROR_C
+        error_strerror( ret, buf, 1024 );
+#endif
+        printf( " failed\n  !  x509write_crt_set_authority_key_identifier returned -0x%02x - %s\n\n", -ret, buf );
+        goto exit;
+    }
+
+    printf( " ok\n" );
+
     /*
      * 1.2. Writing the request
      */