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