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

source code of dart_sdk/third_party/boringssl/src/crypto/pkcs8/pkcs8_x509.c