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