pem_lib.c 24 KB

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