Debian Codegraph @

debian/rust-vendor/aws-lc-sys/aws-lc/crypto/pkcs8/pkcs8_x509.c

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