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