pem_lib.c 25 KB

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