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