Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

836 Zeilen
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, 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, 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_R_UNSUPPORTED_CIPHER);
  270. goto err;
  271. }
  272. }
  273. if ((dsize=i2d(x,NULL)) < 0)
  274. {
  275. OPENSSL_PUT_ERROR(PEM, 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, 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. callback = PEM_def_callback;
  297. klen=(*callback)(buf,PEM_BUFSIZE,1,u);
  298. if (klen <= 0)
  299. {
  300. OPENSSL_PUT_ERROR(PEM, PEM_R_READ_KEY);
  301. goto err;
  302. }
  303. kstr=(unsigned char *)buf;
  304. }
  305. assert(iv_len <= (int)sizeof(iv));
  306. if (!RAND_bytes(iv, iv_len)) /* Generate a salt */
  307. goto err;
  308. /* The 'iv' is used as the iv and as a salt. It is
  309. * NOT taken from the BytesToKey function */
  310. if (!EVP_BytesToKey(enc,EVP_md5(),iv,kstr,klen,1,key,NULL))
  311. goto err;
  312. if (kstr == (unsigned char *)buf) OPENSSL_cleanse(buf,PEM_BUFSIZE);
  313. assert(strlen(objstr)+23+2*iv_len+13 <= sizeof buf);
  314. buf[0]='\0';
  315. PEM_proc_type(buf,PEM_TYPE_ENCRYPTED);
  316. PEM_dek_info(buf,objstr,iv_len,(char *)iv);
  317. /* k=strlen(buf); */
  318. EVP_CIPHER_CTX_init(&ctx);
  319. ret = 1;
  320. if (!EVP_EncryptInit_ex(&ctx,enc,NULL,key,iv)
  321. || !EVP_EncryptUpdate(&ctx,data,&j,data,i)
  322. || !EVP_EncryptFinal_ex(&ctx,&(data[j]),&i))
  323. ret = 0;
  324. else
  325. i += j;
  326. EVP_CIPHER_CTX_cleanup(&ctx);
  327. if (ret == 0)
  328. goto err;
  329. }
  330. else
  331. {
  332. ret=1;
  333. buf[0]='\0';
  334. }
  335. i=PEM_write_bio(bp,name,buf,data,i);
  336. if (i <= 0) ret=0;
  337. err:
  338. OPENSSL_cleanse(key,sizeof(key));
  339. OPENSSL_cleanse(iv,sizeof(iv));
  340. OPENSSL_cleanse((char *)&ctx,sizeof(ctx));
  341. OPENSSL_cleanse(buf,PEM_BUFSIZE);
  342. if (data != NULL)
  343. {
  344. OPENSSL_cleanse(data,(unsigned int)dsize);
  345. OPENSSL_free(data);
  346. }
  347. return(ret);
  348. }
  349. int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
  350. pem_password_cb *callback,void *u)
  351. {
  352. int i=0,j,o,klen;
  353. long len;
  354. EVP_CIPHER_CTX ctx;
  355. unsigned char key[EVP_MAX_KEY_LENGTH];
  356. char buf[PEM_BUFSIZE];
  357. len= *plen;
  358. if (cipher->cipher == NULL) return(1);
  359. klen = 0;
  360. if (!callback) callback = PEM_def_callback;
  361. klen=callback(buf,PEM_BUFSIZE,0,u);
  362. if (klen <= 0)
  363. {
  364. OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_PASSWORD_READ);
  365. return(0);
  366. }
  367. if (!EVP_BytesToKey(cipher->cipher,EVP_md5(),&(cipher->iv[0]),
  368. (unsigned char *)buf,klen,1,key,NULL))
  369. return 0;
  370. j=(int)len;
  371. EVP_CIPHER_CTX_init(&ctx);
  372. o = EVP_DecryptInit_ex(&ctx,cipher->cipher,NULL, key,&(cipher->iv[0]));
  373. if (o)
  374. o = EVP_DecryptUpdate(&ctx,data,&i,data,j);
  375. if (o)
  376. o = EVP_DecryptFinal_ex(&ctx,&(data[i]),&j);
  377. EVP_CIPHER_CTX_cleanup(&ctx);
  378. OPENSSL_cleanse((char *)buf,sizeof(buf));
  379. OPENSSL_cleanse((char *)key,sizeof(key));
  380. if (!o)
  381. {
  382. OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_DECRYPT);
  383. return(0);
  384. }
  385. j+=i;
  386. *plen=j;
  387. return(1);
  388. }
  389. static const EVP_CIPHER* cipher_by_name(const char *name) {
  390. /* This is similar to the (deprecated) function |EVP_get_cipherbyname|. */
  391. if (0 == strcmp(name, SN_rc4)) {
  392. return EVP_rc4();
  393. } else if (0 == strcmp(name, SN_des_cbc)) {
  394. return EVP_des_cbc();
  395. } else if (0 == strcmp(name, SN_des_ede3_cbc)) {
  396. return EVP_des_ede3_cbc();
  397. } else if (0 == strcmp(name, SN_aes_128_cbc)) {
  398. return EVP_aes_128_cbc();
  399. } else if (0 == strcmp(name, SN_aes_192_cbc)) {
  400. return EVP_aes_192_cbc();
  401. } else if (0 == strcmp(name, SN_aes_256_cbc)) {
  402. return EVP_aes_256_cbc();
  403. } else {
  404. return NULL;
  405. }
  406. }
  407. int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
  408. {
  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. { OPENSSL_PUT_ERROR(PEM, 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. { OPENSSL_PUT_ERROR(PEM, PEM_R_NOT_ENCRYPTED); return(0); }
  422. for (; (*header != '\n') && (*header != '\0'); header++)
  423. ;
  424. if (*header == '\0')
  425. { OPENSSL_PUT_ERROR(PEM, PEM_R_SHORT_HEADER); return(0); }
  426. header++;
  427. if (strncmp(header,"DEK-Info: ",10) != 0)
  428. { OPENSSL_PUT_ERROR(PEM, PEM_R_NOT_DEK_INFO); return(0); }
  429. header+=10;
  430. p=header;
  431. for (;;)
  432. {
  433. c= *header;
  434. if (!( ((c >= 'A') && (c <= 'Z')) || (c == '-') ||
  435. ((c >= '0') && (c <= '9'))))
  436. break;
  437. header++;
  438. }
  439. *header='\0';
  440. cipher->cipher=enc=cipher_by_name(p);
  441. *header=c;
  442. header++;
  443. if (enc == NULL)
  444. {
  445. OPENSSL_PUT_ERROR(PEM, PEM_R_UNSUPPORTED_ENCRYPTION);
  446. return(0);
  447. }
  448. if (!load_iv(header_pp,&(cipher->iv[0]),EVP_CIPHER_iv_length(enc)))
  449. return(0);
  450. return(1);
  451. }
  452. static int load_iv(char **fromp, unsigned char *to, int num)
  453. {
  454. int v,i;
  455. char *from;
  456. from= *fromp;
  457. for (i=0; i<num; i++) to[i]=0;
  458. num*=2;
  459. for (i=0; i<num; i++)
  460. {
  461. if ((*from >= '0') && (*from <= '9'))
  462. v= *from-'0';
  463. else if ((*from >= 'A') && (*from <= 'F'))
  464. v= *from-'A'+10;
  465. else if ((*from >= 'a') && (*from <= 'f'))
  466. v= *from-'a'+10;
  467. else
  468. {
  469. OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_IV_CHARS);
  470. return(0);
  471. }
  472. from++;
  473. to[i/2]|=v<<(long)((!(i&1))*4);
  474. }
  475. *fromp=from;
  476. return(1);
  477. }
  478. #ifndef OPENSSL_NO_FP_API
  479. int PEM_write(FILE *fp, const char *name, const char *header,
  480. const unsigned char *data, long len)
  481. {
  482. BIO *b;
  483. int ret;
  484. if ((b=BIO_new(BIO_s_file())) == NULL)
  485. {
  486. OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB);
  487. return(0);
  488. }
  489. BIO_set_fp(b,fp,BIO_NOCLOSE);
  490. ret=PEM_write_bio(b, name, header, data,len);
  491. BIO_free(b);
  492. return(ret);
  493. }
  494. #endif
  495. int PEM_write_bio(BIO *bp, const char *name, const char *header,
  496. const unsigned char *data, long len)
  497. {
  498. int nlen,n,i,j,outl;
  499. unsigned char *buf = NULL;
  500. EVP_ENCODE_CTX ctx;
  501. int reason=ERR_R_BUF_LIB;
  502. EVP_EncodeInit(&ctx);
  503. nlen=strlen(name);
  504. if ( (BIO_write(bp,"-----BEGIN ",11) != 11) ||
  505. (BIO_write(bp,name,nlen) != nlen) ||
  506. (BIO_write(bp,"-----\n",6) != 6))
  507. goto err;
  508. i=strlen(header);
  509. if (i > 0)
  510. {
  511. if ( (BIO_write(bp,header,i) != i) ||
  512. (BIO_write(bp,"\n",1) != 1))
  513. goto err;
  514. }
  515. buf = OPENSSL_malloc(PEM_BUFSIZE*8);
  516. if (buf == NULL)
  517. {
  518. reason=ERR_R_MALLOC_FAILURE;
  519. goto err;
  520. }
  521. i=j=0;
  522. while (len > 0)
  523. {
  524. n=(int)((len>(PEM_BUFSIZE*5))?(PEM_BUFSIZE*5):len);
  525. EVP_EncodeUpdate(&ctx,buf,&outl,&(data[j]),n);
  526. if ((outl) && (BIO_write(bp,(char *)buf,outl) != outl))
  527. goto err;
  528. i+=outl;
  529. len-=n;
  530. j+=n;
  531. }
  532. EVP_EncodeFinal(&ctx,buf,&outl);
  533. if ((outl > 0) && (BIO_write(bp,(char *)buf,outl) != outl)) goto err;
  534. OPENSSL_cleanse(buf, PEM_BUFSIZE*8);
  535. OPENSSL_free(buf);
  536. buf = NULL;
  537. if ( (BIO_write(bp,"-----END ",9) != 9) ||
  538. (BIO_write(bp,name,nlen) != nlen) ||
  539. (BIO_write(bp,"-----\n",6) != 6))
  540. goto err;
  541. return(i+outl);
  542. err:
  543. if (buf) {
  544. OPENSSL_cleanse(buf, PEM_BUFSIZE*8);
  545. OPENSSL_free(buf);
  546. }
  547. OPENSSL_PUT_ERROR(PEM, reason);
  548. return(0);
  549. }
  550. #ifndef OPENSSL_NO_FP_API
  551. int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
  552. long *len)
  553. {
  554. BIO *b;
  555. int ret;
  556. if ((b=BIO_new(BIO_s_file())) == NULL)
  557. {
  558. OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB);
  559. return(0);
  560. }
  561. BIO_set_fp(b,fp,BIO_NOCLOSE);
  562. ret=PEM_read_bio(b, name, header, data,len);
  563. BIO_free(b);
  564. return(ret);
  565. }
  566. #endif
  567. int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
  568. long *len)
  569. {
  570. EVP_ENCODE_CTX ctx;
  571. int end=0,i,k,bl=0,hl=0,nohead=0;
  572. char buf[256];
  573. BUF_MEM *nameB;
  574. BUF_MEM *headerB;
  575. BUF_MEM *dataB,*tmpB;
  576. nameB=BUF_MEM_new();
  577. headerB=BUF_MEM_new();
  578. dataB=BUF_MEM_new();
  579. if ((nameB == NULL) || (headerB == NULL) || (dataB == NULL))
  580. {
  581. BUF_MEM_free(nameB);
  582. BUF_MEM_free(headerB);
  583. BUF_MEM_free(dataB);
  584. OPENSSL_PUT_ERROR(PEM, ERR_R_MALLOC_FAILURE);
  585. return(0);
  586. }
  587. buf[254]='\0';
  588. for (;;)
  589. {
  590. i=BIO_gets(bp,buf,254);
  591. if (i <= 0)
  592. {
  593. OPENSSL_PUT_ERROR(PEM, PEM_R_NO_START_LINE);
  594. goto err;
  595. }
  596. while ((i >= 0) && (buf[i] <= ' ')) i--;
  597. buf[++i]='\n'; buf[++i]='\0';
  598. if (strncmp(buf,"-----BEGIN ",11) == 0)
  599. {
  600. i=strlen(&(buf[11]));
  601. if (strncmp(&(buf[11+i-6]),"-----\n",6) != 0)
  602. continue;
  603. if (!BUF_MEM_grow(nameB,i+9))
  604. {
  605. OPENSSL_PUT_ERROR(PEM, ERR_R_MALLOC_FAILURE);
  606. goto err;
  607. }
  608. memcpy(nameB->data,&(buf[11]),i-6);
  609. nameB->data[i-6]='\0';
  610. break;
  611. }
  612. }
  613. hl=0;
  614. if (!BUF_MEM_grow(headerB,256))
  615. { OPENSSL_PUT_ERROR(PEM, ERR_R_MALLOC_FAILURE); goto err; }
  616. headerB->data[0]='\0';
  617. for (;;)
  618. {
  619. i=BIO_gets(bp,buf,254);
  620. if (i <= 0) break;
  621. while ((i >= 0) && (buf[i] <= ' ')) i--;
  622. buf[++i]='\n'; buf[++i]='\0';
  623. if (buf[0] == '\n') break;
  624. if (!BUF_MEM_grow(headerB,hl+i+9))
  625. { OPENSSL_PUT_ERROR(PEM, ERR_R_MALLOC_FAILURE); goto err; }
  626. if (strncmp(buf,"-----END ",9) == 0)
  627. {
  628. nohead=1;
  629. break;
  630. }
  631. memcpy(&(headerB->data[hl]),buf,i);
  632. headerB->data[hl+i]='\0';
  633. hl+=i;
  634. }
  635. bl=0;
  636. if (!BUF_MEM_grow(dataB,1024))
  637. { OPENSSL_PUT_ERROR(PEM, ERR_R_MALLOC_FAILURE); goto err; }
  638. dataB->data[0]='\0';
  639. if (!nohead)
  640. {
  641. for (;;)
  642. {
  643. i=BIO_gets(bp,buf,254);
  644. if (i <= 0) break;
  645. while ((i >= 0) && (buf[i] <= ' ')) i--;
  646. buf[++i]='\n'; buf[++i]='\0';
  647. if (i != 65) end=1;
  648. if (strncmp(buf,"-----END ",9) == 0)
  649. break;
  650. if (i > 65) break;
  651. if (!BUF_MEM_grow_clean(dataB,i+bl+9))
  652. {
  653. OPENSSL_PUT_ERROR(PEM, ERR_R_MALLOC_FAILURE);
  654. goto err;
  655. }
  656. memcpy(&(dataB->data[bl]),buf,i);
  657. dataB->data[bl+i]='\0';
  658. bl+=i;
  659. if (end)
  660. {
  661. buf[0]='\0';
  662. i=BIO_gets(bp,buf,254);
  663. if (i <= 0) break;
  664. while ((i >= 0) && (buf[i] <= ' ')) i--;
  665. buf[++i]='\n'; buf[++i]='\0';
  666. break;
  667. }
  668. }
  669. }
  670. else
  671. {
  672. tmpB=headerB;
  673. headerB=dataB;
  674. dataB=tmpB;
  675. bl=hl;
  676. }
  677. i=strlen(nameB->data);
  678. if ( (strncmp(buf,"-----END ",9) != 0) ||
  679. (strncmp(nameB->data,&(buf[9]),i) != 0) ||
  680. (strncmp(&(buf[9+i]),"-----\n",6) != 0))
  681. {
  682. OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_END_LINE);
  683. goto err;
  684. }
  685. EVP_DecodeInit(&ctx);
  686. i=EVP_DecodeUpdate(&ctx,
  687. (unsigned char *)dataB->data,&bl,
  688. (unsigned char *)dataB->data,bl);
  689. if (i < 0)
  690. {
  691. OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_BASE64_DECODE);
  692. goto err;
  693. }
  694. i=EVP_DecodeFinal(&ctx,(unsigned char *)&(dataB->data[bl]),&k);
  695. if (i < 0)
  696. {
  697. OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_BASE64_DECODE);
  698. goto err;
  699. }
  700. bl+=k;
  701. if (bl == 0) goto err;
  702. *name=nameB->data;
  703. *header=headerB->data;
  704. *data=(unsigned char *)dataB->data;
  705. *len=bl;
  706. OPENSSL_free(nameB);
  707. OPENSSL_free(headerB);
  708. OPENSSL_free(dataB);
  709. return(1);
  710. err:
  711. BUF_MEM_free(nameB);
  712. BUF_MEM_free(headerB);
  713. BUF_MEM_free(dataB);
  714. return(0);
  715. }
  716. /* Check pem string and return prefix length.
  717. * If for example the pem_str == "RSA PRIVATE KEY" and suffix = "PRIVATE KEY"
  718. * the return value is 3 for the string "RSA".
  719. */
  720. int pem_check_suffix(const char *pem_str, const char *suffix)
  721. {
  722. int pem_len = strlen(pem_str);
  723. int suffix_len = strlen(suffix);
  724. const char *p;
  725. if (suffix_len + 1 >= pem_len)
  726. return 0;
  727. p = pem_str + pem_len - suffix_len;
  728. if (strcmp(p, suffix))
  729. return 0;
  730. p--;
  731. if (*p != ' ')
  732. return 0;
  733. return p - pem_str;
  734. }
  735. int PEM_def_callback(char *buf, int size, int rwflag, void *userdata)
  736. {
  737. if (!buf || !userdata)
  738. {
  739. return 0;
  740. }
  741. size_t len = strlen((char *) userdata);
  742. if (len >= (size_t) size)
  743. {
  744. return 0;
  745. }
  746. strcpy(buf, (char *) userdata);
  747. return len;
  748. }