blob: c5a06519911f6db4c47c328107655ad637b9cddc [file] [log] [blame]
Robert Sloan6d0d00e2017-03-27 07:13:07 -07001/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
2 * project 1999.
3 */
4/* ====================================================================
5 * Copyright (c) 1999 The OpenSSL Project. All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 *
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
17 * distribution.
18 *
19 * 3. All advertising materials mentioning features or use of this
20 * software must display the following acknowledgment:
21 * "This product includes software developed by the OpenSSL Project
22 * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
23 *
24 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
25 * endorse or promote products derived from this software without
26 * prior written permission. For written permission, please contact
27 * licensing@OpenSSL.org.
28 *
29 * 5. Products derived from this software may not be called "OpenSSL"
30 * nor may "OpenSSL" appear in their names without prior written
31 * permission of the OpenSSL Project.
32 *
33 * 6. Redistributions of any form whatsoever must retain the following
34 * acknowledgment:
35 * "This product includes software developed by the OpenSSL Project
36 * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
37 *
38 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
39 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
40 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
41 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
42 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
43 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
44 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
45 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
46 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
47 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
48 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
49 * OF THE POSSIBILITY OF SUCH DAMAGE.
50 * ====================================================================
51 *
52 * This product includes cryptographic software written by Eric Young
53 * (eay@cryptsoft.com). This product includes software written by Tim
54 * Hudson (tjh@cryptsoft.com). */
55
56#include <openssl/pkcs8.h>
57
58#include <limits.h>
59
60#include <openssl/asn1t.h>
61#include <openssl/asn1.h>
62#include <openssl/bio.h>
63#include <openssl/buf.h>
64#include <openssl/bytestring.h>
65#include <openssl/err.h>
66#include <openssl/evp.h>
67#include <openssl/digest.h>
68#include <openssl/hmac.h>
69#include <openssl/mem.h>
Adam Vartanianbfcf3a72018-08-10 14:55:24 +010070#include <openssl/rand.h>
Robert Sloan6d0d00e2017-03-27 07:13:07 -070071#include <openssl/x509.h>
72
73#include "internal.h"
74#include "../bytestring/internal.h"
Robert Sloan6d0d00e2017-03-27 07:13:07 -070075#include "../internal.h"
76
77
Robert Sloan8f860b12017-08-28 07:37:06 -070078// Minor tweak to operation: zero private key data
Robert Sloan6d0d00e2017-03-27 07:13:07 -070079static int pkey_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
80 void *exarg) {
Robert Sloan8f860b12017-08-28 07:37:06 -070081 // Since the structure must still be valid use ASN1_OP_FREE_PRE
Robert Sloan6d0d00e2017-03-27 07:13:07 -070082 if (operation == ASN1_OP_FREE_PRE) {
83 PKCS8_PRIV_KEY_INFO *key = (PKCS8_PRIV_KEY_INFO *)*pval;
84 if (key->pkey && key->pkey->type == V_ASN1_OCTET_STRING &&
85 key->pkey->value.octet_string) {
86 OPENSSL_cleanse(key->pkey->value.octet_string->data,
87 key->pkey->value.octet_string->length);
88 }
89 }
90 return 1;
91}
92
93ASN1_SEQUENCE_cb(PKCS8_PRIV_KEY_INFO, pkey_cb) = {
94 ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, version, ASN1_INTEGER),
95 ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, pkeyalg, X509_ALGOR),
96 ASN1_SIMPLE(PKCS8_PRIV_KEY_INFO, pkey, ASN1_ANY),
97 ASN1_IMP_SET_OF_OPT(PKCS8_PRIV_KEY_INFO, attributes, X509_ATTRIBUTE, 0)
98} ASN1_SEQUENCE_END_cb(PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO)
99
100IMPLEMENT_ASN1_FUNCTIONS(PKCS8_PRIV_KEY_INFO)
101
102EVP_PKEY *EVP_PKCS82PKEY(PKCS8_PRIV_KEY_INFO *p8) {
103 uint8_t *der = NULL;
104 int der_len = i2d_PKCS8_PRIV_KEY_INFO(p8, &der);
105 if (der_len < 0) {
106 return NULL;
107 }
108
109 CBS cbs;
110 CBS_init(&cbs, der, (size_t)der_len);
111 EVP_PKEY *ret = EVP_parse_private_key(&cbs);
112 if (ret == NULL || CBS_len(&cbs) != 0) {
113 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
114 EVP_PKEY_free(ret);
115 OPENSSL_free(der);
116 return NULL;
117 }
118
119 OPENSSL_free(der);
120 return ret;
121}
122
123PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(EVP_PKEY *pkey) {
124 CBB cbb;
125 uint8_t *der = NULL;
126 size_t der_len;
127 if (!CBB_init(&cbb, 0) ||
128 !EVP_marshal_private_key(&cbb, pkey) ||
129 !CBB_finish(&cbb, &der, &der_len) ||
130 der_len > LONG_MAX) {
131 CBB_cleanup(&cbb);
132 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_ENCODE_ERROR);
133 goto err;
134 }
135
136 const uint8_t *p = der;
137 PKCS8_PRIV_KEY_INFO *p8 = d2i_PKCS8_PRIV_KEY_INFO(NULL, &p, (long)der_len);
138 if (p8 == NULL || p != der + der_len) {
139 PKCS8_PRIV_KEY_INFO_free(p8);
140 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
141 goto err;
142 }
143
144 OPENSSL_free(der);
145 return p8;
146
147err:
148 OPENSSL_free(der);
149 return NULL;
150}
151
152PKCS8_PRIV_KEY_INFO *PKCS8_decrypt(X509_SIG *pkcs8, const char *pass,
153 int pass_len_in) {
154 size_t pass_len;
155 if (pass_len_in == -1 && pass != NULL) {
156 pass_len = strlen(pass);
157 } else {
158 pass_len = (size_t)pass_len_in;
159 }
160
161 PKCS8_PRIV_KEY_INFO *ret = NULL;
162 EVP_PKEY *pkey = NULL;
163 uint8_t *in = NULL;
164
Robert Sloan8f860b12017-08-28 07:37:06 -0700165 // Convert the legacy ASN.1 object to a byte string.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700166 int in_len = i2d_X509_SIG(pkcs8, &in);
167 if (in_len < 0) {
168 goto err;
169 }
170
171 CBS cbs;
172 CBS_init(&cbs, in, in_len);
173 pkey = PKCS8_parse_encrypted_private_key(&cbs, pass, pass_len);
174 if (pkey == NULL || CBS_len(&cbs) != 0) {
175 goto err;
176 }
177
178 ret = EVP_PKEY2PKCS8(pkey);
179
180err:
181 OPENSSL_free(in);
182 EVP_PKEY_free(pkey);
183 return ret;
184}
185
186X509_SIG *PKCS8_encrypt(int pbe_nid, const EVP_CIPHER *cipher, const char *pass,
187 int pass_len_in, const uint8_t *salt, size_t salt_len,
188 int iterations, PKCS8_PRIV_KEY_INFO *p8inf) {
189 size_t pass_len;
190 if (pass_len_in == -1 && pass != NULL) {
191 pass_len = strlen(pass);
192 } else {
193 pass_len = (size_t)pass_len_in;
194 }
195
Robert Sloan8f860b12017-08-28 07:37:06 -0700196 // Parse out the private key.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700197 EVP_PKEY *pkey = EVP_PKCS82PKEY(p8inf);
198 if (pkey == NULL) {
199 return NULL;
200 }
201
202 X509_SIG *ret = NULL;
203 uint8_t *der = NULL;
204 size_t der_len;
205 CBB cbb;
206 if (!CBB_init(&cbb, 128) ||
207 !PKCS8_marshal_encrypted_private_key(&cbb, pbe_nid, cipher, pass,
208 pass_len, salt, salt_len, iterations,
209 pkey) ||
210 !CBB_finish(&cbb, &der, &der_len)) {
211 CBB_cleanup(&cbb);
212 goto err;
213 }
214
Robert Sloan8f860b12017-08-28 07:37:06 -0700215 // Convert back to legacy ASN.1 objects.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700216 const uint8_t *ptr = der;
217 ret = d2i_X509_SIG(NULL, &ptr, der_len);
218 if (ret == NULL || ptr != der + der_len) {
219 OPENSSL_PUT_ERROR(PKCS8, ERR_R_INTERNAL_ERROR);
220 X509_SIG_free(ret);
221 ret = NULL;
222 }
223
224err:
225 OPENSSL_free(der);
226 EVP_PKEY_free(pkey);
227 return ret;
228}
229
230struct pkcs12_context {
231 EVP_PKEY **out_key;
232 STACK_OF(X509) *out_certs;
233 const char *password;
234 size_t password_len;
235};
236
Robert Sloan8f860b12017-08-28 07:37:06 -0700237// PKCS12_handle_sequence parses a BER-encoded SEQUENCE of elements in a PKCS#12
238// structure.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700239static int PKCS12_handle_sequence(
240 CBS *sequence, struct pkcs12_context *ctx,
241 int (*handle_element)(CBS *cbs, struct pkcs12_context *ctx)) {
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100242 uint8_t *storage = NULL;
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700243 CBS in;
244 int ret = 0;
245
Robert Sloan8f860b12017-08-28 07:37:06 -0700246 // Although a BER->DER conversion is done at the beginning of |PKCS12_parse|,
247 // the ASN.1 data gets wrapped in OCTETSTRINGs and/or encrypted and the
248 // conversion cannot see through those wrappings. So each time we step
249 // through one we need to convert to DER again.
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100250 if (!CBS_asn1_ber_to_der(sequence, &in, &storage)) {
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700251 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
252 return 0;
253 }
254
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700255 CBS child;
256 if (!CBS_get_asn1(&in, &child, CBS_ASN1_SEQUENCE) ||
257 CBS_len(&in) != 0) {
258 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
259 goto err;
260 }
261
262 while (CBS_len(&child) > 0) {
263 CBS element;
264 if (!CBS_get_asn1(&child, &element, CBS_ASN1_SEQUENCE)) {
265 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
266 goto err;
267 }
268
269 if (!handle_element(&element, ctx)) {
270 goto err;
271 }
272 }
273
274 ret = 1;
275
276err:
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100277 OPENSSL_free(storage);
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700278 return ret;
279}
280
Robert Sloan8f860b12017-08-28 07:37:06 -0700281// 1.2.840.113549.1.12.10.1.2
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700282static const uint8_t kPKCS8ShroudedKeyBag[] = {
283 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x0a, 0x01, 0x02};
284
Robert Sloan8f860b12017-08-28 07:37:06 -0700285// 1.2.840.113549.1.12.10.1.3
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700286static const uint8_t kCertBag[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
287 0x01, 0x0c, 0x0a, 0x01, 0x03};
288
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100289// 1.2.840.113549.1.9.20
290static const uint8_t kFriendlyName[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
291 0x0d, 0x01, 0x09, 0x14};
292
293// 1.2.840.113549.1.9.21
294static const uint8_t kLocalKeyID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
295 0x0d, 0x01, 0x09, 0x15};
296
Robert Sloan8f860b12017-08-28 07:37:06 -0700297// 1.2.840.113549.1.9.22.1
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700298static const uint8_t kX509Certificate[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
299 0x0d, 0x01, 0x09, 0x16, 0x01};
300
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100301// parse_bag_attributes parses the bagAttributes field of a SafeBag structure.
302// It sets |*out_friendly_name| to a newly-allocated copy of the friendly name,
303// encoded as a UTF-8 string, or NULL if there is none. It returns one on
304// success and zero on error.
305static int parse_bag_attributes(CBS *attrs, uint8_t **out_friendly_name,
306 size_t *out_friendly_name_len) {
307 *out_friendly_name = NULL;
308 *out_friendly_name_len = 0;
309
310 // See https://tools.ietf.org/html/rfc7292#section-4.2.
311 while (CBS_len(attrs) != 0) {
312 CBS attr, oid, values;
313 if (!CBS_get_asn1(attrs, &attr, CBS_ASN1_SEQUENCE) ||
314 !CBS_get_asn1(&attr, &oid, CBS_ASN1_OBJECT) ||
315 !CBS_get_asn1(&attr, &values, CBS_ASN1_SET) ||
316 CBS_len(&attr) != 0) {
317 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
318 goto err;
319 }
320 if (CBS_mem_equal(&oid, kFriendlyName, sizeof(kFriendlyName))) {
321 // See https://tools.ietf.org/html/rfc2985, section 5.5.1.
322 CBS value;
323 if (*out_friendly_name != NULL ||
324 !CBS_get_asn1(&values, &value, CBS_ASN1_BMPSTRING) ||
325 CBS_len(&values) != 0 ||
326 CBS_len(&value) == 0) {
327 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
328 goto err;
329 }
330 // Convert the friendly name to UTF-8.
331 CBB cbb;
332 if (!CBB_init(&cbb, CBS_len(&value))) {
333 OPENSSL_PUT_ERROR(PKCS8, ERR_R_MALLOC_FAILURE);
334 goto err;
335 }
336 while (CBS_len(&value) != 0) {
337 uint32_t c;
338 if (!cbs_get_ucs2_be(&value, &c) ||
339 !cbb_add_utf8(&cbb, c)) {
340 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_INVALID_CHARACTERS);
341 CBB_cleanup(&cbb);
342 goto err;
343 }
344 }
345 if (!CBB_finish(&cbb, out_friendly_name, out_friendly_name_len)) {
346 OPENSSL_PUT_ERROR(PKCS8, ERR_R_MALLOC_FAILURE);
347 CBB_cleanup(&cbb);
348 goto err;
349 }
350 }
351 }
352
353 return 1;
354
355err:
356 OPENSSL_free(*out_friendly_name);
357 *out_friendly_name = NULL;
358 *out_friendly_name_len = 0;
359 return 0;
360}
361
Robert Sloan8f860b12017-08-28 07:37:06 -0700362// PKCS12_handle_safe_bag parses a single SafeBag element in a PKCS#12
363// structure.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700364static int PKCS12_handle_safe_bag(CBS *safe_bag, struct pkcs12_context *ctx) {
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100365 CBS bag_id, wrapped_value, bag_attrs;
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700366 if (!CBS_get_asn1(safe_bag, &bag_id, CBS_ASN1_OBJECT) ||
367 !CBS_get_asn1(safe_bag, &wrapped_value,
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100368 CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0)) {
369 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
370 return 0;
371 }
372 if (CBS_len(safe_bag) == 0) {
373 CBS_init(&bag_attrs, NULL, 0);
374 } else if (!CBS_get_asn1(safe_bag, &bag_attrs, CBS_ASN1_SET) ||
375 CBS_len(safe_bag) != 0) {
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700376 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
377 return 0;
378 }
379
380 if (CBS_mem_equal(&bag_id, kPKCS8ShroudedKeyBag,
381 sizeof(kPKCS8ShroudedKeyBag))) {
Robert Sloan8f860b12017-08-28 07:37:06 -0700382 // See RFC 7292, section 4.2.2.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700383 if (*ctx->out_key) {
384 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_MULTIPLE_PRIVATE_KEYS_IN_PKCS12);
385 return 0;
386 }
387
388 EVP_PKEY *pkey = PKCS8_parse_encrypted_private_key(
389 &wrapped_value, ctx->password, ctx->password_len);
390 if (pkey == NULL) {
391 return 0;
392 }
393
394 if (CBS_len(&wrapped_value) != 0) {
395 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
396 EVP_PKEY_free(pkey);
397 return 0;
398 }
399
400 *ctx->out_key = pkey;
401 return 1;
402 }
403
404 if (CBS_mem_equal(&bag_id, kCertBag, sizeof(kCertBag))) {
Robert Sloan8f860b12017-08-28 07:37:06 -0700405 // See RFC 7292, section 4.2.3.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700406 CBS cert_bag, cert_type, wrapped_cert, cert;
407 if (!CBS_get_asn1(&wrapped_value, &cert_bag, CBS_ASN1_SEQUENCE) ||
408 !CBS_get_asn1(&cert_bag, &cert_type, CBS_ASN1_OBJECT) ||
409 !CBS_get_asn1(&cert_bag, &wrapped_cert,
410 CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
411 !CBS_get_asn1(&wrapped_cert, &cert, CBS_ASN1_OCTETSTRING)) {
412 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
413 return 0;
414 }
415
Robert Sloan8f860b12017-08-28 07:37:06 -0700416 // Skip unknown certificate types.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700417 if (!CBS_mem_equal(&cert_type, kX509Certificate,
418 sizeof(kX509Certificate))) {
419 return 1;
420 }
421
422 if (CBS_len(&cert) > LONG_MAX) {
423 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
424 return 0;
425 }
426
427 const uint8_t *inp = CBS_data(&cert);
428 X509 *x509 = d2i_X509(NULL, &inp, (long)CBS_len(&cert));
429 if (!x509) {
430 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
431 return 0;
432 }
433
434 if (inp != CBS_data(&cert) + CBS_len(&cert)) {
435 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
436 X509_free(x509);
437 return 0;
438 }
439
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100440 uint8_t *friendly_name;
441 size_t friendly_name_len;
442 if (!parse_bag_attributes(&bag_attrs, &friendly_name, &friendly_name_len)) {
443 X509_free(x509);
444 return 0;
445 }
446 int ok = friendly_name_len == 0 ||
447 X509_alias_set1(x509, friendly_name, friendly_name_len);
448 OPENSSL_free(friendly_name);
449 if (!ok ||
450 0 == sk_X509_push(ctx->out_certs, x509)) {
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700451 X509_free(x509);
452 return 0;
453 }
454
455 return 1;
456 }
457
Robert Sloan8f860b12017-08-28 07:37:06 -0700458 // Unknown element type - ignore it.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700459 return 1;
460}
461
Robert Sloan8f860b12017-08-28 07:37:06 -0700462// 1.2.840.113549.1.7.1
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700463static const uint8_t kPKCS7Data[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
464 0x0d, 0x01, 0x07, 0x01};
465
Robert Sloan8f860b12017-08-28 07:37:06 -0700466// 1.2.840.113549.1.7.6
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700467static const uint8_t kPKCS7EncryptedData[] = {0x2a, 0x86, 0x48, 0x86, 0xf7,
468 0x0d, 0x01, 0x07, 0x06};
469
Robert Sloan8f860b12017-08-28 07:37:06 -0700470// PKCS12_handle_content_info parses a single PKCS#7 ContentInfo element in a
471// PKCS#12 structure.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700472static int PKCS12_handle_content_info(CBS *content_info,
473 struct pkcs12_context *ctx) {
474 CBS content_type, wrapped_contents, contents;
475 int ret = 0;
476 uint8_t *storage = NULL;
477
478 if (!CBS_get_asn1(content_info, &content_type, CBS_ASN1_OBJECT) ||
479 !CBS_get_asn1(content_info, &wrapped_contents,
480 CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
481 CBS_len(content_info) != 0) {
482 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
483 goto err;
484 }
485
486 if (CBS_mem_equal(&content_type, kPKCS7EncryptedData,
487 sizeof(kPKCS7EncryptedData))) {
Robert Sloan8f860b12017-08-28 07:37:06 -0700488 // See https://tools.ietf.org/html/rfc2315#section-13.
489 //
490 // PKCS#7 encrypted data inside a PKCS#12 structure is generally an
491 // encrypted certificate bag and it's generally encrypted with 40-bit
492 // RC2-CBC.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700493 CBS version_bytes, eci, contents_type, ai, encrypted_contents;
494 uint8_t *out;
495 size_t out_len;
496
497 if (!CBS_get_asn1(&wrapped_contents, &contents, CBS_ASN1_SEQUENCE) ||
498 !CBS_get_asn1(&contents, &version_bytes, CBS_ASN1_INTEGER) ||
Robert Sloan8f860b12017-08-28 07:37:06 -0700499 // EncryptedContentInfo, see
500 // https://tools.ietf.org/html/rfc2315#section-10.1
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700501 !CBS_get_asn1(&contents, &eci, CBS_ASN1_SEQUENCE) ||
502 !CBS_get_asn1(&eci, &contents_type, CBS_ASN1_OBJECT) ||
Robert Sloan8f860b12017-08-28 07:37:06 -0700503 // AlgorithmIdentifier, see
504 // https://tools.ietf.org/html/rfc5280#section-4.1.1.2
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700505 !CBS_get_asn1(&eci, &ai, CBS_ASN1_SEQUENCE) ||
506 !CBS_get_asn1_implicit_string(
507 &eci, &encrypted_contents, &storage,
508 CBS_ASN1_CONTEXT_SPECIFIC | 0, CBS_ASN1_OCTETSTRING)) {
509 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
510 goto err;
511 }
512
513 if (!CBS_mem_equal(&contents_type, kPKCS7Data, sizeof(kPKCS7Data))) {
514 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
515 goto err;
516 }
517
518 if (!pkcs8_pbe_decrypt(&out, &out_len, &ai, ctx->password,
519 ctx->password_len, CBS_data(&encrypted_contents),
520 CBS_len(&encrypted_contents))) {
521 goto err;
522 }
523
524 CBS safe_contents;
525 CBS_init(&safe_contents, out, out_len);
526 ret = PKCS12_handle_sequence(&safe_contents, ctx, PKCS12_handle_safe_bag);
527 OPENSSL_free(out);
528 } else if (CBS_mem_equal(&content_type, kPKCS7Data, sizeof(kPKCS7Data))) {
529 CBS octet_string_contents;
530
531 if (!CBS_get_asn1(&wrapped_contents, &octet_string_contents,
532 CBS_ASN1_OCTETSTRING)) {
533 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
534 goto err;
535 }
536
537 ret = PKCS12_handle_sequence(&octet_string_contents, ctx,
538 PKCS12_handle_safe_bag);
539 } else {
Robert Sloan8f860b12017-08-28 07:37:06 -0700540 // Unknown element type - ignore it.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700541 ret = 1;
542 }
543
544err:
545 OPENSSL_free(storage);
546 return ret;
547}
548
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100549static int pkcs12_check_mac(int *out_mac_ok, const char *password,
550 size_t password_len, const CBS *salt,
551 unsigned iterations, const EVP_MD *md,
552 const CBS *authsafes, const CBS *expected_mac) {
553 int ret = 0;
554 uint8_t hmac_key[EVP_MAX_MD_SIZE];
555 if (!pkcs12_key_gen(password, password_len, CBS_data(salt), CBS_len(salt),
556 PKCS12_MAC_ID, iterations, EVP_MD_size(md), hmac_key,
557 md)) {
558 goto err;
559 }
560
561 uint8_t hmac[EVP_MAX_MD_SIZE];
562 unsigned hmac_len;
563 if (NULL == HMAC(md, hmac_key, EVP_MD_size(md), CBS_data(authsafes),
564 CBS_len(authsafes), hmac, &hmac_len)) {
565 goto err;
566 }
567
568 *out_mac_ok = CBS_mem_equal(expected_mac, hmac, hmac_len);
569#if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
570 *out_mac_ok = 1;
571#endif
572 ret = 1;
573
574err:
575 OPENSSL_cleanse(hmac_key, sizeof(hmac_key));
576 return ret;
577}
578
579
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700580int PKCS12_get_key_and_certs(EVP_PKEY **out_key, STACK_OF(X509) *out_certs,
581 CBS *ber_in, const char *password) {
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100582 uint8_t *storage = NULL;
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700583 CBS in, pfx, mac_data, authsafe, content_type, wrapped_authsafes, authsafes;
584 uint64_t version;
585 int ret = 0;
586 struct pkcs12_context ctx;
587 const size_t original_out_certs_len = sk_X509_num(out_certs);
588
Robert Sloan8f860b12017-08-28 07:37:06 -0700589 // The input may be in BER format.
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100590 if (!CBS_asn1_ber_to_der(ber_in, &in, &storage)) {
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700591 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
592 return 0;
593 }
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700594
595 *out_key = NULL;
596 OPENSSL_memset(&ctx, 0, sizeof(ctx));
597
Robert Sloan8f860b12017-08-28 07:37:06 -0700598 // See ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12v1.pdf, section
599 // four.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700600 if (!CBS_get_asn1(&in, &pfx, CBS_ASN1_SEQUENCE) ||
601 CBS_len(&in) != 0 ||
602 !CBS_get_asn1_uint64(&pfx, &version)) {
603 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
604 goto err;
605 }
606
607 if (version < 3) {
608 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_VERSION);
609 goto err;
610 }
611
612 if (!CBS_get_asn1(&pfx, &authsafe, CBS_ASN1_SEQUENCE)) {
613 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
614 goto err;
615 }
616
617 if (CBS_len(&pfx) == 0) {
618 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_MISSING_MAC);
619 goto err;
620 }
621
622 if (!CBS_get_asn1(&pfx, &mac_data, CBS_ASN1_SEQUENCE)) {
623 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
624 goto err;
625 }
626
Robert Sloan8f860b12017-08-28 07:37:06 -0700627 // authsafe is a PKCS#7 ContentInfo. See
628 // https://tools.ietf.org/html/rfc2315#section-7.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700629 if (!CBS_get_asn1(&authsafe, &content_type, CBS_ASN1_OBJECT) ||
630 !CBS_get_asn1(&authsafe, &wrapped_authsafes,
631 CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0)) {
632 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
633 goto err;
634 }
635
Robert Sloan8f860b12017-08-28 07:37:06 -0700636 // The content type can either be data or signedData. The latter indicates
637 // that it's signed by a public key, which isn't supported.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700638 if (!CBS_mem_equal(&content_type, kPKCS7Data, sizeof(kPKCS7Data))) {
639 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_PKCS12_PUBLIC_KEY_INTEGRITY_NOT_SUPPORTED);
640 goto err;
641 }
642
643 if (!CBS_get_asn1(&wrapped_authsafes, &authsafes, CBS_ASN1_OCTETSTRING)) {
644 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
645 goto err;
646 }
647
648 ctx.out_key = out_key;
649 ctx.out_certs = out_certs;
650 ctx.password = password;
651 ctx.password_len = password != NULL ? strlen(password) : 0;
652
Robert Sloan8f860b12017-08-28 07:37:06 -0700653 // Verify the MAC.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700654 {
655 CBS mac, salt, expected_mac;
656 if (!CBS_get_asn1(&mac_data, &mac, CBS_ASN1_SEQUENCE)) {
657 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
658 goto err;
659 }
660
661 const EVP_MD *md = EVP_parse_digest_algorithm(&mac);
662 if (md == NULL) {
663 goto err;
664 }
665
666 if (!CBS_get_asn1(&mac, &expected_mac, CBS_ASN1_OCTETSTRING) ||
667 !CBS_get_asn1(&mac_data, &salt, CBS_ASN1_OCTETSTRING)) {
668 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
669 goto err;
670 }
671
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100672#if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
673 static const uint64_t kIterationsLimit = 2048;
674#else
675 // Windows imposes a limit of 600K. Mozilla say: “so them increasing
676 // maximum to something like 100M or 1G (to have few decades of breathing
677 // room) would be very welcome”[1]. So here we set the limit to 100M.
678 //
679 // [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1436873#c14
680 static const uint64_t kIterationsLimit = 100 * 1000000;
681#endif
682
Robert Sloan8f860b12017-08-28 07:37:06 -0700683 // The iteration count is optional and the default is one.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700684 uint64_t iterations = 1;
685 if (CBS_len(&mac_data) > 0) {
686 if (!CBS_get_asn1_uint64(&mac_data, &iterations) ||
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100687 iterations > kIterationsLimit) {
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700688 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
689 goto err;
690 }
691 }
692
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100693 int mac_ok;
694 if (!pkcs12_check_mac(&mac_ok, ctx.password, ctx.password_len, &salt,
695 iterations, md, &authsafes, &expected_mac)) {
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700696 goto err;
697 }
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100698 if (!mac_ok && ctx.password_len == 0) {
699 // PKCS#12 encodes passwords as NUL-terminated UCS-2, so the empty
700 // password is encoded as {0, 0}. Some implementations use the empty byte
701 // array for "no password". OpenSSL considers a non-NULL password as {0,
702 // 0} and a NULL password as {}. It then, in high-level PKCS#12 parsing
703 // code, tries both options. We match this behavior.
704 ctx.password = ctx.password != NULL ? NULL : "";
705 if (!pkcs12_check_mac(&mac_ok, ctx.password, ctx.password_len, &salt,
706 iterations, md, &authsafes, &expected_mac)) {
707 goto err;
708 }
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700709 }
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100710 if (!mac_ok) {
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700711 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_INCORRECT_PASSWORD);
712 goto err;
713 }
714 }
715
Robert Sloan8f860b12017-08-28 07:37:06 -0700716 // authsafes contains a series of PKCS#7 ContentInfos.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700717 if (!PKCS12_handle_sequence(&authsafes, &ctx, PKCS12_handle_content_info)) {
718 goto err;
719 }
720
721 ret = 1;
722
723err:
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100724 OPENSSL_free(storage);
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700725 if (!ret) {
726 EVP_PKEY_free(*out_key);
727 *out_key = NULL;
728 while (sk_X509_num(out_certs) > original_out_certs_len) {
729 X509 *x509 = sk_X509_pop(out_certs);
730 X509_free(x509);
731 }
732 }
733
734 return ret;
735}
736
737void PKCS12_PBE_add(void) {}
738
739struct pkcs12_st {
740 uint8_t *ber_bytes;
741 size_t ber_len;
742};
743
744PKCS12 *d2i_PKCS12(PKCS12 **out_p12, const uint8_t **ber_bytes,
745 size_t ber_len) {
746 PKCS12 *p12;
747
748 p12 = OPENSSL_malloc(sizeof(PKCS12));
749 if (!p12) {
750 return NULL;
751 }
752
753 p12->ber_bytes = OPENSSL_malloc(ber_len);
754 if (!p12->ber_bytes) {
755 OPENSSL_free(p12);
756 return NULL;
757 }
758
759 OPENSSL_memcpy(p12->ber_bytes, *ber_bytes, ber_len);
760 p12->ber_len = ber_len;
761 *ber_bytes += ber_len;
762
763 if (out_p12) {
764 PKCS12_free(*out_p12);
765
766 *out_p12 = p12;
767 }
768
769 return p12;
770}
771
772PKCS12* d2i_PKCS12_bio(BIO *bio, PKCS12 **out_p12) {
773 size_t used = 0;
774 BUF_MEM *buf;
775 const uint8_t *dummy;
776 static const size_t kMaxSize = 256 * 1024;
777 PKCS12 *ret = NULL;
778
779 buf = BUF_MEM_new();
780 if (buf == NULL) {
781 return NULL;
782 }
783 if (BUF_MEM_grow(buf, 8192) == 0) {
784 goto out;
785 }
786
787 for (;;) {
788 int n = BIO_read(bio, &buf->data[used], buf->length - used);
789 if (n < 0) {
790 if (used == 0) {
791 goto out;
792 }
Robert Sloan8f860b12017-08-28 07:37:06 -0700793 // Workaround a bug in node.js. It uses a memory BIO for this in the wrong
794 // mode.
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700795 n = 0;
796 }
797
798 if (n == 0) {
799 break;
800 }
801 used += n;
802
803 if (used < buf->length) {
804 continue;
805 }
806
807 if (buf->length > kMaxSize ||
808 BUF_MEM_grow(buf, buf->length * 2) == 0) {
809 goto out;
810 }
811 }
812
813 dummy = (uint8_t*) buf->data;
814 ret = d2i_PKCS12(out_p12, &dummy, used);
815
816out:
817 BUF_MEM_free(buf);
818 return ret;
819}
820
821PKCS12* d2i_PKCS12_fp(FILE *fp, PKCS12 **out_p12) {
822 BIO *bio;
823 PKCS12 *ret;
824
825 bio = BIO_new_fp(fp, 0 /* don't take ownership */);
826 if (!bio) {
827 return NULL;
828 }
829
830 ret = d2i_PKCS12_bio(bio, out_p12);
831 BIO_free(bio);
832 return ret;
833}
834
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100835int i2d_PKCS12(const PKCS12 *p12, uint8_t **out) {
836 if (p12->ber_len > INT_MAX) {
837 OPENSSL_PUT_ERROR(PKCS8, ERR_R_OVERFLOW);
838 return -1;
839 }
840
841 if (out == NULL) {
842 return (int)p12->ber_len;
843 }
844
845 if (*out == NULL) {
846 *out = OPENSSL_malloc(p12->ber_len);
847 if (*out == NULL) {
848 OPENSSL_PUT_ERROR(PKCS8, ERR_R_MALLOC_FAILURE);
849 return -1;
850 }
851 OPENSSL_memcpy(*out, p12->ber_bytes, p12->ber_len);
852 } else {
853 OPENSSL_memcpy(*out, p12->ber_bytes, p12->ber_len);
854 *out += p12->ber_len;
855 }
856 return (int)p12->ber_len;
857}
858
859int i2d_PKCS12_bio(BIO *bio, const PKCS12 *p12) {
860 size_t written = 0;
861 while (written < p12->ber_len) {
862 size_t todo = p12->ber_len - written;
863 int len = todo > INT_MAX ? INT_MAX : (int)todo;
864 int ret = BIO_write(bio, p12->ber_bytes + written, len);
865 if (ret <= 0) {
866 return 0;
867 }
868 written += (size_t)ret;
869 }
870 return 1;
871}
872
873int i2d_PKCS12_fp(FILE *fp, const PKCS12 *p12) {
874 BIO *bio = BIO_new_fp(fp, 0 /* don't take ownership */);
875 if (bio == NULL) {
876 return 0;
877 }
878
879 int ret = i2d_PKCS12_bio(bio, p12);
880 BIO_free(bio);
881 return ret;
882}
883
Robert Sloan6d0d00e2017-03-27 07:13:07 -0700884int PKCS12_parse(const PKCS12 *p12, const char *password, EVP_PKEY **out_pkey,
885 X509 **out_cert, STACK_OF(X509) **out_ca_certs) {
886 CBS ber_bytes;
887 STACK_OF(X509) *ca_certs = NULL;
888 char ca_certs_alloced = 0;
889
890 if (out_ca_certs != NULL && *out_ca_certs != NULL) {
891 ca_certs = *out_ca_certs;
892 }
893
894 if (!ca_certs) {
895 ca_certs = sk_X509_new_null();
896 if (ca_certs == NULL) {
897 OPENSSL_PUT_ERROR(PKCS8, ERR_R_MALLOC_FAILURE);
898 return 0;
899 }
900 ca_certs_alloced = 1;
901 }
902
903 CBS_init(&ber_bytes, p12->ber_bytes, p12->ber_len);
904 if (!PKCS12_get_key_and_certs(out_pkey, ca_certs, &ber_bytes, password)) {
905 if (ca_certs_alloced) {
906 sk_X509_free(ca_certs);
907 }
908 return 0;
909 }
910
911 *out_cert = NULL;
912 if (sk_X509_num(ca_certs) > 0) {
913 *out_cert = sk_X509_shift(ca_certs);
914 }
915
916 if (out_ca_certs) {
917 *out_ca_certs = ca_certs;
918 } else {
919 sk_X509_pop_free(ca_certs, X509_free);
920 }
921
922 return 1;
923}
924
925int PKCS12_verify_mac(const PKCS12 *p12, const char *password,
926 int password_len) {
927 if (password == NULL) {
928 if (password_len != 0) {
929 return 0;
930 }
931 } else if (password_len != -1 &&
932 (password[password_len] != 0 ||
933 OPENSSL_memchr(password, 0, password_len) != NULL)) {
934 return 0;
935 }
936
937 EVP_PKEY *pkey = NULL;
938 X509 *cert = NULL;
939 if (!PKCS12_parse(p12, password, &pkey, &cert, NULL)) {
940 ERR_clear_error();
941 return 0;
942 }
943
944 EVP_PKEY_free(pkey);
945 X509_free(cert);
946
947 return 1;
948}
949
Adam Vartanianbfcf3a72018-08-10 14:55:24 +0100950// add_bag_attributes adds the bagAttributes field of a SafeBag structure,
951// containing the specified friendlyName and localKeyId attributes.
952static int add_bag_attributes(CBB *bag, const char *name, const uint8_t *key_id,
953 size_t key_id_len) {
954 if (name == NULL && key_id_len == 0) {
955 return 1; // Omit the OPTIONAL SET.
956 }
957 // See https://tools.ietf.org/html/rfc7292#section-4.2.
958 CBB attrs, attr, oid, values, value;
959 if (!CBB_add_asn1(bag, &attrs, CBS_ASN1_SET)) {
960 return 0;
961 }
962 if (name != NULL) {
963 // See https://tools.ietf.org/html/rfc2985, section 5.5.1.
964 if (!CBB_add_asn1(&attrs, &attr, CBS_ASN1_SEQUENCE) ||
965 !CBB_add_asn1(&attr, &oid, CBS_ASN1_OBJECT) ||
966 !CBB_add_bytes(&oid, kFriendlyName, sizeof(kFriendlyName)) ||
967 !CBB_add_asn1(&attr, &values, CBS_ASN1_SET) ||
968 !CBB_add_asn1(&values, &value, CBS_ASN1_BMPSTRING)) {
969 return 0;
970 }
971 // Convert the friendly name to a BMPString.
972 CBS name_cbs;
973 CBS_init(&name_cbs, (const uint8_t *)name, strlen(name));
974 while (CBS_len(&name_cbs) != 0) {
975 uint32_t c;
976 if (!cbs_get_utf8(&name_cbs, &c) ||
977 !cbb_add_ucs2_be(&value, c)) {
978 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_INVALID_CHARACTERS);
979 return 0;
980 }
981 }
982 }
983 if (key_id_len != 0) {
984 // See https://tools.ietf.org/html/rfc2985, section 5.5.2.
985 if (!CBB_add_asn1(&attrs, &attr, CBS_ASN1_SEQUENCE) ||
986 !CBB_add_asn1(&attr, &oid, CBS_ASN1_OBJECT) ||
987 !CBB_add_bytes(&oid, kLocalKeyID, sizeof(kLocalKeyID)) ||
988 !CBB_add_asn1(&attr, &values, CBS_ASN1_SET) ||
989 !CBB_add_asn1(&values, &value, CBS_ASN1_OCTETSTRING) ||
990 !CBB_add_bytes(&value, key_id, key_id_len)) {
991 return 0;
992 }
993 }
994 return CBB_flush_asn1_set_of(&attrs) &&
995 CBB_flush(bag);
996}
997
998static int add_cert_bag(CBB *cbb, X509 *cert, const char *name,
999 const uint8_t *key_id, size_t key_id_len) {
1000 CBB bag, bag_oid, bag_contents, cert_bag, cert_type, wrapped_cert, cert_value;
1001 if (// See https://tools.ietf.org/html/rfc7292#section-4.2.
1002 !CBB_add_asn1(cbb, &bag, CBS_ASN1_SEQUENCE) ||
1003 !CBB_add_asn1(&bag, &bag_oid, CBS_ASN1_OBJECT) ||
1004 !CBB_add_bytes(&bag_oid, kCertBag, sizeof(kCertBag)) ||
1005 !CBB_add_asn1(&bag, &bag_contents,
1006 CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) ||
1007 // See https://tools.ietf.org/html/rfc7292#section-4.2.3.
1008 !CBB_add_asn1(&bag_contents, &cert_bag, CBS_ASN1_SEQUENCE) ||
1009 !CBB_add_asn1(&cert_bag, &cert_type, CBS_ASN1_OBJECT) ||
1010 !CBB_add_bytes(&cert_type, kX509Certificate, sizeof(kX509Certificate)) ||
1011 !CBB_add_asn1(&cert_bag, &wrapped_cert,
1012 CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) ||
1013 !CBB_add_asn1(&wrapped_cert, &cert_value, CBS_ASN1_OCTETSTRING)) {
1014 return 0;
1015 }
1016 uint8_t *buf;
1017 int len = i2d_X509(cert, NULL);
1018 if (len < 0 ||
1019 !CBB_add_space(&cert_value, &buf, (size_t)len) ||
1020 i2d_X509(cert, &buf) < 0 ||
1021 !add_bag_attributes(&bag, name, key_id, key_id_len) ||
1022 !CBB_flush(cbb)) {
1023 return 0;
1024 }
1025 return 1;
1026}
1027
1028static int make_cert_safe_contents(uint8_t **out_data, size_t *out_len,
1029 X509 *cert, const STACK_OF(X509) *chain,
1030 const char *name, const uint8_t *key_id,
1031 size_t key_id_len) {
1032 int ret = 0;
1033 CBB cbb, safe_contents;
1034 if (!CBB_init(&cbb, 0) ||
1035 !CBB_add_asn1(&cbb, &safe_contents, CBS_ASN1_SEQUENCE) ||
1036 (cert != NULL &&
1037 !add_cert_bag(&safe_contents, cert, name, key_id, key_id_len))) {
1038 goto err;
1039 }
1040
1041 for (size_t i = 0; i < sk_X509_num(chain); i++) {
1042 // Only the leaf certificate gets attributes.
1043 if (!add_cert_bag(&safe_contents, sk_X509_value(chain, i), NULL, NULL, 0)) {
1044 goto err;
1045 }
1046 }
1047
1048 ret = CBB_finish(&cbb, out_data, out_len);
1049
1050err:
1051 CBB_cleanup(&cbb);
1052 return ret;
1053}
1054
1055static int add_encrypted_data(CBB *out, int pbe_nid, const char *password,
1056 size_t password_len, unsigned iterations,
1057 const uint8_t *in, size_t in_len) {
1058 uint8_t salt[PKCS5_SALT_LEN];
1059 if (!RAND_bytes(salt, sizeof(salt))) {
1060 return 0;
1061 }
1062
1063 int ret = 0;
1064 EVP_CIPHER_CTX ctx;
1065 EVP_CIPHER_CTX_init(&ctx);
1066 CBB content_info, type, wrapper, encrypted_data, encrypted_content_info,
1067 inner_type, encrypted_content;
1068 if (// Add the ContentInfo wrapping.
1069 !CBB_add_asn1(out, &content_info, CBS_ASN1_SEQUENCE) ||
1070 !CBB_add_asn1(&content_info, &type, CBS_ASN1_OBJECT) ||
1071 !CBB_add_bytes(&type, kPKCS7EncryptedData, sizeof(kPKCS7EncryptedData)) ||
1072 !CBB_add_asn1(&content_info, &wrapper,
1073 CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) ||
1074 // See https://tools.ietf.org/html/rfc2315#section-13.
1075 !CBB_add_asn1(&wrapper, &encrypted_data, CBS_ASN1_SEQUENCE) ||
1076 !CBB_add_asn1_uint64(&encrypted_data, 0 /* version */) ||
1077 // See https://tools.ietf.org/html/rfc2315#section-10.1.
1078 !CBB_add_asn1(&encrypted_data, &encrypted_content_info,
1079 CBS_ASN1_SEQUENCE) ||
1080 !CBB_add_asn1(&encrypted_content_info, &inner_type, CBS_ASN1_OBJECT) ||
1081 !CBB_add_bytes(&inner_type, kPKCS7Data, sizeof(kPKCS7Data)) ||
1082 // Set up encryption and fill in contentEncryptionAlgorithm.
1083 !pkcs12_pbe_encrypt_init(&encrypted_content_info, &ctx, pbe_nid,
1084 iterations, password, password_len, salt,
1085 sizeof(salt)) ||
1086 // Note this tag is primitive. It is an implicitly-tagged OCTET_STRING, so
1087 // it inherits the inner tag's constructed bit.
1088 !CBB_add_asn1(&encrypted_content_info, &encrypted_content,
1089 CBS_ASN1_CONTEXT_SPECIFIC | 0)) {
1090 goto err;
1091 }
1092
1093 size_t max_out = in_len + EVP_CIPHER_CTX_block_size(&ctx);
1094 if (max_out < in_len) {
1095 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_TOO_LONG);
1096 goto err;
1097 }
1098
1099 uint8_t *ptr;
1100 int n1, n2;
1101 if (!CBB_reserve(&encrypted_content, &ptr, max_out) ||
1102 !EVP_CipherUpdate(&ctx, ptr, &n1, in, in_len) ||
1103 !EVP_CipherFinal_ex(&ctx, ptr + n1, &n2) ||
1104 !CBB_did_write(&encrypted_content, n1 + n2) ||
1105 !CBB_flush(out)) {
1106 goto err;
1107 }
1108
1109 ret = 1;
1110
1111err:
1112 EVP_CIPHER_CTX_cleanup(&ctx);
1113 return ret;
1114}
1115
1116PKCS12 *PKCS12_create(const char *password, const char *name,
1117 const EVP_PKEY *pkey, X509 *cert,
1118 const STACK_OF(X509)* chain, int key_nid, int cert_nid,
1119 int iterations, int mac_iterations, int key_type) {
1120 if (key_nid == 0) {
1121 key_nid = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
1122 }
1123 if (cert_nid == 0) {
1124 cert_nid = NID_pbe_WithSHA1And40BitRC2_CBC;
1125 }
1126 if (iterations == 0) {
1127 iterations = PKCS5_DEFAULT_ITERATIONS;
1128 }
1129 if (mac_iterations == 0) {
1130 mac_iterations = 1;
1131 }
1132 if (// In OpenSSL, this specifies a non-standard Microsoft key usage extension
1133 // which we do not currently support.
1134 key_type != 0 ||
1135 // In OpenSSL, -1 here means to use no encryption, which we do not
1136 // currently support.
1137 key_nid < 0 || cert_nid < 0 ||
1138 // In OpenSSL, -1 here means to omit the MAC, which we do not
1139 // currently support. Omitting it is also invalid for a password-based
1140 // PKCS#12 file.
1141 mac_iterations < 0 ||
1142 // Don't encode empty objects.
1143 (pkey == NULL && cert == NULL && sk_X509_num(chain) == 0)) {
1144 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNSUPPORTED_OPTIONS);
1145 return 0;
1146 }
1147
1148 // Note that |password| may be NULL to specify no password, rather than the
1149 // empty string. They are encoded differently in PKCS#12. (One is the empty
1150 // byte array and the other is NUL-terminated UCS-2.)
1151 size_t password_len = password != NULL ? strlen(password) : 0;
1152
1153 uint8_t key_id[EVP_MAX_MD_SIZE];
1154 unsigned key_id_len = 0;
1155 if (cert != NULL && pkey != NULL) {
1156 if (!X509_check_private_key(cert, pkey) ||
1157 // Matching OpenSSL, use the SHA-1 hash of the certificate as the local
1158 // key ID. Some PKCS#12 consumers require one to connect the private key
1159 // and certificate.
1160 !X509_digest(cert, EVP_sha1(), key_id, &key_id_len)) {
1161 return 0;
1162 }
1163 }
1164
1165 // See https://tools.ietf.org/html/rfc7292#section-4.
1166 PKCS12 *ret = NULL;
1167 CBB cbb, pfx, auth_safe, auth_safe_oid, auth_safe_wrapper, auth_safe_data,
1168 content_infos;
1169 uint8_t mac_key[EVP_MAX_MD_SIZE];
1170 if (!CBB_init(&cbb, 0) ||
1171 !CBB_add_asn1(&cbb, &pfx, CBS_ASN1_SEQUENCE) ||
1172 !CBB_add_asn1_uint64(&pfx, 3) ||
1173 // auth_safe is a data ContentInfo.
1174 !CBB_add_asn1(&pfx, &auth_safe, CBS_ASN1_SEQUENCE) ||
1175 !CBB_add_asn1(&auth_safe, &auth_safe_oid, CBS_ASN1_OBJECT) ||
1176 !CBB_add_bytes(&auth_safe_oid, kPKCS7Data, sizeof(kPKCS7Data)) ||
1177 !CBB_add_asn1(&auth_safe, &auth_safe_wrapper,
1178 CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) ||
1179 !CBB_add_asn1(&auth_safe_wrapper, &auth_safe_data,
1180 CBS_ASN1_OCTETSTRING) ||
1181 // See https://tools.ietf.org/html/rfc7292#section-4.1. |auth_safe|'s
1182 // contains a SEQUENCE of ContentInfos.
1183 !CBB_add_asn1(&auth_safe_data, &content_infos, CBS_ASN1_SEQUENCE)) {
1184 goto err;
1185 }
1186
1187 // If there are any certificates, place them in CertBags wrapped in a single
1188 // encrypted ContentInfo.
1189 if (cert != NULL || sk_X509_num(chain) > 0) {
1190 uint8_t *data;
1191 size_t len;
1192 if (!make_cert_safe_contents(&data, &len, cert, chain, name, key_id,
1193 key_id_len)) {
1194 goto err;
1195 }
1196 int ok = add_encrypted_data(&content_infos, cert_nid, password,
1197 password_len, iterations, data, len);
1198 OPENSSL_free(data);
1199 if (!ok) {
1200 goto err;
1201 }
1202 }
1203
1204 // If there is a key, place it in a single PKCS8ShroudedKeyBag wrapped in an
1205 // unencrypted ContentInfo. (One could also place it in a KeyBag inside an
1206 // encrypted ContentInfo, but OpenSSL does not do this and some PKCS#12
1207 // consumers do not support KeyBags.)
1208 if (pkey != NULL) {
1209 CBB content_info, oid, wrapper, data, safe_contents, bag, bag_oid,
1210 bag_contents;
1211 if (// Add another data ContentInfo.
1212 !CBB_add_asn1(&content_infos, &content_info, CBS_ASN1_SEQUENCE) ||
1213 !CBB_add_asn1(&content_info, &oid, CBS_ASN1_OBJECT) ||
1214 !CBB_add_bytes(&oid, kPKCS7Data, sizeof(kPKCS7Data)) ||
1215 !CBB_add_asn1(&content_info, &wrapper,
1216 CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) ||
1217 !CBB_add_asn1(&wrapper, &data, CBS_ASN1_OCTETSTRING) ||
1218 !CBB_add_asn1(&data, &safe_contents, CBS_ASN1_SEQUENCE) ||
1219 // Add a SafeBag containing a PKCS8ShroudedKeyBag.
1220 !CBB_add_asn1(&safe_contents, &bag, CBS_ASN1_SEQUENCE) ||
1221 !CBB_add_asn1(&bag, &bag_oid, CBS_ASN1_OBJECT) ||
1222 !CBB_add_bytes(&bag_oid, kPKCS8ShroudedKeyBag,
1223 sizeof(kPKCS8ShroudedKeyBag)) ||
1224 !CBB_add_asn1(&bag, &bag_contents,
1225 CBS_ASN1_CONSTRUCTED | CBS_ASN1_CONTEXT_SPECIFIC | 0) ||
1226 !PKCS8_marshal_encrypted_private_key(
1227 &bag_contents, key_nid, NULL, password, password_len,
1228 NULL /* generate a random salt */, 0 /* use default salt length */,
1229 iterations, pkey) ||
1230 !add_bag_attributes(&bag, name, key_id, key_id_len) ||
1231 !CBB_flush(&content_infos)) {
1232 goto err;
1233 }
1234 }
1235
1236 // Compute the MAC. Match OpenSSL in using SHA-1 as the hash function. The MAC
1237 // covers |auth_safe_data|.
1238 const EVP_MD *mac_md = EVP_sha1();
1239 uint8_t mac_salt[PKCS5_SALT_LEN];
1240 uint8_t mac[EVP_MAX_MD_SIZE];
1241 unsigned mac_len;
1242 if (!CBB_flush(&auth_safe_data) ||
1243 !RAND_bytes(mac_salt, sizeof(mac_salt)) ||
1244 !pkcs12_key_gen(password, password_len, mac_salt, sizeof(mac_salt),
1245 PKCS12_MAC_ID, mac_iterations, EVP_MD_size(mac_md),
1246 mac_key, mac_md) ||
1247 !HMAC(mac_md, mac_key, EVP_MD_size(mac_md), CBB_data(&auth_safe_data),
1248 CBB_len(&auth_safe_data), mac, &mac_len)) {
1249 goto err;
1250 }
1251
1252 CBB mac_data, digest_info, mac_cbb, mac_salt_cbb;
1253 if (!CBB_add_asn1(&pfx, &mac_data, CBS_ASN1_SEQUENCE) ||
1254 !CBB_add_asn1(&mac_data, &digest_info, CBS_ASN1_SEQUENCE) ||
1255 !EVP_marshal_digest_algorithm(&digest_info, mac_md) ||
1256 !CBB_add_asn1(&digest_info, &mac_cbb, CBS_ASN1_OCTETSTRING) ||
1257 !CBB_add_bytes(&mac_cbb, mac, mac_len) ||
1258 !CBB_add_asn1(&mac_data, &mac_salt_cbb, CBS_ASN1_OCTETSTRING) ||
1259 !CBB_add_bytes(&mac_salt_cbb, mac_salt, sizeof(mac_salt)) ||
1260 // The iteration count has a DEFAULT of 1, but RFC 7292 says "The default
1261 // is for historical reasons and its use is deprecated." Thus we
1262 // explicitly encode the iteration count, though it is not valid DER.
1263 !CBB_add_asn1_uint64(&mac_data, mac_iterations)) {
1264 goto err;
1265 }
1266
1267 ret = OPENSSL_malloc(sizeof(PKCS12));
1268 if (ret == NULL ||
1269 !CBB_finish(&cbb, &ret->ber_bytes, &ret->ber_len)) {
1270 OPENSSL_free(ret);
1271 ret = NULL;
1272 goto err;
1273 }
1274
1275err:
1276 OPENSSL_cleanse(mac_key, sizeof(mac_key));
1277 CBB_cleanup(&cbb);
1278 return ret;
1279}
1280
Robert Sloan6d0d00e2017-03-27 07:13:07 -07001281void PKCS12_free(PKCS12 *p12) {
1282 if (p12 == NULL) {
1283 return;
1284 }
1285 OPENSSL_free(p12->ber_bytes);
1286 OPENSSL_free(p12);
1287}