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