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