1 /* Written by Dr Stephen N Henson (steve@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@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@cryptsoft.com).  This product includes software written by Tim
54  * Hudson (tjh@cryptsoft.com). */
55 
56 #include <openssl/pkcs8.h>
57 
58 #include <assert.h>
59 #include <limits.h>
60 #include <string.h>
61 
62 #include <openssl/asn1.h>
63 #include <openssl/bn.h>
64 #include <openssl/buf.h>
65 #include <openssl/cipher.h>
66 #include <openssl/digest.h>
67 #include <openssl/err.h>
68 #include <openssl/hmac.h>
69 #include <openssl/mem.h>
70 #include <openssl/x509.h>
71 
72 #include "../bytestring/internal.h"
73 #include "../evp/internal.h"
74 
75 
76 #define PKCS12_KEY_ID 1
77 #define PKCS12_IV_ID 2
78 #define PKCS12_MAC_ID 3
79 
ascii_to_ucs2(const char * ascii,size_t ascii_len,uint8_t ** out,size_t * out_len)80 static int ascii_to_ucs2(const char *ascii, size_t ascii_len,
81                          uint8_t **out, size_t *out_len) {
82   uint8_t *unitmp;
83   size_t ulen, i;
84 
85   ulen = ascii_len * 2 + 2;
86   if (ulen < ascii_len) {
87     return 0;
88   }
89   unitmp = OPENSSL_malloc(ulen);
90   if (unitmp == NULL) {
91     return 0;
92   }
93   for (i = 0; i < ulen - 2; i += 2) {
94     unitmp[i] = 0;
95     unitmp[i + 1] = ascii[i >> 1];
96   }
97 
98   /* Make result double null terminated */
99   unitmp[ulen - 2] = 0;
100   unitmp[ulen - 1] = 0;
101   *out_len = ulen;
102   *out = unitmp;
103   return 1;
104 }
105 
pkcs12_key_gen_raw(const uint8_t * pass_raw,size_t pass_raw_len,const uint8_t * salt,size_t salt_len,int id,int iterations,size_t out_len,uint8_t * out,const EVP_MD * md_type)106 static int pkcs12_key_gen_raw(const uint8_t *pass_raw, size_t pass_raw_len,
107                               const uint8_t *salt, size_t salt_len,
108                               int id, int iterations,
109                               size_t out_len, uint8_t *out,
110                               const EVP_MD *md_type) {
111   uint8_t *B, *D, *I, *p, *Ai;
112   int Slen, Plen, Ilen, Ijlen;
113   int i, j, v;
114   size_t u;
115   int ret = 0;
116   BIGNUM *Ij, *Bpl1; /* These hold Ij and B + 1 */
117   EVP_MD_CTX ctx;
118 
119   EVP_MD_CTX_init(&ctx);
120   v = EVP_MD_block_size(md_type);
121   u = EVP_MD_size(md_type);
122   D = OPENSSL_malloc(v);
123   Ai = OPENSSL_malloc(u);
124   B = OPENSSL_malloc(v + 1);
125   Slen = v * ((salt_len + v - 1) / v);
126   if (pass_raw_len) {
127     Plen = v * ((pass_raw_len + v - 1) / v);
128   } else {
129     Plen = 0;
130   }
131   Ilen = Slen + Plen;
132   I = OPENSSL_malloc(Ilen);
133   Ij = BN_new();
134   Bpl1 = BN_new();
135   if (!D || !Ai || !B || !I || !Ij || !Bpl1) {
136     goto err;
137   }
138   for (i = 0; i < v; i++) {
139     D[i] = id;
140   }
141   p = I;
142   for (i = 0; i < Slen; i++) {
143     *p++ = salt[i % salt_len];
144   }
145   for (i = 0; i < Plen; i++) {
146     *p++ = pass_raw[i % pass_raw_len];
147   }
148   for (;;) {
149     if (!EVP_DigestInit_ex(&ctx, md_type, NULL) ||
150         !EVP_DigestUpdate(&ctx, D, v) ||
151         !EVP_DigestUpdate(&ctx, I, Ilen) ||
152         !EVP_DigestFinal_ex(&ctx, Ai, NULL)) {
153       goto err;
154     }
155     for (j = 1; j < iterations; j++) {
156       if (!EVP_DigestInit_ex(&ctx, md_type, NULL) ||
157           !EVP_DigestUpdate(&ctx, Ai, u) ||
158           !EVP_DigestFinal_ex(&ctx, Ai, NULL)) {
159         goto err;
160       }
161     }
162     memcpy(out, Ai, out_len < u ? out_len : u);
163     if (u >= out_len) {
164       ret = 1;
165       goto end;
166     }
167     out_len -= u;
168     out += u;
169     for (j = 0; j < v; j++) {
170       B[j] = Ai[j % u];
171     }
172     /* Work out B + 1 first then can use B as tmp space */
173     if (!BN_bin2bn(B, v, Bpl1) ||
174         !BN_add_word(Bpl1, 1)) {
175       goto err;
176     }
177     for (j = 0; j < Ilen; j += v) {
178       if (!BN_bin2bn(I + j, v, Ij) ||
179           !BN_add(Ij, Ij, Bpl1) ||
180           !BN_bn2bin(Ij, B)) {
181         goto err;
182       }
183       Ijlen = BN_num_bytes(Ij);
184       /* If more than 2^(v*8) - 1 cut off MSB */
185       if (Ijlen > v) {
186         if (!BN_bn2bin(Ij, B)) {
187           goto err;
188         }
189         memcpy(I + j, B + 1, v);
190         /* If less than v bytes pad with zeroes */
191       } else if (Ijlen < v) {
192         memset(I + j, 0, v - Ijlen);
193         if (!BN_bn2bin(Ij, I + j + v - Ijlen)) {
194           goto err;
195         }
196       } else if (!BN_bn2bin(Ij, I + j)) {
197         goto err;
198       }
199     }
200   }
201 
202 err:
203   OPENSSL_PUT_ERROR(PKCS8, pkcs12_key_gen_raw, ERR_R_MALLOC_FAILURE);
204 
205 end:
206   OPENSSL_free(Ai);
207   OPENSSL_free(B);
208   OPENSSL_free(D);
209   OPENSSL_free(I);
210   BN_free(Ij);
211   BN_free(Bpl1);
212   EVP_MD_CTX_cleanup(&ctx);
213 
214   return ret;
215 }
216 
pkcs12_pbe_keyivgen(EVP_CIPHER_CTX * ctx,const uint8_t * pass_raw,size_t pass_raw_len,ASN1_TYPE * param,const EVP_CIPHER * cipher,const EVP_MD * md,int is_encrypt)217 static int pkcs12_pbe_keyivgen(EVP_CIPHER_CTX *ctx, const uint8_t *pass_raw,
218                                size_t pass_raw_len, ASN1_TYPE *param,
219                                const EVP_CIPHER *cipher, const EVP_MD *md,
220                                int is_encrypt) {
221   PBEPARAM *pbe;
222   int salt_len, iterations, ret;
223   uint8_t *salt;
224   const uint8_t *pbuf;
225   uint8_t key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH];
226 
227   /* Extract useful info from parameter */
228   if (param == NULL || param->type != V_ASN1_SEQUENCE ||
229       param->value.sequence == NULL) {
230     OPENSSL_PUT_ERROR(PKCS8, pkcs12_pbe_keyivgen, PKCS8_R_DECODE_ERROR);
231     return 0;
232   }
233 
234   pbuf = param->value.sequence->data;
235   pbe = d2i_PBEPARAM(NULL, &pbuf, param->value.sequence->length);
236   if (pbe == NULL) {
237     OPENSSL_PUT_ERROR(PKCS8, pkcs12_pbe_keyivgen, PKCS8_R_DECODE_ERROR);
238     return 0;
239   }
240 
241   if (!pbe->iter) {
242     iterations = 1;
243   } else {
244     iterations = ASN1_INTEGER_get(pbe->iter);
245   }
246   salt = pbe->salt->data;
247   salt_len = pbe->salt->length;
248   if (!pkcs12_key_gen_raw(pass_raw, pass_raw_len, salt, salt_len, PKCS12_KEY_ID,
249                           iterations, EVP_CIPHER_key_length(cipher), key, md)) {
250     OPENSSL_PUT_ERROR(PKCS8, pkcs12_pbe_keyivgen, PKCS8_R_KEY_GEN_ERROR);
251     PBEPARAM_free(pbe);
252     return 0;
253   }
254   if (!pkcs12_key_gen_raw(pass_raw, pass_raw_len, salt, salt_len, PKCS12_IV_ID,
255                           iterations, EVP_CIPHER_iv_length(cipher), iv, md)) {
256     OPENSSL_PUT_ERROR(PKCS8, pkcs12_pbe_keyivgen, PKCS8_R_KEY_GEN_ERROR);
257     PBEPARAM_free(pbe);
258     return 0;
259   }
260   PBEPARAM_free(pbe);
261   ret = EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, is_encrypt);
262   OPENSSL_cleanse(key, EVP_MAX_KEY_LENGTH);
263   OPENSSL_cleanse(iv, EVP_MAX_IV_LENGTH);
264   return ret;
265 }
266 
267 typedef int (*keygen_func)(EVP_CIPHER_CTX *ctx, const uint8_t *pass_raw,
268                            size_t pass_raw_len, ASN1_TYPE *param,
269                            const EVP_CIPHER *cipher, const EVP_MD *md,
270                            int is_encrypt);
271 
272 struct pbe_suite {
273   int pbe_nid;
274   const EVP_CIPHER* (*cipher_func)(void);
275   const EVP_MD* (*md_func)(void);
276   keygen_func keygen;
277 };
278 
279 static const struct pbe_suite kBuiltinPBE[] = {
280     {
281      NID_pbe_WithSHA1And40BitRC2_CBC, EVP_rc2_40_cbc, EVP_sha1, pkcs12_pbe_keyivgen,
282     },
283     {
284      NID_pbe_WithSHA1And128BitRC4, EVP_rc4, EVP_sha1, pkcs12_pbe_keyivgen,
285     },
286     {
287      NID_pbe_WithSHA1And3_Key_TripleDES_CBC, EVP_des_ede3_cbc, EVP_sha1,
288      pkcs12_pbe_keyivgen,
289     },
290 };
291 
pbe_cipher_init(ASN1_OBJECT * pbe_obj,const uint8_t * pass_raw,size_t pass_raw_len,ASN1_TYPE * param,EVP_CIPHER_CTX * ctx,int is_encrypt)292 static int pbe_cipher_init(ASN1_OBJECT *pbe_obj,
293                            const uint8_t *pass_raw, size_t pass_raw_len,
294                            ASN1_TYPE *param,
295                            EVP_CIPHER_CTX *ctx, int is_encrypt) {
296   const EVP_CIPHER *cipher;
297   const EVP_MD *md;
298   unsigned i;
299 
300   const struct pbe_suite *suite = NULL;
301   const int pbe_nid = OBJ_obj2nid(pbe_obj);
302 
303   for (i = 0; i < sizeof(kBuiltinPBE) / sizeof(struct pbe_suite); i++) {
304     if (kBuiltinPBE[i].pbe_nid == pbe_nid) {
305       suite = &kBuiltinPBE[i];
306       break;
307     }
308   }
309 
310   if (suite == NULL) {
311     char obj_str[80];
312     OPENSSL_PUT_ERROR(PKCS8, pbe_cipher_init, PKCS8_R_UNKNOWN_ALGORITHM);
313     if (!pbe_obj) {
314       strncpy(obj_str, "NULL", sizeof(obj_str));
315     } else {
316       i2t_ASN1_OBJECT(obj_str, sizeof(obj_str), pbe_obj);
317     }
318     ERR_add_error_data(2, "TYPE=", obj_str);
319     return 0;
320   }
321 
322   if (suite->cipher_func == NULL) {
323     cipher = NULL;
324   } else {
325     cipher = suite->cipher_func();
326     if (!cipher) {
327       OPENSSL_PUT_ERROR(PKCS8, pbe_cipher_init, PKCS8_R_UNKNOWN_CIPHER);
328       return 0;
329     }
330   }
331 
332   if (suite->md_func == NULL) {
333     md = NULL;
334   } else {
335     md = suite->md_func();
336     if (!md) {
337       OPENSSL_PUT_ERROR(PKCS8, pbe_cipher_init, PKCS8_R_UNKNOWN_DIGEST);
338       return 0;
339     }
340   }
341 
342   if (!suite->keygen(ctx, pass_raw, pass_raw_len, param, cipher, md,
343                      is_encrypt)) {
344     OPENSSL_PUT_ERROR(PKCS8, pbe_cipher_init, PKCS8_R_KEYGEN_FAILURE);
345     return 0;
346   }
347 
348   return 1;
349 }
350 
pbe_crypt(const X509_ALGOR * algor,const uint8_t * pass_raw,size_t pass_raw_len,const uint8_t * in,size_t in_len,uint8_t ** out,size_t * out_len,int is_encrypt)351 static int pbe_crypt(const X509_ALGOR *algor,
352                      const uint8_t *pass_raw, size_t pass_raw_len,
353                      const uint8_t *in, size_t in_len,
354                      uint8_t **out, size_t *out_len,
355                      int is_encrypt) {
356   uint8_t *buf;
357   int n, ret = 0;
358   EVP_CIPHER_CTX ctx;
359   unsigned block_size;
360 
361   EVP_CIPHER_CTX_init(&ctx);
362 
363   if (!pbe_cipher_init(algor->algorithm, pass_raw, pass_raw_len,
364                        algor->parameter, &ctx, is_encrypt)) {
365     OPENSSL_PUT_ERROR(PKCS8, pbe_crypt, PKCS8_R_UNKNOWN_CIPHER_ALGORITHM);
366     return 0;
367   }
368   block_size = EVP_CIPHER_CTX_block_size(&ctx);
369 
370   if (in_len + block_size < in_len) {
371     OPENSSL_PUT_ERROR(PKCS8, pbe_crypt, PKCS8_R_TOO_LONG);
372     goto err;
373   }
374 
375   buf = OPENSSL_malloc(in_len + block_size);
376   if (buf == NULL) {
377     OPENSSL_PUT_ERROR(PKCS8, pbe_crypt, ERR_R_MALLOC_FAILURE);
378     goto err;
379   }
380 
381   if (!EVP_CipherUpdate(&ctx, buf, &n, in, in_len)) {
382     OPENSSL_free(buf);
383     OPENSSL_PUT_ERROR(PKCS8, pbe_crypt, ERR_R_EVP_LIB);
384     goto err;
385   }
386   *out_len = n;
387 
388   if (!EVP_CipherFinal_ex(&ctx, buf + n, &n)) {
389     OPENSSL_free(buf);
390     OPENSSL_PUT_ERROR(PKCS8, pbe_crypt, ERR_R_EVP_LIB);
391     goto err;
392   }
393   *out_len += n;
394   *out = buf;
395   ret = 1;
396 
397 err:
398   EVP_CIPHER_CTX_cleanup(&ctx);
399   return ret;
400 }
401 
pkcs12_item_decrypt_d2i(X509_ALGOR * algor,const ASN1_ITEM * it,const uint8_t * pass_raw,size_t pass_raw_len,ASN1_OCTET_STRING * oct)402 static void *pkcs12_item_decrypt_d2i(X509_ALGOR *algor, const ASN1_ITEM *it,
403                                      const uint8_t *pass_raw,
404                                      size_t pass_raw_len,
405                                      ASN1_OCTET_STRING *oct) {
406   uint8_t *out;
407   const uint8_t *p;
408   void *ret;
409   size_t out_len;
410 
411   if (!pbe_crypt(algor, pass_raw, pass_raw_len, oct->data, oct->length,
412                  &out, &out_len, 0 /* decrypt */)) {
413     OPENSSL_PUT_ERROR(PKCS8, pkcs12_item_decrypt_d2i, PKCS8_R_CRYPT_ERROR);
414     return NULL;
415   }
416   p = out;
417   ret = ASN1_item_d2i(NULL, &p, out_len, it);
418   OPENSSL_cleanse(out, out_len);
419   if (!ret) {
420     OPENSSL_PUT_ERROR(PKCS8, pkcs12_item_decrypt_d2i, PKCS8_R_DECODE_ERROR);
421   }
422   OPENSSL_free(out);
423   return ret;
424 }
425 
PKCS8_decrypt(X509_SIG * pkcs8,const char * pass,int pass_len)426 PKCS8_PRIV_KEY_INFO *PKCS8_decrypt(X509_SIG *pkcs8, const char *pass,
427                                    int pass_len) {
428   uint8_t *pass_raw = NULL;
429   size_t pass_raw_len = 0;
430   PKCS8_PRIV_KEY_INFO *ret;
431 
432   if (pass) {
433     if (pass_len == -1) {
434       pass_len = strlen(pass);
435     }
436     if (!ascii_to_ucs2(pass, pass_len, &pass_raw, &pass_raw_len)) {
437       OPENSSL_PUT_ERROR(PKCS8, PKCS8_decrypt, PKCS8_R_DECODE_ERROR);
438       return NULL;
439     }
440   }
441 
442   ret = PKCS8_decrypt_pbe(pkcs8, pass_raw, pass_raw_len);
443 
444   if (pass_raw) {
445     OPENSSL_cleanse(pass_raw, pass_raw_len);
446     OPENSSL_free(pass_raw);
447   }
448   return ret;
449 }
450 
PKCS8_decrypt_pbe(X509_SIG * pkcs8,const uint8_t * pass_raw,size_t pass_raw_len)451 PKCS8_PRIV_KEY_INFO *PKCS8_decrypt_pbe(X509_SIG *pkcs8, const uint8_t *pass_raw,
452                                        size_t pass_raw_len) {
453   return pkcs12_item_decrypt_d2i(pkcs8->algor,
454                                  ASN1_ITEM_rptr(PKCS8_PRIV_KEY_INFO), pass_raw,
455                                  pass_raw_len, pkcs8->digest);
456 }
457 
pkcs12_item_i2d_encrypt(X509_ALGOR * algor,const ASN1_ITEM * it,const uint8_t * pass_raw,size_t pass_raw_len,void * obj)458 static ASN1_OCTET_STRING *pkcs12_item_i2d_encrypt(X509_ALGOR *algor,
459                                                   const ASN1_ITEM *it,
460                                                   const uint8_t *pass_raw,
461                                                   size_t pass_raw_len, void *obj) {
462   ASN1_OCTET_STRING *oct;
463   uint8_t *in = NULL;
464   int in_len;
465   size_t crypt_len;
466 
467   oct = M_ASN1_OCTET_STRING_new();
468   if (oct == NULL) {
469     OPENSSL_PUT_ERROR(PKCS8, pkcs12_item_i2d_encrypt, ERR_R_MALLOC_FAILURE);
470     return NULL;
471   }
472   in_len = ASN1_item_i2d(obj, &in, it);
473   if (!in) {
474     OPENSSL_PUT_ERROR(PKCS8, pkcs12_item_i2d_encrypt, PKCS8_R_ENCODE_ERROR);
475     return NULL;
476   }
477   if (!pbe_crypt(algor, pass_raw, pass_raw_len, in, in_len, &oct->data, &crypt_len,
478                  1 /* encrypt */)) {
479     OPENSSL_PUT_ERROR(PKCS8, pkcs12_item_i2d_encrypt, PKCS8_R_ENCRYPT_ERROR);
480     OPENSSL_free(in);
481     return NULL;
482   }
483   oct->length = crypt_len;
484   OPENSSL_cleanse(in, in_len);
485   OPENSSL_free(in);
486   return oct;
487 }
488 
PKCS8_encrypt(int pbe_nid,const EVP_CIPHER * cipher,const char * pass,int pass_len,uint8_t * salt,size_t salt_len,int iterations,PKCS8_PRIV_KEY_INFO * p8inf)489 X509_SIG *PKCS8_encrypt(int pbe_nid, const EVP_CIPHER *cipher, const char *pass,
490                         int pass_len, uint8_t *salt, size_t salt_len,
491                         int iterations, PKCS8_PRIV_KEY_INFO *p8inf) {
492   uint8_t *pass_raw = NULL;
493   size_t pass_raw_len = 0;
494   X509_SIG *ret;
495 
496   if (pass) {
497     if (pass_len == -1) {
498       pass_len = strlen(pass);
499     }
500     if (!ascii_to_ucs2(pass, pass_len, &pass_raw, &pass_raw_len)) {
501       OPENSSL_PUT_ERROR(PKCS8, PKCS8_encrypt, PKCS8_R_DECODE_ERROR);
502       return NULL;
503     }
504   }
505 
506   ret = PKCS8_encrypt_pbe(pbe_nid, pass_raw, pass_raw_len,
507                           salt, salt_len, iterations, p8inf);
508 
509   if (pass_raw) {
510     OPENSSL_cleanse(pass_raw, pass_raw_len);
511     OPENSSL_free(pass_raw);
512   }
513   return ret;
514 }
515 
PKCS8_encrypt_pbe(int pbe_nid,const uint8_t * pass_raw,size_t pass_raw_len,uint8_t * salt,size_t salt_len,int iterations,PKCS8_PRIV_KEY_INFO * p8inf)516 X509_SIG *PKCS8_encrypt_pbe(int pbe_nid,
517                             const uint8_t *pass_raw, size_t pass_raw_len,
518                             uint8_t *salt, size_t salt_len,
519                             int iterations, PKCS8_PRIV_KEY_INFO *p8inf) {
520   X509_SIG *pkcs8 = NULL;
521   X509_ALGOR *pbe;
522 
523   pkcs8 = X509_SIG_new();
524   if (pkcs8 == NULL) {
525     OPENSSL_PUT_ERROR(PKCS8, PKCS8_encrypt_pbe, ERR_R_MALLOC_FAILURE);
526     goto err;
527   }
528 
529   pbe = PKCS5_pbe_set(pbe_nid, iterations, salt, salt_len);
530   if (!pbe) {
531     OPENSSL_PUT_ERROR(PKCS8, PKCS8_encrypt_pbe, ERR_R_ASN1_LIB);
532     goto err;
533   }
534 
535   X509_ALGOR_free(pkcs8->algor);
536   pkcs8->algor = pbe;
537   M_ASN1_OCTET_STRING_free(pkcs8->digest);
538   pkcs8->digest = pkcs12_item_i2d_encrypt(
539       pbe, ASN1_ITEM_rptr(PKCS8_PRIV_KEY_INFO), pass_raw, pass_raw_len, p8inf);
540   if (!pkcs8->digest) {
541     OPENSSL_PUT_ERROR(PKCS8, PKCS8_encrypt_pbe, PKCS8_R_ENCRYPT_ERROR);
542     goto err;
543   }
544 
545   return pkcs8;
546 
547 err:
548   X509_SIG_free(pkcs8);
549   return NULL;
550 }
551 
EVP_PKCS82PKEY(PKCS8_PRIV_KEY_INFO * p8)552 EVP_PKEY *EVP_PKCS82PKEY(PKCS8_PRIV_KEY_INFO *p8) {
553   EVP_PKEY *pkey = NULL;
554   ASN1_OBJECT *algoid;
555   char obj_tmp[80];
556 
557   if (!PKCS8_pkey_get0(&algoid, NULL, NULL, NULL, p8)) {
558     return NULL;
559   }
560 
561   pkey = EVP_PKEY_new();
562   if (pkey == NULL) {
563     OPENSSL_PUT_ERROR(PKCS8, EVP_PKCS82PKEY, ERR_R_MALLOC_FAILURE);
564     return NULL;
565   }
566 
567   if (!EVP_PKEY_set_type(pkey, OBJ_obj2nid(algoid))) {
568     OPENSSL_PUT_ERROR(PKCS8, EVP_PKCS82PKEY,
569                       PKCS8_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM);
570     i2t_ASN1_OBJECT(obj_tmp, 80, algoid);
571     ERR_add_error_data(2, "TYPE=", obj_tmp);
572     goto error;
573   }
574 
575   if (pkey->ameth->priv_decode) {
576     if (!pkey->ameth->priv_decode(pkey, p8)) {
577       OPENSSL_PUT_ERROR(PKCS8, EVP_PKCS82PKEY, PKCS8_R_PRIVATE_KEY_DECODE_ERROR);
578       goto error;
579     }
580   } else {
581     OPENSSL_PUT_ERROR(PKCS8, EVP_PKCS82PKEY, PKCS8_R_METHOD_NOT_SUPPORTED);
582     goto error;
583   }
584 
585   return pkey;
586 
587 error:
588   EVP_PKEY_free(pkey);
589   return NULL;
590 }
591 
EVP_PKEY2PKCS8(EVP_PKEY * pkey)592 PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(EVP_PKEY *pkey) {
593   PKCS8_PRIV_KEY_INFO *p8;
594 
595   p8 = PKCS8_PRIV_KEY_INFO_new();
596   if (p8 == NULL) {
597     OPENSSL_PUT_ERROR(PKCS8, EVP_PKEY2PKCS8, ERR_R_MALLOC_FAILURE);
598     return NULL;
599   }
600   p8->broken = PKCS8_OK;
601 
602   if (pkey->ameth) {
603     if (pkey->ameth->priv_encode) {
604       if (!pkey->ameth->priv_encode(p8, pkey)) {
605         OPENSSL_PUT_ERROR(PKCS8, EVP_PKEY2PKCS8,
606                           PKCS8_R_PRIVATE_KEY_ENCODE_ERROR);
607         goto error;
608       }
609     } else {
610       OPENSSL_PUT_ERROR(PKCS8, EVP_PKEY2PKCS8, PKCS8_R_METHOD_NOT_SUPPORTED);
611       goto error;
612     }
613   } else {
614     OPENSSL_PUT_ERROR(PKCS8, EVP_PKEY2PKCS8,
615                       PKCS8_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM);
616     goto error;
617   }
618   return p8;
619 
620 error:
621   PKCS8_PRIV_KEY_INFO_free(p8);
622   return NULL;
623 }
624 
625 struct pkcs12_context {
626   EVP_PKEY **out_key;
627   STACK_OF(X509) *out_certs;
628   uint8_t *password;
629   size_t password_len;
630 };
631 
632 static int PKCS12_handle_content_info(CBS *content_info, unsigned depth,
633                                       struct pkcs12_context *ctx);
634 
635 /* PKCS12_handle_content_infos parses a series of PKCS#7 ContentInfos in a
636  * SEQUENCE. */
PKCS12_handle_content_infos(CBS * content_infos,unsigned depth,struct pkcs12_context * ctx)637 static int PKCS12_handle_content_infos(CBS *content_infos,
638                                        unsigned depth,
639                                        struct pkcs12_context *ctx) {
640   uint8_t *der_bytes = NULL;
641   size_t der_len;
642   CBS in;
643   int ret = 0;
644 
645   /* Generally we only expect depths 0 (the top level, with a
646    * pkcs7-encryptedData and a pkcs7-data) and depth 1 (the various PKCS#12
647    * bags). */
648   if (depth > 3) {
649     OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_infos,
650                       PKCS8_R_PKCS12_TOO_DEEPLY_NESTED);
651     return 0;
652   }
653 
654   /* Although a BER->DER conversion is done at the beginning of |PKCS12_parse|,
655    * the ASN.1 data gets wrapped in OCTETSTRINGs and/or encrypted and the
656    * conversion cannot see through those wrappings. So each time we step
657    * through one we need to convert to DER again. */
658   if (!CBS_asn1_ber_to_der(content_infos, &der_bytes, &der_len)) {
659     return 0;
660   }
661 
662   if (der_bytes != NULL) {
663     CBS_init(&in, der_bytes, der_len);
664   } else {
665     CBS_init(&in, CBS_data(content_infos), CBS_len(content_infos));
666   }
667 
668   if (!CBS_get_asn1(&in, &in, CBS_ASN1_SEQUENCE)) {
669     OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_infos,
670                       PKCS8_R_BAD_PKCS12_DATA);
671     goto err;
672   }
673 
674   while (CBS_len(&in) > 0) {
675     CBS content_info;
676     if (!CBS_get_asn1(&in, &content_info, CBS_ASN1_SEQUENCE)) {
677       OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_infos,
678                         PKCS8_R_BAD_PKCS12_DATA);
679       goto err;
680     }
681 
682     if (!PKCS12_handle_content_info(&content_info, depth + 1, ctx)) {
683       goto err;
684     }
685   }
686 
687   /* NSS includes additional data after the SEQUENCE, but it's an (unwrapped)
688    * copy of the same encrypted private key (with the same IV and
689    * ciphertext)! */
690 
691   ret = 1;
692 
693 err:
694   OPENSSL_free(der_bytes);
695   return ret;
696 }
697 
698 /* PKCS12_handle_content_info parses a single PKCS#7 ContentInfo element in a
699  * PKCS#12 structure. */
PKCS12_handle_content_info(CBS * content_info,unsigned depth,struct pkcs12_context * ctx)700 static int PKCS12_handle_content_info(CBS *content_info, unsigned depth,
701                                       struct pkcs12_context *ctx) {
702   CBS content_type, wrapped_contents, contents, content_infos;
703   int nid, ret = 0;
704 
705   if (!CBS_get_asn1(content_info, &content_type, CBS_ASN1_OBJECT) ||
706       !CBS_get_asn1(content_info, &wrapped_contents,
707                         CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0)) {
708     OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info,
709                       PKCS8_R_BAD_PKCS12_DATA);
710     goto err;
711   }
712 
713   nid = OBJ_cbs2nid(&content_type);
714   if (nid == NID_pkcs7_encrypted) {
715     /* See https://tools.ietf.org/html/rfc2315#section-13.
716      *
717      * PKCS#7 encrypted data inside a PKCS#12 structure is generally an
718      * encrypted certificate bag and it's generally encrypted with 40-bit
719      * RC2-CBC. */
720     CBS version_bytes, eci, contents_type, ai, encrypted_contents;
721     X509_ALGOR *algor = NULL;
722     const uint8_t *inp;
723     uint8_t *out;
724     size_t out_len;
725 
726     if (!CBS_get_asn1(&wrapped_contents, &contents, CBS_ASN1_SEQUENCE) ||
727         !CBS_get_asn1(&contents, &version_bytes, CBS_ASN1_INTEGER) ||
728         /* EncryptedContentInfo, see
729          * https://tools.ietf.org/html/rfc2315#section-10.1 */
730         !CBS_get_asn1(&contents, &eci, CBS_ASN1_SEQUENCE) ||
731         !CBS_get_asn1(&eci, &contents_type, CBS_ASN1_OBJECT) ||
732         /* AlgorithmIdentifier, see
733          * https://tools.ietf.org/html/rfc5280#section-4.1.1.2 */
734         !CBS_get_asn1_element(&eci, &ai, CBS_ASN1_SEQUENCE) ||
735         !CBS_get_asn1(&eci, &encrypted_contents,
736                       CBS_ASN1_CONTEXT_SPECIFIC | 0)) {
737       OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info,
738                         PKCS8_R_BAD_PKCS12_DATA);
739       goto err;
740     }
741 
742     if (OBJ_cbs2nid(&contents_type) != NID_pkcs7_data) {
743       OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info,
744                         PKCS8_R_BAD_PKCS12_DATA);
745       goto err;
746     }
747 
748     inp = CBS_data(&ai);
749     algor = d2i_X509_ALGOR(NULL, &inp, CBS_len(&ai));
750     if (algor == NULL) {
751       goto err;
752     }
753     if (inp != CBS_data(&ai) + CBS_len(&ai)) {
754       X509_ALGOR_free(algor);
755       OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info,
756                         PKCS8_R_BAD_PKCS12_DATA);
757       goto err;
758     }
759 
760     if (!pbe_crypt(algor, ctx->password, ctx->password_len,
761                    CBS_data(&encrypted_contents), CBS_len(&encrypted_contents),
762                    &out, &out_len, 0 /* decrypt */)) {
763       X509_ALGOR_free(algor);
764       goto err;
765     }
766     X509_ALGOR_free(algor);
767 
768     CBS_init(&content_infos, out, out_len);
769     ret = PKCS12_handle_content_infos(&content_infos, depth + 1, ctx);
770     OPENSSL_free(out);
771   } else if (nid == NID_pkcs7_data) {
772     CBS octet_string_contents;
773 
774     if (!CBS_get_asn1(&wrapped_contents, &octet_string_contents,
775                           CBS_ASN1_OCTETSTRING)) {
776       OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info,
777                         PKCS8_R_BAD_PKCS12_DATA);
778       goto err;
779     }
780 
781     ret = PKCS12_handle_content_infos(&octet_string_contents, depth + 1, ctx);
782   } else if (nid == NID_pkcs8ShroudedKeyBag) {
783     /* See ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12v1.pdf, section
784      * 4.2.2. */
785     const uint8_t *inp = CBS_data(&wrapped_contents);
786     PKCS8_PRIV_KEY_INFO *pki = NULL;
787     X509_SIG *encrypted = NULL;
788 
789     if (*ctx->out_key) {
790       OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info,
791                         PKCS8_R_MULTIPLE_PRIVATE_KEYS_IN_PKCS12);
792       goto err;
793     }
794 
795     /* encrypted isn't actually an X.509 signature, but it has the same
796      * structure as one and so |X509_SIG| is reused to store it. */
797     encrypted = d2i_X509_SIG(NULL, &inp, CBS_len(&wrapped_contents));
798     if (encrypted == NULL) {
799       OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info,
800                         PKCS8_R_BAD_PKCS12_DATA);
801       goto err;
802     }
803     if (inp != CBS_data(&wrapped_contents) + CBS_len(&wrapped_contents)) {
804       OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info,
805                         PKCS8_R_BAD_PKCS12_DATA);
806       X509_SIG_free(encrypted);
807       goto err;
808     }
809 
810     pki = PKCS8_decrypt_pbe(encrypted, ctx->password, ctx->password_len);
811     X509_SIG_free(encrypted);
812     if (pki == NULL) {
813       goto err;
814     }
815 
816     *ctx->out_key = EVP_PKCS82PKEY(pki);
817     PKCS8_PRIV_KEY_INFO_free(pki);
818 
819     if (ctx->out_key == NULL) {
820       goto err;
821     }
822     ret = 1;
823   } else if (nid == NID_certBag) {
824     CBS cert_bag, cert_type, wrapped_cert, cert;
825 
826     if (!CBS_get_asn1(&wrapped_contents, &cert_bag, CBS_ASN1_SEQUENCE) ||
827         !CBS_get_asn1(&cert_bag, &cert_type, CBS_ASN1_OBJECT) ||
828         !CBS_get_asn1(&cert_bag, &wrapped_cert,
829                       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
830         !CBS_get_asn1(&wrapped_cert, &cert, CBS_ASN1_OCTETSTRING)) {
831       OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info,
832                         PKCS8_R_BAD_PKCS12_DATA);
833       goto err;
834     }
835 
836     if (OBJ_cbs2nid(&cert_type) == NID_x509Certificate) {
837       const uint8_t *inp = CBS_data(&cert);
838       X509 *x509 = d2i_X509(NULL, &inp, CBS_len(&cert));
839       if (!x509) {
840         OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info,
841                           PKCS8_R_BAD_PKCS12_DATA);
842         goto err;
843       }
844       if (inp != CBS_data(&cert) + CBS_len(&cert)) {
845         OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info,
846                           PKCS8_R_BAD_PKCS12_DATA);
847         X509_free(x509);
848         goto err;
849       }
850 
851       if (0 == sk_X509_push(ctx->out_certs, x509)) {
852         X509_free(x509);
853         goto err;
854       }
855     }
856     ret = 1;
857   } else {
858     /* Unknown element type - ignore it. */
859     ret = 1;
860   }
861 
862 err:
863   return ret;
864 }
865 
PKCS12_get_key_and_certs(EVP_PKEY ** out_key,STACK_OF (X509)* out_certs,CBS * ber_in,const char * password)866 int PKCS12_get_key_and_certs(EVP_PKEY **out_key, STACK_OF(X509) *out_certs,
867                              CBS *ber_in, const char *password) {
868   uint8_t *der_bytes = NULL;
869   size_t der_len;
870   CBS in, pfx, mac_data, authsafe, content_type, wrapped_authsafes, authsafes;
871   uint64_t version;
872   int ret = 0;
873   struct pkcs12_context ctx;
874   const size_t original_out_certs_len = sk_X509_num(out_certs);
875 
876   /* The input may be in BER format. */
877   if (!CBS_asn1_ber_to_der(ber_in, &der_bytes, &der_len)) {
878     return 0;
879   }
880   if (der_bytes != NULL) {
881     CBS_init(&in, der_bytes, der_len);
882   } else {
883     CBS_init(&in, CBS_data(ber_in), CBS_len(ber_in));
884   }
885 
886   *out_key = NULL;
887   memset(&ctx, 0, sizeof(ctx));
888 
889   /* See ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12v1.pdf, section
890    * four. */
891   if (!CBS_get_asn1(&in, &pfx, CBS_ASN1_SEQUENCE) ||
892       CBS_len(&in) != 0 ||
893       !CBS_get_asn1_uint64(&pfx, &version)) {
894     OPENSSL_PUT_ERROR(PKCS8, PKCS12_get_key_and_certs, PKCS8_R_BAD_PKCS12_DATA);
895     goto err;
896   }
897 
898   if (version < 3) {
899     OPENSSL_PUT_ERROR(PKCS8, PKCS12_get_key_and_certs,
900                       PKCS8_R_BAD_PKCS12_VERSION);
901     goto err;
902   }
903 
904   if (!CBS_get_asn1(&pfx, &authsafe, CBS_ASN1_SEQUENCE)) {
905     OPENSSL_PUT_ERROR(PKCS8, PKCS12_get_key_and_certs, PKCS8_R_BAD_PKCS12_DATA);
906     goto err;
907   }
908 
909   if (CBS_len(&pfx) == 0) {
910     OPENSSL_PUT_ERROR(PKCS8, PKCS12_get_key_and_certs, PKCS8_R_MISSING_MAC);
911     goto err;
912   }
913 
914   if (!CBS_get_asn1(&pfx, &mac_data, CBS_ASN1_SEQUENCE)) {
915     OPENSSL_PUT_ERROR(PKCS8, PKCS12_get_key_and_certs, PKCS8_R_BAD_PKCS12_DATA);
916     goto err;
917   }
918 
919   /* authsafe is a PKCS#7 ContentInfo. See
920    * https://tools.ietf.org/html/rfc2315#section-7. */
921   if (!CBS_get_asn1(&authsafe, &content_type, CBS_ASN1_OBJECT) ||
922       !CBS_get_asn1(&authsafe, &wrapped_authsafes,
923                         CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0)) {
924     OPENSSL_PUT_ERROR(PKCS8, PKCS12_get_key_and_certs, PKCS8_R_BAD_PKCS12_DATA);
925     goto err;
926   }
927 
928   /* The content type can either be |NID_pkcs7_data| or |NID_pkcs7_signed|. The
929    * latter indicates that it's signed by a public key, which isn't
930    * supported. */
931   if (OBJ_cbs2nid(&content_type) != NID_pkcs7_data) {
932     OPENSSL_PUT_ERROR(PKCS8, PKCS12_get_key_and_certs,
933                       PKCS8_R_PKCS12_PUBLIC_KEY_INTEGRITY_NOT_SUPPORTED);
934     goto err;
935   }
936 
937   if (!CBS_get_asn1(&wrapped_authsafes, &authsafes, CBS_ASN1_OCTETSTRING)) {
938     OPENSSL_PUT_ERROR(PKCS8, PKCS12_get_key_and_certs, PKCS8_R_BAD_PKCS12_DATA);
939     goto err;
940   }
941 
942   ctx.out_key = out_key;
943   ctx.out_certs = out_certs;
944   if (!ascii_to_ucs2(password, strlen(password), &ctx.password,
945                      &ctx.password_len)) {
946     OPENSSL_PUT_ERROR(PKCS8, PKCS12_get_key_and_certs, PKCS8_R_DECODE_ERROR);
947     goto err;
948   }
949 
950   /* Verify the MAC. */
951   {
952     CBS mac, hash_type_seq, hash_oid, salt, expected_mac;
953     uint64_t iterations;
954     int hash_nid;
955     const EVP_MD *md;
956     uint8_t hmac_key[EVP_MAX_MD_SIZE];
957     uint8_t hmac[EVP_MAX_MD_SIZE];
958     unsigned hmac_len;
959 
960     if (!CBS_get_asn1(&mac_data, &mac, CBS_ASN1_SEQUENCE) ||
961         !CBS_get_asn1(&mac, &hash_type_seq, CBS_ASN1_SEQUENCE) ||
962         !CBS_get_asn1(&hash_type_seq, &hash_oid, CBS_ASN1_OBJECT) ||
963         !CBS_get_asn1(&mac, &expected_mac, CBS_ASN1_OCTETSTRING) ||
964         !CBS_get_asn1(&mac_data, &salt, CBS_ASN1_OCTETSTRING)) {
965       OPENSSL_PUT_ERROR(PKCS8, PKCS12_get_key_and_certs, PKCS8_R_BAD_PKCS12_DATA);
966       goto err;
967     }
968 
969     /* The iteration count is optional and the default is one. */
970     iterations = 1;
971     if (CBS_len(&mac_data) > 0) {
972       if (!CBS_get_asn1_uint64(&mac_data, &iterations) ||
973           iterations > INT_MAX) {
974         OPENSSL_PUT_ERROR(PKCS8, PKCS12_get_key_and_certs,
975                           PKCS8_R_BAD_PKCS12_DATA);
976         goto err;
977       }
978     }
979 
980     hash_nid = OBJ_cbs2nid(&hash_oid);
981     if (hash_nid == NID_undef ||
982         (md = EVP_get_digestbynid(hash_nid)) == NULL) {
983       OPENSSL_PUT_ERROR(PKCS8, PKCS12_get_key_and_certs, PKCS8_R_UNKNOWN_HASH);
984       goto err;
985     }
986 
987     if (!pkcs12_key_gen_raw(ctx.password, ctx.password_len, CBS_data(&salt),
988                             CBS_len(&salt), PKCS12_MAC_ID, iterations,
989                             EVP_MD_size(md), hmac_key, md)) {
990       goto err;
991     }
992 
993     if (NULL == HMAC(md, hmac_key, EVP_MD_size(md), CBS_data(&authsafes),
994                      CBS_len(&authsafes), hmac, &hmac_len)) {
995       goto err;
996     }
997 
998     if (!CBS_mem_equal(&expected_mac, hmac, hmac_len)) {
999       OPENSSL_PUT_ERROR(PKCS8, PKCS12_get_key_and_certs,
1000                         PKCS8_R_INCORRECT_PASSWORD);
1001       goto err;
1002     }
1003   }
1004 
1005   /* authsafes contains a series of PKCS#7 ContentInfos. */
1006   if (!PKCS12_handle_content_infos(&authsafes, 0, &ctx)) {
1007     goto err;
1008   }
1009 
1010   ret = 1;
1011 
1012 err:
1013   OPENSSL_free(ctx.password);
1014   OPENSSL_free(der_bytes);
1015   if (!ret) {
1016     EVP_PKEY_free(*out_key);
1017     *out_key = NULL;
1018     while (sk_X509_num(out_certs) > original_out_certs_len) {
1019       X509 *x509 = sk_X509_pop(out_certs);
1020       X509_free(x509);
1021     }
1022   }
1023 
1024   return ret;
1025 }
1026 
PKCS12_PBE_add(void)1027 void PKCS12_PBE_add(void) {}
1028 
1029 struct pkcs12_st {
1030   uint8_t *ber_bytes;
1031   size_t ber_len;
1032 };
1033 
d2i_PKCS12(PKCS12 ** out_p12,const uint8_t ** ber_bytes,size_t ber_len)1034 PKCS12* d2i_PKCS12(PKCS12 **out_p12, const uint8_t **ber_bytes, size_t ber_len) {
1035   PKCS12 *p12;
1036 
1037   /* out_p12 must be NULL because we don't export the PKCS12 structure. */
1038   assert(out_p12 == NULL);
1039 
1040   p12 = OPENSSL_malloc(sizeof(PKCS12));
1041   if (!p12) {
1042     return NULL;
1043   }
1044 
1045   p12->ber_bytes = OPENSSL_malloc(ber_len);
1046   if (!p12->ber_bytes) {
1047     OPENSSL_free(p12);
1048     return NULL;
1049   }
1050 
1051   memcpy(p12->ber_bytes, *ber_bytes, ber_len);
1052   p12->ber_len = ber_len;
1053   *ber_bytes += ber_len;
1054 
1055   return p12;
1056 }
1057 
d2i_PKCS12_bio(BIO * bio,PKCS12 ** out_p12)1058 PKCS12* d2i_PKCS12_bio(BIO *bio, PKCS12 **out_p12) {
1059   size_t used = 0;
1060   BUF_MEM *buf;
1061   const uint8_t *dummy;
1062   static const size_t kMaxSize = 256 * 1024;
1063   PKCS12 *ret = NULL;
1064 
1065   buf = BUF_MEM_new();
1066   if (buf == NULL) {
1067     return NULL;
1068   }
1069   if (BUF_MEM_grow(buf, 8192) == 0) {
1070     goto out;
1071   }
1072 
1073   for (;;) {
1074     int n = BIO_read(bio, &buf->data[used], buf->length - used);
1075     if (n < 0) {
1076       goto out;
1077     }
1078 
1079     if (n == 0) {
1080       break;
1081     }
1082     used += n;
1083 
1084     if (used < buf->length) {
1085       continue;
1086     }
1087 
1088     if (buf->length > kMaxSize ||
1089         BUF_MEM_grow(buf, buf->length * 2) == 0) {
1090       goto out;
1091     }
1092   }
1093 
1094   dummy = (uint8_t*) buf->data;
1095   ret = d2i_PKCS12(out_p12, &dummy, used);
1096 
1097 out:
1098   BUF_MEM_free(buf);
1099   return ret;
1100 }
1101 
d2i_PKCS12_fp(FILE * fp,PKCS12 ** out_p12)1102 PKCS12* d2i_PKCS12_fp(FILE *fp, PKCS12 **out_p12) {
1103   BIO *bio;
1104   PKCS12 *ret;
1105 
1106   bio = BIO_new_fp(fp, 0 /* don't take ownership */);
1107   if (!bio) {
1108     return NULL;
1109   }
1110 
1111   ret = d2i_PKCS12_bio(bio, out_p12);
1112   BIO_free(bio);
1113   return ret;
1114 }
1115 
PKCS12_parse(const PKCS12 * p12,const char * password,EVP_PKEY ** out_pkey,X509 ** out_cert,STACK_OF (X509)** out_ca_certs)1116 int PKCS12_parse(const PKCS12 *p12, const char *password, EVP_PKEY **out_pkey,
1117                  X509 **out_cert, STACK_OF(X509) **out_ca_certs) {
1118   CBS ber_bytes;
1119   STACK_OF(X509) *ca_certs = NULL;
1120   char ca_certs_alloced = 0;
1121 
1122   if (out_ca_certs != NULL && *out_ca_certs != NULL) {
1123     ca_certs = *out_ca_certs;
1124   }
1125 
1126   if (!ca_certs) {
1127     ca_certs = sk_X509_new_null();
1128     if (ca_certs == NULL) {
1129       return 0;
1130     }
1131     ca_certs_alloced = 1;
1132   }
1133 
1134   CBS_init(&ber_bytes, p12->ber_bytes, p12->ber_len);
1135   if (!PKCS12_get_key_and_certs(out_pkey, ca_certs, &ber_bytes, password)) {
1136     if (ca_certs_alloced) {
1137       sk_X509_free(ca_certs);
1138     }
1139     return 0;
1140   }
1141 
1142   *out_cert = NULL;
1143   if (sk_X509_num(ca_certs) > 0) {
1144     *out_cert = sk_X509_shift(ca_certs);
1145   }
1146 
1147   if (out_ca_certs) {
1148     *out_ca_certs = ca_certs;
1149   } else {
1150     sk_X509_pop_free(ca_certs, X509_free);
1151   }
1152 
1153   return 1;
1154 }
1155 
PKCS12_free(PKCS12 * p12)1156 void PKCS12_free(PKCS12 *p12) {
1157   OPENSSL_free(p12->ber_bytes);
1158   OPENSSL_free(p12);
1159 }
1160