2
0

pem_lib.c 20 KB

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