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