Coverage Report

Created: 2026-03-19 06:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/boringssl/crypto/pkcs8/pkcs8.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 <assert.h>
18
#include <limits.h>
19
#include <string.h>
20
21
#include <openssl/bytestring.h>
22
#include <openssl/cipher.h>
23
#include <openssl/digest.h>
24
#include <openssl/err.h>
25
#include <openssl/mem.h>
26
#include <openssl/nid.h>
27
#include <openssl/rand.h>
28
29
#include "../bytestring/internal.h"
30
#include "../internal.h"
31
#include "internal.h"
32
33
34
using namespace bssl;
35
36
static int pkcs12_encode_password(const char *in, size_t in_len, uint8_t **out,
37
411
                                  size_t *out_len) {
38
411
  ScopedCBB cbb;
39
411
  if (!CBB_init(cbb.get(), in_len * 2)) {
40
0
    return 0;
41
0
  }
42
43
  // Convert the password to BMPString, or UCS-2. See
44
  // https://tools.ietf.org/html/rfc7292#appendix-B.1.
45
411
  CBS cbs;
46
411
  CBS_init(&cbs, (const uint8_t *)in, in_len);
47
1.64k
  while (CBS_len(&cbs) != 0) {
48
1.23k
    uint32_t c;
49
1.23k
    if (!CBS_get_utf8(&cbs, &c) || !CBB_add_ucs2_be(cbb.get(), c)) {
50
0
      OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_INVALID_CHARACTERS);
51
0
      return 0;
52
0
    }
53
1.23k
  }
54
55
  // Terminate the result with a UCS-2 NUL.
56
411
  if (!CBB_add_ucs2_be(cbb.get(), 0) || !CBB_finish(cbb.get(), out, out_len)) {
57
0
    return 0;
58
0
  }
59
60
411
  return 1;
61
411
}
62
63
int bssl::pkcs12_key_gen(const char *pass, size_t pass_len, const uint8_t *salt,
64
                         size_t salt_len, uint8_t id, uint32_t iterations,
65
411
                         size_t out_len, uint8_t *out, const EVP_MD *md) {
66
  // See https://tools.ietf.org/html/rfc7292#appendix-B. Quoted parts of the
67
  // specification have errata applied and other typos fixed.
68
69
411
  if (iterations < 1) {
70
0
    OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_ITERATION_COUNT);
71
0
    return 0;
72
0
  }
73
74
411
  int ret = 0;
75
411
  EVP_MD_CTX ctx;
76
411
  EVP_MD_CTX_init(&ctx);
77
411
  uint8_t *pass_raw = nullptr, *I = nullptr;
78
411
  size_t pass_raw_len = 0, I_len = 0;
79
80
411
  {
81
    // If |pass| is NULL, we use the empty string rather than {0, 0} as the raw
82
    // password.
83
411
    if (pass != nullptr &&
84
411
        !pkcs12_encode_password(pass, pass_len, &pass_raw, &pass_raw_len)) {
85
0
      goto err;
86
0
    }
87
88
    // In the spec, |block_size| is called "v", but measured in bits.
89
411
    size_t block_size = EVP_MD_block_size(md);
90
91
    // 1. Construct a string, D (the "diversifier"), by concatenating v/8 copies
92
    // of ID.
93
411
    uint8_t D[EVP_MAX_MD_BLOCK_SIZE];
94
411
    OPENSSL_memset(D, id, block_size);
95
96
    // 2. Concatenate copies of the salt together to create a string S of length
97
    // v(ceiling(s/v)) bits (the final copy of the salt may be truncated to
98
    // create S). Note that if the salt is the empty string, then so is S.
99
    //
100
    // 3. Concatenate copies of the password together to create a string P of
101
    // length v(ceiling(p/v)) bits (the final copy of the password may be
102
    // truncated to create P).  Note that if the password is the empty string,
103
    // then so is P.
104
    //
105
    // 4. Set I=S||P to be the concatenation of S and P.
106
411
    if (salt_len + block_size - 1 < salt_len ||
107
411
        pass_raw_len + block_size - 1 < pass_raw_len) {
108
0
      OPENSSL_PUT_ERROR(PKCS8, ERR_R_OVERFLOW);
109
0
      goto err;
110
0
    }
111
411
    size_t S_len = block_size * ((salt_len + block_size - 1) / block_size);
112
411
    size_t P_len = block_size * ((pass_raw_len + block_size - 1) / block_size);
113
411
    I_len = S_len + P_len;
114
411
    if (I_len < S_len) {
115
0
      OPENSSL_PUT_ERROR(PKCS8, ERR_R_OVERFLOW);
116
0
      goto err;
117
0
    }
118
119
411
    I = reinterpret_cast<uint8_t *>(OPENSSL_malloc(I_len));
120
411
    if (I_len != 0 && I == nullptr) {
121
0
      goto err;
122
0
    }
123
124
3.44M
    for (size_t i = 0; i < S_len; i++) {
125
3.44M
      I[i] = salt[i % salt_len];
126
3.44M
    }
127
32.4k
    for (size_t i = 0; i < P_len; i++) {
128
32.0k
      I[i + S_len] = pass_raw[i % pass_raw_len];
129
32.0k
    }
130
131
415
    while (out_len != 0) {
132
      // A. Set A_i=H^r(D||I). (i.e., the r-th hash of D||I,
133
      // H(H(H(... H(D||I))))
134
415
      uint8_t A[EVP_MAX_MD_SIZE];
135
415
      unsigned A_len;
136
415
      if (!EVP_DigestInit_ex(&ctx, md, nullptr) ||
137
415
          !EVP_DigestUpdate(&ctx, D, block_size) ||
138
415
          !EVP_DigestUpdate(&ctx, I, I_len) ||
139
415
          !EVP_DigestFinal_ex(&ctx, A, &A_len)) {
140
0
        goto err;
141
0
      }
142
137k
      for (uint32_t iter = 1; iter < iterations; iter++) {
143
137k
        if (!EVP_DigestInit_ex(&ctx, md, nullptr) ||
144
137k
            !EVP_DigestUpdate(&ctx, A, A_len) ||
145
137k
            !EVP_DigestFinal_ex(&ctx, A, &A_len)) {
146
0
          goto err;
147
0
        }
148
137k
      }
149
150
415
      size_t todo = out_len < A_len ? out_len : A_len;
151
415
      OPENSSL_memcpy(out, A, todo);
152
415
      out += todo;
153
415
      out_len -= todo;
154
415
      if (out_len == 0) {
155
411
        break;
156
411
      }
157
158
      // B. Concatenate copies of A_i to create a string B of length v bits (the
159
      // final copy of A_i may be truncated to create B).
160
4
      uint8_t B[EVP_MAX_MD_BLOCK_SIZE];
161
260
      for (size_t i = 0; i < block_size; i++) {
162
256
        B[i] = A[i % A_len];
163
256
      }
164
165
      // C. Treating I as a concatenation I_0, I_1, ..., I_(k-1) of v-bit
166
      // blocks, where k=ceiling(s/v)+ceiling(p/v), modify I by setting
167
      // I_j=(I_j+B+1) mod 2^v for each j.
168
4
      assert(I_len % block_size == 0);
169
12
      for (size_t i = 0; i < I_len; i += block_size) {
170
8
        unsigned carry = 1;
171
520
        for (size_t j = block_size - 1; j < block_size; j--) {
172
512
          carry += I[i + j] + B[j];
173
512
          I[i + j] = (uint8_t)carry;
174
512
          carry >>= 8;
175
512
        }
176
8
      }
177
4
    }
178
179
411
    ret = 1;
180
411
  }
181
182
411
err:
183
411
  OPENSSL_free(I);
184
411
  OPENSSL_free(pass_raw);
185
411
  EVP_MD_CTX_cleanup(&ctx);
186
411
  return ret;
187
411
}
188
189
static int pkcs12_pbe_cipher_init(const struct pbe_suite *suite,
190
                                  EVP_CIPHER_CTX *ctx, uint32_t iterations,
191
                                  const char *pass, size_t pass_len,
192
                                  const uint8_t *salt, size_t salt_len,
193
8
                                  int is_encrypt) {
194
8
  const EVP_CIPHER *cipher = suite->cipher_func();
195
8
  const EVP_MD *md = suite->md_func();
196
197
8
  uint8_t key[EVP_MAX_KEY_LENGTH];
198
8
  uint8_t iv[EVP_MAX_IV_LENGTH];
199
8
  if (!pkcs12_key_gen(pass, pass_len, salt, salt_len, PKCS12_KEY_ID, iterations,
200
8
                      EVP_CIPHER_key_length(cipher), key, md) ||
201
8
      !pkcs12_key_gen(pass, pass_len, salt, salt_len, PKCS12_IV_ID, iterations,
202
8
                      EVP_CIPHER_iv_length(cipher), iv, md)) {
203
0
    OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_KEY_GEN_ERROR);
204
0
    return 0;
205
0
  }
206
207
8
  int ret = EVP_CipherInit_ex(ctx, cipher, nullptr, key, iv, is_encrypt);
208
8
  OPENSSL_cleanse(key, EVP_MAX_KEY_LENGTH);
209
8
  OPENSSL_cleanse(iv, EVP_MAX_IV_LENGTH);
210
8
  return ret;
211
8
}
212
213
static int pkcs12_pbe_decrypt_init(const struct pbe_suite *suite,
214
                                   EVP_CIPHER_CTX *ctx, const char *pass,
215
8
                                   size_t pass_len, CBS *param) {
216
8
  CBS pbe_param, salt;
217
8
  uint64_t iterations;
218
8
  if (!CBS_get_asn1(param, &pbe_param, CBS_ASN1_SEQUENCE) ||
219
8
      !CBS_get_asn1(&pbe_param, &salt, CBS_ASN1_OCTETSTRING) ||
220
8
      !CBS_get_asn1_uint64(&pbe_param, &iterations) ||
221
8
      CBS_len(&pbe_param) != 0 || CBS_len(param) != 0) {
222
0
    OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
223
0
    return 0;
224
0
  }
225
226
8
  if (!pkcs12_iterations_acceptable(iterations)) {
227
0
    OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_ITERATION_COUNT);
228
0
    return 0;
229
0
  }
230
231
8
  return pkcs12_pbe_cipher_init(suite, ctx, (uint32_t)iterations, pass,
232
8
                                pass_len, CBS_data(&salt), CBS_len(&salt),
233
8
                                0 /* decrypt */);
234
8
}
235
236
static const struct bssl::pbe_suite kBuiltinPBE[] = {
237
    {
238
        NID_pbe_WithSHA1And40BitRC2_CBC,
239
        // 1.2.840.113549.1.12.1.6
240
        {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x01, 0x06},
241
        10,
242
        EVP_rc2_40_cbc,
243
        EVP_sha1,
244
        pkcs12_pbe_decrypt_init,
245
    },
246
    {
247
        NID_pbe_WithSHA1And128BitRC4,
248
        // 1.2.840.113549.1.12.1.1
249
        {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x01, 0x01},
250
        10,
251
        EVP_rc4,
252
        EVP_sha1,
253
        pkcs12_pbe_decrypt_init,
254
    },
255
    {
256
        NID_pbe_WithSHA1And3_Key_TripleDES_CBC,
257
        // 1.2.840.113549.1.12.1.3
258
        {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x01, 0x03},
259
        10,
260
        EVP_des_ede3_cbc,
261
        EVP_sha1,
262
        pkcs12_pbe_decrypt_init,
263
    },
264
    {
265
        NID_pbes2,
266
        // 1.2.840.113549.1.5.13
267
        {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x05, 0x0d},
268
        9,
269
        nullptr,
270
        nullptr,
271
        PKCS5_pbe2_decrypt_init,
272
    },
273
};
274
275
0
static const struct bssl::pbe_suite *get_pkcs12_pbe_suite(int pbe_nid) {
276
0
  for (const auto &pbe : kBuiltinPBE) {
277
0
    if (pbe.pbe_nid == pbe_nid &&
278
        // If |cipher_func| or |md_func| are missing, this is a PBES2 scheme.
279
0
        pbe.cipher_func != nullptr && pbe.md_func != nullptr) {
280
0
      return &pbe;
281
0
    }
282
0
  }
283
284
0
  return nullptr;
285
0
}
286
287
int bssl::pkcs12_pbe_encrypt_init(CBB *out, EVP_CIPHER_CTX *ctx, int alg_nid,
288
                                  const EVP_CIPHER *alg_cipher,
289
                                  uint32_t iterations, const char *pass,
290
                                  size_t pass_len, const uint8_t *salt,
291
0
                                  size_t salt_len) {
292
  // TODO(davidben): OpenSSL has since extended |pbe_nid| to control either
293
  // the PBES1 scheme or the PBES2 PRF. E.g. passing |NID_hmacWithSHA256| will
294
  // select PBES2 with HMAC-SHA256 as the PRF. Implement this if anything uses
295
  // it. See 5693a30813a031d3921a016a870420e7eb93ec90 in OpenSSL.
296
0
  if (alg_nid == -1) {
297
0
    return PKCS5_pbe2_encrypt_init(out, ctx, alg_cipher, iterations, pass,
298
0
                                   pass_len, salt, salt_len);
299
0
  }
300
301
0
  const struct pbe_suite *suite = get_pkcs12_pbe_suite(alg_nid);
302
0
  if (suite == nullptr) {
303
0
    OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNKNOWN_ALGORITHM);
304
0
    return 0;
305
0
  }
306
307
  // See RFC 7292, appendix C. All our supported "PBES1" schemes are the PKCS#12
308
  // schemes, which use a different KDF. The true PBES1 schemes in RFC 8018 use
309
  // PBKDF1, which use a very similar PBEParameter structure, but require the
310
  // salt be exactly 8 bytes.
311
0
  CBB algorithm, param;
312
0
  if (!CBB_add_asn1(out, &algorithm, CBS_ASN1_SEQUENCE) ||
313
0
      !CBB_add_asn1_element(&algorithm, CBS_ASN1_OBJECT, suite->oid,
314
0
                            suite->oid_len) ||
315
0
      !CBB_add_asn1(&algorithm, &param, CBS_ASN1_SEQUENCE) ||
316
0
      !CBB_add_asn1_octet_string(&param, salt, salt_len) ||
317
0
      !CBB_add_asn1_uint64(&param, iterations) || !CBB_flush(out)) {
318
0
    return 0;
319
0
  }
320
321
0
  return pkcs12_pbe_cipher_init(suite, ctx, iterations, pass, pass_len, salt,
322
0
                                salt_len, 1 /* encrypt */);
323
0
}
324
325
int bssl::pkcs8_pbe_decrypt(uint8_t **out, size_t *out_len, CBS *algorithm,
326
                            const char *pass, size_t pass_len,
327
10
                            const uint8_t *in, size_t in_len) {
328
10
  int ret = 0;
329
10
  uint8_t *buf = nullptr;
330
10
  ScopedEVP_CIPHER_CTX ctx;
331
332
10
  CBS obj;
333
10
  const struct pbe_suite *suite = nullptr;
334
10
  if (!CBS_get_asn1(algorithm, &obj, CBS_ASN1_OBJECT)) {
335
0
    OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
336
0
    goto err;
337
0
  }
338
339
24
  for (const auto &pbe : kBuiltinPBE) {
340
24
    if (CBS_mem_equal(&obj, pbe.oid, pbe.oid_len)) {
341
10
      suite = &pbe;
342
10
      break;
343
10
    }
344
24
  }
345
10
  if (suite == nullptr) {
346
0
    OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNKNOWN_ALGORITHM);
347
0
    goto err;
348
0
  }
349
350
10
  if (!suite->decrypt_init(suite, ctx.get(), pass, pass_len, algorithm)) {
351
0
    OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_KEYGEN_FAILURE);
352
0
    goto err;
353
0
  }
354
355
10
  buf = reinterpret_cast<uint8_t *>(OPENSSL_malloc(in_len));
356
10
  if (buf == nullptr) {
357
0
    goto err;
358
0
  }
359
360
10
  size_t n1, n2;
361
10
  if (!EVP_DecryptUpdate_ex(ctx.get(), buf, &n1, in_len, in, in_len) ||
362
10
      !EVP_DecryptFinal_ex2(ctx.get(), buf + n1, &n2, in_len - n1)) {
363
0
    goto err;
364
0
  }
365
366
10
  *out = buf;
367
10
  *out_len = n1 + n2;
368
10
  ret = 1;
369
10
  buf = nullptr;
370
371
10
err:
372
10
  OPENSSL_free(buf);
373
10
  return ret;
374
10
}
375
376
EVP_PKEY *PKCS8_parse_encrypted_private_key(CBS *cbs, const char *pass,
377
5
                                            size_t pass_len) {
378
  // See RFC 5208, section 6.
379
5
  CBS epki, algorithm, ciphertext;
380
5
  if (!CBS_get_asn1(cbs, &epki, CBS_ASN1_SEQUENCE) ||
381
5
      !CBS_get_asn1(&epki, &algorithm, CBS_ASN1_SEQUENCE) ||
382
5
      !CBS_get_asn1(&epki, &ciphertext, CBS_ASN1_OCTETSTRING) ||
383
5
      CBS_len(&epki) != 0) {
384
0
    OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
385
0
    return nullptr;
386
0
  }
387
388
5
  uint8_t *out;
389
5
  size_t out_len;
390
5
  if (!pkcs8_pbe_decrypt(&out, &out_len, &algorithm, pass, pass_len,
391
5
                         CBS_data(&ciphertext), CBS_len(&ciphertext))) {
392
0
    return nullptr;
393
0
  }
394
395
5
  CBS pki;
396
5
  CBS_init(&pki, out, out_len);
397
5
  EVP_PKEY *ret = EVP_parse_private_key(&pki);
398
5
  OPENSSL_free(out);
399
5
  return ret;
400
5
}
401
402
int PKCS8_marshal_encrypted_private_key(CBB *out, int pbe_nid,
403
                                        const EVP_CIPHER *cipher,
404
                                        const char *pass, size_t pass_len,
405
                                        const uint8_t *salt, size_t salt_len,
406
0
                                        int iterations, const EVP_PKEY *pkey) {
407
0
  int ret = 0;
408
0
  uint8_t *plaintext = nullptr, *salt_buf = nullptr;
409
0
  size_t plaintext_len = 0;
410
0
  ScopedEVP_CIPHER_CTX ctx;
411
412
0
  {
413
    // Generate a random salt if necessary.
414
0
    if (salt == nullptr) {
415
0
      if (salt_len == 0) {
416
0
        salt_len = PKCS5_SALT_LEN;
417
0
      }
418
419
0
      salt_buf = reinterpret_cast<uint8_t *>(OPENSSL_malloc(salt_len));
420
0
      if (salt_buf == nullptr || !RAND_bytes(salt_buf, salt_len)) {
421
0
        goto err;
422
0
      }
423
424
0
      salt = salt_buf;
425
0
    }
426
427
0
    if (iterations <= 0) {
428
0
      iterations = PKCS12_DEFAULT_ITER;
429
0
    }
430
431
    // Serialize the input key.
432
0
    CBB plaintext_cbb;
433
0
    if (!CBB_init(&plaintext_cbb, 128) ||
434
0
        !EVP_marshal_private_key(&plaintext_cbb, pkey) ||
435
0
        !CBB_finish(&plaintext_cbb, &plaintext, &plaintext_len)) {
436
0
      CBB_cleanup(&plaintext_cbb);
437
0
      goto err;
438
0
    }
439
440
0
    CBB epki;
441
0
    if (!CBB_add_asn1(out, &epki, CBS_ASN1_SEQUENCE) ||
442
0
        !pkcs12_pbe_encrypt_init(&epki, ctx.get(), pbe_nid, cipher,
443
0
                                 (uint32_t)iterations, pass, pass_len, salt,
444
0
                                 salt_len)) {
445
0
      goto err;
446
0
    }
447
448
0
    size_t max_out = plaintext_len + EVP_CIPHER_CTX_block_size(ctx.get());
449
0
    if (max_out < plaintext_len) {
450
0
      OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_TOO_LONG);
451
0
      goto err;
452
0
    }
453
454
0
    CBB ciphertext;
455
0
    uint8_t *ptr;
456
0
    size_t n1, n2;
457
0
    if (!CBB_add_asn1(&epki, &ciphertext, CBS_ASN1_OCTETSTRING) ||
458
0
        !CBB_reserve(&ciphertext, &ptr, max_out) ||
459
0
        !EVP_CipherUpdate_ex(ctx.get(), ptr, &n1, max_out, plaintext,
460
0
                             plaintext_len) ||
461
0
        !EVP_CipherFinal_ex2(ctx.get(), ptr + n1, &n2, max_out - n1) ||
462
0
        !CBB_did_write(&ciphertext, n1 + n2) || !CBB_flush(out)) {
463
0
      goto err;
464
0
    }
465
466
0
    ret = 1;
467
0
  }
468
469
0
err:
470
0
  OPENSSL_free(plaintext);
471
0
  OPENSSL_free(salt_buf);
472
0
  return ret;
473
0
}