xref: /aosp_15_r20/external/cronet/third_party/boringssl/src/crypto/pkcs8/pkcs8_x509.c (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 /* Written by Dr Stephen N Henson ([email protected]) 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  *    [email protected].
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  * ([email protected]).  This product includes software written by Tim
54  * Hudson ([email protected]). */
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/rand.h>
71 #include <openssl/x509.h>
72 
73 #include "../bytestring/internal.h"
74 #include "../internal.h"
75 #include "../x509/internal.h"
76 #include "internal.h"
77 
78 
pkcs12_iterations_acceptable(uint64_t iterations)79 int pkcs12_iterations_acceptable(uint64_t iterations) {
80 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
81   static const uint64_t kIterationsLimit = 2048;
82 #else
83   // Windows imposes a limit of 600K. Mozilla say: “so them increasing
84   // maximum to something like 100M or 1G (to have few decades of breathing
85   // room) would be very welcome”[1]. So here we set the limit to 100M.
86   //
87   // [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1436873#c14
88   static const uint64_t kIterationsLimit = 100 * 1000000;
89 #endif
90 
91   assert(kIterationsLimit <= UINT32_MAX);
92   return 0 < iterations && iterations <= kIterationsLimit;
93 }
94 
95 ASN1_SEQUENCE(PKCS8_PRIV_KEY_INFO) = {
96     ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, version, ASN1_INTEGER),
97     ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, pkeyalg, X509_ALGOR),
98     ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, pkey, ASN1_OCTET_STRING),
99     ASN1_IMP_SET_OF_OPT(PKCS8_PRIV_KEY_INFO, attributes, X509_ATTRIBUTE, 0),
100 } ASN1_SEQUENCE_END(PKCS8_PRIV_KEY_INFO)
101 
102 IMPLEMENT_ASN1_FUNCTIONS_const(PKCS8_PRIV_KEY_INFO)
103 
104 EVP_PKEY *EVP_PKCS82PKEY(const PKCS8_PRIV_KEY_INFO *p8) {
105   uint8_t *der = NULL;
106   int der_len = i2d_PKCS8_PRIV_KEY_INFO(p8, &der);
107   if (der_len < 0) {
108     return NULL;
109   }
110 
111   CBS cbs;
112   CBS_init(&cbs, der, (size_t)der_len);
113   EVP_PKEY *ret = EVP_parse_private_key(&cbs);
114   if (ret == NULL || CBS_len(&cbs) != 0) {
115     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
116     EVP_PKEY_free(ret);
117     OPENSSL_free(der);
118     return NULL;
119   }
120 
121   OPENSSL_free(der);
122   return ret;
123 }
124 
EVP_PKEY2PKCS8(const EVP_PKEY * pkey)125 PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(const EVP_PKEY *pkey) {
126   CBB cbb;
127   uint8_t *der = NULL;
128   size_t der_len;
129   if (!CBB_init(&cbb, 0) ||
130       !EVP_marshal_private_key(&cbb, pkey) ||
131       !CBB_finish(&cbb, &der, &der_len) ||
132       der_len > LONG_MAX) {
133     CBB_cleanup(&cbb);
134     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_ENCODE_ERROR);
135     goto err;
136   }
137 
138   const uint8_t *p = der;
139   PKCS8_PRIV_KEY_INFO *p8 = d2i_PKCS8_PRIV_KEY_INFO(NULL, &p, (long)der_len);
140   if (p8 == NULL || p != der + der_len) {
141     PKCS8_PRIV_KEY_INFO_free(p8);
142     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
143     goto err;
144   }
145 
146   OPENSSL_free(der);
147   return p8;
148 
149 err:
150   OPENSSL_free(der);
151   return NULL;
152 }
153 
PKCS8_decrypt(X509_SIG * pkcs8,const char * pass,int pass_len_in)154 PKCS8_PRIV_KEY_INFO *PKCS8_decrypt(X509_SIG *pkcs8, const char *pass,
155                                    int pass_len_in) {
156   size_t pass_len;
157   if (pass_len_in == -1 && pass != NULL) {
158     pass_len = strlen(pass);
159   } else {
160     pass_len = (size_t)pass_len_in;
161   }
162 
163   PKCS8_PRIV_KEY_INFO *ret = NULL;
164   EVP_PKEY *pkey = NULL;
165   uint8_t *in = NULL;
166 
167   // Convert the legacy ASN.1 object to a byte string.
168   int in_len = i2d_X509_SIG(pkcs8, &in);
169   if (in_len < 0) {
170     goto err;
171   }
172 
173   CBS cbs;
174   CBS_init(&cbs, in, in_len);
175   pkey = PKCS8_parse_encrypted_private_key(&cbs, pass, pass_len);
176   if (pkey == NULL || CBS_len(&cbs) != 0) {
177     goto err;
178   }
179 
180   ret = EVP_PKEY2PKCS8(pkey);
181 
182 err:
183   OPENSSL_free(in);
184   EVP_PKEY_free(pkey);
185   return ret;
186 }
187 
PKCS8_encrypt(int pbe_nid,const EVP_CIPHER * cipher,const char * pass,int pass_len_in,const uint8_t * salt,size_t salt_len,int iterations,PKCS8_PRIV_KEY_INFO * p8inf)188 X509_SIG *PKCS8_encrypt(int pbe_nid, const EVP_CIPHER *cipher, const char *pass,
189                         int pass_len_in, const uint8_t *salt, size_t salt_len,
190                         int iterations, PKCS8_PRIV_KEY_INFO *p8inf) {
191   size_t pass_len;
192   if (pass_len_in == -1 && pass != NULL) {
193     pass_len = strlen(pass);
194   } else {
195     pass_len = (size_t)pass_len_in;
196   }
197 
198   // Parse out the private key.
199   EVP_PKEY *pkey = EVP_PKCS82PKEY(p8inf);
200   if (pkey == NULL) {
201     return NULL;
202   }
203 
204   X509_SIG *ret = NULL;
205   uint8_t *der = NULL;
206   size_t der_len;
207   CBB cbb;
208   if (!CBB_init(&cbb, 128) ||
209       !PKCS8_marshal_encrypted_private_key(&cbb, pbe_nid, cipher, pass,
210                                            pass_len, salt, salt_len, iterations,
211                                            pkey) ||
212       !CBB_finish(&cbb, &der, &der_len)) {
213     CBB_cleanup(&cbb);
214     goto err;
215   }
216 
217   // Convert back to legacy ASN.1 objects.
218   const uint8_t *ptr = der;
219   ret = d2i_X509_SIG(NULL, &ptr, der_len);
220   if (ret == NULL || ptr != der + der_len) {
221     OPENSSL_PUT_ERROR(PKCS8, ERR_R_INTERNAL_ERROR);
222     X509_SIG_free(ret);
223     ret = NULL;
224   }
225 
226 err:
227   OPENSSL_free(der);
228   EVP_PKEY_free(pkey);
229   return ret;
230 }
231 
232 struct pkcs12_context {
233   EVP_PKEY **out_key;
234   STACK_OF(X509) *out_certs;
235   const char *password;
236   size_t password_len;
237 };
238 
239 // PKCS12_handle_sequence parses a BER-encoded SEQUENCE of elements in a PKCS#12
240 // structure.
PKCS12_handle_sequence(CBS * sequence,struct pkcs12_context * ctx,int (* handle_element)(CBS * cbs,struct pkcs12_context * ctx))241 static int PKCS12_handle_sequence(
242     CBS *sequence, struct pkcs12_context *ctx,
243     int (*handle_element)(CBS *cbs, struct pkcs12_context *ctx)) {
244   uint8_t *storage = NULL;
245   CBS in;
246   int ret = 0;
247 
248   // Although a BER->DER conversion is done at the beginning of |PKCS12_parse|,
249   // the ASN.1 data gets wrapped in OCTETSTRINGs and/or encrypted and the
250   // conversion cannot see through those wrappings. So each time we step
251   // through one we need to convert to DER again.
252   if (!CBS_asn1_ber_to_der(sequence, &in, &storage)) {
253     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
254     return 0;
255   }
256 
257   CBS child;
258   if (!CBS_get_asn1(&in, &child, CBS_ASN1_SEQUENCE) ||
259       CBS_len(&in) != 0) {
260     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
261     goto err;
262   }
263 
264   while (CBS_len(&child) > 0) {
265     CBS element;
266     if (!CBS_get_asn1(&child, &element, CBS_ASN1_SEQUENCE)) {
267       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
268       goto err;
269     }
270 
271     if (!handle_element(&element, ctx)) {
272       goto err;
273     }
274   }
275 
276   ret = 1;
277 
278 err:
279   OPENSSL_free(storage);
280   return ret;
281 }
282 
283 // 1.2.840.113549.1.12.10.1.1
284 static const uint8_t kKeyBag[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
285                                   0x01, 0x0c, 0x0a, 0x01, 0x01};
286 
287 // 1.2.840.113549.1.12.10.1.2
288 static const uint8_t kPKCS8ShroudedKeyBag[] = {
289     0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x0a, 0x01, 0x02};
290 
291 // 1.2.840.113549.1.12.10.1.3
292 static const uint8_t kCertBag[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
293                                    0x01, 0x0c, 0x0a, 0x01, 0x03};
294 
295 // 1.2.840.113549.1.9.20
296 static const uint8_t kFriendlyName[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
297                                         0x0d, 0x01, 0x09, 0x14};
298 
299 // 1.2.840.113549.1.9.21
300 static const uint8_t kLocalKeyID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
301                                       0x0d, 0x01, 0x09, 0x15};
302 
303 // 1.2.840.113549.1.9.22.1
304 static const uint8_t kX509Certificate[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
305                                            0x0d, 0x01, 0x09, 0x16, 0x01};
306 
307 // parse_bag_attributes parses the bagAttributes field of a SafeBag structure.
308 // It sets |*out_friendly_name| to a newly-allocated copy of the friendly name,
309 // encoded as a UTF-8 string, or NULL if there is none. It returns one on
310 // success and zero on error.
parse_bag_attributes(CBS * attrs,uint8_t ** out_friendly_name,size_t * out_friendly_name_len)311 static int parse_bag_attributes(CBS *attrs, uint8_t **out_friendly_name,
312                                 size_t *out_friendly_name_len) {
313   *out_friendly_name = NULL;
314   *out_friendly_name_len = 0;
315 
316   // See https://tools.ietf.org/html/rfc7292#section-4.2.
317   while (CBS_len(attrs) != 0) {
318     CBS attr, oid, values;
319     if (!CBS_get_asn1(attrs, &attr, CBS_ASN1_SEQUENCE) ||
320         !CBS_get_asn1(&attr, &oid, CBS_ASN1_OBJECT) ||
321         !CBS_get_asn1(&attr, &values, CBS_ASN1_SET) ||
322         CBS_len(&attr) != 0) {
323       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
324       goto err;
325     }
326     if (CBS_mem_equal(&oid, kFriendlyName, sizeof(kFriendlyName))) {
327       // See https://tools.ietf.org/html/rfc2985, section 5.5.1.
328       CBS value;
329       if (*out_friendly_name != NULL ||
330           !CBS_get_asn1(&values, &value, CBS_ASN1_BMPSTRING) ||
331           CBS_len(&values) != 0 ||
332           CBS_len(&value) == 0) {
333         OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
334         goto err;
335       }
336       // Convert the friendly name to UTF-8.
337       CBB cbb;
338       if (!CBB_init(&cbb, CBS_len(&value))) {
339         goto err;
340       }
341       while (CBS_len(&value) != 0) {
342         uint32_t c;
343         if (!CBS_get_ucs2_be(&value, &c) ||
344             !CBB_add_utf8(&cbb, c)) {
345           OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_INVALID_CHARACTERS);
346           CBB_cleanup(&cbb);
347           goto err;
348         }
349       }
350       if (!CBB_finish(&cbb, out_friendly_name, out_friendly_name_len)) {
351         CBB_cleanup(&cbb);
352         goto err;
353       }
354     }
355   }
356 
357   return 1;
358 
359 err:
360   OPENSSL_free(*out_friendly_name);
361   *out_friendly_name = NULL;
362   *out_friendly_name_len = 0;
363   return 0;
364 }
365 
366 // PKCS12_handle_safe_bag parses a single SafeBag element in a PKCS#12
367 // structure.
PKCS12_handle_safe_bag(CBS * safe_bag,struct pkcs12_context * ctx)368 static int PKCS12_handle_safe_bag(CBS *safe_bag, struct pkcs12_context *ctx) {
369   CBS bag_id, wrapped_value, bag_attrs;
370   if (!CBS_get_asn1(safe_bag, &bag_id, CBS_ASN1_OBJECT) ||
371       !CBS_get_asn1(safe_bag, &wrapped_value,
372                     CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0)) {
373     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
374     return 0;
375   }
376   if (CBS_len(safe_bag) == 0) {
377     CBS_init(&bag_attrs, NULL, 0);
378   } else if (!CBS_get_asn1(safe_bag, &bag_attrs, CBS_ASN1_SET) ||
379              CBS_len(safe_bag) != 0) {
380     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
381     return 0;
382   }
383 
384   const int is_key_bag = CBS_mem_equal(&bag_id, kKeyBag, sizeof(kKeyBag));
385   const int is_shrouded_key_bag = CBS_mem_equal(&bag_id, kPKCS8ShroudedKeyBag,
386                                                 sizeof(kPKCS8ShroudedKeyBag));
387   if (is_key_bag || is_shrouded_key_bag) {
388     // See RFC 7292, section 4.2.1 and 4.2.2.
389     if (*ctx->out_key) {
390       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_MULTIPLE_PRIVATE_KEYS_IN_PKCS12);
391       return 0;
392     }
393 
394     EVP_PKEY *pkey =
395         is_key_bag ? EVP_parse_private_key(&wrapped_value)
396                    : PKCS8_parse_encrypted_private_key(
397                          &wrapped_value, ctx->password, ctx->password_len);
398     if (pkey == NULL) {
399       return 0;
400     }
401 
402     if (CBS_len(&wrapped_value) != 0) {
403       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
404       EVP_PKEY_free(pkey);
405       return 0;
406     }
407 
408     *ctx->out_key = pkey;
409     return 1;
410   }
411 
412   if (CBS_mem_equal(&bag_id, kCertBag, sizeof(kCertBag))) {
413     // See RFC 7292, section 4.2.3.
414     CBS cert_bag, cert_type, wrapped_cert, cert;
415     if (!CBS_get_asn1(&wrapped_value, &cert_bag, CBS_ASN1_SEQUENCE) ||
416         !CBS_get_asn1(&cert_bag, &cert_type, CBS_ASN1_OBJECT) ||
417         !CBS_get_asn1(&cert_bag, &wrapped_cert,
418                       CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
419         !CBS_get_asn1(&wrapped_cert, &cert, CBS_ASN1_OCTETSTRING)) {
420       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
421       return 0;
422     }
423 
424     // Skip unknown certificate types.
425     if (!CBS_mem_equal(&cert_type, kX509Certificate,
426                        sizeof(kX509Certificate))) {
427       return 1;
428     }
429 
430     if (CBS_len(&cert) > LONG_MAX) {
431       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
432       return 0;
433     }
434 
435     const uint8_t *inp = CBS_data(&cert);
436     X509 *x509 = d2i_X509(NULL, &inp, (long)CBS_len(&cert));
437     if (!x509) {
438       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
439       return 0;
440     }
441 
442     if (inp != CBS_data(&cert) + CBS_len(&cert)) {
443       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
444       X509_free(x509);
445       return 0;
446     }
447 
448     uint8_t *friendly_name;
449     size_t friendly_name_len;
450     if (!parse_bag_attributes(&bag_attrs, &friendly_name, &friendly_name_len)) {
451       X509_free(x509);
452       return 0;
453     }
454     int ok = friendly_name_len == 0 ||
455              X509_alias_set1(x509, friendly_name, friendly_name_len);
456     OPENSSL_free(friendly_name);
457     if (!ok ||
458         0 == sk_X509_push(ctx->out_certs, x509)) {
459       X509_free(x509);
460       return 0;
461     }
462 
463     return 1;
464   }
465 
466   // Unknown element type - ignore it.
467   return 1;
468 }
469 
470 // 1.2.840.113549.1.7.1
471 static const uint8_t kPKCS7Data[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
472                                      0x0d, 0x01, 0x07, 0x01};
473 
474 // 1.2.840.113549.1.7.6
475 static const uint8_t kPKCS7EncryptedData[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
476                                               0x0d, 0x01, 0x07, 0x06};
477 
478 // PKCS12_handle_content_info parses a single PKCS#7 ContentInfo element in a
479 // PKCS#12 structure.
PKCS12_handle_content_info(CBS * content_info,struct pkcs12_context * ctx)480 static int PKCS12_handle_content_info(CBS *content_info,
481                                       struct pkcs12_context *ctx) {
482   CBS content_type, wrapped_contents, contents;
483   int ret = 0;
484   uint8_t *storage = NULL;
485 
486   if (!CBS_get_asn1(content_info, &content_type, CBS_ASN1_OBJECT) ||
487       !CBS_get_asn1(content_info, &wrapped_contents,
488                         CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
489       CBS_len(content_info) != 0) {
490     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
491     goto err;
492   }
493 
494   if (CBS_mem_equal(&content_type, kPKCS7EncryptedData,
495                     sizeof(kPKCS7EncryptedData))) {
496     // See https://tools.ietf.org/html/rfc2315#section-13.
497     //
498     // PKCS#7 encrypted data inside a PKCS#12 structure is generally an
499     // encrypted certificate bag and it's generally encrypted with 40-bit
500     // RC2-CBC.
501     CBS version_bytes, eci, contents_type, ai, encrypted_contents;
502     uint8_t *out;
503     size_t out_len;
504 
505     if (!CBS_get_asn1(&wrapped_contents, &contents, CBS_ASN1_SEQUENCE) ||
506         !CBS_get_asn1(&contents, &version_bytes, CBS_ASN1_INTEGER) ||
507         // EncryptedContentInfo, see
508         // https://tools.ietf.org/html/rfc2315#section-10.1
509         !CBS_get_asn1(&contents, &eci, CBS_ASN1_SEQUENCE) ||
510         !CBS_get_asn1(&eci, &contents_type, CBS_ASN1_OBJECT) ||
511         // AlgorithmIdentifier, see
512         // https://tools.ietf.org/html/rfc5280#section-4.1.1.2
513         !CBS_get_asn1(&eci, &ai, CBS_ASN1_SEQUENCE) ||
514         !CBS_get_asn1_implicit_string(
515             &eci, &encrypted_contents, &storage,
516             CBS_ASN1_CONTEXT_SPECIFIC | 0, CBS_ASN1_OCTETSTRING)) {
517       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
518       goto err;
519     }
520 
521     if (!CBS_mem_equal(&contents_type, kPKCS7Data, sizeof(kPKCS7Data))) {
522       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
523       goto err;
524     }
525 
526     if (!pkcs8_pbe_decrypt(&out, &out_len, &ai, ctx->password,
527                            ctx->password_len, CBS_data(&encrypted_contents),
528                            CBS_len(&encrypted_contents))) {
529       goto err;
530     }
531 
532     CBS safe_contents;
533     CBS_init(&safe_contents, out, out_len);
534     ret = PKCS12_handle_sequence(&safe_contents, ctx, PKCS12_handle_safe_bag);
535     OPENSSL_free(out);
536   } else if (CBS_mem_equal(&content_type, kPKCS7Data, sizeof(kPKCS7Data))) {
537     CBS octet_string_contents;
538 
539     if (!CBS_get_asn1(&wrapped_contents, &octet_string_contents,
540                       CBS_ASN1_OCTETSTRING)) {
541       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
542       goto err;
543     }
544 
545     ret = PKCS12_handle_sequence(&octet_string_contents, ctx,
546                                  PKCS12_handle_safe_bag);
547   } else {
548     // Unknown element type - ignore it.
549     ret = 1;
550   }
551 
552 err:
553   OPENSSL_free(storage);
554   return ret;
555 }
556 
pkcs12_check_mac(int * out_mac_ok,const char * password,size_t password_len,const CBS * salt,uint32_t iterations,const EVP_MD * md,const CBS * authsafes,const CBS * expected_mac)557 static int pkcs12_check_mac(int *out_mac_ok, const char *password,
558                             size_t password_len, const CBS *salt,
559                             uint32_t iterations, const EVP_MD *md,
560                             const CBS *authsafes, const CBS *expected_mac) {
561   int ret = 0;
562   uint8_t hmac_key[EVP_MAX_MD_SIZE];
563   if (!pkcs12_key_gen(password, password_len, CBS_data(salt), CBS_len(salt),
564                       PKCS12_MAC_ID, iterations, EVP_MD_size(md), hmac_key,
565                       md)) {
566     goto err;
567   }
568 
569   uint8_t hmac[EVP_MAX_MD_SIZE];
570   unsigned hmac_len;
571   if (NULL == HMAC(md, hmac_key, EVP_MD_size(md), CBS_data(authsafes),
572                    CBS_len(authsafes), hmac, &hmac_len)) {
573     goto err;
574   }
575 
576   *out_mac_ok = CBS_mem_equal(expected_mac, hmac, hmac_len);
577 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
578   *out_mac_ok = 1;
579 #endif
580   ret = 1;
581 
582 err:
583   OPENSSL_cleanse(hmac_key, sizeof(hmac_key));
584   return ret;
585 }
586 
587 
PKCS12_get_key_and_certs(EVP_PKEY ** out_key,STACK_OF (X509)* out_certs,CBS * ber_in,const char * password)588 int PKCS12_get_key_and_certs(EVP_PKEY **out_key, STACK_OF(X509) *out_certs,
589                              CBS *ber_in, const char *password) {
590   uint8_t *storage = NULL;
591   CBS in, pfx, mac_data, authsafe, content_type, wrapped_authsafes, authsafes;
592   uint64_t version;
593   int ret = 0;
594   struct pkcs12_context ctx;
595   const size_t original_out_certs_len = sk_X509_num(out_certs);
596 
597   // The input may be in BER format.
598   if (!CBS_asn1_ber_to_der(ber_in, &in, &storage)) {
599     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
600     return 0;
601   }
602 
603   *out_key = NULL;
604   OPENSSL_memset(&ctx, 0, sizeof(ctx));
605 
606   // See ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12v1.pdf, section
607   // four.
608   if (!CBS_get_asn1(&in, &pfx, CBS_ASN1_SEQUENCE) ||
609       CBS_len(&in) != 0 ||
610       !CBS_get_asn1_uint64(&pfx, &version)) {
611     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
612     goto err;
613   }
614 
615   if (version < 3) {
616     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_VERSION);
617     goto err;
618   }
619 
620   if (!CBS_get_asn1(&pfx, &authsafe, CBS_ASN1_SEQUENCE)) {
621     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
622     goto err;
623   }
624 
625   if (CBS_len(&pfx) == 0) {
626     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_MISSING_MAC);
627     goto err;
628   }
629 
630   if (!CBS_get_asn1(&pfx, &mac_data, CBS_ASN1_SEQUENCE)) {
631     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
632     goto err;
633   }
634 
635   // authsafe is a PKCS#7 ContentInfo. See
636   // https://tools.ietf.org/html/rfc2315#section-7.
637   if (!CBS_get_asn1(&authsafe, &content_type, CBS_ASN1_OBJECT) ||
638       !CBS_get_asn1(&authsafe, &wrapped_authsafes,
639                         CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0)) {
640     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
641     goto err;
642   }
643 
644   // The content type can either be data or signedData. The latter indicates
645   // that it's signed by a public key, which isn't supported.
646   if (!CBS_mem_equal(&content_type, kPKCS7Data, sizeof(kPKCS7Data))) {
647     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_PKCS12_PUBLIC_KEY_INTEGRITY_NOT_SUPPORTED);
648     goto err;
649   }
650 
651   if (!CBS_get_asn1(&wrapped_authsafes, &authsafes, CBS_ASN1_OCTETSTRING)) {
652     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
653     goto err;
654   }
655 
656   ctx.out_key = out_key;
657   ctx.out_certs = out_certs;
658   ctx.password = password;
659   ctx.password_len = password != NULL ? strlen(password) : 0;
660 
661   // Verify the MAC.
662   {
663     CBS mac, salt, expected_mac;
664     if (!CBS_get_asn1(&mac_data, &mac, CBS_ASN1_SEQUENCE)) {
665       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
666       goto err;
667     }
668 
669     const EVP_MD *md = EVP_parse_digest_algorithm(&mac);
670     if (md == NULL) {
671       goto err;
672     }
673 
674     if (!CBS_get_asn1(&mac, &expected_mac, CBS_ASN1_OCTETSTRING) ||
675         !CBS_get_asn1(&mac_data, &salt, CBS_ASN1_OCTETSTRING)) {
676       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
677       goto err;
678     }
679 
680     // The iteration count is optional and the default is one.
681     uint32_t iterations = 1;
682     if (CBS_len(&mac_data) > 0) {
683       uint64_t iterations_u64;
684       if (!CBS_get_asn1_uint64(&mac_data, &iterations_u64) ||
685           !pkcs12_iterations_acceptable(iterations_u64)) {
686         OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
687         goto err;
688       }
689       iterations = (uint32_t)iterations_u64;
690     }
691 
692     int mac_ok;
693     if (!pkcs12_check_mac(&mac_ok, ctx.password, ctx.password_len, &salt,
694                           iterations, md, &authsafes, &expected_mac)) {
695       goto err;
696     }
697     if (!mac_ok && ctx.password_len == 0) {
698       // PKCS#12 encodes passwords as NUL-terminated UCS-2, so the empty
699       // password is encoded as {0, 0}. Some implementations use the empty byte
700       // array for "no password". OpenSSL considers a non-NULL password as {0,
701       // 0} and a NULL password as {}. It then, in high-level PKCS#12 parsing
702       // code, tries both options. We match this behavior.
703       ctx.password = ctx.password != NULL ? NULL : "";
704       if (!pkcs12_check_mac(&mac_ok, ctx.password, ctx.password_len, &salt,
705                             iterations, md, &authsafes, &expected_mac)) {
706         goto err;
707       }
708     }
709     if (!mac_ok) {
710       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_INCORRECT_PASSWORD);
711       goto err;
712     }
713   }
714 
715   // authsafes contains a series of PKCS#7 ContentInfos.
716   if (!PKCS12_handle_sequence(&authsafes, &ctx, PKCS12_handle_content_info)) {
717     goto err;
718   }
719 
720   ret = 1;
721 
722 err:
723   OPENSSL_free(storage);
724   if (!ret) {
725     EVP_PKEY_free(*out_key);
726     *out_key = NULL;
727     while (sk_X509_num(out_certs) > original_out_certs_len) {
728       X509 *x509 = sk_X509_pop(out_certs);
729       X509_free(x509);
730     }
731   }
732 
733   return ret;
734 }
735 
PKCS12_PBE_add(void)736 void PKCS12_PBE_add(void) {}
737 
738 struct pkcs12_st {
739   uint8_t *ber_bytes;
740   size_t ber_len;
741 };
742 
d2i_PKCS12(PKCS12 ** out_p12,const uint8_t ** ber_bytes,size_t ber_len)743 PKCS12 *d2i_PKCS12(PKCS12 **out_p12, const uint8_t **ber_bytes,
744                    size_t ber_len) {
745   PKCS12 *p12 = OPENSSL_malloc(sizeof(PKCS12));
746   if (!p12) {
747     return NULL;
748   }
749 
750   p12->ber_bytes = OPENSSL_memdup(*ber_bytes, ber_len);
751   if (!p12->ber_bytes) {
752     OPENSSL_free(p12);
753     return NULL;
754   }
755 
756   p12->ber_len = ber_len;
757   *ber_bytes += ber_len;
758 
759   if (out_p12) {
760     PKCS12_free(*out_p12);
761     *out_p12 = p12;
762   }
763 
764   return p12;
765 }
766 
d2i_PKCS12_bio(BIO * bio,PKCS12 ** out_p12)767 PKCS12* d2i_PKCS12_bio(BIO *bio, PKCS12 **out_p12) {
768   size_t used = 0;
769   BUF_MEM *buf;
770   const uint8_t *dummy;
771   static const size_t kMaxSize = 256 * 1024;
772   PKCS12 *ret = NULL;
773 
774   buf = BUF_MEM_new();
775   if (buf == NULL) {
776     return NULL;
777   }
778   if (BUF_MEM_grow(buf, 8192) == 0) {
779     goto out;
780   }
781 
782   for (;;) {
783     size_t max_read = buf->length - used;
784     int n = BIO_read(bio, &buf->data[used],
785                      max_read > INT_MAX ? INT_MAX : (int)max_read);
786     if (n < 0) {
787       if (used == 0) {
788         goto out;
789       }
790       // Workaround a bug in node.js. It uses a memory BIO for this in the wrong
791       // mode.
792       n = 0;
793     }
794 
795     if (n == 0) {
796       break;
797     }
798     used += n;
799 
800     if (used < buf->length) {
801       continue;
802     }
803 
804     if (buf->length > kMaxSize ||
805         BUF_MEM_grow(buf, buf->length * 2) == 0) {
806       goto out;
807     }
808   }
809 
810   dummy = (uint8_t*) buf->data;
811   ret = d2i_PKCS12(out_p12, &dummy, used);
812 
813 out:
814   BUF_MEM_free(buf);
815   return ret;
816 }
817 
d2i_PKCS12_fp(FILE * fp,PKCS12 ** out_p12)818 PKCS12* d2i_PKCS12_fp(FILE *fp, PKCS12 **out_p12) {
819   BIO *bio;
820   PKCS12 *ret;
821 
822   bio = BIO_new_fp(fp, 0 /* don't take ownership */);
823   if (!bio) {
824     return NULL;
825   }
826 
827   ret = d2i_PKCS12_bio(bio, out_p12);
828   BIO_free(bio);
829   return ret;
830 }
831 
i2d_PKCS12(const PKCS12 * p12,uint8_t ** out)832 int i2d_PKCS12(const PKCS12 *p12, uint8_t **out) {
833   if (p12->ber_len > INT_MAX) {
834     OPENSSL_PUT_ERROR(PKCS8, ERR_R_OVERFLOW);
835     return -1;
836   }
837 
838   if (out == NULL) {
839     return (int)p12->ber_len;
840   }
841 
842   if (*out == NULL) {
843     *out = OPENSSL_memdup(p12->ber_bytes, p12->ber_len);
844     if (*out == NULL) {
845       return -1;
846     }
847   } else {
848     OPENSSL_memcpy(*out, p12->ber_bytes, p12->ber_len);
849     *out += p12->ber_len;
850   }
851   return (int)p12->ber_len;
852 }
853 
i2d_PKCS12_bio(BIO * bio,const PKCS12 * p12)854 int i2d_PKCS12_bio(BIO *bio, const PKCS12 *p12) {
855   return BIO_write_all(bio, p12->ber_bytes, p12->ber_len);
856 }
857 
i2d_PKCS12_fp(FILE * fp,const PKCS12 * p12)858 int i2d_PKCS12_fp(FILE *fp, const PKCS12 *p12) {
859   BIO *bio = BIO_new_fp(fp, 0 /* don't take ownership */);
860   if (bio == NULL) {
861     return 0;
862   }
863 
864   int ret = i2d_PKCS12_bio(bio, p12);
865   BIO_free(bio);
866   return ret;
867 }
868 
PKCS12_parse(const PKCS12 * p12,const char * password,EVP_PKEY ** out_pkey,X509 ** out_cert,STACK_OF (X509)** out_ca_certs)869 int PKCS12_parse(const PKCS12 *p12, const char *password, EVP_PKEY **out_pkey,
870                  X509 **out_cert, STACK_OF(X509) **out_ca_certs) {
871   CBS ber_bytes;
872   STACK_OF(X509) *ca_certs = NULL;
873   char ca_certs_alloced = 0;
874 
875   if (out_ca_certs != NULL && *out_ca_certs != NULL) {
876     ca_certs = *out_ca_certs;
877   }
878 
879   if (!ca_certs) {
880     ca_certs = sk_X509_new_null();
881     if (ca_certs == NULL) {
882       return 0;
883     }
884     ca_certs_alloced = 1;
885   }
886 
887   CBS_init(&ber_bytes, p12->ber_bytes, p12->ber_len);
888   if (!PKCS12_get_key_and_certs(out_pkey, ca_certs, &ber_bytes, password)) {
889     if (ca_certs_alloced) {
890       sk_X509_free(ca_certs);
891     }
892     return 0;
893   }
894 
895   // OpenSSL selects the last certificate which matches the private key as
896   // |out_cert|.
897   *out_cert = NULL;
898   size_t num_certs = sk_X509_num(ca_certs);
899   if (*out_pkey != NULL && num_certs > 0) {
900     for (size_t i = num_certs - 1; i < num_certs; i--) {
901       X509 *cert = sk_X509_value(ca_certs, i);
902       if (X509_check_private_key(cert, *out_pkey)) {
903         *out_cert = cert;
904         sk_X509_delete(ca_certs, i);
905         break;
906       }
907       ERR_clear_error();
908     }
909   }
910 
911   if (out_ca_certs) {
912     *out_ca_certs = ca_certs;
913   } else {
914     sk_X509_pop_free(ca_certs, X509_free);
915   }
916 
917   return 1;
918 }
919 
PKCS12_verify_mac(const PKCS12 * p12,const char * password,int password_len)920 int PKCS12_verify_mac(const PKCS12 *p12, const char *password,
921                       int password_len) {
922   if (password == NULL) {
923     if (password_len != 0) {
924       return 0;
925     }
926   } else if (password_len != -1 &&
927              (password[password_len] != 0 ||
928               OPENSSL_memchr(password, 0, password_len) != NULL)) {
929     return 0;
930   }
931 
932   EVP_PKEY *pkey = NULL;
933   X509 *cert = NULL;
934   if (!PKCS12_parse(p12, password, &pkey, &cert, NULL)) {
935     ERR_clear_error();
936     return 0;
937   }
938 
939   EVP_PKEY_free(pkey);
940   X509_free(cert);
941 
942   return 1;
943 }
944 
945 // add_bag_attributes adds the bagAttributes field of a SafeBag structure,
946 // containing the specified friendlyName and localKeyId attributes.
add_bag_attributes(CBB * bag,const char * name,size_t name_len,const uint8_t * key_id,size_t key_id_len)947 static int add_bag_attributes(CBB *bag, const char *name, size_t name_len,
948                               const uint8_t *key_id, size_t key_id_len) {
949   if (name == NULL && key_id_len == 0) {
950     return 1;  // Omit the OPTIONAL SET.
951   }
952   // See https://tools.ietf.org/html/rfc7292#section-4.2.
953   CBB attrs, attr, oid, values, value;
954   if (!CBB_add_asn1(bag, &attrs, CBS_ASN1_SET)) {
955     return 0;
956   }
957   if (name_len != 0) {
958     // See https://tools.ietf.org/html/rfc2985, section 5.5.1.
959     if (!CBB_add_asn1(&attrs, &attr, CBS_ASN1_SEQUENCE) ||
960         !CBB_add_asn1(&attr, &oid, CBS_ASN1_OBJECT) ||
961         !CBB_add_bytes(&oid, kFriendlyName, sizeof(kFriendlyName)) ||
962         !CBB_add_asn1(&attr, &values, CBS_ASN1_SET) ||
963         !CBB_add_asn1(&values, &value, CBS_ASN1_BMPSTRING)) {
964       return 0;
965     }
966     // Convert the friendly name to a BMPString.
967     CBS name_cbs;
968     CBS_init(&name_cbs, (const uint8_t *)name, name_len);
969     while (CBS_len(&name_cbs) != 0) {
970       uint32_t c;
971       if (!CBS_get_utf8(&name_cbs, &c) ||
972           !CBB_add_ucs2_be(&value, c)) {
973         OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_INVALID_CHARACTERS);
974         return 0;
975       }
976     }
977   }
978   if (key_id_len != 0) {
979     // See https://tools.ietf.org/html/rfc2985, section 5.5.2.
980     if (!CBB_add_asn1(&attrs, &attr, CBS_ASN1_SEQUENCE) ||
981         !CBB_add_asn1(&attr, &oid, CBS_ASN1_OBJECT) ||
982         !CBB_add_bytes(&oid, kLocalKeyID, sizeof(kLocalKeyID)) ||
983         !CBB_add_asn1(&attr, &values, CBS_ASN1_SET) ||
984         !CBB_add_asn1(&values, &value, CBS_ASN1_OCTETSTRING) ||
985         !CBB_add_bytes(&value, key_id, key_id_len)) {
986       return 0;
987     }
988   }
989   return CBB_flush_asn1_set_of(&attrs) &&
990          CBB_flush(bag);
991 }
992 
add_cert_bag(CBB * cbb,X509 * cert,const char * name,const uint8_t * key_id,size_t key_id_len)993 static int add_cert_bag(CBB *cbb, X509 *cert, const char *name,
994                         const uint8_t *key_id, size_t key_id_len) {
995   CBB bag, bag_oid, bag_contents, cert_bag, cert_type, wrapped_cert, cert_value;
996   if (// See https://tools.ietf.org/html/rfc7292#section-4.2.
997       !CBB_add_asn1(cbb, &bag, CBS_ASN1_SEQUENCE) ||
998       !CBB_add_asn1(&bag, &bag_oid, CBS_ASN1_OBJECT) ||
999       !CBB_add_bytes(&bag_oid, kCertBag, sizeof(kCertBag)) ||
1000       !CBB_add_asn1(&bag, &bag_contents,
1001                     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) ||
1002       // See https://tools.ietf.org/html/rfc7292#section-4.2.3.
1003       !CBB_add_asn1(&bag_contents, &cert_bag, CBS_ASN1_SEQUENCE) ||
1004       !CBB_add_asn1(&cert_bag, &cert_type, CBS_ASN1_OBJECT) ||
1005       !CBB_add_bytes(&cert_type, kX509Certificate, sizeof(kX509Certificate)) ||
1006       !CBB_add_asn1(&cert_bag, &wrapped_cert,
1007                     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) ||
1008       !CBB_add_asn1(&wrapped_cert, &cert_value, CBS_ASN1_OCTETSTRING)) {
1009     return 0;
1010   }
1011   uint8_t *buf;
1012   int len = i2d_X509(cert, NULL);
1013 
1014   int int_name_len = 0;
1015   const char *cert_name = (const char *)X509_alias_get0(cert, &int_name_len);
1016   size_t name_len = int_name_len;
1017   if (name) {
1018     if (name_len != 0) {
1019       OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_AMBIGUOUS_FRIENDLY_NAME);
1020       return 0;
1021     }
1022     name_len = strlen(name);
1023   } else {
1024     name = cert_name;
1025   }
1026 
1027   if (len < 0 ||
1028       !CBB_add_space(&cert_value, &buf, (size_t)len) ||
1029       i2d_X509(cert, &buf) < 0 ||
1030       !add_bag_attributes(&bag, name, name_len, key_id, key_id_len) ||
1031       !CBB_flush(cbb)) {
1032     return 0;
1033   }
1034   return 1;
1035 }
1036 
add_cert_safe_contents(CBB * cbb,X509 * cert,const STACK_OF (X509)* chain,const char * name,const uint8_t * key_id,size_t key_id_len)1037 static int add_cert_safe_contents(CBB *cbb, X509 *cert,
1038                                   const STACK_OF(X509) *chain, const char *name,
1039                                   const uint8_t *key_id, size_t key_id_len) {
1040   CBB safe_contents;
1041   if (!CBB_add_asn1(cbb, &safe_contents, CBS_ASN1_SEQUENCE) ||
1042       (cert != NULL &&
1043        !add_cert_bag(&safe_contents, cert, name, key_id, key_id_len))) {
1044     return 0;
1045   }
1046 
1047   for (size_t i = 0; i < sk_X509_num(chain); i++) {
1048     // Only the leaf certificate gets attributes.
1049     if (!add_cert_bag(&safe_contents, sk_X509_value(chain, i), NULL, NULL, 0)) {
1050       return 0;
1051     }
1052   }
1053 
1054   return CBB_flush(cbb);
1055 }
1056 
add_encrypted_data(CBB * out,int pbe_nid,const char * password,size_t password_len,uint32_t iterations,const uint8_t * in,size_t in_len)1057 static int add_encrypted_data(CBB *out, int pbe_nid, const char *password,
1058                               size_t password_len, uint32_t iterations,
1059                               const uint8_t *in, size_t in_len) {
1060   uint8_t salt[PKCS5_SALT_LEN];
1061   if (!RAND_bytes(salt, sizeof(salt))) {
1062     return 0;
1063   }
1064 
1065   int ret = 0;
1066   EVP_CIPHER_CTX ctx;
1067   EVP_CIPHER_CTX_init(&ctx);
1068   CBB content_info, type, wrapper, encrypted_data, encrypted_content_info,
1069       inner_type, encrypted_content;
1070   if (// Add the ContentInfo wrapping.
1071       !CBB_add_asn1(out, &content_info, CBS_ASN1_SEQUENCE) ||
1072       !CBB_add_asn1(&content_info, &type, CBS_ASN1_OBJECT) ||
1073       !CBB_add_bytes(&type, kPKCS7EncryptedData, sizeof(kPKCS7EncryptedData)) ||
1074       !CBB_add_asn1(&content_info, &wrapper,
1075                     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) ||
1076       // See https://tools.ietf.org/html/rfc2315#section-13.
1077       !CBB_add_asn1(&wrapper, &encrypted_data, CBS_ASN1_SEQUENCE) ||
1078       !CBB_add_asn1_uint64(&encrypted_data, 0 /* version */) ||
1079       // See https://tools.ietf.org/html/rfc2315#section-10.1.
1080       !CBB_add_asn1(&encrypted_data, &encrypted_content_info,
1081                     CBS_ASN1_SEQUENCE) ||
1082       !CBB_add_asn1(&encrypted_content_info, &inner_type, CBS_ASN1_OBJECT) ||
1083       !CBB_add_bytes(&inner_type, kPKCS7Data, sizeof(kPKCS7Data)) ||
1084       // Set up encryption and fill in contentEncryptionAlgorithm.
1085       !pkcs12_pbe_encrypt_init(&encrypted_content_info, &ctx, pbe_nid,
1086                                iterations, password, password_len, salt,
1087                                sizeof(salt)) ||
1088       // Note this tag is primitive. It is an implicitly-tagged OCTET_STRING, so
1089       // it inherits the inner tag's constructed bit.
1090       !CBB_add_asn1(&encrypted_content_info, &encrypted_content,
1091                     CBS_ASN1_CONTEXT_SPECIFIC | 0)) {
1092     goto err;
1093   }
1094 
1095   size_t max_out = in_len + EVP_CIPHER_CTX_block_size(&ctx);
1096   if (max_out < in_len) {
1097     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_TOO_LONG);
1098     goto err;
1099   }
1100 
1101   uint8_t *ptr;
1102   int n1, n2;
1103   if (!CBB_reserve(&encrypted_content, &ptr, max_out) ||
1104       !EVP_CipherUpdate(&ctx, ptr, &n1, in, in_len) ||
1105       !EVP_CipherFinal_ex(&ctx, ptr + n1, &n2) ||
1106       !CBB_did_write(&encrypted_content, n1 + n2) ||
1107       !CBB_flush(out)) {
1108     goto err;
1109   }
1110 
1111   ret = 1;
1112 
1113 err:
1114   EVP_CIPHER_CTX_cleanup(&ctx);
1115   return ret;
1116 }
1117 
PKCS12_create(const char * password,const char * name,const EVP_PKEY * pkey,X509 * cert,const STACK_OF (X509)* chain,int key_nid,int cert_nid,int iterations,int mac_iterations,int key_type)1118 PKCS12 *PKCS12_create(const char *password, const char *name,
1119                       const EVP_PKEY *pkey, X509 *cert,
1120                       const STACK_OF(X509)* chain, int key_nid, int cert_nid,
1121                       int iterations, int mac_iterations, int key_type) {
1122   if (key_nid == 0) {
1123     key_nid = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
1124   }
1125   if (cert_nid == 0) {
1126     cert_nid = NID_pbe_WithSHA1And40BitRC2_CBC;
1127   }
1128   if (iterations == 0) {
1129     iterations = PKCS12_DEFAULT_ITER;
1130   }
1131   if (mac_iterations == 0) {
1132     mac_iterations = 1;
1133   }
1134   if (// In OpenSSL, this specifies a non-standard Microsoft key usage extension
1135       // which we do not currently support.
1136       key_type != 0 ||
1137       // In OpenSSL, -1 here means to omit the MAC, which we do not
1138       // currently support. Omitting it is also invalid for a password-based
1139       // PKCS#12 file.
1140       mac_iterations < 0 ||
1141       // Don't encode empty objects.
1142       (pkey == NULL && cert == NULL && sk_X509_num(chain) == 0)) {
1143     OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNSUPPORTED_OPTIONS);
1144     return 0;
1145   }
1146 
1147   // PKCS#12 is a very confusing recursive data format, built out of another
1148   // recursive data format. Section 5.1 of RFC 7292 describes the encoding
1149   // algorithm, but there is no clear overview. A quick summary:
1150   //
1151   // PKCS#7 defines a ContentInfo structure, which is a overgeneralized typed
1152   // combinator structure for applying cryptography. We care about two types. A
1153   // data ContentInfo contains an OCTET STRING and is a leaf node of the
1154   // combinator tree. An encrypted-data ContentInfo contains encryption
1155   // parameters (key derivation and encryption) and wraps another ContentInfo,
1156   // usually data.
1157   //
1158   // A PKCS#12 file is a PFX structure (section 4), which contains a single data
1159   // ContentInfo and a MAC over it. This root ContentInfo is the
1160   // AuthenticatedSafe and its payload is a SEQUENCE of other ContentInfos, so
1161   // that different parts of the PKCS#12 file can by differently protected.
1162   //
1163   // Each ContentInfo in the AuthenticatedSafe, after undoing all the PKCS#7
1164   // combinators, has SafeContents payload. A SafeContents is a SEQUENCE of
1165   // SafeBag. SafeBag is PKCS#12's typed structure, with subtypes such as KeyBag
1166   // and CertBag. Confusingly, there is a SafeContents bag type which itself
1167   // recursively contains more SafeBags, but we do not implement this. Bags also
1168   // can have attributes.
1169   //
1170   // The grouping of SafeBags into intermediate ContentInfos does not appear to
1171   // be significant, except that all SafeBags sharing a ContentInfo have the
1172   // same level of protection. Additionally, while keys may be encrypted by
1173   // placing a KeyBag in an encrypted-data ContentInfo, PKCS#12 also defines a
1174   // key-specific encryption container, PKCS8ShroudedKeyBag, which is used
1175   // instead.
1176 
1177   // Note that |password| may be NULL to specify no password, rather than the
1178   // empty string. They are encoded differently in PKCS#12. (One is the empty
1179   // byte array and the other is NUL-terminated UCS-2.)
1180   size_t password_len = password != NULL ? strlen(password) : 0;
1181 
1182   uint8_t key_id[EVP_MAX_MD_SIZE];
1183   unsigned key_id_len = 0;
1184   if (cert != NULL && pkey != NULL) {
1185     if (!X509_check_private_key(cert, pkey) ||
1186         // Matching OpenSSL, use the SHA-1 hash of the certificate as the local
1187         // key ID. Some PKCS#12 consumers require one to connect the private key
1188         // and certificate.
1189         !X509_digest(cert, EVP_sha1(), key_id, &key_id_len)) {
1190       return 0;
1191     }
1192   }
1193 
1194   // See https://tools.ietf.org/html/rfc7292#section-4.
1195   PKCS12 *ret = NULL;
1196   CBB cbb, pfx, auth_safe, auth_safe_oid, auth_safe_wrapper, auth_safe_data,
1197       content_infos;
1198   uint8_t mac_key[EVP_MAX_MD_SIZE];
1199   if (!CBB_init(&cbb, 0) ||
1200       !CBB_add_asn1(&cbb, &pfx, CBS_ASN1_SEQUENCE) ||
1201       !CBB_add_asn1_uint64(&pfx, 3) ||
1202       // auth_safe is a data ContentInfo.
1203       !CBB_add_asn1(&pfx, &auth_safe, CBS_ASN1_SEQUENCE) ||
1204       !CBB_add_asn1(&auth_safe, &auth_safe_oid, CBS_ASN1_OBJECT) ||
1205       !CBB_add_bytes(&auth_safe_oid, kPKCS7Data, sizeof(kPKCS7Data)) ||
1206       !CBB_add_asn1(&auth_safe, &auth_safe_wrapper,
1207                     CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) ||
1208       !CBB_add_asn1(&auth_safe_wrapper, &auth_safe_data,
1209                     CBS_ASN1_OCTETSTRING) ||
1210       // See https://tools.ietf.org/html/rfc7292#section-4.1. |auth_safe|'s
1211       // contains a SEQUENCE of ContentInfos.
1212       !CBB_add_asn1(&auth_safe_data, &content_infos, CBS_ASN1_SEQUENCE)) {
1213     goto err;
1214   }
1215 
1216   // If there are any certificates, place them in CertBags wrapped in a single
1217   // encrypted ContentInfo.
1218   if (cert != NULL || sk_X509_num(chain) > 0) {
1219     if (cert_nid < 0) {
1220       // Place the certificates in an unencrypted ContentInfo. This could be
1221       // more compactly-encoded by reusing the same ContentInfo as the key, but
1222       // OpenSSL does not do this. We keep them separate for consistency. (Keys,
1223       // even when encrypted, are always placed in unencrypted ContentInfos.
1224       // PKCS#12 defines bag-level encryption for keys.)
1225       CBB content_info, oid, wrapper, data;
1226       if (!CBB_add_asn1(&content_infos, &content_info, CBS_ASN1_SEQUENCE) ||
1227           !CBB_add_asn1(&content_info, &oid, CBS_ASN1_OBJECT) ||
1228           !CBB_add_bytes(&oid, kPKCS7Data, sizeof(kPKCS7Data)) ||
1229           !CBB_add_asn1(&content_info, &wrapper,
1230                         CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) ||
1231           !CBB_add_asn1(&wrapper, &data, CBS_ASN1_OCTETSTRING) ||
1232           !add_cert_safe_contents(&data, cert, chain, name, key_id,
1233                                   key_id_len) ||
1234           !CBB_flush(&content_infos)) {
1235         goto err;
1236       }
1237     } else {
1238       CBB plaintext_cbb;
1239       int ok = CBB_init(&plaintext_cbb, 0) &&
1240                add_cert_safe_contents(&plaintext_cbb, cert, chain, name, key_id,
1241                                       key_id_len) &&
1242                add_encrypted_data(
1243                    &content_infos, cert_nid, password, password_len, iterations,
1244                    CBB_data(&plaintext_cbb), CBB_len(&plaintext_cbb));
1245       CBB_cleanup(&plaintext_cbb);
1246       if (!ok) {
1247         goto err;
1248       }
1249     }
1250   }
1251 
1252   // If there is a key, place it in a single KeyBag or PKCS8ShroudedKeyBag
1253   // wrapped in an unencrypted ContentInfo. (One could also place it in a KeyBag
1254   // inside an encrypted ContentInfo, but OpenSSL does not do this and some
1255   // PKCS#12 consumers do not support KeyBags.)
1256   if (pkey != NULL) {
1257     CBB content_info, oid, wrapper, data, safe_contents, bag, bag_oid,
1258         bag_contents;
1259     if (// Add another data ContentInfo.
1260         !CBB_add_asn1(&content_infos, &content_info, CBS_ASN1_SEQUENCE) ||
1261         !CBB_add_asn1(&content_info, &oid, CBS_ASN1_OBJECT) ||
1262         !CBB_add_bytes(&oid, kPKCS7Data, sizeof(kPKCS7Data)) ||
1263         !CBB_add_asn1(&content_info, &wrapper,
1264                       CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) ||
1265         !CBB_add_asn1(&wrapper, &data, CBS_ASN1_OCTETSTRING) ||
1266         !CBB_add_asn1(&data, &safe_contents, CBS_ASN1_SEQUENCE) ||
1267         // Add a SafeBag containing a PKCS8ShroudedKeyBag.
1268         !CBB_add_asn1(&safe_contents, &bag, CBS_ASN1_SEQUENCE) ||
1269         !CBB_add_asn1(&bag, &bag_oid, CBS_ASN1_OBJECT)) {
1270       goto err;
1271     }
1272     if (key_nid < 0) {
1273       if (!CBB_add_bytes(&bag_oid, kKeyBag, sizeof(kKeyBag)) ||
1274           !CBB_add_asn1(&bag, &bag_contents,
1275                         CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) ||
1276           !EVP_marshal_private_key(&bag_contents, pkey)) {
1277         goto err;
1278       }
1279     } else {
1280       if (!CBB_add_bytes(&bag_oid, kPKCS8ShroudedKeyBag,
1281                          sizeof(kPKCS8ShroudedKeyBag)) ||
1282           !CBB_add_asn1(&bag, &bag_contents,
1283                         CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) ||
1284           !PKCS8_marshal_encrypted_private_key(
1285               &bag_contents, key_nid, NULL, password, password_len,
1286               NULL /* generate a random salt */,
1287               0 /* use default salt length */, iterations, pkey)) {
1288         goto err;
1289       }
1290     }
1291     size_t name_len = 0;
1292     if (name) {
1293       name_len = strlen(name);
1294     }
1295     if (!add_bag_attributes(&bag, name, name_len, key_id, key_id_len) ||
1296         !CBB_flush(&content_infos)) {
1297       goto err;
1298     }
1299   }
1300 
1301   // Compute the MAC. Match OpenSSL in using SHA-1 as the hash function. The MAC
1302   // covers |auth_safe_data|.
1303   const EVP_MD *mac_md = EVP_sha1();
1304   uint8_t mac_salt[PKCS5_SALT_LEN];
1305   uint8_t mac[EVP_MAX_MD_SIZE];
1306   unsigned mac_len;
1307   if (!CBB_flush(&auth_safe_data) ||
1308       !RAND_bytes(mac_salt, sizeof(mac_salt)) ||
1309       !pkcs12_key_gen(password, password_len, mac_salt, sizeof(mac_salt),
1310                       PKCS12_MAC_ID, mac_iterations, EVP_MD_size(mac_md),
1311                       mac_key, mac_md) ||
1312       !HMAC(mac_md, mac_key, EVP_MD_size(mac_md), CBB_data(&auth_safe_data),
1313             CBB_len(&auth_safe_data), mac, &mac_len)) {
1314     goto err;
1315   }
1316 
1317   CBB mac_data, digest_info, mac_cbb, mac_salt_cbb;
1318   if (!CBB_add_asn1(&pfx, &mac_data, CBS_ASN1_SEQUENCE) ||
1319       !CBB_add_asn1(&mac_data, &digest_info, CBS_ASN1_SEQUENCE) ||
1320       !EVP_marshal_digest_algorithm(&digest_info, mac_md) ||
1321       !CBB_add_asn1(&digest_info, &mac_cbb, CBS_ASN1_OCTETSTRING) ||
1322       !CBB_add_bytes(&mac_cbb, mac, mac_len) ||
1323       !CBB_add_asn1(&mac_data, &mac_salt_cbb, CBS_ASN1_OCTETSTRING) ||
1324       !CBB_add_bytes(&mac_salt_cbb, mac_salt, sizeof(mac_salt)) ||
1325       // The iteration count has a DEFAULT of 1, but RFC 7292 says "The default
1326       // is for historical reasons and its use is deprecated." Thus we
1327       // explicitly encode the iteration count, though it is not valid DER.
1328       !CBB_add_asn1_uint64(&mac_data, mac_iterations)) {
1329     goto err;
1330   }
1331 
1332   ret = OPENSSL_malloc(sizeof(PKCS12));
1333   if (ret == NULL ||
1334       !CBB_finish(&cbb, &ret->ber_bytes, &ret->ber_len)) {
1335     OPENSSL_free(ret);
1336     ret = NULL;
1337     goto err;
1338   }
1339 
1340 err:
1341   OPENSSL_cleanse(mac_key, sizeof(mac_key));
1342   CBB_cleanup(&cbb);
1343   return ret;
1344 }
1345 
PKCS12_free(PKCS12 * p12)1346 void PKCS12_free(PKCS12 *p12) {
1347   if (p12 == NULL) {
1348     return;
1349   }
1350   OPENSSL_free(p12->ber_bytes);
1351   OPENSSL_free(p12);
1352 }
1353