pem_lib.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. /* crypto/pem/pem_lib.c */
  2. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  3. * All rights reserved.
  4. *
  5. * This package is an SSL implementation written
  6. * by Eric Young (eay@cryptsoft.com).
  7. * The implementation was written so as to conform with Netscapes SSL.
  8. *
  9. * This library is free for commercial and non-commercial use as long as
  10. * the following conditions are aheared to. The following conditions
  11. * apply to all code found in this distribution, be it the RC4, RSA,
  12. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  13. * included with this distribution is covered by the same copyright terms
  14. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  15. *
  16. * Copyright remains Eric Young's, and as such any Copyright notices in
  17. * the code are not to be removed.
  18. * If this package is used in a product, Eric Young should be given attribution
  19. * as the author of the parts of the library used.
  20. * This can be in the form of a textual message at program startup or
  21. * in documentation (online or textual) provided with the package.
  22. *
  23. * Redistribution and use in source and binary forms, with or without
  24. * modification, are permitted provided that the following conditions
  25. * are met:
  26. * 1. Redistributions of source code must retain the copyright
  27. * notice, this list of conditions and the following disclaimer.
  28. * 2. Redistributions in binary form must reproduce the above copyright
  29. * notice, this list of conditions and the following disclaimer in the
  30. * documentation and/or other materials provided with the distribution.
  31. * 3. All advertising materials mentioning features or use of this software
  32. * must display the following acknowledgement:
  33. * "This product includes cryptographic software written by
  34. * Eric Young (eay@cryptsoft.com)"
  35. * The word 'cryptographic' can be left out if the rouines from the library
  36. * being used are not cryptographic related :-).
  37. * 4. If you include any Windows specific code (or a derivative thereof) from
  38. * the apps directory (application code) you must include an acknowledgement:
  39. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  40. *
  41. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  42. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  43. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  44. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  45. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  46. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  47. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  48. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  49. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  50. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  51. * SUCH DAMAGE.
  52. *
  53. * The licence and distribution terms for any publically available version or
  54. * derivative of this code cannot be changed. i.e. this code cannot simply be
  55. * copied and put under another distribution licence
  56. * [including the GNU Public Licence.]
  57. */
  58. #include <stdio.h>
  59. #include "cryptlib.h"
  60. #include <openssl/buffer.h>
  61. #include <openssl/objects.h>
  62. #include <openssl/evp.h>
  63. #include <openssl/rand.h>
  64. #include <openssl/x509.h>
  65. #include <openssl/pem.h>
  66. #include <openssl/pkcs12.h>
  67. #ifndef OPENSSL_NO_DES
  68. # include <openssl/des.h>
  69. #endif
  70. const char PEM_version[] = "PEM" OPENSSL_VERSION_PTEXT;
  71. #define MIN_LENGTH 4
  72. static int load_iv(char **fromp, unsigned char *to, int num);
  73. static int check_pem(const char *nm, const char *name);
  74. int PEM_def_callback(char *buf, int num, int w, void *key)
  75. {
  76. #ifdef OPENSSL_NO_FP_API
  77. /*
  78. * We should not ever call the default callback routine from windows.
  79. */
  80. PEMerr(PEM_F_PEM_DEF_CALLBACK, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  81. return (-1);
  82. #else
  83. int i, j;
  84. const char *prompt;
  85. if (key) {
  86. i = strlen(key);
  87. i = (i > num) ? num : i;
  88. memcpy(buf, key, i);
  89. return (i);
  90. }
  91. prompt = EVP_get_pw_prompt();
  92. if (prompt == NULL)
  93. prompt = "Enter PEM pass phrase:";
  94. for (;;) {
  95. i = EVP_read_pw_string(buf, num, prompt, w);
  96. if (i != 0) {
  97. PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
  98. memset(buf, 0, (unsigned int)num);
  99. return (-1);
  100. }
  101. j = strlen(buf);
  102. if (j < MIN_LENGTH) {
  103. fprintf(stderr,
  104. "phrase is too short, needs to be at least %d chars\n",
  105. MIN_LENGTH);
  106. } else
  107. break;
  108. }
  109. return (j);
  110. #endif
  111. }
  112. void PEM_proc_type(char *buf, int type)
  113. {
  114. const char *str;
  115. if (type == PEM_TYPE_ENCRYPTED)
  116. str = "ENCRYPTED";
  117. else if (type == PEM_TYPE_MIC_CLEAR)
  118. str = "MIC-CLEAR";
  119. else if (type == PEM_TYPE_MIC_ONLY)
  120. str = "MIC-ONLY";
  121. else
  122. str = "BAD-TYPE";
  123. BUF_strlcat(buf, "Proc-Type: 4,", PEM_BUFSIZE);
  124. BUF_strlcat(buf, str, PEM_BUFSIZE);
  125. BUF_strlcat(buf, "\n", PEM_BUFSIZE);
  126. }
  127. void PEM_dek_info(char *buf, const char *type, int len, char *str)
  128. {
  129. static const unsigned char map[17] = "0123456789ABCDEF";
  130. long i;
  131. int j;
  132. BUF_strlcat(buf, "DEK-Info: ", PEM_BUFSIZE);
  133. BUF_strlcat(buf, type, PEM_BUFSIZE);
  134. BUF_strlcat(buf, ",", PEM_BUFSIZE);
  135. j = strlen(buf);
  136. if (j + (len * 2) + 1 > PEM_BUFSIZE)
  137. return;
  138. for (i = 0; i < len; i++) {
  139. buf[j + i * 2] = map[(str[i] >> 4) & 0x0f];
  140. buf[j + i * 2 + 1] = map[(str[i]) & 0x0f];
  141. }
  142. buf[j + i * 2] = '\n';
  143. buf[j + i * 2 + 1] = '\0';
  144. }
  145. #ifndef OPENSSL_NO_FP_API
  146. void *PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x,
  147. pem_password_cb *cb, void *u)
  148. {
  149. BIO *b;
  150. void *ret;
  151. if ((b = BIO_new(BIO_s_file())) == NULL) {
  152. PEMerr(PEM_F_PEM_ASN1_READ, ERR_R_BUF_LIB);
  153. return (0);
  154. }
  155. BIO_set_fp(b, fp, BIO_NOCLOSE);
  156. ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u);
  157. BIO_free(b);
  158. return (ret);
  159. }
  160. #endif
  161. static int check_pem(const char *nm, const char *name)
  162. {
  163. /* Normal matching nm and name */
  164. if (!strcmp(nm, name))
  165. return 1;
  166. /* Make PEM_STRING_EVP_PKEY match any private key */
  167. if (!strcmp(nm, PEM_STRING_PKCS8) && !strcmp(name, PEM_STRING_EVP_PKEY))
  168. return 1;
  169. if (!strcmp(nm, PEM_STRING_PKCS8INF) &&
  170. !strcmp(name, PEM_STRING_EVP_PKEY))
  171. return 1;
  172. if (!strcmp(nm, PEM_STRING_RSA) && !strcmp(name, PEM_STRING_EVP_PKEY))
  173. return 1;
  174. if (!strcmp(nm, PEM_STRING_DSA) && !strcmp(name, PEM_STRING_EVP_PKEY))
  175. return 1;
  176. if (!strcmp(nm, PEM_STRING_ECPRIVATEKEY) &&
  177. !strcmp(name, PEM_STRING_EVP_PKEY))
  178. return 1;
  179. /* Permit older strings */
  180. if (!strcmp(nm, PEM_STRING_X509_OLD) && !strcmp(name, PEM_STRING_X509))
  181. return 1;
  182. if (!strcmp(nm, PEM_STRING_X509_REQ_OLD) &&
  183. !strcmp(name, PEM_STRING_X509_REQ))
  184. return 1;
  185. /* Allow normal certs to be read as trusted certs */
  186. if (!strcmp(nm, PEM_STRING_X509) &&
  187. !strcmp(name, PEM_STRING_X509_TRUSTED))
  188. return 1;
  189. if (!strcmp(nm, PEM_STRING_X509_OLD) &&
  190. !strcmp(name, PEM_STRING_X509_TRUSTED))
  191. return 1;
  192. /* Some CAs use PKCS#7 with CERTIFICATE headers */
  193. if (!strcmp(nm, PEM_STRING_X509) && !strcmp(name, PEM_STRING_PKCS7))
  194. return 1;
  195. if (!strcmp(nm, PEM_STRING_PKCS7_SIGNED) &&
  196. !strcmp(name, PEM_STRING_PKCS7))
  197. return 1;
  198. return 0;
  199. }
  200. int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
  201. const char *name, BIO *bp, pem_password_cb *cb,
  202. void *u)
  203. {
  204. EVP_CIPHER_INFO cipher;
  205. char *nm = NULL, *header = NULL;
  206. unsigned char *data = NULL;
  207. long len;
  208. int ret = 0;
  209. for (;;) {
  210. if (!PEM_read_bio(bp, &nm, &header, &data, &len)) {
  211. if (ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE)
  212. ERR_add_error_data(2, "Expecting: ", name);
  213. return 0;
  214. }
  215. if (check_pem(nm, name))
  216. break;
  217. OPENSSL_free(nm);
  218. OPENSSL_free(header);
  219. OPENSSL_free(data);
  220. }
  221. if (!PEM_get_EVP_CIPHER_INFO(header, &cipher))
  222. goto err;
  223. if (!PEM_do_header(&cipher, data, &len, cb, u))
  224. goto err;
  225. *pdata = data;
  226. *plen = len;
  227. if (pnm)
  228. *pnm = nm;
  229. ret = 1;
  230. err:
  231. if (!ret || !pnm)
  232. OPENSSL_free(nm);
  233. OPENSSL_free(header);
  234. if (!ret)
  235. OPENSSL_free(data);
  236. return ret;
  237. }
  238. #ifndef OPENSSL_NO_FP_API
  239. int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp,
  240. char *x, const EVP_CIPHER *enc, unsigned char *kstr,
  241. int klen, pem_password_cb *callback, void *u)
  242. {
  243. BIO *b;
  244. int ret;
  245. if ((b = BIO_new(BIO_s_file())) == NULL) {
  246. PEMerr(PEM_F_PEM_ASN1_WRITE, ERR_R_BUF_LIB);
  247. return (0);
  248. }
  249. BIO_set_fp(b, fp, BIO_NOCLOSE);
  250. ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u);
  251. BIO_free(b);
  252. return (ret);
  253. }
  254. #endif
  255. int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp,
  256. char *x, const EVP_CIPHER *enc, unsigned char *kstr,
  257. int klen, pem_password_cb *callback, void *u)
  258. {
  259. EVP_CIPHER_CTX ctx;
  260. int dsize = 0, i, j, ret = 0;
  261. unsigned char *p, *data = NULL;
  262. const char *objstr = NULL;
  263. char buf[PEM_BUFSIZE];
  264. unsigned char key[EVP_MAX_KEY_LENGTH];
  265. unsigned char iv[EVP_MAX_IV_LENGTH];
  266. if (enc != NULL) {
  267. objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc));
  268. if (objstr == NULL) {
  269. PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_UNSUPPORTED_CIPHER);
  270. goto err;
  271. }
  272. }
  273. if ((dsize = i2d(x, NULL)) < 0) {
  274. PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_ASN1_LIB);
  275. dsize = 0;
  276. goto err;
  277. }
  278. /* dzise + 8 bytes are needed */
  279. /* actually it needs the cipher block size extra... */
  280. data = (unsigned char *)OPENSSL_malloc((unsigned int)dsize + 20);
  281. if (data == NULL) {
  282. PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_MALLOC_FAILURE);
  283. goto err;
  284. }
  285. p = data;
  286. i = i2d(x, &p);
  287. if (enc != NULL) {
  288. if (kstr == NULL) {
  289. if (callback == NULL)
  290. klen = PEM_def_callback(buf, PEM_BUFSIZE, 1, u);
  291. else
  292. klen = (*callback) (buf, PEM_BUFSIZE, 1, u);
  293. if (klen <= 0) {
  294. PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_READ_KEY);
  295. goto err;
  296. }
  297. #ifdef CHARSET_EBCDIC
  298. /* Convert the pass phrase from EBCDIC */
  299. ebcdic2ascii(buf, buf, klen);
  300. #endif
  301. kstr = (unsigned char *)buf;
  302. }
  303. RAND_add(data, i, 0); /* put in the RSA key. */
  304. OPENSSL_assert(enc->iv_len <= (int)sizeof(iv));
  305. if (RAND_pseudo_bytes(iv, enc->iv_len) < 0) /* Generate a salt */
  306. goto err;
  307. /*
  308. * The 'iv' is used as the iv and as a salt. It is NOT taken from
  309. * the BytesToKey function
  310. */
  311. EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1, key, NULL);
  312. if (kstr == (unsigned char *)buf)
  313. OPENSSL_cleanse(buf, PEM_BUFSIZE);
  314. OPENSSL_assert(strlen(objstr) + 23 + 2 * enc->iv_len + 13 <=
  315. sizeof buf);
  316. buf[0] = '\0';
  317. PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
  318. PEM_dek_info(buf, objstr, enc->iv_len, (char *)iv);
  319. /* k=strlen(buf); */
  320. EVP_CIPHER_CTX_init(&ctx);
  321. EVP_EncryptInit_ex(&ctx, enc, NULL, key, iv);
  322. EVP_EncryptUpdate(&ctx, data, &j, data, i);
  323. EVP_EncryptFinal_ex(&ctx, &(data[j]), &i);
  324. EVP_CIPHER_CTX_cleanup(&ctx);
  325. i += j;
  326. ret = 1;
  327. } else {
  328. ret = 1;
  329. buf[0] = '\0';
  330. }
  331. i = PEM_write_bio(bp, name, buf, data, i);
  332. if (i <= 0)
  333. ret = 0;
  334. err:
  335. OPENSSL_cleanse(key, sizeof(key));
  336. OPENSSL_cleanse(iv, sizeof(iv));
  337. OPENSSL_cleanse((char *)&ctx, sizeof(ctx));
  338. OPENSSL_cleanse(buf, PEM_BUFSIZE);
  339. if (data != NULL) {
  340. OPENSSL_cleanse(data, (unsigned int)dsize);
  341. OPENSSL_free(data);
  342. }
  343. return (ret);
  344. }
  345. int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
  346. pem_password_cb *callback, void *u)
  347. {
  348. int i, j, o, klen;
  349. long len;
  350. EVP_CIPHER_CTX ctx;
  351. unsigned char key[EVP_MAX_KEY_LENGTH];
  352. char buf[PEM_BUFSIZE];
  353. len = *plen;
  354. if (cipher->cipher == NULL)
  355. return (1);
  356. if (callback == NULL)
  357. klen = PEM_def_callback(buf, PEM_BUFSIZE, 0, u);
  358. else
  359. klen = callback(buf, PEM_BUFSIZE, 0, u);
  360. if (klen <= 0) {
  361. PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_PASSWORD_READ);
  362. return (0);
  363. }
  364. #ifdef CHARSET_EBCDIC
  365. /* Convert the pass phrase from EBCDIC */
  366. ebcdic2ascii(buf, buf, klen);
  367. #endif
  368. EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
  369. (unsigned char *)buf, klen, 1, key, NULL);
  370. j = (int)len;
  371. EVP_CIPHER_CTX_init(&ctx);
  372. EVP_DecryptInit_ex(&ctx, cipher->cipher, NULL, key, &(cipher->iv[0]));
  373. EVP_DecryptUpdate(&ctx, data, &i, data, j);
  374. o = EVP_DecryptFinal_ex(&ctx, &(data[i]), &j);
  375. EVP_CIPHER_CTX_cleanup(&ctx);
  376. OPENSSL_cleanse((char *)buf, sizeof(buf));
  377. OPENSSL_cleanse((char *)key, sizeof(key));
  378. j += i;
  379. if (!o) {
  380. PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_DECRYPT);
  381. return (0);
  382. }
  383. *plen = j;
  384. return (1);
  385. }
  386. int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
  387. {
  388. const EVP_CIPHER *enc = NULL;
  389. char *p, c;
  390. char **header_pp = &header;
  391. cipher->cipher = NULL;
  392. if ((header == NULL) || (*header == '\0') || (*header == '\n'))
  393. return (1);
  394. if (strncmp(header, "Proc-Type: ", 11) != 0) {
  395. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_PROC_TYPE);
  396. return (0);
  397. }
  398. header += 11;
  399. if (*header != '4')
  400. return (0);
  401. header++;
  402. if (*header != ',')
  403. return (0);
  404. header++;
  405. if (strncmp(header, "ENCRYPTED", 9) != 0) {
  406. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_ENCRYPTED);
  407. return (0);
  408. }
  409. for (; (*header != '\n') && (*header != '\0'); header++) ;
  410. if (*header == '\0') {
  411. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_SHORT_HEADER);
  412. return (0);
  413. }
  414. header++;
  415. if (strncmp(header, "DEK-Info: ", 10) != 0) {
  416. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_DEK_INFO);
  417. return (0);
  418. }
  419. header += 10;
  420. p = header;
  421. for (;;) {
  422. c = *header;
  423. #ifndef CHARSET_EBCDIC
  424. if (!(((c >= 'A') && (c <= 'Z')) || (c == '-') ||
  425. ((c >= '0') && (c <= '9'))))
  426. break;
  427. #else
  428. if (!(isupper(c) || (c == '-') || isdigit(c)))
  429. break;
  430. #endif
  431. header++;
  432. }
  433. *header = '\0';
  434. cipher->cipher = enc = EVP_get_cipherbyname(p);
  435. *header = c;
  436. header++;
  437. if (enc == NULL) {
  438. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_UNSUPPORTED_ENCRYPTION);
  439. return (0);
  440. }
  441. if (!load_iv(header_pp, &(cipher->iv[0]), enc->iv_len))
  442. return (0);
  443. return (1);
  444. }
  445. static int load_iv(char **fromp, unsigned char *to, int num)
  446. {
  447. int v, i;
  448. char *from;
  449. from = *fromp;
  450. for (i = 0; i < num; i++)
  451. to[i] = 0;
  452. num *= 2;
  453. for (i = 0; i < num; i++) {
  454. if ((*from >= '0') && (*from <= '9'))
  455. v = *from - '0';
  456. else if ((*from >= 'A') && (*from <= 'F'))
  457. v = *from - 'A' + 10;
  458. else if ((*from >= 'a') && (*from <= 'f'))
  459. v = *from - 'a' + 10;
  460. else {
  461. PEMerr(PEM_F_LOAD_IV, PEM_R_BAD_IV_CHARS);
  462. return (0);
  463. }
  464. from++;
  465. to[i / 2] |= v << (long)((!(i & 1)) * 4);
  466. }
  467. *fromp = from;
  468. return (1);
  469. }
  470. #ifndef OPENSSL_NO_FP_API
  471. int PEM_write(FILE *fp, char *name, char *header, unsigned char *data,
  472. long len)
  473. {
  474. BIO *b;
  475. int ret;
  476. if ((b = BIO_new(BIO_s_file())) == NULL) {
  477. PEMerr(PEM_F_PEM_WRITE, ERR_R_BUF_LIB);
  478. return (0);
  479. }
  480. BIO_set_fp(b, fp, BIO_NOCLOSE);
  481. ret = PEM_write_bio(b, name, header, data, len);
  482. BIO_free(b);
  483. return (ret);
  484. }
  485. #endif
  486. int PEM_write_bio(BIO *bp, const char *name, char *header,
  487. unsigned char *data, long len)
  488. {
  489. int nlen, n, i, j, outl;
  490. unsigned char *buf = NULL;
  491. EVP_ENCODE_CTX ctx;
  492. int reason = ERR_R_BUF_LIB;
  493. EVP_EncodeInit(&ctx);
  494. nlen = strlen(name);
  495. if ((BIO_write(bp, "-----BEGIN ", 11) != 11) ||
  496. (BIO_write(bp, name, nlen) != nlen) ||
  497. (BIO_write(bp, "-----\n", 6) != 6))
  498. goto err;
  499. i = strlen(header);
  500. if (i > 0) {
  501. if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1))
  502. goto err;
  503. }
  504. buf = OPENSSL_malloc(PEM_BUFSIZE * 8);
  505. if (buf == NULL) {
  506. reason = ERR_R_MALLOC_FAILURE;
  507. goto err;
  508. }
  509. i = j = 0;
  510. while (len > 0) {
  511. n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
  512. EVP_EncodeUpdate(&ctx, buf, &outl, &(data[j]), n);
  513. if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl))
  514. goto err;
  515. i += outl;
  516. len -= n;
  517. j += n;
  518. }
  519. EVP_EncodeFinal(&ctx, buf, &outl);
  520. if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl))
  521. goto err;
  522. OPENSSL_cleanse(buf, PEM_BUFSIZE * 8);
  523. OPENSSL_free(buf);
  524. buf = NULL;
  525. if ((BIO_write(bp, "-----END ", 9) != 9) ||
  526. (BIO_write(bp, name, nlen) != nlen) ||
  527. (BIO_write(bp, "-----\n", 6) != 6))
  528. goto err;
  529. return (i + outl);
  530. err:
  531. if (buf) {
  532. OPENSSL_cleanse(buf, PEM_BUFSIZE * 8);
  533. OPENSSL_free(buf);
  534. }
  535. PEMerr(PEM_F_PEM_WRITE_BIO, reason);
  536. return (0);
  537. }
  538. #ifndef OPENSSL_NO_FP_API
  539. int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
  540. long *len)
  541. {
  542. BIO *b;
  543. int ret;
  544. if ((b = BIO_new(BIO_s_file())) == NULL) {
  545. PEMerr(PEM_F_PEM_READ, ERR_R_BUF_LIB);
  546. return (0);
  547. }
  548. BIO_set_fp(b, fp, BIO_NOCLOSE);
  549. ret = PEM_read_bio(b, name, header, data, len);
  550. BIO_free(b);
  551. return (ret);
  552. }
  553. #endif
  554. int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
  555. long *len)
  556. {
  557. EVP_ENCODE_CTX ctx;
  558. int end = 0, i, k, bl = 0, hl = 0, nohead = 0;
  559. char buf[256];
  560. BUF_MEM *nameB;
  561. BUF_MEM *headerB;
  562. BUF_MEM *dataB, *tmpB;
  563. nameB = BUF_MEM_new();
  564. headerB = BUF_MEM_new();
  565. dataB = BUF_MEM_new();
  566. if ((nameB == NULL) || (headerB == NULL) || (dataB == NULL)) {
  567. BUF_MEM_free(nameB);
  568. BUF_MEM_free(headerB);
  569. BUF_MEM_free(dataB);
  570. PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
  571. return (0);
  572. }
  573. buf[254] = '\0';
  574. for (;;) {
  575. i = BIO_gets(bp, buf, 254);
  576. if (i <= 0) {
  577. PEMerr(PEM_F_PEM_READ_BIO, PEM_R_NO_START_LINE);
  578. goto err;
  579. }
  580. while ((i >= 0) && (buf[i] <= ' '))
  581. i--;
  582. buf[++i] = '\n';
  583. buf[++i] = '\0';
  584. if (strncmp(buf, "-----BEGIN ", 11) == 0) {
  585. i = strlen(&(buf[11]));
  586. if (strncmp(&(buf[11 + i - 6]), "-----\n", 6) != 0)
  587. continue;
  588. if (!BUF_MEM_grow(nameB, i + 9)) {
  589. PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
  590. goto err;
  591. }
  592. memcpy(nameB->data, &(buf[11]), i - 6);
  593. nameB->data[i - 6] = '\0';
  594. break;
  595. }
  596. }
  597. hl = 0;
  598. if (!BUF_MEM_grow(headerB, 256)) {
  599. PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
  600. goto err;
  601. }
  602. headerB->data[0] = '\0';
  603. for (;;) {
  604. i = BIO_gets(bp, buf, 254);
  605. if (i <= 0)
  606. break;
  607. while ((i >= 0) && (buf[i] <= ' '))
  608. i--;
  609. buf[++i] = '\n';
  610. buf[++i] = '\0';
  611. if (buf[0] == '\n')
  612. break;
  613. if (!BUF_MEM_grow(headerB, hl + i + 9)) {
  614. PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
  615. goto err;
  616. }
  617. if (strncmp(buf, "-----END ", 9) == 0) {
  618. nohead = 1;
  619. break;
  620. }
  621. memcpy(&(headerB->data[hl]), buf, i);
  622. headerB->data[hl + i] = '\0';
  623. hl += i;
  624. }
  625. bl = 0;
  626. if (!BUF_MEM_grow(dataB, 1024)) {
  627. PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
  628. goto err;
  629. }
  630. dataB->data[0] = '\0';
  631. if (!nohead) {
  632. for (;;) {
  633. i = BIO_gets(bp, buf, 254);
  634. if (i <= 0)
  635. break;
  636. while ((i >= 0) && (buf[i] <= ' '))
  637. i--;
  638. buf[++i] = '\n';
  639. buf[++i] = '\0';
  640. if (i != 65)
  641. end = 1;
  642. if (strncmp(buf, "-----END ", 9) == 0)
  643. break;
  644. if (i > 65)
  645. break;
  646. if (!BUF_MEM_grow_clean(dataB, i + bl + 9)) {
  647. PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
  648. goto err;
  649. }
  650. memcpy(&(dataB->data[bl]), buf, i);
  651. dataB->data[bl + i] = '\0';
  652. bl += i;
  653. if (end) {
  654. buf[0] = '\0';
  655. i = BIO_gets(bp, buf, 254);
  656. if (i <= 0)
  657. break;
  658. while ((i >= 0) && (buf[i] <= ' '))
  659. i--;
  660. buf[++i] = '\n';
  661. buf[++i] = '\0';
  662. break;
  663. }
  664. }
  665. } else {
  666. tmpB = headerB;
  667. headerB = dataB;
  668. dataB = tmpB;
  669. bl = hl;
  670. }
  671. i = strlen(nameB->data);
  672. if ((strncmp(buf, "-----END ", 9) != 0) ||
  673. (strncmp(nameB->data, &(buf[9]), i) != 0) ||
  674. (strncmp(&(buf[9 + i]), "-----\n", 6) != 0)) {
  675. PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_END_LINE);
  676. goto err;
  677. }
  678. EVP_DecodeInit(&ctx);
  679. i = EVP_DecodeUpdate(&ctx,
  680. (unsigned char *)dataB->data, &bl,
  681. (unsigned char *)dataB->data, bl);
  682. if (i < 0) {
  683. PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_BASE64_DECODE);
  684. goto err;
  685. }
  686. i = EVP_DecodeFinal(&ctx, (unsigned char *)&(dataB->data[bl]), &k);
  687. if (i < 0) {
  688. PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_BASE64_DECODE);
  689. goto err;
  690. }
  691. bl += k;
  692. if (bl == 0)
  693. goto err;
  694. *name = nameB->data;
  695. *header = headerB->data;
  696. *data = (unsigned char *)dataB->data;
  697. *len = bl;
  698. OPENSSL_free(nameB);
  699. OPENSSL_free(headerB);
  700. OPENSSL_free(dataB);
  701. return (1);
  702. err:
  703. BUF_MEM_free(nameB);
  704. BUF_MEM_free(headerB);
  705. BUF_MEM_free(dataB);
  706. return (0);
  707. }