Coverage Report

Created: 2026-02-14 06:34

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