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.
 
 
 
 
 
 

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