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