Coverage Report

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