Home | History | Annotate | Download | only in pkcs8
      1 /* Written by Dr Stephen N Henson (steve (at) openssl.org) for the OpenSSL
      2  * project 1999.
      3  */
      4 /* ====================================================================
      5  * Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  *
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  *
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in
     16  *    the documentation and/or other materials provided with the
     17  *    distribution.
     18  *
     19  * 3. All advertising materials mentioning features or use of this
     20  *    software must display the following acknowledgment:
     21  *    "This product includes software developed by the OpenSSL Project
     22  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
     23  *
     24  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
     25  *    endorse or promote products derived from this software without
     26  *    prior written permission. For written permission, please contact
     27  *    licensing (at) OpenSSL.org.
     28  *
     29  * 5. Products derived from this software may not be called "OpenSSL"
     30  *    nor may "OpenSSL" appear in their names without prior written
     31  *    permission of the OpenSSL Project.
     32  *
     33  * 6. Redistributions of any form whatsoever must retain the following
     34  *    acknowledgment:
     35  *    "This product includes software developed by the OpenSSL Project
     36  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
     37  *
     38  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
     39  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     40  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     41  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
     42  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     43  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     44  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     45  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     46  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
     47  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     48  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
     49  * OF THE POSSIBILITY OF SUCH DAMAGE.
     50  * ====================================================================
     51  *
     52  * This product includes cryptographic software written by Eric Young
     53  * (eay (at) cryptsoft.com).  This product includes software written by Tim
     54  * Hudson (tjh (at) cryptsoft.com). */
     55 
     56 #include <openssl/pkcs8.h>
     57 
     58 #include <limits.h>
     59 
     60 #include <openssl/asn1t.h>
     61 #include <openssl/asn1.h>
     62 #include <openssl/bio.h>
     63 #include <openssl/buf.h>
     64 #include <openssl/bytestring.h>
     65 #include <openssl/err.h>
     66 #include <openssl/evp.h>
     67 #include <openssl/digest.h>
     68 #include <openssl/hmac.h>
     69 #include <openssl/mem.h>
     70 #include <openssl/x509.h>
     71 
     72 #include "internal.h"
     73 #include "../bytestring/internal.h"
     74 #include "../digest_extra/internal.h"
     75 #include "../internal.h"
     76 
     77 
     78 /* Minor tweak to operation: zero private key data */
     79 static int pkey_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
     80                    void *exarg) {
     81   /* Since the structure must still be valid use ASN1_OP_FREE_PRE */
     82   if (operation == ASN1_OP_FREE_PRE) {
     83     PKCS8_PRIV_KEY_INFO *key = (PKCS8_PRIV_KEY_INFO *)*pval;
     84     if (key->pkey && key->pkey->type == V_ASN1_OCTET_STRING &&
     85         key->pkey->value.octet_string) {
     86       OPENSSL_cleanse(key->pkey->value.octet_string->data,
     87                       key->pkey->value.octet_string->length);
     88     }
     89   }
     90   return 1;
     91 }
     92 
     93 ASN1_SEQUENCE_cb(PKCS8_PRIV_KEY_INFO, pkey_cb) = {
     94   ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, version, ASN1_INTEGER),
     95   ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, pkeyalg, X509_ALGOR),
     96   ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, pkey, ASN1_ANY),
     97   ASN1_IMP_SET_OF_OPT(PKCS8_PRIV_KEY_INFO, attributes, X509_ATTRIBUTE, 0)
     98 } ASN1_SEQUENCE_END_cb(PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO)
     99 
    100 IMPLEMENT_ASN1_FUNCTIONS(PKCS8_PRIV_KEY_INFO)
    101 
    102 EVP_PKEY *EVP_PKCS82PKEY(PKCS8_PRIV_KEY_INFO *p8) {
    103   uint8_t *der = NULL;
    104   int der_len = i2d_PKCS8_PRIV_KEY_INFO(p8, &der);
    105   if (der_len < 0) {
    106     return NULL;
    107   }
    108 
    109   CBS cbs;
    110   CBS_init(&cbs, der, (size_t)der_len);
    111   EVP_PKEY *ret = EVP_parse_private_key(&cbs);
    112   if (ret == NULL || CBS_len(&cbs) != 0) {
    113     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
    114     EVP_PKEY_free(ret);
    115     OPENSSL_free(der);
    116     return NULL;
    117   }
    118 
    119   OPENSSL_free(der);
    120   return ret;
    121 }
    122 
    123 PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(EVP_PKEY *pkey) {
    124   CBB cbb;
    125   uint8_t *der = NULL;
    126   size_t der_len;
    127   if (!CBB_init(&cbb, 0) ||
    128       !EVP_marshal_private_key(&cbb, pkey) ||
    129       !CBB_finish(&cbb, &der, &der_len) ||
    130       der_len > LONG_MAX) {
    131     CBB_cleanup(&cbb);
    132     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_ENCODE_ERROR);
    133     goto err;
    134   }
    135 
    136   const uint8_t *p = der;
    137   PKCS8_PRIV_KEY_INFO *p8 = d2i_PKCS8_PRIV_KEY_INFO(NULL, &p, (long)der_len);
    138   if (p8 == NULL || p != der + der_len) {
    139     PKCS8_PRIV_KEY_INFO_free(p8);
    140     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
    141     goto err;
    142   }
    143 
    144   OPENSSL_free(der);
    145   return p8;
    146 
    147 err:
    148   OPENSSL_free(der);
    149   return NULL;
    150 }
    151 
    152 PKCS8_PRIV_KEY_INFO *PKCS8_decrypt(X509_SIG *pkcs8, const char *pass,
    153                                    int pass_len_in) {
    154   size_t pass_len;
    155   if (pass_len_in == -1 && pass != NULL) {
    156     pass_len = strlen(pass);
    157   } else {
    158     pass_len = (size_t)pass_len_in;
    159   }
    160 
    161   PKCS8_PRIV_KEY_INFO *ret = NULL;
    162   EVP_PKEY *pkey = NULL;
    163   uint8_t *in = NULL;
    164 
    165   /* Convert the legacy ASN.1 object to a byte string. */
    166   int in_len = i2d_X509_SIG(pkcs8, &in);
    167   if (in_len < 0) {
    168     goto err;
    169   }
    170 
    171   CBS cbs;
    172   CBS_init(&cbs, in, in_len);
    173   pkey = PKCS8_parse_encrypted_private_key(&cbs, pass, pass_len);
    174   if (pkey == NULL || CBS_len(&cbs) != 0) {
    175     goto err;
    176   }
    177 
    178   ret = EVP_PKEY2PKCS8(pkey);
    179 
    180 err:
    181   OPENSSL_free(in);
    182   EVP_PKEY_free(pkey);
    183   return ret;
    184 }
    185 
    186 X509_SIG *PKCS8_encrypt(int pbe_nid, const EVP_CIPHER *cipher, const char *pass,
    187                         int pass_len_in, const uint8_t *salt, size_t salt_len,
    188                         int iterations, PKCS8_PRIV_KEY_INFO *p8inf) {
    189   size_t pass_len;
    190   if (pass_len_in == -1 && pass != NULL) {
    191     pass_len = strlen(pass);
    192   } else {
    193     pass_len = (size_t)pass_len_in;
    194   }
    195 
    196   /* Parse out the private key. */
    197   EVP_PKEY *pkey = EVP_PKCS82PKEY(p8inf);
    198   if (pkey == NULL) {
    199     return NULL;
    200   }
    201 
    202   X509_SIG *ret = NULL;
    203   uint8_t *der = NULL;
    204   size_t der_len;
    205   CBB cbb;
    206   if (!CBB_init(&cbb, 128) ||
    207       !PKCS8_marshal_encrypted_private_key(&cbb, pbe_nid, cipher, pass,
    208                                            pass_len, salt, salt_len, iterations,
    209                                            pkey) ||
    210       !CBB_finish(&cbb, &der, &der_len)) {
    211     CBB_cleanup(&cbb);
    212     goto err;
    213   }
    214 
    215   /* Convert back to legacy ASN.1 objects. */
    216   const uint8_t *ptr = der;
    217   ret = d2i_X509_SIG(NULL, &ptr, der_len);
    218   if (ret == NULL || ptr != der + der_len) {
    219     OPENSSL_PUT_ERROR(PKCS8, ERR_R_INTERNAL_ERROR);
    220     X509_SIG_free(ret);
    221     ret = NULL;
    222   }
    223 
    224 err:
    225   OPENSSL_free(der);
    226   EVP_PKEY_free(pkey);
    227   return ret;
    228 }
    229 
    230 struct pkcs12_context {
    231   EVP_PKEY **out_key;
    232   STACK_OF(X509) *out_certs;
    233   const char *password;
    234   size_t password_len;
    235 };
    236 
    237 /* PKCS12_handle_sequence parses a BER-encoded SEQUENCE of elements in a PKCS#12
    238  * structure. */
    239 static int PKCS12_handle_sequence(
    240     CBS *sequence, struct pkcs12_context *ctx,
    241     int (*handle_element)(CBS *cbs, struct pkcs12_context *ctx)) {
    242   uint8_t *der_bytes = NULL;
    243   size_t der_len;
    244   CBS in;
    245   int ret = 0;
    246 
    247   /* Although a BER->DER conversion is done at the beginning of |PKCS12_parse|,
    248    * the ASN.1 data gets wrapped in OCTETSTRINGs and/or encrypted and the
    249    * conversion cannot see through those wrappings. So each time we step
    250    * through one we need to convert to DER again. */
    251   if (!CBS_asn1_ber_to_der(sequence, &der_bytes, &der_len)) {
    252     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    253     return 0;
    254   }
    255 
    256   if (der_bytes != NULL) {
    257     CBS_init(&in, der_bytes, der_len);
    258   } else {
    259     CBS_init(&in, CBS_data(sequence), CBS_len(sequence));
    260   }
    261 
    262   CBS child;
    263   if (!CBS_get_asn1(&in, &child, CBS_ASN1_SEQUENCE) ||
    264       CBS_len(&in) != 0) {
    265     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    266     goto err;
    267   }
    268 
    269   while (CBS_len(&child) > 0) {
    270     CBS element;
    271     if (!CBS_get_asn1(&child, &element, CBS_ASN1_SEQUENCE)) {
    272       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    273       goto err;
    274     }
    275 
    276     if (!handle_element(&element, ctx)) {
    277       goto err;
    278     }
    279   }
    280 
    281   ret = 1;
    282 
    283 err:
    284   OPENSSL_free(der_bytes);
    285   return ret;
    286 }
    287 
    288 /* 1.2.840.113549.1.12.10.1.2 */
    289 static const uint8_t kPKCS8ShroudedKeyBag[] = {
    290     0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x0a, 0x01, 0x02};
    291 
    292 /* 1.2.840.113549.1.12.10.1.3 */
    293 static const uint8_t kCertBag[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
    294                                    0x01, 0x0c, 0x0a, 0x01, 0x03};
    295 
    296 /* 1.2.840.113549.1.9.22.1 */
    297 static const uint8_t kX509Certificate[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
    298                                            0x0d, 0x01, 0x09, 0x16, 0x01};
    299 
    300 /* PKCS12_handle_safe_bag parses a single SafeBag element in a PKCS#12
    301  * structure. */
    302 static int PKCS12_handle_safe_bag(CBS *safe_bag, struct pkcs12_context *ctx) {
    303   CBS bag_id, wrapped_value;
    304   if (!CBS_get_asn1(safe_bag, &bag_id, CBS_ASN1_OBJECT) ||
    305       !CBS_get_asn1(safe_bag, &wrapped_value,
    306                         CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0)
    307       /* Ignore the bagAttributes field. */) {
    308     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    309     return 0;
    310   }
    311 
    312   if (CBS_mem_equal(&bag_id, kPKCS8ShroudedKeyBag,
    313                     sizeof(kPKCS8ShroudedKeyBag))) {
    314     /* See RFC 7292, section 4.2.2. */
    315     if (*ctx->out_key) {
    316       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_MULTIPLE_PRIVATE_KEYS_IN_PKCS12);
    317       return 0;
    318     }
    319 
    320     EVP_PKEY *pkey = PKCS8_parse_encrypted_private_key(
    321         &wrapped_value, ctx->password, ctx->password_len);
    322     if (pkey == NULL) {
    323       return 0;
    324     }
    325 
    326     if (CBS_len(&wrapped_value) != 0) {
    327       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    328       EVP_PKEY_free(pkey);
    329       return 0;
    330     }
    331 
    332     *ctx->out_key = pkey;
    333     return 1;
    334   }
    335 
    336   if (CBS_mem_equal(&bag_id, kCertBag, sizeof(kCertBag))) {
    337     /* See RFC 7292, section 4.2.3. */
    338     CBS cert_bag, cert_type, wrapped_cert, cert;
    339     if (!CBS_get_asn1(&wrapped_value, &cert_bag, CBS_ASN1_SEQUENCE) ||
    340         !CBS_get_asn1(&cert_bag, &cert_type, CBS_ASN1_OBJECT) ||
    341         !CBS_get_asn1(&cert_bag, &wrapped_cert,
    342                       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
    343         !CBS_get_asn1(&wrapped_cert, &cert, CBS_ASN1_OCTETSTRING)) {
    344       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    345       return 0;
    346     }
    347 
    348     /* Skip unknown certificate types. */
    349     if (!CBS_mem_equal(&cert_type, kX509Certificate,
    350                        sizeof(kX509Certificate))) {
    351       return 1;
    352     }
    353 
    354     if (CBS_len(&cert) > LONG_MAX) {
    355       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    356       return 0;
    357     }
    358 
    359     const uint8_t *inp = CBS_data(&cert);
    360     X509 *x509 = d2i_X509(NULL, &inp, (long)CBS_len(&cert));
    361     if (!x509) {
    362       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    363       return 0;
    364     }
    365 
    366     if (inp != CBS_data(&cert) + CBS_len(&cert)) {
    367       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    368       X509_free(x509);
    369       return 0;
    370     }
    371 
    372     if (0 == sk_X509_push(ctx->out_certs, x509)) {
    373       X509_free(x509);
    374       return 0;
    375     }
    376 
    377     return 1;
    378   }
    379 
    380   /* Unknown element type - ignore it. */
    381   return 1;
    382 }
    383 
    384 /* 1.2.840.113549.1.7.1 */
    385 static const uint8_t kPKCS7Data[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
    386                                      0x0d, 0x01, 0x07, 0x01};
    387 
    388 /* 1.2.840.113549.1.7.6 */
    389 static const uint8_t kPKCS7EncryptedData[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
    390                                               0x0d, 0x01, 0x07, 0x06};
    391 
    392 /* PKCS12_handle_content_info parses a single PKCS#7 ContentInfo element in a
    393  * PKCS#12 structure. */
    394 static int PKCS12_handle_content_info(CBS *content_info,
    395                                       struct pkcs12_context *ctx) {
    396   CBS content_type, wrapped_contents, contents;
    397   int ret = 0;
    398   uint8_t *storage = NULL;
    399 
    400   if (!CBS_get_asn1(content_info, &content_type, CBS_ASN1_OBJECT) ||
    401       !CBS_get_asn1(content_info, &wrapped_contents,
    402                         CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
    403       CBS_len(content_info) != 0) {
    404     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    405     goto err;
    406   }
    407 
    408   if (CBS_mem_equal(&content_type, kPKCS7EncryptedData,
    409                     sizeof(kPKCS7EncryptedData))) {
    410     /* See https://tools.ietf.org/html/rfc2315#section-13.
    411      *
    412      * PKCS#7 encrypted data inside a PKCS#12 structure is generally an
    413      * encrypted certificate bag and it's generally encrypted with 40-bit
    414      * RC2-CBC. */
    415     CBS version_bytes, eci, contents_type, ai, encrypted_contents;
    416     uint8_t *out;
    417     size_t out_len;
    418 
    419     if (!CBS_get_asn1(&wrapped_contents, &contents, CBS_ASN1_SEQUENCE) ||
    420         !CBS_get_asn1(&contents, &version_bytes, CBS_ASN1_INTEGER) ||
    421         /* EncryptedContentInfo, see
    422          * https://tools.ietf.org/html/rfc2315#section-10.1 */
    423         !CBS_get_asn1(&contents, &eci, CBS_ASN1_SEQUENCE) ||
    424         !CBS_get_asn1(&eci, &contents_type, CBS_ASN1_OBJECT) ||
    425         /* AlgorithmIdentifier, see
    426          * https://tools.ietf.org/html/rfc5280#section-4.1.1.2 */
    427         !CBS_get_asn1(&eci, &ai, CBS_ASN1_SEQUENCE) ||
    428         !CBS_get_asn1_implicit_string(
    429             &eci, &encrypted_contents, &storage,
    430             CBS_ASN1_CONTEXT_SPECIFIC | 0, CBS_ASN1_OCTETSTRING)) {
    431       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    432       goto err;
    433     }
    434 
    435     if (!CBS_mem_equal(&contents_type, kPKCS7Data, sizeof(kPKCS7Data))) {
    436       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    437       goto err;
    438     }
    439 
    440     if (!pkcs8_pbe_decrypt(&out, &out_len, &ai, ctx->password,
    441                            ctx->password_len, CBS_data(&encrypted_contents),
    442                            CBS_len(&encrypted_contents))) {
    443       goto err;
    444     }
    445 
    446     CBS safe_contents;
    447     CBS_init(&safe_contents, out, out_len);
    448     ret = PKCS12_handle_sequence(&safe_contents, ctx, PKCS12_handle_safe_bag);
    449     OPENSSL_free(out);
    450   } else if (CBS_mem_equal(&content_type, kPKCS7Data, sizeof(kPKCS7Data))) {
    451     CBS octet_string_contents;
    452 
    453     if (!CBS_get_asn1(&wrapped_contents, &octet_string_contents,
    454                       CBS_ASN1_OCTETSTRING)) {
    455       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    456       goto err;
    457     }
    458 
    459     ret = PKCS12_handle_sequence(&octet_string_contents, ctx,
    460                                  PKCS12_handle_safe_bag);
    461   } else {
    462     /* Unknown element type - ignore it. */
    463     ret = 1;
    464   }
    465 
    466 err:
    467   OPENSSL_free(storage);
    468   return ret;
    469 }
    470 
    471 int PKCS12_get_key_and_certs(EVP_PKEY **out_key, STACK_OF(X509) *out_certs,
    472                              CBS *ber_in, const char *password) {
    473   uint8_t *der_bytes = NULL;
    474   size_t der_len;
    475   CBS in, pfx, mac_data, authsafe, content_type, wrapped_authsafes, authsafes;
    476   uint64_t version;
    477   int ret = 0;
    478   struct pkcs12_context ctx;
    479   const size_t original_out_certs_len = sk_X509_num(out_certs);
    480 
    481   /* The input may be in BER format. */
    482   if (!CBS_asn1_ber_to_der(ber_in, &der_bytes, &der_len)) {
    483     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    484     return 0;
    485   }
    486   if (der_bytes != NULL) {
    487     CBS_init(&in, der_bytes, der_len);
    488   } else {
    489     CBS_init(&in, CBS_data(ber_in), CBS_len(ber_in));
    490   }
    491 
    492   *out_key = NULL;
    493   OPENSSL_memset(&ctx, 0, sizeof(ctx));
    494 
    495   /* See ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12v1.pdf, section
    496    * four. */
    497   if (!CBS_get_asn1(&in, &pfx, CBS_ASN1_SEQUENCE) ||
    498       CBS_len(&in) != 0 ||
    499       !CBS_get_asn1_uint64(&pfx, &version)) {
    500     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    501     goto err;
    502   }
    503 
    504   if (version < 3) {
    505     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_VERSION);
    506     goto err;
    507   }
    508 
    509   if (!CBS_get_asn1(&pfx, &authsafe, CBS_ASN1_SEQUENCE)) {
    510     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    511     goto err;
    512   }
    513 
    514   if (CBS_len(&pfx) == 0) {
    515     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_MISSING_MAC);
    516     goto err;
    517   }
    518 
    519   if (!CBS_get_asn1(&pfx, &mac_data, CBS_ASN1_SEQUENCE)) {
    520     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    521     goto err;
    522   }
    523 
    524   /* authsafe is a PKCS#7 ContentInfo. See
    525    * https://tools.ietf.org/html/rfc2315#section-7. */
    526   if (!CBS_get_asn1(&authsafe, &content_type, CBS_ASN1_OBJECT) ||
    527       !CBS_get_asn1(&authsafe, &wrapped_authsafes,
    528                         CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0)) {
    529     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    530     goto err;
    531   }
    532 
    533   /* The content type can either be data or signedData. The latter indicates
    534    * that it's signed by a public key, which isn't supported. */
    535   if (!CBS_mem_equal(&content_type, kPKCS7Data, sizeof(kPKCS7Data))) {
    536     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_PKCS12_PUBLIC_KEY_INTEGRITY_NOT_SUPPORTED);
    537     goto err;
    538   }
    539 
    540   if (!CBS_get_asn1(&wrapped_authsafes, &authsafes, CBS_ASN1_OCTETSTRING)) {
    541     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    542     goto err;
    543   }
    544 
    545   ctx.out_key = out_key;
    546   ctx.out_certs = out_certs;
    547   ctx.password = password;
    548   ctx.password_len = password != NULL ? strlen(password) : 0;
    549 
    550   /* Verify the MAC. */
    551   {
    552     CBS mac, salt, expected_mac;
    553     if (!CBS_get_asn1(&mac_data, &mac, CBS_ASN1_SEQUENCE)) {
    554       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    555       goto err;
    556     }
    557 
    558     const EVP_MD *md = EVP_parse_digest_algorithm(&mac);
    559     if (md == NULL) {
    560       goto err;
    561     }
    562 
    563     if (!CBS_get_asn1(&mac, &expected_mac, CBS_ASN1_OCTETSTRING) ||
    564         !CBS_get_asn1(&mac_data, &salt, CBS_ASN1_OCTETSTRING)) {
    565       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    566       goto err;
    567     }
    568 
    569     /* The iteration count is optional and the default is one. */
    570     uint64_t iterations = 1;
    571     if (CBS_len(&mac_data) > 0) {
    572       if (!CBS_get_asn1_uint64(&mac_data, &iterations) ||
    573           iterations > UINT_MAX) {
    574         OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
    575         goto err;
    576       }
    577     }
    578 
    579     uint8_t hmac_key[EVP_MAX_MD_SIZE];
    580     if (!pkcs12_key_gen(ctx.password, ctx.password_len, CBS_data(&salt),
    581                         CBS_len(&salt), PKCS12_MAC_ID, iterations,
    582                         EVP_MD_size(md), hmac_key, md)) {
    583       goto err;
    584     }
    585 
    586     uint8_t hmac[EVP_MAX_MD_SIZE];
    587     unsigned hmac_len;
    588     if (NULL == HMAC(md, hmac_key, EVP_MD_size(md), CBS_data(&authsafes),
    589                      CBS_len(&authsafes), hmac, &hmac_len)) {
    590       goto err;
    591     }
    592 
    593     if (!CBS_mem_equal(&expected_mac, hmac, hmac_len)) {
    594       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_INCORRECT_PASSWORD);
    595       goto err;
    596     }
    597   }
    598 
    599   /* authsafes contains a series of PKCS#7 ContentInfos. */
    600   if (!PKCS12_handle_sequence(&authsafes, &ctx, PKCS12_handle_content_info)) {
    601     goto err;
    602   }
    603 
    604   ret = 1;
    605 
    606 err:
    607   OPENSSL_free(der_bytes);
    608   if (!ret) {
    609     EVP_PKEY_free(*out_key);
    610     *out_key = NULL;
    611     while (sk_X509_num(out_certs) > original_out_certs_len) {
    612       X509 *x509 = sk_X509_pop(out_certs);
    613       X509_free(x509);
    614     }
    615   }
    616 
    617   return ret;
    618 }
    619 
    620 void PKCS12_PBE_add(void) {}
    621 
    622 struct pkcs12_st {
    623   uint8_t *ber_bytes;
    624   size_t ber_len;
    625 };
    626 
    627 PKCS12 *d2i_PKCS12(PKCS12 **out_p12, const uint8_t **ber_bytes,
    628                    size_t ber_len) {
    629   PKCS12 *p12;
    630 
    631   p12 = OPENSSL_malloc(sizeof(PKCS12));
    632   if (!p12) {
    633     return NULL;
    634   }
    635 
    636   p12->ber_bytes = OPENSSL_malloc(ber_len);
    637   if (!p12->ber_bytes) {
    638     OPENSSL_free(p12);
    639     return NULL;
    640   }
    641 
    642   OPENSSL_memcpy(p12->ber_bytes, *ber_bytes, ber_len);
    643   p12->ber_len = ber_len;
    644   *ber_bytes += ber_len;
    645 
    646   if (out_p12) {
    647     PKCS12_free(*out_p12);
    648 
    649     *out_p12 = p12;
    650   }
    651 
    652   return p12;
    653 }
    654 
    655 PKCS12* d2i_PKCS12_bio(BIO *bio, PKCS12 **out_p12) {
    656   size_t used = 0;
    657   BUF_MEM *buf;
    658   const uint8_t *dummy;
    659   static const size_t kMaxSize = 256 * 1024;
    660   PKCS12 *ret = NULL;
    661 
    662   buf = BUF_MEM_new();
    663   if (buf == NULL) {
    664     return NULL;
    665   }
    666   if (BUF_MEM_grow(buf, 8192) == 0) {
    667     goto out;
    668   }
    669 
    670   for (;;) {
    671     int n = BIO_read(bio, &buf->data[used], buf->length - used);
    672     if (n < 0) {
    673       if (used == 0) {
    674         goto out;
    675       }
    676       /* Workaround a bug in node.js. It uses a memory BIO for this in the wrong
    677        * mode. */
    678       n = 0;
    679     }
    680 
    681     if (n == 0) {
    682       break;
    683     }
    684     used += n;
    685 
    686     if (used < buf->length) {
    687       continue;
    688     }
    689 
    690     if (buf->length > kMaxSize ||
    691         BUF_MEM_grow(buf, buf->length * 2) == 0) {
    692       goto out;
    693     }
    694   }
    695 
    696   dummy = (uint8_t*) buf->data;
    697   ret = d2i_PKCS12(out_p12, &dummy, used);
    698 
    699 out:
    700   BUF_MEM_free(buf);
    701   return ret;
    702 }
    703 
    704 PKCS12* d2i_PKCS12_fp(FILE *fp, PKCS12 **out_p12) {
    705   BIO *bio;
    706   PKCS12 *ret;
    707 
    708   bio = BIO_new_fp(fp, 0 /* don't take ownership */);
    709   if (!bio) {
    710     return NULL;
    711   }
    712 
    713   ret = d2i_PKCS12_bio(bio, out_p12);
    714   BIO_free(bio);
    715   return ret;
    716 }
    717 
    718 int PKCS12_parse(const PKCS12 *p12, const char *password, EVP_PKEY **out_pkey,
    719                  X509 **out_cert, STACK_OF(X509) **out_ca_certs) {
    720   CBS ber_bytes;
    721   STACK_OF(X509) *ca_certs = NULL;
    722   char ca_certs_alloced = 0;
    723 
    724   if (out_ca_certs != NULL && *out_ca_certs != NULL) {
    725     ca_certs = *out_ca_certs;
    726   }
    727 
    728   if (!ca_certs) {
    729     ca_certs = sk_X509_new_null();
    730     if (ca_certs == NULL) {
    731       OPENSSL_PUT_ERROR(PKCS8, ERR_R_MALLOC_FAILURE);
    732       return 0;
    733     }
    734     ca_certs_alloced = 1;
    735   }
    736 
    737   CBS_init(&ber_bytes, p12->ber_bytes, p12->ber_len);
    738   if (!PKCS12_get_key_and_certs(out_pkey, ca_certs, &ber_bytes, password)) {
    739     if (ca_certs_alloced) {
    740       sk_X509_free(ca_certs);
    741     }
    742     return 0;
    743   }
    744 
    745   *out_cert = NULL;
    746   if (sk_X509_num(ca_certs) > 0) {
    747     *out_cert = sk_X509_shift(ca_certs);
    748   }
    749 
    750   if (out_ca_certs) {
    751     *out_ca_certs = ca_certs;
    752   } else {
    753     sk_X509_pop_free(ca_certs, X509_free);
    754   }
    755 
    756   return 1;
    757 }
    758 
    759 int PKCS12_verify_mac(const PKCS12 *p12, const char *password,
    760                       int password_len) {
    761   if (password == NULL) {
    762     if (password_len != 0) {
    763       return 0;
    764     }
    765   } else if (password_len != -1 &&
    766              (password[password_len] != 0 ||
    767               OPENSSL_memchr(password, 0, password_len) != NULL)) {
    768     return 0;
    769   }
    770 
    771   EVP_PKEY *pkey = NULL;
    772   X509 *cert = NULL;
    773   if (!PKCS12_parse(p12, password, &pkey, &cert, NULL)) {
    774     ERR_clear_error();
    775     return 0;
    776   }
    777 
    778   EVP_PKEY_free(pkey);
    779   X509_free(cert);
    780 
    781   return 1;
    782 }
    783 
    784 void PKCS12_free(PKCS12 *p12) {
    785   if (p12 == NULL) {
    786     return;
    787   }
    788   OPENSSL_free(p12->ber_bytes);
    789   OPENSSL_free(p12);
    790 }
    791