You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1139 lines
31 KiB

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