pkcs8.c 16 KB

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