Coverage Report

Created: 2025-06-11 06:40

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