Coverage Report

Created: 2023-11-19 06:09

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