pkcs8.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  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/buf.h>
  61. #include <openssl/bytestring.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/obj.h>
  68. #include <openssl/rand.h>
  69. #include <openssl/x509.h>
  70. #include "internal.h"
  71. #include "../internal.h"
  72. #include "../bytestring/internal.h"
  73. #define PKCS12_KEY_ID 1
  74. #define PKCS12_IV_ID 2
  75. #define PKCS12_MAC_ID 3
  76. static int ascii_to_ucs2(const char *ascii, size_t ascii_len,
  77. uint8_t **out, size_t *out_len) {
  78. size_t ulen = ascii_len * 2 + 2;
  79. if (ascii_len * 2 < ascii_len || ulen < ascii_len * 2) {
  80. return 0;
  81. }
  82. uint8_t *unitmp = OPENSSL_malloc(ulen);
  83. if (unitmp == NULL) {
  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. /* Terminate the result with a UCS-2 NUL. */
  91. unitmp[ulen - 2] = 0;
  92. unitmp[ulen - 1] = 0;
  93. *out_len = ulen;
  94. *out = unitmp;
  95. return 1;
  96. }
  97. static int pkcs12_key_gen_raw(const uint8_t *pass_raw, size_t pass_raw_len,
  98. const uint8_t *salt, size_t salt_len,
  99. uint8_t id, unsigned iterations,
  100. size_t out_len, uint8_t *out,
  101. 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. if (iterations < 1) {
  105. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_ITERATION_COUNT);
  106. return 0;
  107. }
  108. /* In the spec, |block_size| is called "v", but measured in bits. */
  109. size_t block_size = EVP_MD_block_size(md);
  110. /* 1. Construct a string, D (the "diversifier"), by concatenating v/8 copies
  111. * of ID. */
  112. uint8_t D[EVP_MAX_MD_BLOCK_SIZE];
  113. OPENSSL_memset(D, id, block_size);
  114. /* 2. Concatenate copies of the salt together to create a string S of length
  115. * v(ceiling(s/v)) bits (the final copy of the salt may be truncated to
  116. * create S). Note that if the salt is the empty string, then so is S.
  117. *
  118. * 3. Concatenate copies of the password together to create a string P of
  119. * length v(ceiling(p/v)) bits (the final copy of the password may be
  120. * truncated to create P). Note that if the password is the empty string,
  121. * then so is P.
  122. *
  123. * 4. Set I=S||P to be the concatenation of S and P. */
  124. if (salt_len + block_size - 1 < salt_len ||
  125. pass_raw_len + block_size - 1 < pass_raw_len) {
  126. OPENSSL_PUT_ERROR(PKCS8, ERR_R_OVERFLOW);
  127. return 0;
  128. }
  129. size_t S_len = block_size * ((salt_len + block_size - 1) / block_size);
  130. size_t P_len = block_size * ((pass_raw_len + block_size - 1) / block_size);
  131. size_t I_len = S_len + P_len;
  132. if (I_len < S_len) {
  133. OPENSSL_PUT_ERROR(PKCS8, ERR_R_OVERFLOW);
  134. return 0;
  135. }
  136. uint8_t *I = OPENSSL_malloc(I_len);
  137. if (I_len != 0 && I == NULL) {
  138. OPENSSL_PUT_ERROR(PKCS8, ERR_R_MALLOC_FAILURE);
  139. return 0;
  140. }
  141. for (size_t i = 0; i < S_len; i++) {
  142. I[i] = salt[i % salt_len];
  143. }
  144. for (size_t i = 0; i < P_len; i++) {
  145. I[i + S_len] = pass_raw[i % pass_raw_len];
  146. }
  147. int ret = 0;
  148. EVP_MD_CTX ctx;
  149. EVP_MD_CTX_init(&ctx);
  150. while (out_len != 0) {
  151. /* A. Set A_i=H^r(D||I). (i.e., the r-th hash of D||I,
  152. * H(H(H(... H(D||I)))) */
  153. uint8_t A[EVP_MAX_MD_SIZE];
  154. unsigned A_len;
  155. if (!EVP_DigestInit_ex(&ctx, md, NULL) ||
  156. !EVP_DigestUpdate(&ctx, D, block_size) ||
  157. !EVP_DigestUpdate(&ctx, I, I_len) ||
  158. !EVP_DigestFinal_ex(&ctx, A, &A_len)) {
  159. goto err;
  160. }
  161. for (unsigned iter = 1; iter < iterations; iter++) {
  162. if (!EVP_DigestInit_ex(&ctx, md, NULL) ||
  163. !EVP_DigestUpdate(&ctx, A, A_len) ||
  164. !EVP_DigestFinal_ex(&ctx, A, &A_len)) {
  165. goto err;
  166. }
  167. }
  168. size_t todo = out_len < A_len ? out_len : A_len;
  169. OPENSSL_memcpy(out, A, todo);
  170. out += todo;
  171. out_len -= todo;
  172. if (out_len == 0) {
  173. break;
  174. }
  175. /* B. Concatenate copies of A_i to create a string B of length v bits (the
  176. * final copy of A_i may be truncated to create B). */
  177. uint8_t B[EVP_MAX_MD_BLOCK_SIZE];
  178. for (size_t i = 0; i < block_size; i++) {
  179. B[i] = A[i % A_len];
  180. }
  181. /* C. Treating I as a concatenation I_0, I_1, ..., I_(k-1) of v-bit blocks,
  182. * where k=ceiling(s/v)+ceiling(p/v), modify I by setting I_j=(I_j+B+1) mod
  183. * 2^v for each j. */
  184. assert(I_len % block_size == 0);
  185. for (size_t i = 0; i < I_len; i += block_size) {
  186. unsigned carry = 1;
  187. for (size_t j = block_size - 1; j < block_size; j--) {
  188. carry += I[i + j] + B[j];
  189. I[i + j] = (uint8_t)carry;
  190. carry >>= 8;
  191. }
  192. }
  193. }
  194. ret = 1;
  195. err:
  196. OPENSSL_cleanse(I, I_len);
  197. OPENSSL_free(I);
  198. EVP_MD_CTX_cleanup(&ctx);
  199. return ret;
  200. }
  201. static int pkcs12_pbe_cipher_init(const struct pbe_suite *suite,
  202. EVP_CIPHER_CTX *ctx, unsigned iterations,
  203. const uint8_t *pass_raw, size_t pass_raw_len,
  204. const uint8_t *salt, size_t salt_len,
  205. int is_encrypt) {
  206. const EVP_CIPHER *cipher = suite->cipher_func();
  207. const EVP_MD *md = suite->md_func();
  208. uint8_t key[EVP_MAX_KEY_LENGTH];
  209. if (!pkcs12_key_gen_raw(pass_raw, pass_raw_len, salt,
  210. salt_len, PKCS12_KEY_ID, iterations,
  211. EVP_CIPHER_key_length(cipher), key, md)) {
  212. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_KEY_GEN_ERROR);
  213. return 0;
  214. }
  215. uint8_t iv[EVP_MAX_IV_LENGTH];
  216. if (!pkcs12_key_gen_raw(pass_raw, pass_raw_len, salt,
  217. salt_len, PKCS12_IV_ID, iterations,
  218. EVP_CIPHER_iv_length(cipher), iv, md)) {
  219. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_KEY_GEN_ERROR);
  220. return 0;
  221. }
  222. int ret = EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, is_encrypt);
  223. OPENSSL_cleanse(key, EVP_MAX_KEY_LENGTH);
  224. OPENSSL_cleanse(iv, EVP_MAX_IV_LENGTH);
  225. return ret;
  226. }
  227. static int pkcs12_pbe_decrypt_init(const struct pbe_suite *suite,
  228. EVP_CIPHER_CTX *ctx, const uint8_t *pass_raw,
  229. size_t pass_raw_len, CBS *param) {
  230. CBS pbe_param, salt;
  231. uint64_t iterations;
  232. if (!CBS_get_asn1(param, &pbe_param, CBS_ASN1_SEQUENCE) ||
  233. !CBS_get_asn1(&pbe_param, &salt, CBS_ASN1_OCTETSTRING) ||
  234. !CBS_get_asn1_uint64(&pbe_param, &iterations) ||
  235. CBS_len(&pbe_param) != 0 ||
  236. CBS_len(param) != 0) {
  237. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
  238. return 0;
  239. }
  240. if (iterations == 0 || iterations > UINT_MAX) {
  241. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_ITERATION_COUNT);
  242. return 0;
  243. }
  244. return pkcs12_pbe_cipher_init(suite, ctx, (unsigned)iterations, pass_raw,
  245. pass_raw_len, CBS_data(&salt), CBS_len(&salt),
  246. 0 /* decrypt */);
  247. }
  248. static const struct pbe_suite kBuiltinPBE[] = {
  249. {
  250. NID_pbe_WithSHA1And40BitRC2_CBC, EVP_rc2_40_cbc, EVP_sha1,
  251. pkcs12_pbe_decrypt_init, PBE_UCS2_CONVERT_PASSWORD,
  252. },
  253. {
  254. NID_pbe_WithSHA1And128BitRC4, EVP_rc4, EVP_sha1,
  255. pkcs12_pbe_decrypt_init, PBE_UCS2_CONVERT_PASSWORD,
  256. },
  257. {
  258. NID_pbe_WithSHA1And3_Key_TripleDES_CBC, EVP_des_ede3_cbc, EVP_sha1,
  259. pkcs12_pbe_decrypt_init, PBE_UCS2_CONVERT_PASSWORD,
  260. },
  261. {
  262. NID_pbes2, NULL, NULL, PKCS5_pbe2_decrypt_init, 0,
  263. },
  264. };
  265. static const struct pbe_suite *get_pbe_suite(int pbe_nid) {
  266. unsigned i;
  267. for (i = 0; i < OPENSSL_ARRAY_SIZE(kBuiltinPBE); i++) {
  268. if (kBuiltinPBE[i].pbe_nid == pbe_nid) {
  269. return &kBuiltinPBE[i];
  270. }
  271. }
  272. return NULL;
  273. }
  274. /* pass_to_pass_raw performs a password conversion (possibly a no-op)
  275. * appropriate to the supplied |pbe_nid|. The input |pass| is treated as a
  276. * NUL-terminated string if |pass_len| is -1, otherwise it is treated as a
  277. * buffer of the specified length. If the supplied PBE NID sets the
  278. * |PBE_UCS2_CONVERT_PASSWORD| flag, the supplied |pass| will be converted to
  279. * UCS-2.
  280. *
  281. * It sets |*out_pass_raw| to a new buffer that must be freed by the caller. It
  282. * returns one on success and zero on error. */
  283. static int pass_to_pass_raw(int pbe_nid, const char *pass, int pass_len,
  284. uint8_t **out_pass_raw, size_t *out_pass_raw_len) {
  285. if (pass == NULL) {
  286. *out_pass_raw = NULL;
  287. *out_pass_raw_len = 0;
  288. return 1;
  289. }
  290. if (pass_len == -1) {
  291. pass_len = strlen(pass);
  292. } else if (pass_len < 0 || pass_len > 2000000000) {
  293. OPENSSL_PUT_ERROR(PKCS8, ERR_R_OVERFLOW);
  294. return 0;
  295. }
  296. const struct pbe_suite *suite = get_pbe_suite(pbe_nid);
  297. if (suite != NULL && (suite->flags & PBE_UCS2_CONVERT_PASSWORD)) {
  298. if (!ascii_to_ucs2(pass, pass_len, out_pass_raw, out_pass_raw_len)) {
  299. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
  300. return 0;
  301. }
  302. } else {
  303. *out_pass_raw = BUF_memdup(pass, pass_len);
  304. if (*out_pass_raw == NULL) {
  305. OPENSSL_PUT_ERROR(PKCS8, ERR_R_MALLOC_FAILURE);
  306. return 0;
  307. }
  308. *out_pass_raw_len = (size_t)pass_len;
  309. }
  310. return 1;
  311. }
  312. static int pkcs12_pbe_encrypt_init(CBB *out, EVP_CIPHER_CTX *ctx, int alg,
  313. unsigned iterations, const uint8_t *pass_raw,
  314. size_t pass_raw_len, const uint8_t *salt,
  315. size_t salt_len) {
  316. const struct pbe_suite *suite = get_pbe_suite(alg);
  317. if (suite == NULL) {
  318. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNKNOWN_ALGORITHM);
  319. return 0;
  320. }
  321. /* See RFC 2898, appendix A.3. */
  322. CBB algorithm, param, salt_cbb;
  323. if (!CBB_add_asn1(out, &algorithm, CBS_ASN1_SEQUENCE) ||
  324. !OBJ_nid2cbb(&algorithm, alg) ||
  325. !CBB_add_asn1(&algorithm, &param, CBS_ASN1_SEQUENCE) ||
  326. !CBB_add_asn1(&param, &salt_cbb, CBS_ASN1_OCTETSTRING) ||
  327. !CBB_add_bytes(&salt_cbb, salt, salt_len) ||
  328. !CBB_add_asn1_uint64(&param, iterations) ||
  329. !CBB_flush(out)) {
  330. return 0;
  331. }
  332. return pkcs12_pbe_cipher_init(suite, ctx, iterations, pass_raw, pass_raw_len,
  333. salt, salt_len, 1 /* encrypt */);
  334. }
  335. static int pbe_decrypt(uint8_t **out, size_t *out_len, CBS *algorithm,
  336. const uint8_t *pass_raw, size_t pass_raw_len,
  337. const uint8_t *in, size_t in_len) {
  338. int ret = 0;
  339. uint8_t *buf = NULL;;
  340. EVP_CIPHER_CTX ctx;
  341. EVP_CIPHER_CTX_init(&ctx);
  342. CBS obj;
  343. if (!CBS_get_asn1(algorithm, &obj, CBS_ASN1_OBJECT)) {
  344. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
  345. goto err;
  346. }
  347. const struct pbe_suite *suite = get_pbe_suite(OBJ_cbs2nid(&obj));
  348. if (suite == NULL) {
  349. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNKNOWN_ALGORITHM);
  350. goto err;
  351. }
  352. if (!suite->decrypt_init(suite, &ctx, pass_raw, pass_raw_len, algorithm)) {
  353. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_KEYGEN_FAILURE);
  354. goto err;
  355. }
  356. buf = OPENSSL_malloc(in_len);
  357. if (buf == NULL) {
  358. OPENSSL_PUT_ERROR(PKCS8, ERR_R_MALLOC_FAILURE);
  359. goto err;
  360. }
  361. if (in_len > INT_MAX) {
  362. OPENSSL_PUT_ERROR(PKCS8, ERR_R_OVERFLOW);
  363. goto err;
  364. }
  365. int n1, n2;
  366. if (!EVP_DecryptUpdate(&ctx, buf, &n1, in, (int)in_len) ||
  367. !EVP_DecryptFinal_ex(&ctx, buf + n1, &n2)) {
  368. goto err;
  369. }
  370. *out = buf;
  371. *out_len = n1 + n2;
  372. ret = 1;
  373. buf = NULL;
  374. err:
  375. OPENSSL_free(buf);
  376. EVP_CIPHER_CTX_cleanup(&ctx);
  377. return ret;
  378. }
  379. static PKCS8_PRIV_KEY_INFO *pkcs8_decrypt_raw(X509_SIG *pkcs8,
  380. const uint8_t *pass_raw,
  381. size_t pass_raw_len) {
  382. PKCS8_PRIV_KEY_INFO *ret = NULL;
  383. uint8_t *in = NULL, *out = NULL;
  384. size_t out_len = 0;
  385. /* Convert the legacy ASN.1 object to a byte string. */
  386. int in_len = i2d_X509_SIG(pkcs8, &in);
  387. if (in_len < 0) {
  388. goto err;
  389. }
  390. /* See RFC 5208, section 6. */
  391. CBS cbs, epki, algorithm, ciphertext;
  392. CBS_init(&cbs, in, in_len);
  393. if (!CBS_get_asn1(&cbs, &epki, CBS_ASN1_SEQUENCE) ||
  394. !CBS_get_asn1(&epki, &algorithm, CBS_ASN1_SEQUENCE) ||
  395. !CBS_get_asn1(&epki, &ciphertext, CBS_ASN1_OCTETSTRING) ||
  396. CBS_len(&epki) != 0 ||
  397. CBS_len(&cbs) != 0) {
  398. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
  399. goto err;
  400. }
  401. if (!pbe_decrypt(&out, &out_len, &algorithm, pass_raw, pass_raw_len,
  402. CBS_data(&ciphertext), CBS_len(&ciphertext))) {
  403. goto err;
  404. }
  405. if (out_len > LONG_MAX) {
  406. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
  407. goto err;
  408. }
  409. /* Convert back to legacy ASN.1 objects. */
  410. const uint8_t *ptr = out;
  411. ret = d2i_PKCS8_PRIV_KEY_INFO(NULL, &ptr, (long)out_len);
  412. OPENSSL_cleanse(out, out_len);
  413. if (ret == NULL || ptr != out + out_len) {
  414. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
  415. PKCS8_PRIV_KEY_INFO_free(ret);
  416. ret = NULL;
  417. }
  418. err:
  419. OPENSSL_free(in);
  420. OPENSSL_cleanse(out, out_len);
  421. OPENSSL_free(out);
  422. return ret;
  423. }
  424. PKCS8_PRIV_KEY_INFO *PKCS8_decrypt(X509_SIG *pkcs8, const char *pass,
  425. int pass_len) {
  426. uint8_t *pass_raw = NULL;
  427. size_t pass_raw_len = 0;
  428. if (!pass_to_pass_raw(OBJ_obj2nid(pkcs8->algor->algorithm), pass, pass_len,
  429. &pass_raw, &pass_raw_len)) {
  430. return NULL;
  431. }
  432. PKCS8_PRIV_KEY_INFO *ret = pkcs8_decrypt_raw(pkcs8, pass_raw, pass_raw_len);
  433. if (pass_raw) {
  434. OPENSSL_cleanse(pass_raw, pass_raw_len);
  435. OPENSSL_free(pass_raw);
  436. }
  437. return ret;
  438. }
  439. static X509_SIG *pkcs8_encrypt_raw(int pbe_nid, const EVP_CIPHER *cipher,
  440. const uint8_t *pass_raw, size_t pass_raw_len,
  441. const uint8_t *salt, size_t salt_len,
  442. int iterations, PKCS8_PRIV_KEY_INFO *p8inf) {
  443. X509_SIG *ret = NULL;
  444. uint8_t *plaintext = NULL, *salt_buf = NULL, *der = NULL;
  445. int plaintext_len = -1;
  446. size_t der_len;
  447. CBB cbb;
  448. CBB_zero(&cbb);
  449. EVP_CIPHER_CTX ctx;
  450. EVP_CIPHER_CTX_init(&ctx);
  451. /* Generate a random salt if necessary. */
  452. if (salt == NULL) {
  453. if (salt_len == 0) {
  454. salt_len = PKCS5_SALT_LEN;
  455. }
  456. salt_buf = OPENSSL_malloc(salt_len);
  457. if (salt_buf == NULL ||
  458. !RAND_bytes(salt_buf, salt_len)) {
  459. goto err;
  460. }
  461. salt = salt_buf;
  462. }
  463. if (iterations <= 0) {
  464. iterations = PKCS5_DEFAULT_ITERATIONS;
  465. }
  466. /* Convert the input from the legacy ASN.1 format. */
  467. plaintext_len = i2d_PKCS8_PRIV_KEY_INFO(p8inf, &plaintext);
  468. if (plaintext_len < 0) {
  469. goto err;
  470. }
  471. CBB epki;
  472. if (!CBB_init(&cbb, 128) ||
  473. !CBB_add_asn1(&cbb, &epki, CBS_ASN1_SEQUENCE)) {
  474. goto err;
  475. }
  476. int alg_ok;
  477. if (pbe_nid == -1) {
  478. alg_ok = PKCS5_pbe2_encrypt_init(&epki, &ctx, cipher, (unsigned)iterations,
  479. pass_raw, pass_raw_len, salt, salt_len);
  480. } else {
  481. alg_ok = pkcs12_pbe_encrypt_init(&epki, &ctx, pbe_nid, (unsigned)iterations,
  482. pass_raw, pass_raw_len, salt, salt_len);
  483. }
  484. if (!alg_ok) {
  485. goto err;
  486. }
  487. size_t max_out = (size_t)plaintext_len + EVP_CIPHER_CTX_block_size(&ctx);
  488. if (max_out < (size_t)plaintext_len) {
  489. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_TOO_LONG);
  490. goto err;
  491. }
  492. CBB ciphertext;
  493. uint8_t *out;
  494. int n1, n2;
  495. if (!CBB_add_asn1(&epki, &ciphertext, CBS_ASN1_OCTETSTRING) ||
  496. !CBB_reserve(&ciphertext, &out, max_out) ||
  497. !EVP_CipherUpdate(&ctx, out, &n1, plaintext, plaintext_len) ||
  498. !EVP_CipherFinal_ex(&ctx, out + n1, &n2) ||
  499. !CBB_did_write(&ciphertext, n1 + n2) ||
  500. !CBB_finish(&cbb, &der, &der_len)) {
  501. goto err;
  502. }
  503. /* Convert back to legacy ASN.1 objects. */
  504. const uint8_t *ptr = der;
  505. ret = d2i_X509_SIG(NULL, &ptr, der_len);
  506. if (ret == NULL || ptr != der + der_len) {
  507. OPENSSL_PUT_ERROR(PKCS8, ERR_R_INTERNAL_ERROR);
  508. X509_SIG_free(ret);
  509. ret = NULL;
  510. }
  511. err:
  512. if (plaintext_len > 0) {
  513. OPENSSL_cleanse(plaintext, plaintext_len);
  514. }
  515. OPENSSL_free(plaintext);
  516. OPENSSL_free(salt_buf);
  517. OPENSSL_free(der);
  518. CBB_cleanup(&cbb);
  519. EVP_CIPHER_CTX_cleanup(&ctx);
  520. return ret;
  521. }
  522. X509_SIG *PKCS8_encrypt(int pbe_nid, const EVP_CIPHER *cipher, const char *pass,
  523. int pass_len, const uint8_t *salt, size_t salt_len,
  524. int iterations, PKCS8_PRIV_KEY_INFO *p8inf) {
  525. uint8_t *pass_raw = NULL;
  526. size_t pass_raw_len = 0;
  527. if (!pass_to_pass_raw(pbe_nid, pass, pass_len, &pass_raw, &pass_raw_len)) {
  528. return NULL;
  529. }
  530. X509_SIG *ret = pkcs8_encrypt_raw(pbe_nid, cipher, pass_raw, pass_raw_len,
  531. salt, salt_len, iterations, p8inf);
  532. if (pass_raw) {
  533. OPENSSL_cleanse(pass_raw, pass_raw_len);
  534. OPENSSL_free(pass_raw);
  535. }
  536. return ret;
  537. }
  538. EVP_PKEY *EVP_PKCS82PKEY(PKCS8_PRIV_KEY_INFO *p8) {
  539. uint8_t *der = NULL;
  540. int der_len = i2d_PKCS8_PRIV_KEY_INFO(p8, &der);
  541. if (der_len < 0) {
  542. return NULL;
  543. }
  544. CBS cbs;
  545. CBS_init(&cbs, der, (size_t)der_len);
  546. EVP_PKEY *ret = EVP_parse_private_key(&cbs);
  547. if (ret == NULL || CBS_len(&cbs) != 0) {
  548. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
  549. EVP_PKEY_free(ret);
  550. OPENSSL_free(der);
  551. return NULL;
  552. }
  553. OPENSSL_free(der);
  554. return ret;
  555. }
  556. PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(EVP_PKEY *pkey) {
  557. CBB cbb;
  558. uint8_t *der = NULL;
  559. size_t der_len;
  560. if (!CBB_init(&cbb, 0) ||
  561. !EVP_marshal_private_key(&cbb, pkey) ||
  562. !CBB_finish(&cbb, &der, &der_len) ||
  563. der_len > LONG_MAX) {
  564. CBB_cleanup(&cbb);
  565. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_ENCODE_ERROR);
  566. goto err;
  567. }
  568. const uint8_t *p = der;
  569. PKCS8_PRIV_KEY_INFO *p8 = d2i_PKCS8_PRIV_KEY_INFO(NULL, &p, (long)der_len);
  570. if (p8 == NULL || p != der + der_len) {
  571. PKCS8_PRIV_KEY_INFO_free(p8);
  572. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
  573. goto err;
  574. }
  575. OPENSSL_free(der);
  576. return p8;
  577. err:
  578. OPENSSL_free(der);
  579. return NULL;
  580. }
  581. struct pkcs12_context {
  582. EVP_PKEY **out_key;
  583. STACK_OF(X509) *out_certs;
  584. uint8_t *password;
  585. size_t password_len;
  586. };
  587. /* PKCS12_handle_sequence parses a BER-encoded SEQUENCE of elements in a PKCS#12
  588. * structure. */
  589. static int PKCS12_handle_sequence(
  590. CBS *sequence, struct pkcs12_context *ctx,
  591. int (*handle_element)(CBS *cbs, struct pkcs12_context *ctx)) {
  592. uint8_t *der_bytes = NULL;
  593. size_t der_len;
  594. CBS in;
  595. int ret = 0;
  596. /* Although a BER->DER conversion is done at the beginning of |PKCS12_parse|,
  597. * the ASN.1 data gets wrapped in OCTETSTRINGs and/or encrypted and the
  598. * conversion cannot see through those wrappings. So each time we step
  599. * through one we need to convert to DER again. */
  600. if (!CBS_asn1_ber_to_der(sequence, &der_bytes, &der_len)) {
  601. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  602. return 0;
  603. }
  604. if (der_bytes != NULL) {
  605. CBS_init(&in, der_bytes, der_len);
  606. } else {
  607. CBS_init(&in, CBS_data(sequence), CBS_len(sequence));
  608. }
  609. CBS child;
  610. if (!CBS_get_asn1(&in, &child, CBS_ASN1_SEQUENCE) ||
  611. CBS_len(&in) != 0) {
  612. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  613. goto err;
  614. }
  615. while (CBS_len(&child) > 0) {
  616. CBS element;
  617. if (!CBS_get_asn1(&child, &element, CBS_ASN1_SEQUENCE)) {
  618. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  619. goto err;
  620. }
  621. if (!handle_element(&element, ctx)) {
  622. goto err;
  623. }
  624. }
  625. ret = 1;
  626. err:
  627. OPENSSL_free(der_bytes);
  628. return ret;
  629. }
  630. /* PKCS12_handle_safe_bag parses a single SafeBag element in a PKCS#12
  631. * structure. */
  632. static int PKCS12_handle_safe_bag(CBS *safe_bag, struct pkcs12_context *ctx) {
  633. CBS bag_id, wrapped_value;
  634. if (!CBS_get_asn1(safe_bag, &bag_id, CBS_ASN1_OBJECT) ||
  635. !CBS_get_asn1(safe_bag, &wrapped_value,
  636. CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0)
  637. /* Ignore the bagAttributes field. */) {
  638. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  639. return 0;
  640. }
  641. int nid = OBJ_cbs2nid(&bag_id);
  642. if (nid == NID_pkcs8ShroudedKeyBag) {
  643. /* See RFC 7292, section 4.2.2. */
  644. if (*ctx->out_key) {
  645. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_MULTIPLE_PRIVATE_KEYS_IN_PKCS12);
  646. return 0;
  647. }
  648. if (CBS_len(&wrapped_value) > LONG_MAX) {
  649. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  650. return 0;
  651. }
  652. /* |encrypted| isn't actually an X.509 signature, but it has the same
  653. * structure as one and so |X509_SIG| is reused to store it. */
  654. const uint8_t *inp = CBS_data(&wrapped_value);
  655. X509_SIG *encrypted =
  656. d2i_X509_SIG(NULL, &inp, (long)CBS_len(&wrapped_value));
  657. if (encrypted == NULL) {
  658. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  659. return 0;
  660. }
  661. if (inp != CBS_data(&wrapped_value) + CBS_len(&wrapped_value)) {
  662. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  663. X509_SIG_free(encrypted);
  664. return 0;
  665. }
  666. PKCS8_PRIV_KEY_INFO *pki =
  667. pkcs8_decrypt_raw(encrypted, ctx->password, ctx->password_len);
  668. X509_SIG_free(encrypted);
  669. if (pki == NULL) {
  670. return 0;
  671. }
  672. *ctx->out_key = EVP_PKCS82PKEY(pki);
  673. PKCS8_PRIV_KEY_INFO_free(pki);
  674. return ctx->out_key != NULL;
  675. }
  676. if (nid == NID_certBag) {
  677. /* See RFC 7292, section 4.2.3. */
  678. CBS cert_bag, cert_type, wrapped_cert, cert;
  679. if (!CBS_get_asn1(&wrapped_value, &cert_bag, CBS_ASN1_SEQUENCE) ||
  680. !CBS_get_asn1(&cert_bag, &cert_type, CBS_ASN1_OBJECT) ||
  681. !CBS_get_asn1(&cert_bag, &wrapped_cert,
  682. CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
  683. !CBS_get_asn1(&wrapped_cert, &cert, CBS_ASN1_OCTETSTRING)) {
  684. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  685. return 0;
  686. }
  687. if (OBJ_cbs2nid(&cert_type) != NID_x509Certificate) {
  688. return 1;
  689. }
  690. if (CBS_len(&cert) > LONG_MAX) {
  691. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  692. return 0;
  693. }
  694. const uint8_t *inp = CBS_data(&cert);
  695. X509 *x509 = d2i_X509(NULL, &inp, (long)CBS_len(&cert));
  696. if (!x509) {
  697. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  698. return 0;
  699. }
  700. if (inp != CBS_data(&cert) + CBS_len(&cert)) {
  701. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  702. X509_free(x509);
  703. return 0;
  704. }
  705. if (0 == sk_X509_push(ctx->out_certs, x509)) {
  706. X509_free(x509);
  707. return 0;
  708. }
  709. return 1;
  710. }
  711. /* Unknown element type - ignore it. */
  712. return 1;
  713. }
  714. /* PKCS12_handle_content_info parses a single PKCS#7 ContentInfo element in a
  715. * PKCS#12 structure. */
  716. static int PKCS12_handle_content_info(CBS *content_info,
  717. struct pkcs12_context *ctx) {
  718. CBS content_type, wrapped_contents, contents;
  719. int nid, ret = 0;
  720. uint8_t *storage = NULL;
  721. if (!CBS_get_asn1(content_info, &content_type, CBS_ASN1_OBJECT) ||
  722. !CBS_get_asn1(content_info, &wrapped_contents,
  723. CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
  724. CBS_len(content_info) != 0) {
  725. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  726. goto err;
  727. }
  728. nid = OBJ_cbs2nid(&content_type);
  729. if (nid == NID_pkcs7_encrypted) {
  730. /* See https://tools.ietf.org/html/rfc2315#section-13.
  731. *
  732. * PKCS#7 encrypted data inside a PKCS#12 structure is generally an
  733. * encrypted certificate bag and it's generally encrypted with 40-bit
  734. * RC2-CBC. */
  735. CBS version_bytes, eci, contents_type, ai, encrypted_contents;
  736. uint8_t *out;
  737. size_t out_len;
  738. if (!CBS_get_asn1(&wrapped_contents, &contents, CBS_ASN1_SEQUENCE) ||
  739. !CBS_get_asn1(&contents, &version_bytes, CBS_ASN1_INTEGER) ||
  740. /* EncryptedContentInfo, see
  741. * https://tools.ietf.org/html/rfc2315#section-10.1 */
  742. !CBS_get_asn1(&contents, &eci, CBS_ASN1_SEQUENCE) ||
  743. !CBS_get_asn1(&eci, &contents_type, CBS_ASN1_OBJECT) ||
  744. /* AlgorithmIdentifier, see
  745. * https://tools.ietf.org/html/rfc5280#section-4.1.1.2 */
  746. !CBS_get_asn1(&eci, &ai, CBS_ASN1_SEQUENCE) ||
  747. !CBS_get_asn1_implicit_string(
  748. &eci, &encrypted_contents, &storage,
  749. CBS_ASN1_CONTEXT_SPECIFIC | 0, CBS_ASN1_OCTETSTRING)) {
  750. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  751. goto err;
  752. }
  753. if (OBJ_cbs2nid(&contents_type) != NID_pkcs7_data) {
  754. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  755. goto err;
  756. }
  757. if (!pbe_decrypt(&out, &out_len, &ai, ctx->password, ctx->password_len,
  758. CBS_data(&encrypted_contents),
  759. CBS_len(&encrypted_contents))) {
  760. goto err;
  761. }
  762. CBS safe_contents;
  763. CBS_init(&safe_contents, out, out_len);
  764. ret = PKCS12_handle_sequence(&safe_contents, ctx, PKCS12_handle_safe_bag);
  765. OPENSSL_free(out);
  766. } else if (nid == NID_pkcs7_data) {
  767. CBS octet_string_contents;
  768. if (!CBS_get_asn1(&wrapped_contents, &octet_string_contents,
  769. CBS_ASN1_OCTETSTRING)) {
  770. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  771. goto err;
  772. }
  773. ret = PKCS12_handle_sequence(&octet_string_contents, ctx,
  774. PKCS12_handle_safe_bag);
  775. } else {
  776. /* Unknown element type - ignore it. */
  777. ret = 1;
  778. }
  779. err:
  780. OPENSSL_free(storage);
  781. return ret;
  782. }
  783. int PKCS12_get_key_and_certs(EVP_PKEY **out_key, STACK_OF(X509) *out_certs,
  784. CBS *ber_in, const char *password) {
  785. uint8_t *der_bytes = NULL;
  786. size_t der_len;
  787. CBS in, pfx, mac_data, authsafe, content_type, wrapped_authsafes, authsafes;
  788. uint64_t version;
  789. int ret = 0;
  790. struct pkcs12_context ctx;
  791. const size_t original_out_certs_len = sk_X509_num(out_certs);
  792. /* The input may be in BER format. */
  793. if (!CBS_asn1_ber_to_der(ber_in, &der_bytes, &der_len)) {
  794. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  795. return 0;
  796. }
  797. if (der_bytes != NULL) {
  798. CBS_init(&in, der_bytes, der_len);
  799. } else {
  800. CBS_init(&in, CBS_data(ber_in), CBS_len(ber_in));
  801. }
  802. *out_key = NULL;
  803. OPENSSL_memset(&ctx, 0, sizeof(ctx));
  804. /* See ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12v1.pdf, section
  805. * four. */
  806. if (!CBS_get_asn1(&in, &pfx, CBS_ASN1_SEQUENCE) ||
  807. CBS_len(&in) != 0 ||
  808. !CBS_get_asn1_uint64(&pfx, &version)) {
  809. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  810. goto err;
  811. }
  812. if (version < 3) {
  813. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_VERSION);
  814. goto err;
  815. }
  816. if (!CBS_get_asn1(&pfx, &authsafe, CBS_ASN1_SEQUENCE)) {
  817. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  818. goto err;
  819. }
  820. if (CBS_len(&pfx) == 0) {
  821. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_MISSING_MAC);
  822. goto err;
  823. }
  824. if (!CBS_get_asn1(&pfx, &mac_data, CBS_ASN1_SEQUENCE)) {
  825. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  826. goto err;
  827. }
  828. /* authsafe is a PKCS#7 ContentInfo. See
  829. * https://tools.ietf.org/html/rfc2315#section-7. */
  830. if (!CBS_get_asn1(&authsafe, &content_type, CBS_ASN1_OBJECT) ||
  831. !CBS_get_asn1(&authsafe, &wrapped_authsafes,
  832. CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0)) {
  833. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  834. goto err;
  835. }
  836. /* The content type can either be |NID_pkcs7_data| or |NID_pkcs7_signed|. The
  837. * latter indicates that it's signed by a public key, which isn't
  838. * supported. */
  839. if (OBJ_cbs2nid(&content_type) != NID_pkcs7_data) {
  840. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_PKCS12_PUBLIC_KEY_INTEGRITY_NOT_SUPPORTED);
  841. goto err;
  842. }
  843. if (!CBS_get_asn1(&wrapped_authsafes, &authsafes, CBS_ASN1_OCTETSTRING)) {
  844. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  845. goto err;
  846. }
  847. ctx.out_key = out_key;
  848. ctx.out_certs = out_certs;
  849. if (!ascii_to_ucs2(password, password ? strlen(password) : 0, &ctx.password,
  850. &ctx.password_len)) {
  851. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_DECODE_ERROR);
  852. goto err;
  853. }
  854. /* Verify the MAC. */
  855. {
  856. CBS mac, hash_type_seq, hash_oid, salt, expected_mac;
  857. uint64_t iterations;
  858. int hash_nid;
  859. const EVP_MD *md;
  860. uint8_t hmac_key[EVP_MAX_MD_SIZE];
  861. uint8_t hmac[EVP_MAX_MD_SIZE];
  862. unsigned hmac_len;
  863. if (!CBS_get_asn1(&mac_data, &mac, CBS_ASN1_SEQUENCE) ||
  864. !CBS_get_asn1(&mac, &hash_type_seq, CBS_ASN1_SEQUENCE) ||
  865. !CBS_get_asn1(&hash_type_seq, &hash_oid, CBS_ASN1_OBJECT) ||
  866. !CBS_get_asn1(&mac, &expected_mac, CBS_ASN1_OCTETSTRING) ||
  867. !CBS_get_asn1(&mac_data, &salt, CBS_ASN1_OCTETSTRING)) {
  868. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  869. goto err;
  870. }
  871. /* The iteration count is optional and the default is one. */
  872. iterations = 1;
  873. if (CBS_len(&mac_data) > 0) {
  874. if (!CBS_get_asn1_uint64(&mac_data, &iterations) ||
  875. iterations > UINT_MAX) {
  876. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_BAD_PKCS12_DATA);
  877. goto err;
  878. }
  879. }
  880. hash_nid = OBJ_cbs2nid(&hash_oid);
  881. if (hash_nid == NID_undef ||
  882. (md = EVP_get_digestbynid(hash_nid)) == NULL) {
  883. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_UNKNOWN_HASH);
  884. goto err;
  885. }
  886. if (!pkcs12_key_gen_raw(ctx.password, ctx.password_len, CBS_data(&salt),
  887. CBS_len(&salt), PKCS12_MAC_ID, iterations,
  888. EVP_MD_size(md), hmac_key, md)) {
  889. goto err;
  890. }
  891. if (NULL == HMAC(md, hmac_key, EVP_MD_size(md), CBS_data(&authsafes),
  892. CBS_len(&authsafes), hmac, &hmac_len)) {
  893. goto err;
  894. }
  895. if (!CBS_mem_equal(&expected_mac, hmac, hmac_len)) {
  896. OPENSSL_PUT_ERROR(PKCS8, PKCS8_R_INCORRECT_PASSWORD);
  897. goto err;
  898. }
  899. }
  900. /* authsafes contains a series of PKCS#7 ContentInfos. */
  901. if (!PKCS12_handle_sequence(&authsafes, &ctx, PKCS12_handle_content_info)) {
  902. goto err;
  903. }
  904. ret = 1;
  905. err:
  906. OPENSSL_free(ctx.password);
  907. OPENSSL_free(der_bytes);
  908. if (!ret) {
  909. EVP_PKEY_free(*out_key);
  910. *out_key = NULL;
  911. while (sk_X509_num(out_certs) > original_out_certs_len) {
  912. X509 *x509 = sk_X509_pop(out_certs);
  913. X509_free(x509);
  914. }
  915. }
  916. return ret;
  917. }
  918. void PKCS12_PBE_add(void) {}
  919. struct pkcs12_st {
  920. uint8_t *ber_bytes;
  921. size_t ber_len;
  922. };
  923. PKCS12 *d2i_PKCS12(PKCS12 **out_p12, const uint8_t **ber_bytes,
  924. size_t ber_len) {
  925. PKCS12 *p12;
  926. p12 = OPENSSL_malloc(sizeof(PKCS12));
  927. if (!p12) {
  928. return NULL;
  929. }
  930. p12->ber_bytes = OPENSSL_malloc(ber_len);
  931. if (!p12->ber_bytes) {
  932. OPENSSL_free(p12);
  933. return NULL;
  934. }
  935. OPENSSL_memcpy(p12->ber_bytes, *ber_bytes, ber_len);
  936. p12->ber_len = ber_len;
  937. *ber_bytes += ber_len;
  938. if (out_p12) {
  939. PKCS12_free(*out_p12);
  940. *out_p12 = p12;
  941. }
  942. return p12;
  943. }
  944. PKCS12* d2i_PKCS12_bio(BIO *bio, PKCS12 **out_p12) {
  945. size_t used = 0;
  946. BUF_MEM *buf;
  947. const uint8_t *dummy;
  948. static const size_t kMaxSize = 256 * 1024;
  949. PKCS12 *ret = NULL;
  950. buf = BUF_MEM_new();
  951. if (buf == NULL) {
  952. return NULL;
  953. }
  954. if (BUF_MEM_grow(buf, 8192) == 0) {
  955. goto out;
  956. }
  957. for (;;) {
  958. int n = BIO_read(bio, &buf->data[used], buf->length - used);
  959. if (n < 0) {
  960. if (used == 0) {
  961. goto out;
  962. }
  963. /* Workaround a bug in node.js. It uses a memory BIO for this in the wrong
  964. * mode. */
  965. n = 0;
  966. }
  967. if (n == 0) {
  968. break;
  969. }
  970. used += n;
  971. if (used < buf->length) {
  972. continue;
  973. }
  974. if (buf->length > kMaxSize ||
  975. BUF_MEM_grow(buf, buf->length * 2) == 0) {
  976. goto out;
  977. }
  978. }
  979. dummy = (uint8_t*) buf->data;
  980. ret = d2i_PKCS12(out_p12, &dummy, used);
  981. out:
  982. BUF_MEM_free(buf);
  983. return ret;
  984. }
  985. PKCS12* d2i_PKCS12_fp(FILE *fp, PKCS12 **out_p12) {
  986. BIO *bio;
  987. PKCS12 *ret;
  988. bio = BIO_new_fp(fp, 0 /* don't take ownership */);
  989. if (!bio) {
  990. return NULL;
  991. }
  992. ret = d2i_PKCS12_bio(bio, out_p12);
  993. BIO_free(bio);
  994. return ret;
  995. }
  996. int PKCS12_parse(const PKCS12 *p12, const char *password, EVP_PKEY **out_pkey,
  997. X509 **out_cert, STACK_OF(X509) **out_ca_certs) {
  998. CBS ber_bytes;
  999. STACK_OF(X509) *ca_certs = NULL;
  1000. char ca_certs_alloced = 0;
  1001. if (out_ca_certs != NULL && *out_ca_certs != NULL) {
  1002. ca_certs = *out_ca_certs;
  1003. }
  1004. if (!ca_certs) {
  1005. ca_certs = sk_X509_new_null();
  1006. if (ca_certs == NULL) {
  1007. OPENSSL_PUT_ERROR(PKCS8, ERR_R_MALLOC_FAILURE);
  1008. return 0;
  1009. }
  1010. ca_certs_alloced = 1;
  1011. }
  1012. CBS_init(&ber_bytes, p12->ber_bytes, p12->ber_len);
  1013. if (!PKCS12_get_key_and_certs(out_pkey, ca_certs, &ber_bytes, password)) {
  1014. if (ca_certs_alloced) {
  1015. sk_X509_free(ca_certs);
  1016. }
  1017. return 0;
  1018. }
  1019. *out_cert = NULL;
  1020. if (sk_X509_num(ca_certs) > 0) {
  1021. *out_cert = sk_X509_shift(ca_certs);
  1022. }
  1023. if (out_ca_certs) {
  1024. *out_ca_certs = ca_certs;
  1025. } else {
  1026. sk_X509_pop_free(ca_certs, X509_free);
  1027. }
  1028. return 1;
  1029. }
  1030. int PKCS12_verify_mac(const PKCS12 *p12, const char *password,
  1031. int password_len) {
  1032. if (password == NULL) {
  1033. if (password_len != 0) {
  1034. return 0;
  1035. }
  1036. } else if (password_len != -1 &&
  1037. (password[password_len] != 0 ||
  1038. OPENSSL_memchr(password, 0, password_len) != NULL)) {
  1039. return 0;
  1040. }
  1041. EVP_PKEY *pkey = NULL;
  1042. X509 *cert = NULL;
  1043. if (!PKCS12_parse(p12, password, &pkey, &cert, NULL)) {
  1044. ERR_clear_error();
  1045. return 0;
  1046. }
  1047. EVP_PKEY_free(pkey);
  1048. X509_free(cert);
  1049. return 1;
  1050. }
  1051. void PKCS12_free(PKCS12 *p12) {
  1052. if (p12 == NULL) {
  1053. return;
  1054. }
  1055. OPENSSL_free(p12->ber_bytes);
  1056. OPENSSL_free(p12);
  1057. }