Parsing of PKCS#8 encrypted private key files added and PKCS#12 basis

PKCS#8 encrypted key file support has been added to x509parse_key() with
support for some PCKS#12 PBE functions (pbeWithSHAAnd128BitRC4,
pbeWithSHAAnd3-KeyTripleDES-CBC and pbeWithSHAAnd2-KeyTripleDES-CBC)
diff --git a/library/CMakeLists.txt b/library/CMakeLists.txt
index a663e52..801da88 100644
--- a/library/CMakeLists.txt
+++ b/library/CMakeLists.txt
@@ -31,6 +31,7 @@
      pbkdf2.c
      pem.c
      pkcs11.c
+     pkcs12.c
      rsa.c
      sha1.c
      sha2.c
diff --git a/library/Makefile b/library/Makefile
index 603f5d1..a66333f 100644
--- a/library/Makefile
+++ b/library/Makefile
@@ -44,7 +44,7 @@
 		md.o		md_wrap.o	md2.o			\
 		md4.o		md5.o		net.o			\
 		padlock.o	pbkdf2.o	pem.o			\
-		pkcs11.o								\
+		pkcs11.o	pkcs12.o					\
 		rsa.o		sha1.o		sha2.o			\
 		sha4.o		ssl_cache.o	ssl_cli.o		\
 		ssl_srv.o								\
diff --git a/library/error.c b/library/error.c
index 42f3cac..48f8e49 100644
--- a/library/error.c
+++ b/library/error.c
@@ -105,6 +105,10 @@
 #include "polarssl/pem.h"
 #endif
 
+#if defined(POLARSSL_PKCS12_C)
+#include "polarssl/pkcs12.h"
+#endif
+
 #if defined(POLARSSL_RSA_C)
 #include "polarssl/rsa.h"
 #endif
@@ -216,6 +220,15 @@
             snprintf( buf, buflen, "PEM - Bad input parameters to function" );
 #endif /* POLARSSL_PEM_C */
 
+#if defined(POLARSSL_PKCS12_C)
+        if( use_ret == -(POLARSSL_ERR_PKCS12_BAD_INPUT_DATA) )
+            snprintf( buf, buflen, "PKCS12 - Bad input parameters to function" );
+        if( use_ret == -(POLARSSL_ERR_PKCS12_FEATURE_UNAVAILABLE) )
+            snprintf( buf, buflen, "PKCS12 - Feature not available, e.g. unsupported encryption scheme" );
+        if( use_ret == -(POLARSSL_ERR_PKCS12_PBE_INVALID_FORMAT) )
+            snprintf( buf, buflen, "PKCS12 - PBE ASN.1 data not as expected" );
+#endif /* POLARSSL_PKCS12_C */
+
 #if defined(POLARSSL_RSA_C)
         if( use_ret == -(POLARSSL_ERR_RSA_BAD_INPUT_DATA) )
             snprintf( buf, buflen, "RSA - Bad input parameters to function" );
diff --git a/library/pkcs12.c b/library/pkcs12.c
new file mode 100644
index 0000000..39ab10f
--- /dev/null
+++ b/library/pkcs12.c
@@ -0,0 +1,363 @@
+/*
+ *  PKCS#12 Personal Information Exchange Syntax
+ *
+ *  Copyright (C) 2006-2013, Brainspark B.V.
+ *
+ *  This file is part of PolarSSL (http://www.polarssl.org)
+ *  Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
+ *
+ *  All rights reserved.
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License along
+ *  with this program; if not, write to the Free Software Foundation, Inc.,
+ *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+/*
+ *  The PKCS #12 Personal Information Exchange Syntax Standard v1.1
+ *
+ *  http://www.rsa.com/rsalabs/pkcs/files/h11301-wp-pkcs-12v1-1-personal-information-exchange-syntax.pdf
+ *  ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12v1-1.asn
+ */
+
+#include "polarssl/config.h"
+
+#if defined(POLARSSL_PKCS12_C)
+
+#include "polarssl/pkcs12.h"
+#include "polarssl/asn1.h"
+
+#if defined(POLARSSL_ARC4_C)
+#include "polarssl/arc4.h"
+#endif
+
+#if defined(POLARSSL_DES_C)
+#include "polarssl/des.h"
+#endif
+
+static int pkcs12_parse_pbe_params( unsigned char **p,
+                                    const unsigned char *end,
+                                    asn1_buf *salt, int *iterations )
+{
+    int ret;
+    size_t len = 0;
+
+    /*
+     *  pkcs-12PbeParams ::= SEQUENCE {
+     *    salt          OCTET STRING,
+     *    iterations    INTEGER
+     *  }
+     *
+     */
+    if( ( ret = asn1_get_tag( p, end, &len,
+            ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
+    {
+        return( POLARSSL_ERR_PKCS12_PBE_INVALID_FORMAT + ret );
+    }
+
+    end = *p + len;
+
+    if( ( ret = asn1_get_tag( p, end, &salt->len, ASN1_OCTET_STRING ) ) != 0 )
+        return( POLARSSL_ERR_PKCS12_PBE_INVALID_FORMAT + ret );
+
+    salt->p = *p;
+    *p += salt->len;
+
+    if( ( ret = asn1_get_int( p, end, iterations ) ) != 0 )
+        return( POLARSSL_ERR_PKCS12_PBE_INVALID_FORMAT + ret );
+
+    if( *p != end )
+        return( POLARSSL_ERR_PKCS12_PBE_INVALID_FORMAT +
+                POLARSSL_ERR_ASN1_LENGTH_MISMATCH );
+
+    return( 0 );
+}
+
+static int pkcs12_pbe_derive_key_iv( asn1_buf *pbe_params,
+                                     const unsigned char *pwd,  size_t pwdlen,
+                                     unsigned char *key, size_t keylen,
+                                     unsigned char *iv,  size_t ivlen )
+{
+    int ret, iterations;
+    asn1_buf salt;
+    size_t i;
+    unsigned char *p, *end;
+    unsigned char unipwd[258];
+
+    memset(&salt, 0, sizeof(asn1_buf));
+    memset(&unipwd, 0, sizeof(unipwd));
+
+    p = pbe_params->p;
+    end = p + pbe_params->len;
+
+    if( ( ret = pkcs12_parse_pbe_params( &p, end, &salt, &iterations ) ) != 0 )
+        return( ret );
+
+    for(i = 0; i < pwdlen; i++)
+        unipwd[i * 2 + 1] = pwd[i];
+
+    if( ( ret = pkcs12_derivation( key, keylen, unipwd, pwdlen * 2 + 2,
+                                   salt.p, salt.len, POLARSSL_MD_SHA1,
+                                   PKCS12_DERIVE_KEY, iterations ) ) != 0 )
+    {
+        return( ret );
+    }
+
+    if( iv == NULL || ivlen == 0 )
+        return( 0 );
+
+    if( ( ret = pkcs12_derivation( iv, ivlen, unipwd, pwdlen * 2 + 2,
+                                   salt.p, salt.len, POLARSSL_MD_SHA1,
+                                   PKCS12_DERIVE_IV, iterations ) ) != 0 )
+    {
+        return( ret );
+    }
+    return( 0 );
+}
+
+int pkcs12_pbe_sha1_rc4_128( asn1_buf *pbe_params, int mode,
+                             const unsigned char *pwd,  size_t pwdlen,
+                             const unsigned char *data, size_t len,
+                             unsigned char *output )
+{
+#if !defined(POLARSSL_ARC4_C)
+    ((void) pbe_params);
+    ((void) mode);
+    ((void) pwd);
+    ((void) pwdlen);
+    ((void) data);
+    ((void) len);
+    ((void) output);
+    return( POLARSSL_ERR_PKCS12_FEATURE_UNAVAILABLE );
+#else
+    int ret;
+    unsigned char key[16];
+    arc4_context ctx;
+    ((void) mode);
+
+    if( ( ret = pkcs12_pbe_derive_key_iv( pbe_params, pwd, pwdlen,
+                                          key, 16, NULL, 0 ) ) != 0 )
+    {
+        return( ret );
+    }
+
+    arc4_setup( &ctx, key, 16 );
+    if( ( ret = arc4_crypt( &ctx, len, data, output ) ) != 0 )
+        return( ret );
+
+    return( 0 );
+}
+#endif /* POLARSSL_ARC4_C */
+
+int pkcs12_pbe_sha1_des2_ede_cbc( asn1_buf *pbe_params, int mode,
+                                  const unsigned char *pwd,  size_t pwdlen,
+                                  const unsigned char *data, size_t len,
+                                  unsigned char *output )
+{
+#if !defined(POLARSSL_DES_C)
+    ((void) pbe_params);
+    ((void) mode);
+    ((void) pwd);
+    ((void) pwdlen);
+    ((void) data);
+    ((void) len);
+    ((void) output);
+    return( POLARSSL_ERR_PKCS12_FEATURE_UNAVAILABLE );
+#else
+    int ret;
+    unsigned char key[16];
+    unsigned char iv[8];
+    des3_context ctx;
+
+    if( ( ret = pkcs12_pbe_derive_key_iv( pbe_params, pwd, pwdlen,
+                                          key, 16, iv, 8 ) ) != 0 )
+    {
+        return( ret );
+    }
+
+    if( mode == PKCS12_PBE_ENCRYPT )
+    {
+        des3_set2key_enc( &ctx, key );
+        des3_crypt_cbc( &ctx, DES_ENCRYPT, len, iv, data, output );
+    }
+    else
+    {
+        des3_set2key_dec( &ctx, key );
+        des3_crypt_cbc( &ctx, DES_DECRYPT, len, iv, data, output );
+    }
+
+    return( 0 );
+}
+#endif /* POLARSSL_DES_C */
+
+int pkcs12_pbe_sha1_des3_ede_cbc( asn1_buf *pbe_params, int mode,
+                                  const unsigned char *pwd,  size_t pwdlen,
+                                  const unsigned char *data, size_t len,
+                                  unsigned char *output )
+{
+#if !defined(POLARSSL_DES_C)
+    ((void) pbe_params);
+    ((void) mode);
+    ((void) pwd);
+    ((void) pwdlen);
+    ((void) data);
+    ((void) len);
+    ((void) output);
+    return( POLARSSL_ERR_PKCS12_FEATURE_UNAVAILABLE );
+#else
+    int ret;
+    unsigned char key[24];
+    unsigned char iv[8];
+    des3_context ctx;
+
+    if( ( ret = pkcs12_pbe_derive_key_iv( pbe_params, pwd, pwdlen,
+                                          key, 24, iv, 8 ) ) != 0 )
+    {
+        return( ret );
+    }
+
+    if( mode == PKCS12_PBE_ENCRYPT )
+    {
+        des3_set3key_enc( &ctx, key );
+        des3_crypt_cbc( &ctx, DES_ENCRYPT, len, iv, data, output );
+    }
+    else
+    {
+        des3_set3key_dec( &ctx, key );
+        des3_crypt_cbc( &ctx, DES_DECRYPT, len, iv, data, output );
+    }
+
+    return( 0 );
+}
+#endif /* POLARSSL_DES_C */
+
+static void pkcs12_fill_buffer( unsigned char *data, size_t data_len,
+                                const unsigned char *filler, size_t fill_len )
+{
+    unsigned char *p = data;
+    size_t use_len;
+
+    while( data_len > 0 )
+    {
+        use_len = ( data_len > fill_len ) ? fill_len : data_len;
+        memcpy( p, filler, use_len );
+        p += use_len;
+        data_len -= use_len;
+    }
+}
+
+int pkcs12_derivation( unsigned char *data, size_t datalen,
+                       const unsigned char *pwd, size_t pwdlen,
+                       const unsigned char *salt, size_t saltlen,
+                       md_type_t md_type, int id, int iterations )
+{
+    int ret, i;
+    unsigned int j;
+
+    unsigned char diversifier[128];
+    unsigned char salt_block[128], pwd_block[128], hash_block[128];
+    unsigned char hash_output[POLARSSL_MD_MAX_SIZE];
+    unsigned char *p;
+    unsigned char c;
+
+    size_t hlen, use_len, v;
+
+    const md_info_t *md_info;
+    md_context_t md_ctx;
+
+    // This version only allows max of 64 bytes of password or salt
+    if( datalen > 128 || pwdlen > 64 || saltlen > 64 )
+        return( POLARSSL_ERR_PKCS12_BAD_INPUT_DATA );
+
+    md_info = md_info_from_type( md_type );
+    if( md_info == NULL )
+        return( POLARSSL_ERR_PKCS12_FEATURE_UNAVAILABLE );
+
+    if ( ( ret = md_init_ctx( &md_ctx, md_info ) ) != 0 )
+        return( ret );
+    hlen = md_get_size( md_info );
+
+    if( hlen <= 32 )
+        v = 64;
+    else
+        v = 128;
+
+    memset( diversifier, (unsigned char) id, v );
+
+    pkcs12_fill_buffer( salt_block, v, salt, saltlen );
+    pkcs12_fill_buffer( pwd_block,  v, pwd,  pwdlen  );
+
+    p = data;
+    while( datalen > 0 )
+    {
+        // Calculate hash( diversifier || salt_block || pwd_block )
+        if( ( ret = md_starts( &md_ctx ) ) != 0 )
+            return( ret );
+
+        if( ( ret = md_update( &md_ctx, diversifier, v ) ) != 0 )
+            return( ret );
+
+        if( ( ret = md_update( &md_ctx, salt_block, v ) ) != 0 )
+            return( ret );
+
+        if( ( ret = md_update( &md_ctx, pwd_block, v ) ) != 0 )
+            return( ret );
+
+        if( ( ret = md_finish( &md_ctx, hash_output ) ) != 0 )
+            return( ret );
+
+        // Perform remaining ( iterations - 1 ) recursive hash calculations
+        for( i = 1; i < iterations; i++ )
+        {
+            if( ( ret = md( md_info, hash_output, hlen, hash_output ) ) != 0 )
+                return( ret );
+        }
+
+        use_len = ( datalen > hlen ) ? hlen : datalen;
+        memcpy( p, hash_output, use_len );
+        datalen -= use_len;
+        p += use_len;
+
+        if( datalen == 0 )
+            break;
+
+        // Concatenating copies of hash_output into hash_block (B)
+        pkcs12_fill_buffer( hash_block, v, hash_output, hlen );
+
+        // B += 1
+        for( i = v; i > 0; i-- )
+            if( ++hash_block[i - 1] != 0 )
+                break;
+
+        // salt_block += B
+        c = 0;
+        for( i = v; i > 0; i-- )
+        {
+            j = salt_block[i - 1] + hash_block[i - 1] + c;
+            c = (unsigned char) (j >> 8);
+            salt_block[i - 1] = j & 0xFF;
+        }
+
+        // pwd_block  += B
+        c = 0;
+        for( i = v; i > 0; i-- )
+        {
+            j = pwd_block[i - 1] + hash_block[i - 1] + c;
+            c = (unsigned char) (j >> 8);
+            pwd_block[i - 1] = j & 0xFF;
+        }
+    }
+
+    return( 0 );
+}
+
+#endif /* POLARSSL_PKCS12_C */
diff --git a/library/x509parse.c b/library/x509parse.c
index 1906df6..ce75d59 100644
--- a/library/x509parse.c
+++ b/library/x509parse.c
@@ -61,6 +61,7 @@
 #include "polarssl/sha4.h"
 #endif
 #include "polarssl/dhm.h"
+#include "polarssl/pkcs12.h"
 
 #include <string.h>
 #include <stdlib.h>
@@ -78,6 +79,11 @@
 #endif
 #endif
 
+/* Compare a given OID string with an OID x509_buf * */
+#define OID_CMP(oid_str, oid_buf) \
+        ( ( OID_SIZE(oid_str) == (oid_buf)->len ) && \
+                memcmp( (oid_str), (oid_buf)->p, (oid_buf)->len) == 0)
+
 /*
  *  Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }
  */
@@ -2190,6 +2196,116 @@
 }
 
 /*
+ * Parse an unencrypted PKCS#8 encoded private RSA key
+ */
+static int x509parse_key_pkcs8_encrypted_der(
+                                    rsa_context *rsa,
+                                    const unsigned char *key,
+                                    size_t keylen,
+                                    const unsigned char *pwd,
+                                    size_t pwdlen )
+{
+    int ret;
+    size_t len;
+    unsigned char *p, *end, *end2;
+    x509_buf pbe_alg_oid, pbe_params;
+    unsigned char buf[2048];
+
+    memset(buf, 0, 2048);
+
+    p = (unsigned char *) key;
+    end = p + keylen;
+
+    /*
+     * This function parses the EncryptedPrivatKeyInfo object (PKCS#8)
+     *
+     *  EncryptedPrivateKeyInfo ::= SEQUENCE {
+     *    encryptionAlgorithm  EncryptionAlgorithmIdentifier,
+     *    encryptedData        EncryptedData
+     *  }
+     *
+     *  EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
+     *
+     *  EncryptedData ::= OCTET STRING
+     *
+     *  The EncryptedData OCTET STRING is a PKCS#8 PrivateKeyInfo
+     */
+    if( ( ret = asn1_get_tag( &p, end, &len,
+            ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
+    {
+        return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
+    }
+
+    end = p + len;
+
+    if( ( ret = asn1_get_tag( &p, end, &len,
+            ASN1_CONSTRUCTED | ASN1_SEQUENCE ) ) != 0 )
+    {
+        return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
+    }
+
+    end2 = p + len;
+
+    if( ( ret = asn1_get_tag( &p, end, &pbe_alg_oid.len, ASN1_OID ) ) != 0 )
+        return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
+
+    pbe_alg_oid.p = p;
+    p += pbe_alg_oid.len;
+
+    /*
+     * Store the algorithm parameters
+     */
+    pbe_params.p = p;
+    pbe_params.len = end2 - p;
+    p += pbe_params.len;
+
+    if( ( ret = asn1_get_tag( &p, end, &len, ASN1_OCTET_STRING ) ) != 0 )
+        return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT + ret );
+
+    // buf has been sized to 2048 bytes
+    if( len > 2048 )
+        return( POLARSSL_ERR_X509_INVALID_INPUT );
+
+    /*
+     * Decrypt EncryptedData with appropriate PDE
+     */
+    if( OID_CMP( OID_PKCS12_PBE_SHA1_DES3_EDE_CBC, &pbe_alg_oid ) )
+    {
+        if( ( ret = pkcs12_pbe_sha1_des3_ede_cbc( &pbe_params,
+                                                   PKCS12_PBE_DECRYPT,
+                                                   pwd, pwdlen,
+                                                   p, len, buf ) ) != 0 )
+        {
+            return( ret );
+        }
+    }
+    else if( OID_CMP( OID_PKCS12_PBE_SHA1_DES2_EDE_CBC, &pbe_alg_oid ) )
+    {
+        if( ( ret = pkcs12_pbe_sha1_des2_ede_cbc( &pbe_params,
+                                                   PKCS12_PBE_DECRYPT,
+                                                   pwd, pwdlen,
+                                                   p, len, buf ) ) != 0 )
+        {
+            return( ret );
+        }
+    }
+    else if( OID_CMP( OID_PKCS12_PBE_SHA1_RC4_128, &pbe_alg_oid ) )
+    {
+        if( ( ret = pkcs12_pbe_sha1_rc4_128( &pbe_params,
+                                             PKCS12_PBE_DECRYPT,
+                                             pwd, pwdlen,
+                                             p, len, buf ) ) != 0 )
+        {
+            return( ret );
+        }
+    }
+    else
+        return( POLARSSL_ERR_X509_FEATURE_UNAVAILABLE );
+
+    return x509parse_key_pkcs8_unencrypted_der( rsa, buf, len );
+}
+
+/*
  * Parse a private RSA key
  */
 int x509parse_key( rsa_context *rsa, const unsigned char *key, size_t keylen,
@@ -2243,7 +2359,27 @@
         return( ret );
     }
 
-    pem_free( &pem );
+    ret = pem_read_buffer( &pem,
+                           "-----BEGIN ENCRYPTED PRIVATE KEY-----",
+                           "-----END ENCRYPTED PRIVATE KEY-----",
+                           key, NULL, 0, &len );
+    if( ret == 0 )
+    {
+        if( ( ret = x509parse_key_pkcs8_encrypted_der( rsa,
+                                                pem.buf, pem.buflen,
+                                                pwd, pwdlen ) ) != 0 )
+        {
+            rsa_free( rsa );
+        }
+
+        pem_free( &pem );
+        return( ret );
+    }
+    else if( ret != POLARSSL_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
+    {
+        pem_free( &pem );
+        return( ret );
+    }
 #else
     ((void) pwd);
     ((void) pwdlen);
@@ -2255,18 +2391,22 @@
     // We try the different DER format parsers to see if one passes without
     // error
     //
-    if( ( ret = x509parse_key_pkcs8_unencrypted_der( rsa, key, keylen ) ) != 0 )
+    if( ( ret = x509parse_key_pkcs8_encrypted_der( rsa, key, keylen,
+                                                   pwd, pwdlen ) ) == 0 )
     {
-        rsa_free( rsa );
-
-        if( ( ret = x509parse_key_pkcs1_der( rsa, key, keylen ) ) != 0 )
-        {
-            rsa_free( rsa );
-            return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT );
-        }
+        return( 0 );
     }
 
-    return( 0 );
+    rsa_free( rsa );
+    if( ( ret = x509parse_key_pkcs8_unencrypted_der( rsa, key, keylen ) ) == 0 )
+        return( 0 );
+
+    rsa_free( rsa );
+    if( ( ret = x509parse_key_pkcs1_der( rsa, key, keylen ) ) == 0 )
+        return( 0 );
+
+    rsa_free( rsa );
+    return( POLARSSL_ERR_X509_KEY_INVALID_FORMAT );
 }
 
 /*
@@ -2726,11 +2866,6 @@
     return( (int) ( size - n ) );
 }
 
-/* Compare a given OID string with an OID x509_buf * */
-#define OID_CMP(oid_str, oid_buf) \
-        ( ( OID_SIZE(oid_str) == (oid_buf)->len ) && \
-                memcmp( (oid_str), (oid_buf)->p, (oid_buf)->len) == 0)
-
 /*
  * Return an informational string describing the given OID
  */