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