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 61 #include <openssl/asn1.h> 62 #include <openssl/bn.h> 63 #include <openssl/buf.h> 64 #include <openssl/cipher.h> 65 #include <openssl/digest.h> 66 #include <openssl/err.h> 67 #include <openssl/hmac.h> 68 #include <openssl/mem.h> 69 #include <openssl/x509.h> 70 71 #include "../bytestring/internal.h" 72 #include "../evp/internal.h" 73 74 75 #define PKCS12_KEY_ID 1 76 #define PKCS12_IV_ID 2 77 #define PKCS12_MAC_ID 3 78 79 static int ascii_to_ucs2(const char *ascii, size_t ascii_len, 80 uint8_t **out, size_t *out_len) { 81 uint8_t *unitmp; 82 size_t ulen, i; 83 84 ulen = ascii_len * 2 + 2; 85 if (ulen < ascii_len) { 86 return 0; 87 } 88 unitmp = OPENSSL_malloc(ulen); 89 if (unitmp == NULL) { 90 return 0; 91 } 92 for (i = 0; i < ulen - 2; i += 2) { 93 unitmp[i] = 0; 94 unitmp[i + 1] = ascii[i >> 1]; 95 } 96 97 /* Make result double null terminated */ 98 unitmp[ulen - 2] = 0; 99 unitmp[ulen - 1] = 0; 100 *out_len = ulen; 101 *out = unitmp; 102 return 1; 103 } 104 105 static int pkcs12_key_gen_raw(const uint8_t *pass_raw, size_t pass_raw_len, 106 const uint8_t *salt, size_t salt_len, 107 int id, int iterations, 108 size_t out_len, uint8_t *out, 109 const EVP_MD *md_type) { 110 uint8_t *B, *D, *I, *p, *Ai; 111 int Slen, Plen, Ilen, Ijlen; 112 int i, j, v; 113 size_t u; 114 int ret = 0; 115 BIGNUM *Ij, *Bpl1; /* These hold Ij and B + 1 */ 116 EVP_MD_CTX ctx; 117 118 EVP_MD_CTX_init(&ctx); 119 v = EVP_MD_block_size(md_type); 120 u = EVP_MD_size(md_type); 121 D = OPENSSL_malloc(v); 122 Ai = OPENSSL_malloc(u); 123 B = OPENSSL_malloc(v + 1); 124 Slen = v * ((salt_len + v - 1) / v); 125 if (pass_raw_len) 126 Plen = v * ((pass_raw_len + v - 1) / v); 127 else 128 Plen = 0; 129 Ilen = Slen + Plen; 130 I = OPENSSL_malloc(Ilen); 131 Ij = BN_new(); 132 Bpl1 = BN_new(); 133 if (!D || !Ai || !B || !I || !Ij || !Bpl1) 134 goto err; 135 for (i = 0; i < v; i++) 136 D[i] = id; 137 p = I; 138 for (i = 0; i < Slen; i++) 139 *p++ = salt[i % salt_len]; 140 for (i = 0; i < Plen; i++) 141 *p++ = pass_raw[i % pass_raw_len]; 142 for (;;) { 143 if (!EVP_DigestInit_ex(&ctx, md_type, NULL) || 144 !EVP_DigestUpdate(&ctx, D, v) || 145 !EVP_DigestUpdate(&ctx, I, Ilen) || 146 !EVP_DigestFinal_ex(&ctx, Ai, NULL)) { 147 goto err; 148 } 149 for (j = 1; j < iterations; j++) { 150 if (!EVP_DigestInit_ex(&ctx, md_type, NULL) || 151 !EVP_DigestUpdate(&ctx, Ai, u) || 152 !EVP_DigestFinal_ex(&ctx, Ai, NULL)) { 153 goto err; 154 } 155 } 156 memcpy(out, Ai, out_len < u ? out_len : u); 157 if (u >= out_len) { 158 ret = 1; 159 goto end; 160 } 161 out_len -= u; 162 out += u; 163 for (j = 0; j < v; j++) 164 B[j] = Ai[j % u]; 165 /* Work out B + 1 first then can use B as tmp space */ 166 if (!BN_bin2bn(B, v, Bpl1)) 167 goto err; 168 if (!BN_add_word(Bpl1, 1)) 169 goto err; 170 for (j = 0; j < Ilen; j += v) { 171 if (!BN_bin2bn(I + j, v, Ij)) 172 goto err; 173 if (!BN_add(Ij, Ij, Bpl1)) 174 goto err; 175 if (!BN_bn2bin(Ij, B)) 176 goto err; 177 Ijlen = BN_num_bytes(Ij); 178 /* If more than 2^(v*8) - 1 cut off MSB */ 179 if (Ijlen > v) { 180 if (!BN_bn2bin(Ij, B)) 181 goto err; 182 memcpy(I + j, B + 1, v); 183 /* If less than v bytes pad with zeroes */ 184 } else if (Ijlen < v) { 185 memset(I + j, 0, v - Ijlen); 186 if (!BN_bn2bin(Ij, I + j + v - Ijlen)) 187 goto err; 188 } else if (!BN_bn2bin(Ij, I + j)) { 189 goto err; 190 } 191 } 192 } 193 194 err: 195 OPENSSL_PUT_ERROR(PKCS8, pkcs12_key_gen_raw, ERR_R_MALLOC_FAILURE); 196 197 end: 198 OPENSSL_free(Ai); 199 OPENSSL_free(B); 200 OPENSSL_free(D); 201 OPENSSL_free(I); 202 BN_free(Ij); 203 BN_free(Bpl1); 204 EVP_MD_CTX_cleanup(&ctx); 205 206 return ret; 207 } 208 209 static int pkcs12_pbe_keyivgen(EVP_CIPHER_CTX *ctx, const uint8_t *pass_raw, 210 size_t pass_raw_len, ASN1_TYPE *param, 211 const EVP_CIPHER *cipher, const EVP_MD *md, 212 int is_encrypt) { 213 PBEPARAM *pbe; 214 int salt_len, iterations, ret; 215 uint8_t *salt; 216 const uint8_t *pbuf; 217 uint8_t key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH]; 218 219 /* Extract useful info from parameter */ 220 if (param == NULL || param->type != V_ASN1_SEQUENCE || 221 param->value.sequence == NULL) { 222 OPENSSL_PUT_ERROR(PKCS8, pkcs12_pbe_keyivgen, PKCS8_R_DECODE_ERROR); 223 return 0; 224 } 225 226 pbuf = param->value.sequence->data; 227 pbe = d2i_PBEPARAM(NULL, &pbuf, param->value.sequence->length); 228 if (pbe == NULL) { 229 OPENSSL_PUT_ERROR(PKCS8, pkcs12_pbe_keyivgen, PKCS8_R_DECODE_ERROR); 230 return 0; 231 } 232 233 if (!pbe->iter) { 234 iterations = 1; 235 } else { 236 iterations = ASN1_INTEGER_get(pbe->iter); 237 } 238 salt = pbe->salt->data; 239 salt_len = pbe->salt->length; 240 if (!pkcs12_key_gen_raw(pass_raw, pass_raw_len, salt, salt_len, PKCS12_KEY_ID, 241 iterations, EVP_CIPHER_key_length(cipher), key, md)) { 242 OPENSSL_PUT_ERROR(PKCS8, pkcs12_pbe_keyivgen, PKCS8_R_KEY_GEN_ERROR); 243 PBEPARAM_free(pbe); 244 return 0; 245 } 246 if (!pkcs12_key_gen_raw(pass_raw, pass_raw_len, salt, salt_len, PKCS12_IV_ID, 247 iterations, EVP_CIPHER_iv_length(cipher), iv, md)) { 248 OPENSSL_PUT_ERROR(PKCS8, pkcs12_pbe_keyivgen, PKCS8_R_KEY_GEN_ERROR); 249 PBEPARAM_free(pbe); 250 return 0; 251 } 252 PBEPARAM_free(pbe); 253 ret = EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, is_encrypt); 254 OPENSSL_cleanse(key, EVP_MAX_KEY_LENGTH); 255 OPENSSL_cleanse(iv, EVP_MAX_IV_LENGTH); 256 return ret; 257 } 258 259 typedef int (*keygen_func)(EVP_CIPHER_CTX *ctx, const uint8_t *pass_raw, 260 size_t pass_raw_len, ASN1_TYPE *param, 261 const EVP_CIPHER *cipher, const EVP_MD *md, 262 int is_encrypt); 263 264 struct pbe_suite { 265 int pbe_nid; 266 const EVP_CIPHER* (*cipher_func)(); 267 const EVP_MD* (*md_func)(); 268 keygen_func keygen; 269 }; 270 271 static const struct pbe_suite kBuiltinPBE[] = { 272 { 273 NID_pbe_WithSHA1And40BitRC2_CBC, EVP_rc2_40_cbc, EVP_sha1, pkcs12_pbe_keyivgen, 274 }, 275 { 276 NID_pbe_WithSHA1And128BitRC4, EVP_rc4, EVP_sha1, pkcs12_pbe_keyivgen, 277 }, 278 { 279 NID_pbe_WithSHA1And3_Key_TripleDES_CBC, EVP_des_ede3_cbc, EVP_sha1, 280 pkcs12_pbe_keyivgen, 281 }, 282 }; 283 284 static int pbe_cipher_init(ASN1_OBJECT *pbe_obj, 285 const uint8_t *pass_raw, size_t pass_raw_len, 286 ASN1_TYPE *param, 287 EVP_CIPHER_CTX *ctx, int is_encrypt) { 288 const EVP_CIPHER *cipher; 289 const EVP_MD *md; 290 unsigned i; 291 292 const struct pbe_suite *suite = NULL; 293 const int pbe_nid = OBJ_obj2nid(pbe_obj); 294 295 for (i = 0; i < sizeof(kBuiltinPBE) / sizeof(struct pbe_suite); i++) { 296 if (kBuiltinPBE[i].pbe_nid == pbe_nid) { 297 suite = &kBuiltinPBE[i]; 298 break; 299 } 300 } 301 302 if (suite == NULL) { 303 char obj_str[80]; 304 OPENSSL_PUT_ERROR(PKCS8, pbe_cipher_init, PKCS8_R_UNKNOWN_ALGORITHM); 305 if (!pbe_obj) { 306 strncpy(obj_str, "NULL", sizeof(obj_str)); 307 } else { 308 i2t_ASN1_OBJECT(obj_str, sizeof(obj_str), pbe_obj); 309 } 310 ERR_add_error_data(2, "TYPE=", obj_str); 311 return 0; 312 } 313 314 if (suite->cipher_func == NULL) { 315 cipher = NULL; 316 } else { 317 cipher = suite->cipher_func(); 318 if (!cipher) { 319 OPENSSL_PUT_ERROR(PKCS8, pbe_cipher_init, PKCS8_R_UNKNOWN_CIPHER); 320 return 0; 321 } 322 } 323 324 if (suite->md_func == NULL) { 325 md = NULL; 326 } else { 327 md = suite->md_func(); 328 if (!md) { 329 OPENSSL_PUT_ERROR(PKCS8, pbe_cipher_init, PKCS8_R_UNKNOWN_DIGEST); 330 return 0; 331 } 332 } 333 334 if (!suite->keygen(ctx, pass_raw, pass_raw_len, param, cipher, md, 335 is_encrypt)) { 336 OPENSSL_PUT_ERROR(PKCS8, pbe_cipher_init, PKCS8_R_KEYGEN_FAILURE); 337 return 0; 338 } 339 340 return 1; 341 } 342 343 static int pbe_crypt(const X509_ALGOR *algor, 344 const uint8_t *pass_raw, size_t pass_raw_len, 345 const uint8_t *in, size_t in_len, 346 uint8_t **out, size_t *out_len, 347 int is_encrypt) { 348 uint8_t *buf; 349 int n, ret = 0; 350 EVP_CIPHER_CTX ctx; 351 unsigned block_size; 352 353 EVP_CIPHER_CTX_init(&ctx); 354 355 if (!pbe_cipher_init(algor->algorithm, pass_raw, pass_raw_len, 356 algor->parameter, &ctx, is_encrypt)) { 357 OPENSSL_PUT_ERROR(PKCS8, pbe_crypt, PKCS8_R_UNKNOWN_CIPHER_ALGORITHM); 358 return 0; 359 } 360 block_size = EVP_CIPHER_CTX_block_size(&ctx); 361 362 if (in_len + block_size < in_len) { 363 OPENSSL_PUT_ERROR(PKCS8, pbe_crypt, PKCS8_R_TOO_LONG); 364 goto err; 365 } 366 367 buf = OPENSSL_malloc(in_len + block_size); 368 if (buf == NULL) { 369 OPENSSL_PUT_ERROR(PKCS8, pbe_crypt, ERR_R_MALLOC_FAILURE); 370 goto err; 371 } 372 373 if (!EVP_CipherUpdate(&ctx, buf, &n, in, in_len)) { 374 OPENSSL_free(buf); 375 OPENSSL_PUT_ERROR(PKCS8, pbe_crypt, ERR_R_EVP_LIB); 376 goto err; 377 } 378 *out_len = n; 379 380 if (!EVP_CipherFinal_ex(&ctx, buf + n, &n)) { 381 OPENSSL_free(buf); 382 OPENSSL_PUT_ERROR(PKCS8, pbe_crypt, ERR_R_EVP_LIB); 383 goto err; 384 } 385 *out_len += n; 386 *out = buf; 387 ret = 1; 388 389 err: 390 EVP_CIPHER_CTX_cleanup(&ctx); 391 return ret; 392 } 393 394 static void *pkcs12_item_decrypt_d2i(X509_ALGOR *algor, const ASN1_ITEM *it, 395 const uint8_t *pass_raw, 396 size_t pass_raw_len, 397 ASN1_OCTET_STRING *oct) { 398 uint8_t *out; 399 const uint8_t *p; 400 void *ret; 401 size_t out_len; 402 403 if (!pbe_crypt(algor, pass_raw, pass_raw_len, oct->data, oct->length, 404 &out, &out_len, 0 /* decrypt */)) { 405 OPENSSL_PUT_ERROR(PKCS8, pkcs12_item_decrypt_d2i, PKCS8_R_CRYPT_ERROR); 406 return NULL; 407 } 408 p = out; 409 ret = ASN1_item_d2i(NULL, &p, out_len, it); 410 OPENSSL_cleanse(out, out_len); 411 if (!ret) { 412 OPENSSL_PUT_ERROR(PKCS8, pkcs12_item_decrypt_d2i, PKCS8_R_DECODE_ERROR); 413 } 414 OPENSSL_free(out); 415 return ret; 416 } 417 418 PKCS8_PRIV_KEY_INFO *PKCS8_decrypt(X509_SIG *pkcs8, const char *pass, 419 int pass_len) { 420 uint8_t *pass_raw = NULL; 421 size_t pass_raw_len = 0; 422 PKCS8_PRIV_KEY_INFO *ret; 423 424 if (pass) { 425 if (pass_len == -1) { 426 pass_len = strlen(pass); 427 } 428 if (!ascii_to_ucs2(pass, pass_len, &pass_raw, &pass_raw_len)) { 429 OPENSSL_PUT_ERROR(PKCS8, pkcs12_key_gen_asc, PKCS8_R_DECODE_ERROR); 430 return NULL; 431 } 432 } 433 434 ret = PKCS8_decrypt_pbe(pkcs8, pass_raw, pass_raw_len); 435 436 if (pass_raw) { 437 OPENSSL_cleanse(pass_raw, pass_raw_len); 438 OPENSSL_free(pass_raw); 439 } 440 return ret; 441 } 442 443 PKCS8_PRIV_KEY_INFO *PKCS8_decrypt_pbe(X509_SIG *pkcs8, const uint8_t *pass_raw, 444 size_t pass_raw_len) { 445 return pkcs12_item_decrypt_d2i(pkcs8->algor, 446 ASN1_ITEM_rptr(PKCS8_PRIV_KEY_INFO), pass_raw, 447 pass_raw_len, pkcs8->digest); 448 } 449 450 static ASN1_OCTET_STRING *pkcs12_item_i2d_encrypt(X509_ALGOR *algor, 451 const ASN1_ITEM *it, 452 const uint8_t *pass_raw, 453 size_t pass_raw_len, void *obj) { 454 ASN1_OCTET_STRING *oct; 455 uint8_t *in = NULL; 456 int in_len; 457 size_t crypt_len; 458 459 oct = M_ASN1_OCTET_STRING_new(); 460 if (oct == NULL) { 461 OPENSSL_PUT_ERROR(PKCS8, pkcs12_item_i2d_encrypt, ERR_R_MALLOC_FAILURE); 462 return NULL; 463 } 464 in_len = ASN1_item_i2d(obj, &in, it); 465 if (!in) { 466 OPENSSL_PUT_ERROR(PKCS8, pkcs12_item_i2d_encrypt, PKCS8_R_ENCODE_ERROR); 467 return NULL; 468 } 469 if (!pbe_crypt(algor, pass_raw, pass_raw_len, in, in_len, &oct->data, &crypt_len, 470 1 /* encrypt */)) { 471 OPENSSL_PUT_ERROR(PKCS8, pkcs12_item_i2d_encrypt, PKCS8_R_ENCRYPT_ERROR); 472 OPENSSL_free(in); 473 return NULL; 474 } 475 oct->length = crypt_len; 476 OPENSSL_cleanse(in, in_len); 477 OPENSSL_free(in); 478 return oct; 479 } 480 481 X509_SIG *PKCS8_encrypt(int pbe_nid, const EVP_CIPHER *cipher, const char *pass, 482 int pass_len, uint8_t *salt, size_t salt_len, 483 int iterations, PKCS8_PRIV_KEY_INFO *p8inf) { 484 uint8_t *pass_raw = NULL; 485 size_t pass_raw_len = 0; 486 X509_SIG *ret; 487 488 if (pass) { 489 if (pass_len == -1) { 490 pass_len = strlen(pass); 491 } 492 if (!ascii_to_ucs2(pass, pass_len, &pass_raw, &pass_raw_len)) { 493 OPENSSL_PUT_ERROR(PKCS8, pkcs12_key_gen_asc, PKCS8_R_DECODE_ERROR); 494 return NULL; 495 } 496 } 497 498 ret = PKCS8_encrypt_pbe(pbe_nid, pass_raw, pass_raw_len, 499 salt, salt_len, iterations, p8inf); 500 501 if (pass_raw) { 502 OPENSSL_cleanse(pass_raw, pass_raw_len); 503 OPENSSL_free(pass_raw); 504 } 505 return ret; 506 } 507 508 X509_SIG *PKCS8_encrypt_pbe(int pbe_nid, 509 const uint8_t *pass_raw, size_t pass_raw_len, 510 uint8_t *salt, size_t salt_len, 511 int iterations, PKCS8_PRIV_KEY_INFO *p8inf) { 512 X509_SIG *pkcs8 = NULL; 513 X509_ALGOR *pbe; 514 515 pkcs8 = X509_SIG_new(); 516 if (pkcs8 == NULL) { 517 OPENSSL_PUT_ERROR(PKCS8, PKCS8_encrypt_pbe, ERR_R_MALLOC_FAILURE); 518 goto err; 519 } 520 521 pbe = PKCS5_pbe_set(pbe_nid, iterations, salt, salt_len); 522 if (!pbe) { 523 OPENSSL_PUT_ERROR(PKCS8, PKCS8_encrypt_pbe, ERR_R_ASN1_LIB); 524 goto err; 525 } 526 527 X509_ALGOR_free(pkcs8->algor); 528 pkcs8->algor = pbe; 529 M_ASN1_OCTET_STRING_free(pkcs8->digest); 530 pkcs8->digest = pkcs12_item_i2d_encrypt( 531 pbe, ASN1_ITEM_rptr(PKCS8_PRIV_KEY_INFO), pass_raw, pass_raw_len, p8inf); 532 if (!pkcs8->digest) { 533 OPENSSL_PUT_ERROR(PKCS8, PKCS8_encrypt_pbe, PKCS8_R_ENCRYPT_ERROR); 534 goto err; 535 } 536 537 return pkcs8; 538 539 err: 540 X509_SIG_free(pkcs8); 541 return NULL; 542 } 543 544 EVP_PKEY *EVP_PKCS82PKEY(PKCS8_PRIV_KEY_INFO *p8) { 545 EVP_PKEY *pkey = NULL; 546 ASN1_OBJECT *algoid; 547 char obj_tmp[80]; 548 549 if (!PKCS8_pkey_get0(&algoid, NULL, NULL, NULL, p8)) 550 return NULL; 551 552 pkey = EVP_PKEY_new(); 553 if (pkey == NULL) { 554 OPENSSL_PUT_ERROR(PKCS8, EVP_PKCS82PKEY, ERR_R_MALLOC_FAILURE); 555 return NULL; 556 } 557 558 if (!EVP_PKEY_set_type(pkey, OBJ_obj2nid(algoid))) { 559 OPENSSL_PUT_ERROR(PKCS8, EVP_PKCS82PKEY, 560 PKCS8_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM); 561 i2t_ASN1_OBJECT(obj_tmp, 80, algoid); 562 ERR_add_error_data(2, "TYPE=", obj_tmp); 563 goto error; 564 } 565 566 if (pkey->ameth->priv_decode) { 567 if (!pkey->ameth->priv_decode(pkey, p8)) { 568 OPENSSL_PUT_ERROR(PKCS8, EVP_PKCS82PKEY, PKCS8_R_PRIVATE_KEY_DECODE_ERROR); 569 goto error; 570 } 571 } else { 572 OPENSSL_PUT_ERROR(PKCS8, EVP_PKCS82PKEY, PKCS8_R_METHOD_NOT_SUPPORTED); 573 goto error; 574 } 575 576 return pkey; 577 578 error: 579 EVP_PKEY_free(pkey); 580 return NULL; 581 } 582 583 PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(EVP_PKEY *pkey) { 584 PKCS8_PRIV_KEY_INFO *p8; 585 586 p8 = PKCS8_PRIV_KEY_INFO_new(); 587 if (p8 == NULL) { 588 OPENSSL_PUT_ERROR(PKCS8, EVP_PKEY2PKCS8, ERR_R_MALLOC_FAILURE); 589 return NULL; 590 } 591 p8->broken = PKCS8_OK; 592 593 if (pkey->ameth) { 594 if (pkey->ameth->priv_encode) { 595 if (!pkey->ameth->priv_encode(p8, pkey)) { 596 OPENSSL_PUT_ERROR(PKCS8, EVP_PKEY2PKCS8, 597 PKCS8_R_PRIVATE_KEY_ENCODE_ERROR); 598 goto error; 599 } 600 } else { 601 OPENSSL_PUT_ERROR(PKCS8, EVP_PKEY2PKCS8, PKCS8_R_METHOD_NOT_SUPPORTED); 602 goto error; 603 } 604 } else { 605 OPENSSL_PUT_ERROR(PKCS8, EVP_PKEY2PKCS8, 606 PKCS8_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM); 607 goto error; 608 } 609 return p8; 610 611 error: 612 PKCS8_PRIV_KEY_INFO_free(p8); 613 return NULL; 614 } 615 616 struct pkcs12_context { 617 EVP_PKEY **out_key; 618 STACK_OF(X509) *out_certs; 619 uint8_t *password; 620 size_t password_len; 621 }; 622 623 static int PKCS12_handle_content_info(CBS *content_info, unsigned depth, 624 struct pkcs12_context *ctx); 625 626 /* PKCS12_handle_content_infos parses a series of PKCS#7 ContentInfos in a 627 * SEQUENCE. */ 628 static int PKCS12_handle_content_infos(CBS *content_infos, 629 unsigned depth, 630 struct pkcs12_context *ctx) { 631 uint8_t *der_bytes = NULL; 632 size_t der_len; 633 CBS in; 634 int ret = 0; 635 636 /* Generally we only expect depths 0 (the top level, with a 637 * pkcs7-encryptedData and a pkcs7-data) and depth 1 (the various PKCS#12 638 * bags). */ 639 if (depth > 3) { 640 OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_infos, 641 PKCS8_R_PKCS12_TOO_DEEPLY_NESTED); 642 return 0; 643 } 644 645 /* Although a BER->DER conversion is done at the beginning of |PKCS12_parse|, 646 * the ASN.1 data gets wrapped in OCTETSTRINGs and/or encrypted and the 647 * conversion cannot see through those wrappings. So each time we step 648 * through one we need to convert to DER again. */ 649 if (!CBS_asn1_ber_to_der(content_infos, &der_bytes, &der_len)) { 650 return 0; 651 } 652 653 if (der_bytes != NULL) { 654 CBS_init(&in, der_bytes, der_len); 655 } else { 656 CBS_init(&in, CBS_data(content_infos), CBS_len(content_infos)); 657 } 658 659 if (!CBS_get_asn1(&in, &in, CBS_ASN1_SEQUENCE)) { 660 OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_infos, 661 PKCS8_R_BAD_PKCS12_DATA); 662 goto err; 663 } 664 665 while (CBS_len(&in) > 0) { 666 CBS content_info; 667 if (!CBS_get_asn1(&in, &content_info, CBS_ASN1_SEQUENCE)) { 668 OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_infos, 669 PKCS8_R_BAD_PKCS12_DATA); 670 goto err; 671 } 672 673 if (!PKCS12_handle_content_info(&content_info, depth + 1, ctx)) { 674 goto err; 675 } 676 } 677 678 /* NSS includes additional data after the SEQUENCE, but it's an (unwrapped) 679 * copy of the same encrypted private key (with the same IV and 680 * ciphertext)! */ 681 682 ret = 1; 683 684 err: 685 if (der_bytes != NULL) { 686 OPENSSL_free(der_bytes); 687 } 688 return ret; 689 } 690 691 /* PKCS12_handle_content_info parses a single PKCS#7 ContentInfo element in a 692 * PKCS#12 structure. */ 693 static int PKCS12_handle_content_info(CBS *content_info, unsigned depth, 694 struct pkcs12_context *ctx) { 695 CBS content_type, wrapped_contents, contents, content_infos; 696 int nid, ret = 0; 697 698 if (!CBS_get_asn1(content_info, &content_type, CBS_ASN1_OBJECT) || 699 !CBS_get_asn1(content_info, &wrapped_contents, 700 CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0)) { 701 OPENSSL_PUT_ERROR(PKCS8, PKCS12_parse, PKCS8_R_BAD_PKCS12_DATA); 702 goto err; 703 } 704 705 nid = OBJ_cbs2nid(&content_type); 706 if (nid == NID_pkcs7_encrypted) { 707 /* See https://tools.ietf.org/html/rfc2315#section-13. 708 * 709 * PKCS#7 encrypted data inside a PKCS#12 structure is generally an 710 * encrypted certificate bag and it's generally encrypted with 40-bit 711 * RC2-CBC. */ 712 CBS version_bytes, eci, contents_type, ai, encrypted_contents; 713 X509_ALGOR *algor = NULL; 714 const uint8_t *inp; 715 uint8_t *out; 716 size_t out_len; 717 718 if (!CBS_get_asn1(&wrapped_contents, &contents, CBS_ASN1_SEQUENCE) || 719 !CBS_get_asn1(&contents, &version_bytes, CBS_ASN1_INTEGER) || 720 /* EncryptedContentInfo, see 721 * https://tools.ietf.org/html/rfc2315#section-10.1 */ 722 !CBS_get_asn1(&contents, &eci, CBS_ASN1_SEQUENCE) || 723 !CBS_get_asn1(&eci, &contents_type, CBS_ASN1_OBJECT) || 724 /* AlgorithmIdentifier, see 725 * https://tools.ietf.org/html/rfc5280#section-4.1.1.2 */ 726 !CBS_get_asn1_element(&eci, &ai, CBS_ASN1_SEQUENCE) || 727 !CBS_get_asn1(&eci, &encrypted_contents, 728 CBS_ASN1_CONTEXT_SPECIFIC | 0)) { 729 OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info, 730 PKCS8_R_BAD_PKCS12_DATA); 731 goto err; 732 } 733 734 if (OBJ_cbs2nid(&contents_type) != NID_pkcs7_data) { 735 OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info, 736 PKCS8_R_BAD_PKCS12_DATA); 737 goto err; 738 } 739 740 inp = CBS_data(&ai); 741 algor = d2i_X509_ALGOR(NULL, &inp, CBS_len(&ai)); 742 if (algor == NULL) { 743 goto err; 744 } 745 if (inp != CBS_data(&ai) + CBS_len(&ai)) { 746 X509_ALGOR_free(algor); 747 OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info, 748 PKCS8_R_BAD_PKCS12_DATA); 749 goto err; 750 } 751 752 if (!pbe_crypt(algor, ctx->password, ctx->password_len, 753 CBS_data(&encrypted_contents), CBS_len(&encrypted_contents), 754 &out, &out_len, 0 /* decrypt */)) { 755 X509_ALGOR_free(algor); 756 goto err; 757 } 758 X509_ALGOR_free(algor); 759 760 CBS_init(&content_infos, out, out_len); 761 ret = PKCS12_handle_content_infos(&content_infos, depth + 1, ctx); 762 OPENSSL_free(out); 763 } else if (nid == NID_pkcs7_data) { 764 CBS octet_string_contents; 765 766 if (!CBS_get_asn1(&wrapped_contents, &octet_string_contents, 767 CBS_ASN1_OCTETSTRING)) { 768 OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info, 769 PKCS8_R_BAD_PKCS12_DATA); 770 goto err; 771 } 772 773 ret = PKCS12_handle_content_infos(&octet_string_contents, depth + 1, ctx); 774 } else if (nid == NID_pkcs8ShroudedKeyBag) { 775 /* See ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12v1.pdf, section 776 * 4.2.2. */ 777 const uint8_t *inp = CBS_data(&wrapped_contents); 778 PKCS8_PRIV_KEY_INFO *pki = NULL; 779 X509_SIG *encrypted = NULL; 780 781 if (*ctx->out_key) { 782 OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info, 783 PKCS8_R_MULTIPLE_PRIVATE_KEYS_IN_PKCS12); 784 goto err; 785 } 786 787 /* encrypted isn't actually an X.509 signature, but it has the same 788 * structure as one and so |X509_SIG| is reused to store it. */ 789 encrypted = d2i_X509_SIG(NULL, &inp, CBS_len(&wrapped_contents)); 790 if (encrypted == NULL) { 791 OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info, 792 PKCS8_R_BAD_PKCS12_DATA); 793 goto err; 794 } 795 if (inp != CBS_data(&wrapped_contents) + CBS_len(&wrapped_contents)) { 796 OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info, 797 PKCS8_R_BAD_PKCS12_DATA); 798 X509_SIG_free(encrypted); 799 goto err; 800 } 801 802 pki = PKCS8_decrypt_pbe(encrypted, ctx->password, ctx->password_len); 803 X509_SIG_free(encrypted); 804 if (pki == NULL) { 805 goto err; 806 } 807 808 *ctx->out_key = EVP_PKCS82PKEY(pki); 809 PKCS8_PRIV_KEY_INFO_free(pki); 810 811 if (ctx->out_key == NULL) { 812 goto err; 813 } 814 ret = 1; 815 } else if (nid == NID_certBag) { 816 CBS cert_bag, cert_type, wrapped_cert, cert; 817 818 if (!CBS_get_asn1(&wrapped_contents, &cert_bag, CBS_ASN1_SEQUENCE) || 819 !CBS_get_asn1(&cert_bag, &cert_type, CBS_ASN1_OBJECT) || 820 !CBS_get_asn1(&cert_bag, &wrapped_cert, 821 CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) || 822 !CBS_get_asn1(&wrapped_cert, &cert, CBS_ASN1_OCTETSTRING)) { 823 OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info, 824 PKCS8_R_BAD_PKCS12_DATA); 825 goto err; 826 } 827 828 if (OBJ_cbs2nid(&cert_type) == NID_x509Certificate) { 829 const uint8_t *inp = CBS_data(&cert); 830 X509 *x509 = d2i_X509(NULL, &inp, CBS_len(&cert)); 831 if (!x509) { 832 OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info, 833 PKCS8_R_BAD_PKCS12_DATA); 834 goto err; 835 } 836 if (inp != CBS_data(&cert) + CBS_len(&cert)) { 837 OPENSSL_PUT_ERROR(PKCS8, PKCS12_handle_content_info, 838 PKCS8_R_BAD_PKCS12_DATA); 839 X509_free(x509); 840 goto err; 841 } 842 843 if (0 == sk_X509_push(ctx->out_certs, x509)) { 844 X509_free(x509); 845 goto err; 846 } 847 } 848 ret = 1; 849 } else { 850 /* Unknown element type - ignore it. */ 851 ret = 1; 852 } 853 854 err: 855 return ret; 856 } 857 858 int PKCS12_get_key_and_certs(EVP_PKEY **out_key, STACK_OF(X509) *out_certs, 859 CBS *ber_in, const char *password) { 860 uint8_t *der_bytes = NULL; 861 size_t der_len; 862 CBS in, pfx, mac_data, authsafe, content_type, wrapped_authsafes, authsafes; 863 uint64_t version; 864 int ret = 0; 865 struct pkcs12_context ctx; 866 const size_t original_out_certs_len = sk_X509_num(out_certs); 867 868 /* The input may be in BER format. */ 869 if (!CBS_asn1_ber_to_der(ber_in, &der_bytes, &der_len)) { 870 return 0; 871 } 872 if (der_bytes != NULL) { 873 CBS_init(&in, der_bytes, der_len); 874 } else { 875 CBS_init(&in, CBS_data(ber_in), CBS_len(ber_in)); 876 } 877 878 *out_key = NULL; 879 memset(&ctx, 0, sizeof(ctx)); 880 881 /* See ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12v1.pdf, section 882 * four. */ 883 if (!CBS_get_asn1(&in, &pfx, CBS_ASN1_SEQUENCE) || 884 CBS_len(&in) != 0 || 885 !CBS_get_asn1_uint64(&pfx, &version)) { 886 OPENSSL_PUT_ERROR(PKCS8, PKCS12_parse, PKCS8_R_BAD_PKCS12_DATA); 887 goto err; 888 } 889 890 if (version < 3) { 891 OPENSSL_PUT_ERROR(PKCS8, PKCS12_parse, PKCS8_R_BAD_PKCS12_VERSION); 892 goto err; 893 } 894 895 if (!CBS_get_asn1(&pfx, &authsafe, CBS_ASN1_SEQUENCE)) { 896 OPENSSL_PUT_ERROR(PKCS8, PKCS12_parse, PKCS8_R_BAD_PKCS12_DATA); 897 goto err; 898 } 899 900 if (CBS_len(&pfx) == 0) { 901 OPENSSL_PUT_ERROR(PKCS8, PKCS12_parse, PKCS8_R_MISSING_MAC); 902 goto err; 903 } 904 905 if (!CBS_get_asn1(&pfx, &mac_data, CBS_ASN1_SEQUENCE)) { 906 OPENSSL_PUT_ERROR(PKCS8, PKCS12_parse, PKCS8_R_BAD_PKCS12_DATA); 907 goto err; 908 } 909 910 /* authsafe is a PKCS#7 ContentInfo. See 911 * https://tools.ietf.org/html/rfc2315#section-7. */ 912 if (!CBS_get_asn1(&authsafe, &content_type, CBS_ASN1_OBJECT) || 913 !CBS_get_asn1(&authsafe, &wrapped_authsafes, 914 CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0)) { 915 OPENSSL_PUT_ERROR(PKCS8, PKCS12_parse, PKCS8_R_BAD_PKCS12_DATA); 916 goto err; 917 } 918 919 /* The content type can either be |NID_pkcs7_data| or |NID_pkcs7_signed|. The 920 * latter indicates that it's signed by a public key, which isn't 921 * supported. */ 922 if (OBJ_cbs2nid(&content_type) != NID_pkcs7_data) { 923 OPENSSL_PUT_ERROR(PKCS8, PKCS12_parse, 924 PKCS8_R_PKCS12_PUBLIC_KEY_INTEGRITY_NOT_SUPPORTED); 925 goto err; 926 } 927 928 if (!CBS_get_asn1(&wrapped_authsafes, &authsafes, CBS_ASN1_OCTETSTRING)) { 929 OPENSSL_PUT_ERROR(PKCS8, PKCS12_parse, PKCS8_R_BAD_PKCS12_DATA); 930 goto err; 931 } 932 933 ctx.out_key = out_key; 934 ctx.out_certs = out_certs; 935 if (!ascii_to_ucs2(password, strlen(password), &ctx.password, 936 &ctx.password_len)) { 937 OPENSSL_PUT_ERROR(PKCS8, PKCS12_parse, PKCS8_R_DECODE_ERROR); 938 goto err; 939 } 940 941 /* Verify the MAC. */ 942 { 943 CBS mac, hash_type_seq, hash_oid, salt, expected_mac; 944 uint64_t iterations; 945 int hash_nid; 946 const EVP_MD *md; 947 uint8_t hmac_key[EVP_MAX_MD_SIZE]; 948 uint8_t hmac[EVP_MAX_MD_SIZE]; 949 unsigned hmac_len; 950 951 if (!CBS_get_asn1(&mac_data, &mac, CBS_ASN1_SEQUENCE) || 952 !CBS_get_asn1(&mac, &hash_type_seq, CBS_ASN1_SEQUENCE) || 953 !CBS_get_asn1(&hash_type_seq, &hash_oid, CBS_ASN1_OBJECT) || 954 !CBS_get_asn1(&mac, &expected_mac, CBS_ASN1_OCTETSTRING) || 955 !CBS_get_asn1(&mac_data, &salt, CBS_ASN1_OCTETSTRING)) { 956 OPENSSL_PUT_ERROR(PKCS8, PKCS12_parse, PKCS8_R_BAD_PKCS12_DATA); 957 goto err; 958 } 959 960 /* The iteration count is optional and the default is one. */ 961 iterations = 1; 962 if (CBS_len(&mac_data) > 0) { 963 if (!CBS_get_asn1_uint64(&mac_data, &iterations) || 964 iterations > INT_MAX) { 965 OPENSSL_PUT_ERROR(PKCS8, PKCS12_parse, PKCS8_R_BAD_PKCS12_DATA); 966 goto err; 967 } 968 } 969 970 hash_nid = OBJ_cbs2nid(&hash_oid); 971 if (hash_nid == NID_undef || 972 (md = EVP_get_digestbynid(hash_nid)) == NULL) { 973 OPENSSL_PUT_ERROR(PKCS8, PKCS12_parse, PKCS8_R_UNKNOWN_HASH); 974 goto err; 975 } 976 977 if (!pkcs12_key_gen_raw(ctx.password, ctx.password_len, CBS_data(&salt), 978 CBS_len(&salt), PKCS12_MAC_ID, iterations, 979 EVP_MD_size(md), hmac_key, md)) { 980 goto err; 981 } 982 983 if (NULL == HMAC(md, hmac_key, EVP_MD_size(md), CBS_data(&authsafes), 984 CBS_len(&authsafes), hmac, &hmac_len)) { 985 goto err; 986 } 987 988 if (!CBS_mem_equal(&expected_mac, hmac, hmac_len)) { 989 OPENSSL_PUT_ERROR(PKCS8, PKCS12_parse, PKCS8_R_INCORRECT_PASSWORD); 990 goto err; 991 } 992 } 993 994 /* authsafes contains a series of PKCS#7 ContentInfos. */ 995 if (!PKCS12_handle_content_infos(&authsafes, 0, &ctx)) { 996 goto err; 997 } 998 999 ret = 1; 1000 1001 err: 1002 if (ctx.password) { 1003 OPENSSL_free(ctx.password); 1004 } 1005 if (der_bytes) { 1006 OPENSSL_free(der_bytes); 1007 } 1008 if (!ret) { 1009 if (*out_key) { 1010 EVP_PKEY_free(*out_key); 1011 *out_key = NULL; 1012 } 1013 while (sk_X509_num(out_certs) > original_out_certs_len) { 1014 X509 *x509 = sk_X509_pop(out_certs); 1015 X509_free(x509); 1016 } 1017 } 1018 1019 return ret; 1020 } 1021 1022 void PKCS12_PBE_add(){}; 1023 1024 struct pkcs12_st { 1025 uint8_t *ber_bytes; 1026 size_t ber_len; 1027 }; 1028 1029 PKCS12* d2i_PKCS12(PKCS12 **out_p12, const uint8_t **ber_bytes, size_t ber_len) { 1030 PKCS12 *p12; 1031 1032 /* out_p12 must be NULL because we don't export the PKCS12 structure. */ 1033 assert(out_p12 == NULL); 1034 1035 p12 = OPENSSL_malloc(sizeof(PKCS12)); 1036 if (!p12) { 1037 return NULL; 1038 } 1039 1040 p12->ber_bytes = OPENSSL_malloc(ber_len); 1041 if (!p12->ber_bytes) { 1042 OPENSSL_free(p12); 1043 return NULL; 1044 } 1045 1046 memcpy(p12->ber_bytes, *ber_bytes, ber_len); 1047 p12->ber_len = ber_len; 1048 *ber_bytes += ber_len; 1049 1050 return p12; 1051 } 1052 1053 PKCS12* d2i_PKCS12_bio(BIO *bio, PKCS12 **out_p12) { 1054 size_t used = 0; 1055 BUF_MEM *buf; 1056 const uint8_t *dummy; 1057 static const size_t kMaxSize = 256 * 1024; 1058 PKCS12 *ret = NULL; 1059 1060 buf = BUF_MEM_new(); 1061 if (buf == NULL) { 1062 return NULL; 1063 } 1064 if (BUF_MEM_grow(buf, 8192) == 0) { 1065 goto out; 1066 } 1067 1068 for (;;) { 1069 int n = BIO_read(bio, &buf->data[used], buf->length - used); 1070 if (n < 0) { 1071 goto out; 1072 } 1073 1074 if (n == 0) { 1075 break; 1076 } 1077 used += n; 1078 1079 if (used < buf->length) { 1080 continue; 1081 } 1082 1083 if (buf->length > kMaxSize || 1084 BUF_MEM_grow(buf, buf->length * 2) == 0) { 1085 goto out; 1086 } 1087 } 1088 1089 dummy = (uint8_t*) buf->data; 1090 ret = d2i_PKCS12(out_p12, &dummy, used); 1091 1092 out: 1093 BUF_MEM_free(buf); 1094 return ret; 1095 } 1096 1097 PKCS12* d2i_PKCS12_fp(FILE *fp, PKCS12 **out_p12) { 1098 BIO *bio; 1099 PKCS12 *ret; 1100 1101 bio = BIO_new_fp(fp, 0 /* don't take ownership */); 1102 if (!bio) { 1103 return NULL; 1104 } 1105 1106 ret = d2i_PKCS12_bio(bio, out_p12); 1107 BIO_free(bio); 1108 return ret; 1109 } 1110 1111 int PKCS12_parse(const PKCS12 *p12, const char *password, EVP_PKEY **out_pkey, 1112 X509 **out_cert, STACK_OF(X509) **out_ca_certs) { 1113 CBS ber_bytes; 1114 STACK_OF(X509) *ca_certs = NULL; 1115 char ca_certs_alloced = 0; 1116 1117 if (out_ca_certs != NULL && *out_ca_certs != NULL) { 1118 ca_certs = *out_ca_certs; 1119 } 1120 1121 if (!ca_certs) { 1122 ca_certs = sk_X509_new_null(); 1123 if (ca_certs == NULL) { 1124 return 0; 1125 } 1126 ca_certs_alloced = 1; 1127 } 1128 1129 CBS_init(&ber_bytes, p12->ber_bytes, p12->ber_len); 1130 if (!PKCS12_get_key_and_certs(out_pkey, ca_certs, &ber_bytes, password)) { 1131 if (ca_certs_alloced) { 1132 sk_X509_free(ca_certs); 1133 } 1134 return 0; 1135 } 1136 1137 *out_cert = NULL; 1138 if (sk_X509_num(ca_certs) > 0) { 1139 *out_cert = sk_X509_shift(ca_certs); 1140 } 1141 1142 if (out_ca_certs) { 1143 *out_ca_certs = ca_certs; 1144 } else { 1145 sk_X509_pop_free(ca_certs, X509_free); 1146 } 1147 1148 return 1; 1149 } 1150 1151 void PKCS12_free(PKCS12 *p12) { 1152 OPENSSL_free(p12->ber_bytes); 1153 OPENSSL_free(p12); 1154 } 1155