You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

814 lines
20 KiB

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