1 /* Written by Dr Stephen N Henson (steve (at) 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 (at) 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 (at) cryptsoft.com). This product includes software written by Tim 54 * Hudson (tjh (at) cryptsoft.com). */ 55 56 #include <openssl/pkcs8.h> 57 58 #include <assert.h> 59 #include <limits.h> 60 #include <string.h> 61 62 #include <openssl/bytestring.h> 63 #include <openssl/cipher.h> 64 #include <openssl/digest.h> 65 #include <openssl/err.h> 66 #include <openssl/mem.h> 67 #include <openssl/nid.h> 68 #include <openssl/rand.h> 69 70 #include "internal.h" 71 #include "../internal.h" 72 73 74 static int ascii_to_ucs2(const char *ascii, size_t ascii_len, 75 uint8_t **out, size_t *out_len) { 76 size_t ulen = ascii_len * 2 + 2; 77 if (ascii_len * 2 < ascii_len || ulen < ascii_len * 2) { 78 return 0; 79 } 80 81 uint8_t *unitmp = OPENSSL_malloc(ulen); 82 if (unitmp == NULL) { 83 OPENSSL_PUT_ERROR(PKCS8, ERR_R_MALLOC_FAILURE); 84 return 0; 85 } 86 for (size_t i = 0; i < ulen - 2; i += 2) { 87 unitmp[i] = 0; 88 unitmp[i + 1] = ascii[i >> 1]; 89 } 90 91 // Terminate the result with a UCS-2 NUL. 92 unitmp[ulen - 2] = 0; 93 unitmp[ulen - 1] = 0; 94 *out_len = ulen; 95 *out = unitmp; 96 return 1; 97 } 98 99 int pkcs12_key_gen(const char *pass, size_t pass_len, const uint8_t *salt, 100 size_t salt_len, uint8_t id, unsigned iterations, 101 size_t out_len, uint8_t *out, const EVP_MD *md) { 102 // See https://tools.ietf.org/html/rfc7292#appendix-B. Quoted parts of the 103 // specification have errata applied and other typos fixed. 104 105 if (iterations < 1) { 106 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_ITERATION_COUNT); 107 return 0; 108 } 109 110 int ret = 0; 111 EVP_MD_CTX ctx; 112 EVP_MD_CTX_init(&ctx); 113 uint8_t *pass_raw = NULL, *I = NULL; 114 size_t pass_raw_len = 0, I_len = 0; 115 // If |pass| is NULL, we use the empty string rather than {0, 0} as the raw 116 // password. 117 if (pass != NULL && 118 !ascii_to_ucs2(pass, pass_len, &pass_raw, &pass_raw_len)) { 119 goto err; 120 } 121 122 // In the spec, |block_size| is called "v", but measured in bits. 123 size_t block_size = EVP_MD_block_size(md); 124 125 // 1. Construct a string, D (the "diversifier"), by concatenating v/8 copies 126 // of ID. 127 uint8_t D[EVP_MAX_MD_BLOCK_SIZE]; 128 OPENSSL_memset(D, id, block_size); 129 130 // 2. Concatenate copies of the salt together to create a string S of length 131 // v(ceiling(s/v)) bits (the final copy of the salt may be truncated to 132 // create S). Note that if the salt is the empty string, then so is S. 133 // 134 // 3. Concatenate copies of the password together to create a string P of 135 // length v(ceiling(p/v)) bits (the final copy of the password may be 136 // truncated to create P). Note that if the password is the empty string, 137 // then so is P. 138 // 139 // 4. Set I=S||P to be the concatenation of S and P. 140 if (salt_len + block_size - 1 < salt_len || 141 pass_raw_len + block_size - 1 < pass_raw_len) { 142 OPENSSL_PUT_ERROR(PKCS8, ERR_R_OVERFLOW); 143 goto err; 144 } 145 size_t S_len = block_size * ((salt_len + block_size - 1) / block_size); 146 size_t P_len = block_size * ((pass_raw_len + block_size - 1) / block_size); 147 I_len = S_len + P_len; 148 if (I_len < S_len) { 149 OPENSSL_PUT_ERROR(PKCS8, ERR_R_OVERFLOW); 150 goto err; 151 } 152 153 I = OPENSSL_malloc(I_len); 154 if (I_len != 0 && I == NULL) { 155 OPENSSL_PUT_ERROR(PKCS8, ERR_R_MALLOC_FAILURE); 156 goto err; 157 } 158 159 for (size_t i = 0; i < S_len; i++) { 160 I[i] = salt[i % salt_len]; 161 } 162 for (size_t i = 0; i < P_len; i++) { 163 I[i + S_len] = pass_raw[i % pass_raw_len]; 164 } 165 166 while (out_len != 0) { 167 // A. Set A_i=H^r(D||I). (i.e., the r-th hash of D||I, 168 // H(H(H(... H(D||I)))) 169 uint8_t A[EVP_MAX_MD_SIZE]; 170 unsigned A_len; 171 if (!EVP_DigestInit_ex(&ctx, md, NULL) || 172 !EVP_DigestUpdate(&ctx, D, block_size) || 173 !EVP_DigestUpdate(&ctx, I, I_len) || 174 !EVP_DigestFinal_ex(&ctx, A, &A_len)) { 175 goto err; 176 } 177 for (unsigned iter = 1; iter < iterations; iter++) { 178 if (!EVP_DigestInit_ex(&ctx, md, NULL) || 179 !EVP_DigestUpdate(&ctx, A, A_len) || 180 !EVP_DigestFinal_ex(&ctx, A, &A_len)) { 181 goto err; 182 } 183 } 184 185 size_t todo = out_len < A_len ? out_len : A_len; 186 OPENSSL_memcpy(out, A, todo); 187 out += todo; 188 out_len -= todo; 189 if (out_len == 0) { 190 break; 191 } 192 193 // B. Concatenate copies of A_i to create a string B of length v bits (the 194 // final copy of A_i may be truncated to create B). 195 uint8_t B[EVP_MAX_MD_BLOCK_SIZE]; 196 for (size_t i = 0; i < block_size; i++) { 197 B[i] = A[i % A_len]; 198 } 199 200 // C. Treating I as a concatenation I_0, I_1, ..., I_(k-1) of v-bit blocks, 201 // where k=ceiling(s/v)+ceiling(p/v), modify I by setting I_j=(I_j+B+1) mod 202 // 2^v for each j. 203 assert(I_len % block_size == 0); 204 for (size_t i = 0; i < I_len; i += block_size) { 205 unsigned carry = 1; 206 for (size_t j = block_size - 1; j < block_size; j--) { 207 carry += I[i + j] + B[j]; 208 I[i + j] = (uint8_t)carry; 209 carry >>= 8; 210 } 211 } 212 } 213 214 ret = 1; 215 216 err: 217 OPENSSL_free(I); 218 OPENSSL_free(pass_raw); 219 EVP_MD_CTX_cleanup(&ctx); 220 return ret; 221 } 222 223 static int pkcs12_pbe_cipher_init(const struct pbe_suite *suite, 224 EVP_CIPHER_CTX *ctx, unsigned iterations, 225 const char *pass, size_t pass_len, 226 const uint8_t *salt, size_t salt_len, 227 int is_encrypt) { 228 const EVP_CIPHER *cipher = suite->cipher_func(); 229 const EVP_MD *md = suite->md_func(); 230 231 uint8_t key[EVP_MAX_KEY_LENGTH]; 232 uint8_t iv[EVP_MAX_IV_LENGTH]; 233 if (!pkcs12_key_gen(pass, pass_len, salt, salt_len, PKCS12_KEY_ID, iterations, 234 EVP_CIPHER_key_length(cipher), key, md) || 235 !pkcs12_key_gen(pass, pass_len, salt, salt_len, PKCS12_IV_ID, iterations, 236 EVP_CIPHER_iv_length(cipher), iv, md)) { 237 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_KEY_GEN_ERROR); 238 return 0; 239 } 240 241 int ret = EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, is_encrypt); 242 OPENSSL_cleanse(key, EVP_MAX_KEY_LENGTH); 243 OPENSSL_cleanse(iv, EVP_MAX_IV_LENGTH); 244 return ret; 245 } 246 247 static int pkcs12_pbe_decrypt_init(const struct pbe_suite *suite, 248 EVP_CIPHER_CTX *ctx, const char *pass, 249 size_t pass_len, CBS *param) { 250 CBS pbe_param, salt; 251 uint64_t iterations; 252 if (!CBS_get_asn1(param, &pbe_param, CBS_ASN1_SEQUENCE) || 253 !CBS_get_asn1(&pbe_param, &salt, CBS_ASN1_OCTETSTRING) || 254 !CBS_get_asn1_uint64(&pbe_param, &iterations) || 255 CBS_len(&pbe_param) != 0 || 256 CBS_len(param) != 0) { 257 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR); 258 return 0; 259 } 260 261 if (iterations == 0 || iterations > UINT_MAX) { 262 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_ITERATION_COUNT); 263 return 0; 264 } 265 266 return pkcs12_pbe_cipher_init(suite, ctx, (unsigned)iterations, pass, 267 pass_len, CBS_data(&salt), CBS_len(&salt), 268 0 /* decrypt */); 269 } 270 271 static const struct pbe_suite kBuiltinPBE[] = { 272 { 273 NID_pbe_WithSHA1And40BitRC2_CBC, 274 // 1.2.840.113549.1.12.1.6 275 {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x01, 0x06}, 276 10, 277 EVP_rc2_40_cbc, 278 EVP_sha1, 279 pkcs12_pbe_decrypt_init, 280 }, 281 { 282 NID_pbe_WithSHA1And128BitRC4, 283 // 1.2.840.113549.1.12.1.1 284 {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x01, 0x01}, 285 10, 286 EVP_rc4, 287 EVP_sha1, 288 pkcs12_pbe_decrypt_init, 289 }, 290 { 291 NID_pbe_WithSHA1And3_Key_TripleDES_CBC, 292 // 1.2.840.113549.1.12.1.3 293 {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x0c, 0x01, 0x03}, 294 10, 295 EVP_des_ede3_cbc, 296 EVP_sha1, 297 pkcs12_pbe_decrypt_init, 298 }, 299 { 300 NID_pbes2, 301 // 1.2.840.113549.1.5.13 302 {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x05, 0x0d}, 303 9, 304 NULL, 305 NULL, 306 PKCS5_pbe2_decrypt_init, 307 }, 308 }; 309 310 static const struct pbe_suite *get_pbe_suite(int pbe_nid) { 311 for (unsigned i = 0; i < OPENSSL_ARRAY_SIZE(kBuiltinPBE); i++) { 312 if (kBuiltinPBE[i].pbe_nid == pbe_nid) { 313 return &kBuiltinPBE[i]; 314 } 315 } 316 317 return NULL; 318 } 319 320 static int pkcs12_pbe_encrypt_init(CBB *out, EVP_CIPHER_CTX *ctx, int alg, 321 unsigned iterations, const char *pass, 322 size_t pass_len, const uint8_t *salt, 323 size_t salt_len) { 324 const struct pbe_suite *suite = get_pbe_suite(alg); 325 if (suite == NULL) { 326 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNKNOWN_ALGORITHM); 327 return 0; 328 } 329 330 // See RFC 2898, appendix A.3. 331 CBB algorithm, oid, param, salt_cbb; 332 if (!CBB_add_asn1(out, &algorithm, CBS_ASN1_SEQUENCE) || 333 !CBB_add_asn1(&algorithm, &oid, CBS_ASN1_OBJECT) || 334 !CBB_add_bytes(&oid, suite->oid, suite->oid_len) || 335 !CBB_add_asn1(&algorithm, ¶m, CBS_ASN1_SEQUENCE) || 336 !CBB_add_asn1(¶m, &salt_cbb, CBS_ASN1_OCTETSTRING) || 337 !CBB_add_bytes(&salt_cbb, salt, salt_len) || 338 !CBB_add_asn1_uint64(¶m, iterations) || 339 !CBB_flush(out)) { 340 return 0; 341 } 342 343 return pkcs12_pbe_cipher_init(suite, ctx, iterations, pass, pass_len, salt, 344 salt_len, 1 /* encrypt */); 345 } 346 347 int pkcs8_pbe_decrypt(uint8_t **out, size_t *out_len, CBS *algorithm, 348 const char *pass, size_t pass_len, const uint8_t *in, 349 size_t in_len) { 350 int ret = 0; 351 uint8_t *buf = NULL;; 352 EVP_CIPHER_CTX ctx; 353 EVP_CIPHER_CTX_init(&ctx); 354 355 CBS obj; 356 if (!CBS_get_asn1(algorithm, &obj, CBS_ASN1_OBJECT)) { 357 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR); 358 goto err; 359 } 360 361 const struct pbe_suite *suite = NULL; 362 for (unsigned i = 0; i < OPENSSL_ARRAY_SIZE(kBuiltinPBE); i++) { 363 if (CBS_mem_equal(&obj, kBuiltinPBE[i].oid, kBuiltinPBE[i].oid_len)) { 364 suite = &kBuiltinPBE[i]; 365 break; 366 } 367 } 368 if (suite == NULL) { 369 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNKNOWN_ALGORITHM); 370 goto err; 371 } 372 373 if (!suite->decrypt_init(suite, &ctx, pass, pass_len, algorithm)) { 374 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_KEYGEN_FAILURE); 375 goto err; 376 } 377 378 buf = OPENSSL_malloc(in_len); 379 if (buf == NULL) { 380 OPENSSL_PUT_ERROR(PKCS8, ERR_R_MALLOC_FAILURE); 381 goto err; 382 } 383 384 if (in_len > INT_MAX) { 385 OPENSSL_PUT_ERROR(PKCS8, ERR_R_OVERFLOW); 386 goto err; 387 } 388 389 int n1, n2; 390 if (!EVP_DecryptUpdate(&ctx, buf, &n1, in, (int)in_len) || 391 !EVP_DecryptFinal_ex(&ctx, buf + n1, &n2)) { 392 goto err; 393 } 394 395 *out = buf; 396 *out_len = n1 + n2; 397 ret = 1; 398 buf = NULL; 399 400 err: 401 OPENSSL_free(buf); 402 EVP_CIPHER_CTX_cleanup(&ctx); 403 return ret; 404 } 405 406 EVP_PKEY *PKCS8_parse_encrypted_private_key(CBS *cbs, const char *pass, 407 size_t pass_len) { 408 // See RFC 5208, section 6. 409 CBS epki, algorithm, ciphertext; 410 if (!CBS_get_asn1(cbs, &epki, CBS_ASN1_SEQUENCE) || 411 !CBS_get_asn1(&epki, &algorithm, CBS_ASN1_SEQUENCE) || 412 !CBS_get_asn1(&epki, &ciphertext, CBS_ASN1_OCTETSTRING) || 413 CBS_len(&epki) != 0) { 414 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR); 415 return 0; 416 } 417 418 uint8_t *out; 419 size_t out_len; 420 if (!pkcs8_pbe_decrypt(&out, &out_len, &algorithm, pass, pass_len, 421 CBS_data(&ciphertext), CBS_len(&ciphertext))) { 422 return 0; 423 } 424 425 CBS pki; 426 CBS_init(&pki, out, out_len); 427 EVP_PKEY *ret = EVP_parse_private_key(&pki); 428 OPENSSL_free(out); 429 return ret; 430 } 431 432 int PKCS8_marshal_encrypted_private_key(CBB *out, int pbe_nid, 433 const EVP_CIPHER *cipher, 434 const char *pass, size_t pass_len, 435 const uint8_t *salt, size_t salt_len, 436 int iterations, const EVP_PKEY *pkey) { 437 int ret = 0; 438 uint8_t *plaintext = NULL, *salt_buf = NULL; 439 size_t plaintext_len = 0; 440 EVP_CIPHER_CTX ctx; 441 EVP_CIPHER_CTX_init(&ctx); 442 443 // Generate a random salt if necessary. 444 if (salt == NULL) { 445 if (salt_len == 0) { 446 salt_len = PKCS5_SALT_LEN; 447 } 448 449 salt_buf = OPENSSL_malloc(salt_len); 450 if (salt_buf == NULL || 451 !RAND_bytes(salt_buf, salt_len)) { 452 goto err; 453 } 454 455 salt = salt_buf; 456 } 457 458 if (iterations <= 0) { 459 iterations = PKCS5_DEFAULT_ITERATIONS; 460 } 461 462 // Serialize the input key. 463 CBB plaintext_cbb; 464 if (!CBB_init(&plaintext_cbb, 128) || 465 !EVP_marshal_private_key(&plaintext_cbb, pkey) || 466 !CBB_finish(&plaintext_cbb, &plaintext, &plaintext_len)) { 467 CBB_cleanup(&plaintext_cbb); 468 goto err; 469 } 470 471 CBB epki; 472 if (!CBB_add_asn1(out, &epki, CBS_ASN1_SEQUENCE)) { 473 goto err; 474 } 475 476 int alg_ok; 477 if (pbe_nid == -1) { 478 alg_ok = PKCS5_pbe2_encrypt_init(&epki, &ctx, cipher, (unsigned)iterations, 479 pass, pass_len, salt, salt_len); 480 } else { 481 alg_ok = pkcs12_pbe_encrypt_init(&epki, &ctx, pbe_nid, (unsigned)iterations, 482 pass, pass_len, salt, salt_len); 483 } 484 if (!alg_ok) { 485 goto err; 486 } 487 488 size_t max_out = plaintext_len + EVP_CIPHER_CTX_block_size(&ctx); 489 if (max_out < plaintext_len) { 490 OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_TOO_LONG); 491 goto err; 492 } 493 494 CBB ciphertext; 495 uint8_t *ptr; 496 int n1, n2; 497 if (!CBB_add_asn1(&epki, &ciphertext, CBS_ASN1_OCTETSTRING) || 498 !CBB_reserve(&ciphertext, &ptr, max_out) || 499 !EVP_CipherUpdate(&ctx, ptr, &n1, plaintext, plaintext_len) || 500 !EVP_CipherFinal_ex(&ctx, ptr + n1, &n2) || 501 !CBB_did_write(&ciphertext, n1 + n2) || 502 !CBB_flush(out)) { 503 goto err; 504 } 505 506 ret = 1; 507 508 err: 509 OPENSSL_free(plaintext); 510 OPENSSL_free(salt_buf); 511 EVP_CIPHER_CTX_cleanup(&ctx); 512 return ret; 513 } 514