pem_lib.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  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. #include <assert.h>
  58. #include <ctype.h>
  59. #include <stdio.h>
  60. #include <string.h>
  61. #include <openssl/base64.h>
  62. #include <openssl/buf.h>
  63. #include <openssl/des.h>
  64. #include <openssl/err.h>
  65. #include <openssl/evp.h>
  66. #include <openssl/mem.h>
  67. #include <openssl/obj.h>
  68. #include <openssl/pem.h>
  69. #include <openssl/rand.h>
  70. #include <openssl/x509.h>
  71. #include "../evp/internal.h"
  72. #define MIN_LENGTH 4
  73. static int load_iv(char **fromp, unsigned char *to, int num);
  74. static int check_pem(const char *nm, const char *name);
  75. int pem_check_suffix(const char *pem_str, const char *suffix);
  76. void PEM_proc_type(char *buf, int type)
  77. {
  78. const char *str;
  79. if (type == PEM_TYPE_ENCRYPTED)
  80. str = "ENCRYPTED";
  81. else if (type == PEM_TYPE_MIC_CLEAR)
  82. str = "MIC-CLEAR";
  83. else if (type == PEM_TYPE_MIC_ONLY)
  84. str = "MIC-ONLY";
  85. else
  86. str = "BAD-TYPE";
  87. BUF_strlcat(buf, "Proc-Type: 4,", PEM_BUFSIZE);
  88. BUF_strlcat(buf, str, PEM_BUFSIZE);
  89. BUF_strlcat(buf, "\n", PEM_BUFSIZE);
  90. }
  91. void PEM_dek_info(char *buf, const char *type, int len, char *str)
  92. {
  93. static const unsigned char map[17] = "0123456789ABCDEF";
  94. long i;
  95. int j;
  96. BUF_strlcat(buf, "DEK-Info: ", PEM_BUFSIZE);
  97. BUF_strlcat(buf, type, PEM_BUFSIZE);
  98. BUF_strlcat(buf, ",", PEM_BUFSIZE);
  99. j = strlen(buf);
  100. if (j + (len * 2) + 1 > PEM_BUFSIZE)
  101. return;
  102. for (i = 0; i < len; i++) {
  103. buf[j + i * 2] = map[(str[i] >> 4) & 0x0f];
  104. buf[j + i * 2 + 1] = map[(str[i]) & 0x0f];
  105. }
  106. buf[j + i * 2] = '\n';
  107. buf[j + i * 2 + 1] = '\0';
  108. }
  109. #ifndef OPENSSL_NO_FP_API
  110. void *PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x,
  111. pem_password_cb *cb, void *u)
  112. {
  113. BIO *b;
  114. void *ret;
  115. if ((b = BIO_new(BIO_s_file())) == NULL) {
  116. OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB);
  117. return (0);
  118. }
  119. BIO_set_fp(b, fp, BIO_NOCLOSE);
  120. ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u);
  121. BIO_free(b);
  122. return (ret);
  123. }
  124. #endif
  125. static int check_pem(const char *nm, const char *name)
  126. {
  127. /* Normal matching nm and name */
  128. if (!strcmp(nm, name))
  129. return 1;
  130. /* Make PEM_STRING_EVP_PKEY match any private key */
  131. if (!strcmp(name, PEM_STRING_EVP_PKEY)) {
  132. int slen;
  133. const EVP_PKEY_ASN1_METHOD *ameth;
  134. if (!strcmp(nm, PEM_STRING_PKCS8))
  135. return 1;
  136. if (!strcmp(nm, PEM_STRING_PKCS8INF))
  137. return 1;
  138. slen = pem_check_suffix(nm, "PRIVATE KEY");
  139. if (slen > 0) {
  140. /*
  141. * NB: ENGINE implementations wont contain a deprecated old
  142. * private key decode function so don't look for them.
  143. */
  144. ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen);
  145. if (ameth && ameth->old_priv_decode)
  146. return 1;
  147. }
  148. return 0;
  149. }
  150. /* Permit older strings */
  151. if (!strcmp(nm, PEM_STRING_X509_OLD) && !strcmp(name, PEM_STRING_X509))
  152. return 1;
  153. if (!strcmp(nm, PEM_STRING_X509_REQ_OLD) &&
  154. !strcmp(name, PEM_STRING_X509_REQ))
  155. return 1;
  156. /* Allow normal certs to be read as trusted certs */
  157. if (!strcmp(nm, PEM_STRING_X509) &&
  158. !strcmp(name, PEM_STRING_X509_TRUSTED))
  159. return 1;
  160. if (!strcmp(nm, PEM_STRING_X509_OLD) &&
  161. !strcmp(name, PEM_STRING_X509_TRUSTED))
  162. return 1;
  163. /* Some CAs use PKCS#7 with CERTIFICATE headers */
  164. if (!strcmp(nm, PEM_STRING_X509) && !strcmp(name, PEM_STRING_PKCS7))
  165. return 1;
  166. if (!strcmp(nm, PEM_STRING_PKCS7_SIGNED) &&
  167. !strcmp(name, PEM_STRING_PKCS7))
  168. return 1;
  169. #ifndef OPENSSL_NO_CMS
  170. if (!strcmp(nm, PEM_STRING_X509) && !strcmp(name, PEM_STRING_CMS))
  171. return 1;
  172. /* Allow CMS to be read from PKCS#7 headers */
  173. if (!strcmp(nm, PEM_STRING_PKCS7) && !strcmp(name, PEM_STRING_CMS))
  174. return 1;
  175. #endif
  176. return 0;
  177. }
  178. int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
  179. const char *name, BIO *bp, pem_password_cb *cb,
  180. void *u)
  181. {
  182. EVP_CIPHER_INFO cipher;
  183. char *nm = NULL, *header = NULL;
  184. unsigned char *data = NULL;
  185. long len;
  186. int ret = 0;
  187. for (;;) {
  188. if (!PEM_read_bio(bp, &nm, &header, &data, &len)) {
  189. if (ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE)
  190. ERR_add_error_data(2, "Expecting: ", name);
  191. return 0;
  192. }
  193. if (check_pem(nm, name))
  194. break;
  195. OPENSSL_free(nm);
  196. OPENSSL_free(header);
  197. OPENSSL_free(data);
  198. }
  199. if (!PEM_get_EVP_CIPHER_INFO(header, &cipher))
  200. goto err;
  201. if (!PEM_do_header(&cipher, data, &len, cb, u))
  202. goto err;
  203. *pdata = data;
  204. *plen = len;
  205. if (pnm)
  206. *pnm = nm;
  207. ret = 1;
  208. err:
  209. if (!ret || !pnm)
  210. OPENSSL_free(nm);
  211. OPENSSL_free(header);
  212. if (!ret)
  213. OPENSSL_free(data);
  214. return ret;
  215. }
  216. #ifndef OPENSSL_NO_FP_API
  217. int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp,
  218. void *x, const EVP_CIPHER *enc, unsigned char *kstr,
  219. int klen, pem_password_cb *callback, void *u)
  220. {
  221. BIO *b;
  222. int ret;
  223. if ((b = BIO_new(BIO_s_file())) == NULL) {
  224. OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB);
  225. return (0);
  226. }
  227. BIO_set_fp(b, fp, BIO_NOCLOSE);
  228. ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u);
  229. BIO_free(b);
  230. return (ret);
  231. }
  232. #endif
  233. int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp,
  234. void *x, const EVP_CIPHER *enc, unsigned char *kstr,
  235. int klen, pem_password_cb *callback, void *u)
  236. {
  237. EVP_CIPHER_CTX ctx;
  238. int dsize = 0, i, j, ret = 0;
  239. unsigned char *p, *data = NULL;
  240. const char *objstr = NULL;
  241. char buf[PEM_BUFSIZE];
  242. unsigned char key[EVP_MAX_KEY_LENGTH];
  243. unsigned char iv[EVP_MAX_IV_LENGTH];
  244. if (enc != NULL) {
  245. objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc));
  246. if (objstr == NULL) {
  247. OPENSSL_PUT_ERROR(PEM, PEM_R_UNSUPPORTED_CIPHER);
  248. goto err;
  249. }
  250. }
  251. if ((dsize = i2d(x, NULL)) < 0) {
  252. OPENSSL_PUT_ERROR(PEM, ERR_R_ASN1_LIB);
  253. dsize = 0;
  254. goto err;
  255. }
  256. /* dzise + 8 bytes are needed */
  257. /* actually it needs the cipher block size extra... */
  258. data = (unsigned char *)OPENSSL_malloc((unsigned int)dsize + 20);
  259. if (data == NULL) {
  260. OPENSSL_PUT_ERROR(PEM, ERR_R_MALLOC_FAILURE);
  261. goto err;
  262. }
  263. p = data;
  264. i = i2d(x, &p);
  265. if (enc != NULL) {
  266. const unsigned iv_len = EVP_CIPHER_iv_length(enc);
  267. if (kstr == NULL) {
  268. klen = 0;
  269. if (!callback)
  270. callback = PEM_def_callback;
  271. klen = (*callback) (buf, PEM_BUFSIZE, 1, u);
  272. if (klen <= 0) {
  273. OPENSSL_PUT_ERROR(PEM, PEM_R_READ_KEY);
  274. goto err;
  275. }
  276. kstr = (unsigned char *)buf;
  277. }
  278. assert(iv_len <= (int)sizeof(iv));
  279. if (!RAND_bytes(iv, iv_len)) /* Generate a salt */
  280. goto err;
  281. /*
  282. * The 'iv' is used as the iv and as a salt. It is NOT taken from
  283. * the BytesToKey function
  284. */
  285. if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1, key, NULL))
  286. goto err;
  287. if (kstr == (unsigned char *)buf)
  288. OPENSSL_cleanse(buf, PEM_BUFSIZE);
  289. assert(strlen(objstr) + 23 + 2 * iv_len + 13 <= sizeof buf);
  290. buf[0] = '\0';
  291. PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
  292. PEM_dek_info(buf, objstr, iv_len, (char *)iv);
  293. /* k=strlen(buf); */
  294. EVP_CIPHER_CTX_init(&ctx);
  295. ret = 1;
  296. if (!EVP_EncryptInit_ex(&ctx, enc, NULL, key, iv)
  297. || !EVP_EncryptUpdate(&ctx, data, &j, data, i)
  298. || !EVP_EncryptFinal_ex(&ctx, &(data[j]), &i))
  299. ret = 0;
  300. else
  301. i += j;
  302. EVP_CIPHER_CTX_cleanup(&ctx);
  303. if (ret == 0)
  304. goto err;
  305. } else {
  306. ret = 1;
  307. buf[0] = '\0';
  308. }
  309. i = PEM_write_bio(bp, name, buf, data, i);
  310. if (i <= 0)
  311. ret = 0;
  312. err:
  313. OPENSSL_cleanse(key, sizeof(key));
  314. OPENSSL_cleanse(iv, sizeof(iv));
  315. OPENSSL_cleanse((char *)&ctx, sizeof(ctx));
  316. OPENSSL_cleanse(buf, PEM_BUFSIZE);
  317. if (data != NULL) {
  318. OPENSSL_cleanse(data, (unsigned int)dsize);
  319. OPENSSL_free(data);
  320. }
  321. return (ret);
  322. }
  323. int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
  324. pem_password_cb *callback, void *u)
  325. {
  326. int i = 0, j, o, klen;
  327. long len;
  328. EVP_CIPHER_CTX ctx;
  329. unsigned char key[EVP_MAX_KEY_LENGTH];
  330. char buf[PEM_BUFSIZE];
  331. len = *plen;
  332. if (cipher->cipher == NULL)
  333. return (1);
  334. klen = 0;
  335. if (!callback)
  336. callback = PEM_def_callback;
  337. klen = callback(buf, PEM_BUFSIZE, 0, u);
  338. if (klen <= 0) {
  339. OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_PASSWORD_READ);
  340. return (0);
  341. }
  342. if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
  343. (unsigned char *)buf, klen, 1, key, NULL))
  344. return 0;
  345. j = (int)len;
  346. EVP_CIPHER_CTX_init(&ctx);
  347. o = EVP_DecryptInit_ex(&ctx, cipher->cipher, NULL, key, &(cipher->iv[0]));
  348. if (o)
  349. o = EVP_DecryptUpdate(&ctx, data, &i, data, j);
  350. if (o)
  351. o = EVP_DecryptFinal_ex(&ctx, &(data[i]), &j);
  352. EVP_CIPHER_CTX_cleanup(&ctx);
  353. OPENSSL_cleanse((char *)buf, sizeof(buf));
  354. OPENSSL_cleanse((char *)key, sizeof(key));
  355. if (!o) {
  356. OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_DECRYPT);
  357. return (0);
  358. }
  359. j += i;
  360. *plen = j;
  361. return (1);
  362. }
  363. static const EVP_CIPHER *cipher_by_name(const char *name)
  364. {
  365. /* This is similar to the (deprecated) function |EVP_get_cipherbyname|. */
  366. if (0 == strcmp(name, SN_rc4)) {
  367. return EVP_rc4();
  368. } else if (0 == strcmp(name, SN_des_cbc)) {
  369. return EVP_des_cbc();
  370. } else if (0 == strcmp(name, SN_des_ede3_cbc)) {
  371. return EVP_des_ede3_cbc();
  372. } else if (0 == strcmp(name, SN_aes_128_cbc)) {
  373. return EVP_aes_128_cbc();
  374. } else if (0 == strcmp(name, SN_aes_192_cbc)) {
  375. return EVP_aes_192_cbc();
  376. } else if (0 == strcmp(name, SN_aes_256_cbc)) {
  377. return EVP_aes_256_cbc();
  378. } else {
  379. return NULL;
  380. }
  381. }
  382. int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
  383. {
  384. const EVP_CIPHER *enc = NULL;
  385. char *p, c;
  386. char **header_pp = &header;
  387. cipher->cipher = NULL;
  388. if ((header == NULL) || (*header == '\0') || (*header == '\n'))
  389. return (1);
  390. if (strncmp(header, "Proc-Type: ", 11) != 0) {
  391. OPENSSL_PUT_ERROR(PEM, PEM_R_NOT_PROC_TYPE);
  392. return (0);
  393. }
  394. header += 11;
  395. if (*header != '4')
  396. return (0);
  397. header++;
  398. if (*header != ',')
  399. return (0);
  400. header++;
  401. if (strncmp(header, "ENCRYPTED", 9) != 0) {
  402. OPENSSL_PUT_ERROR(PEM, PEM_R_NOT_ENCRYPTED);
  403. return (0);
  404. }
  405. for (; (*header != '\n') && (*header != '\0'); header++) ;
  406. if (*header == '\0') {
  407. OPENSSL_PUT_ERROR(PEM, PEM_R_SHORT_HEADER);
  408. return (0);
  409. }
  410. header++;
  411. if (strncmp(header, "DEK-Info: ", 10) != 0) {
  412. OPENSSL_PUT_ERROR(PEM, PEM_R_NOT_DEK_INFO);
  413. return (0);
  414. }
  415. header += 10;
  416. p = header;
  417. for (;;) {
  418. c = *header;
  419. if (!(((c >= 'A') && (c <= 'Z')) || (c == '-') ||
  420. ((c >= '0') && (c <= '9'))))
  421. break;
  422. header++;
  423. }
  424. *header = '\0';
  425. cipher->cipher = enc = cipher_by_name(p);
  426. *header = c;
  427. header++;
  428. if (enc == NULL) {
  429. OPENSSL_PUT_ERROR(PEM, PEM_R_UNSUPPORTED_ENCRYPTION);
  430. return (0);
  431. }
  432. if (!load_iv(header_pp, &(cipher->iv[0]), EVP_CIPHER_iv_length(enc)))
  433. return (0);
  434. return (1);
  435. }
  436. static int load_iv(char **fromp, unsigned char *to, int num)
  437. {
  438. int v, i;
  439. char *from;
  440. from = *fromp;
  441. for (i = 0; i < num; i++)
  442. to[i] = 0;
  443. num *= 2;
  444. for (i = 0; i < num; i++) {
  445. if ((*from >= '0') && (*from <= '9'))
  446. v = *from - '0';
  447. else if ((*from >= 'A') && (*from <= 'F'))
  448. v = *from - 'A' + 10;
  449. else if ((*from >= 'a') && (*from <= 'f'))
  450. v = *from - 'a' + 10;
  451. else {
  452. OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_IV_CHARS);
  453. return (0);
  454. }
  455. from++;
  456. to[i / 2] |= v << (long)((!(i & 1)) * 4);
  457. }
  458. *fromp = from;
  459. return (1);
  460. }
  461. #ifndef OPENSSL_NO_FP_API
  462. int PEM_write(FILE *fp, const char *name, const char *header,
  463. const unsigned char *data, long len)
  464. {
  465. BIO *b;
  466. int ret;
  467. if ((b = BIO_new(BIO_s_file())) == NULL) {
  468. OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB);
  469. return (0);
  470. }
  471. BIO_set_fp(b, fp, BIO_NOCLOSE);
  472. ret = PEM_write_bio(b, name, header, data, len);
  473. BIO_free(b);
  474. return (ret);
  475. }
  476. #endif
  477. int PEM_write_bio(BIO *bp, const char *name, const char *header,
  478. const unsigned char *data, long len)
  479. {
  480. int nlen, n, i, j, outl;
  481. unsigned char *buf = NULL;
  482. EVP_ENCODE_CTX ctx;
  483. int reason = ERR_R_BUF_LIB;
  484. EVP_EncodeInit(&ctx);
  485. nlen = strlen(name);
  486. if ((BIO_write(bp, "-----BEGIN ", 11) != 11) ||
  487. (BIO_write(bp, name, nlen) != nlen) ||
  488. (BIO_write(bp, "-----\n", 6) != 6))
  489. goto err;
  490. i = strlen(header);
  491. if (i > 0) {
  492. if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1))
  493. goto err;
  494. }
  495. buf = OPENSSL_malloc(PEM_BUFSIZE * 8);
  496. if (buf == NULL) {
  497. reason = ERR_R_MALLOC_FAILURE;
  498. goto err;
  499. }
  500. i = j = 0;
  501. while (len > 0) {
  502. n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
  503. EVP_EncodeUpdate(&ctx, buf, &outl, &(data[j]), n);
  504. if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl))
  505. goto err;
  506. i += outl;
  507. len -= n;
  508. j += n;
  509. }
  510. EVP_EncodeFinal(&ctx, buf, &outl);
  511. if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl))
  512. goto err;
  513. OPENSSL_cleanse(buf, PEM_BUFSIZE * 8);
  514. OPENSSL_free(buf);
  515. buf = NULL;
  516. if ((BIO_write(bp, "-----END ", 9) != 9) ||
  517. (BIO_write(bp, name, nlen) != nlen) ||
  518. (BIO_write(bp, "-----\n", 6) != 6))
  519. goto err;
  520. return (i + outl);
  521. err:
  522. if (buf) {
  523. OPENSSL_cleanse(buf, PEM_BUFSIZE * 8);
  524. OPENSSL_free(buf);
  525. }
  526. OPENSSL_PUT_ERROR(PEM, reason);
  527. return (0);
  528. }
  529. #ifndef OPENSSL_NO_FP_API
  530. int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
  531. long *len)
  532. {
  533. BIO *b;
  534. int ret;
  535. if ((b = BIO_new(BIO_s_file())) == NULL) {
  536. OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB);
  537. return (0);
  538. }
  539. BIO_set_fp(b, fp, BIO_NOCLOSE);
  540. ret = PEM_read_bio(b, name, header, data, len);
  541. BIO_free(b);
  542. return (ret);
  543. }
  544. #endif
  545. int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
  546. long *len)
  547. {
  548. EVP_ENCODE_CTX ctx;
  549. int end = 0, i, k, bl = 0, hl = 0, nohead = 0;
  550. char buf[256];
  551. BUF_MEM *nameB;
  552. BUF_MEM *headerB;
  553. BUF_MEM *dataB, *tmpB;
  554. nameB = BUF_MEM_new();
  555. headerB = BUF_MEM_new();
  556. dataB = BUF_MEM_new();
  557. if ((nameB == NULL) || (headerB == NULL) || (dataB == NULL)) {
  558. BUF_MEM_free(nameB);
  559. BUF_MEM_free(headerB);
  560. BUF_MEM_free(dataB);
  561. OPENSSL_PUT_ERROR(PEM, ERR_R_MALLOC_FAILURE);
  562. return (0);
  563. }
  564. buf[254] = '\0';
  565. for (;;) {
  566. i = BIO_gets(bp, buf, 254);
  567. if (i <= 0) {
  568. OPENSSL_PUT_ERROR(PEM, PEM_R_NO_START_LINE);
  569. goto err;
  570. }
  571. while ((i >= 0) && (buf[i] <= ' '))
  572. i--;
  573. buf[++i] = '\n';
  574. buf[++i] = '\0';
  575. if (strncmp(buf, "-----BEGIN ", 11) == 0) {
  576. i = strlen(&(buf[11]));
  577. if (strncmp(&(buf[11 + i - 6]), "-----\n", 6) != 0)
  578. continue;
  579. if (!BUF_MEM_grow(nameB, i + 9)) {
  580. OPENSSL_PUT_ERROR(PEM, ERR_R_MALLOC_FAILURE);
  581. goto err;
  582. }
  583. memcpy(nameB->data, &(buf[11]), i - 6);
  584. nameB->data[i - 6] = '\0';
  585. break;
  586. }
  587. }
  588. hl = 0;
  589. if (!BUF_MEM_grow(headerB, 256)) {
  590. OPENSSL_PUT_ERROR(PEM, ERR_R_MALLOC_FAILURE);
  591. goto err;
  592. }
  593. headerB->data[0] = '\0';
  594. for (;;) {
  595. i = BIO_gets(bp, buf, 254);
  596. if (i <= 0)
  597. break;
  598. while ((i >= 0) && (buf[i] <= ' '))
  599. i--;
  600. buf[++i] = '\n';
  601. buf[++i] = '\0';
  602. if (buf[0] == '\n')
  603. break;
  604. if (!BUF_MEM_grow(headerB, hl + i + 9)) {
  605. OPENSSL_PUT_ERROR(PEM, ERR_R_MALLOC_FAILURE);
  606. goto err;
  607. }
  608. if (strncmp(buf, "-----END ", 9) == 0) {
  609. nohead = 1;
  610. break;
  611. }
  612. memcpy(&(headerB->data[hl]), buf, i);
  613. headerB->data[hl + i] = '\0';
  614. hl += i;
  615. }
  616. bl = 0;
  617. if (!BUF_MEM_grow(dataB, 1024)) {
  618. OPENSSL_PUT_ERROR(PEM, ERR_R_MALLOC_FAILURE);
  619. goto err;
  620. }
  621. dataB->data[0] = '\0';
  622. if (!nohead) {
  623. for (;;) {
  624. i = BIO_gets(bp, buf, 254);
  625. if (i <= 0)
  626. break;
  627. while ((i >= 0) && (buf[i] <= ' '))
  628. i--;
  629. buf[++i] = '\n';
  630. buf[++i] = '\0';
  631. if (i != 65)
  632. end = 1;
  633. if (strncmp(buf, "-----END ", 9) == 0)
  634. break;
  635. if (i > 65)
  636. break;
  637. if (!BUF_MEM_grow_clean(dataB, i + bl + 9)) {
  638. OPENSSL_PUT_ERROR(PEM, ERR_R_MALLOC_FAILURE);
  639. goto err;
  640. }
  641. memcpy(&(dataB->data[bl]), buf, i);
  642. dataB->data[bl + i] = '\0';
  643. bl += i;
  644. if (end) {
  645. buf[0] = '\0';
  646. i = BIO_gets(bp, buf, 254);
  647. if (i <= 0)
  648. break;
  649. while ((i >= 0) && (buf[i] <= ' '))
  650. i--;
  651. buf[++i] = '\n';
  652. buf[++i] = '\0';
  653. break;
  654. }
  655. }
  656. } else {
  657. tmpB = headerB;
  658. headerB = dataB;
  659. dataB = tmpB;
  660. bl = hl;
  661. }
  662. i = strlen(nameB->data);
  663. if ((strncmp(buf, "-----END ", 9) != 0) ||
  664. (strncmp(nameB->data, &(buf[9]), i) != 0) ||
  665. (strncmp(&(buf[9 + i]), "-----\n", 6) != 0)) {
  666. OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_END_LINE);
  667. goto err;
  668. }
  669. EVP_DecodeInit(&ctx);
  670. i = EVP_DecodeUpdate(&ctx,
  671. (unsigned char *)dataB->data, &bl,
  672. (unsigned char *)dataB->data, bl);
  673. if (i < 0) {
  674. OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_BASE64_DECODE);
  675. goto err;
  676. }
  677. i = EVP_DecodeFinal(&ctx, (unsigned char *)&(dataB->data[bl]), &k);
  678. if (i < 0) {
  679. OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_BASE64_DECODE);
  680. goto err;
  681. }
  682. bl += k;
  683. if (bl == 0)
  684. goto err;
  685. *name = nameB->data;
  686. *header = headerB->data;
  687. *data = (unsigned char *)dataB->data;
  688. *len = bl;
  689. OPENSSL_free(nameB);
  690. OPENSSL_free(headerB);
  691. OPENSSL_free(dataB);
  692. return (1);
  693. err:
  694. BUF_MEM_free(nameB);
  695. BUF_MEM_free(headerB);
  696. BUF_MEM_free(dataB);
  697. return (0);
  698. }
  699. /*
  700. * Check pem string and return prefix length. If for example the pem_str ==
  701. * "RSA PRIVATE KEY" and suffix = "PRIVATE KEY" the return value is 3 for the
  702. * string "RSA".
  703. */
  704. int pem_check_suffix(const char *pem_str, const char *suffix)
  705. {
  706. int pem_len = strlen(pem_str);
  707. int suffix_len = strlen(suffix);
  708. const char *p;
  709. if (suffix_len + 1 >= pem_len)
  710. return 0;
  711. p = pem_str + pem_len - suffix_len;
  712. if (strcmp(p, suffix))
  713. return 0;
  714. p--;
  715. if (*p != ' ')
  716. return 0;
  717. return p - pem_str;
  718. }
  719. int PEM_def_callback(char *buf, int size, int rwflag, void *userdata)
  720. {
  721. if (!buf || !userdata) {
  722. return 0;
  723. }
  724. size_t len = strlen((char *)userdata);
  725. if (len >= (size_t)size) {
  726. return 0;
  727. }
  728. strcpy(buf, (char *)userdata);
  729. return len;
  730. }