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