• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.] */
56 
57 #include <assert.h>
58 #include <ctype.h>
59 #include <stdio.h>
60 #include <string.h>
61 
62 #include <openssl/base64.h>
63 #include <openssl/buf.h>
64 #include <openssl/des.h>
65 #include <openssl/err.h>
66 #include <openssl/evp.h>
67 #include <openssl/mem.h>
68 #include <openssl/obj.h>
69 #include <openssl/pem.h>
70 #include <openssl/rand.h>
71 #include <openssl/x509.h>
72 
73 #include "../internal.h"
74 
75 
76 #define MIN_LENGTH 4
77 
78 static int load_iv(char **fromp, unsigned char *to, size_t num);
79 static int check_pem(const char *nm, const char *name);
80 
81 // PEM_proc_type appends a Proc-Type header to |buf|, determined by |type|.
PEM_proc_type(char buf[PEM_BUFSIZE],int type)82 static void PEM_proc_type(char buf[PEM_BUFSIZE], int type) {
83   const char *str;
84 
85   if (type == PEM_TYPE_ENCRYPTED) {
86     str = "ENCRYPTED";
87   } else if (type == PEM_TYPE_MIC_CLEAR) {
88     str = "MIC-CLEAR";
89   } else if (type == PEM_TYPE_MIC_ONLY) {
90     str = "MIC-ONLY";
91   } else {
92     str = "BAD-TYPE";
93   }
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 
100 // PEM_dek_info appends a DEK-Info header to |buf|, with an algorithm of |type|
101 // and a single parameter, specified by hex-encoding |len| bytes from |str|.
PEM_dek_info(char buf[PEM_BUFSIZE],const char * type,size_t len,char * str)102 static void PEM_dek_info(char buf[PEM_BUFSIZE], const char *type, size_t len,
103                          char *str) {
104   static const unsigned char map[17] = "0123456789ABCDEF";
105 
106   OPENSSL_strlcat(buf, "DEK-Info: ", PEM_BUFSIZE);
107   OPENSSL_strlcat(buf, type, PEM_BUFSIZE);
108   OPENSSL_strlcat(buf, ",", PEM_BUFSIZE);
109   size_t buf_len = strlen(buf);
110   // We must write an additional |2 * len + 2| bytes after |buf_len|, including
111   // the trailing newline and NUL.
112   if (len > (PEM_BUFSIZE - buf_len - 2) / 2) {
113     return;
114   }
115   for (size_t i = 0; i < len; i++) {
116     buf[buf_len + i * 2] = map[(str[i] >> 4) & 0x0f];
117     buf[buf_len + i * 2 + 1] = map[(str[i]) & 0x0f];
118   }
119   buf[buf_len + len * 2] = '\n';
120   buf[buf_len + len * 2 + 1] = '\0';
121 }
122 
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   BIO *b = BIO_new_fp(fp, BIO_NOCLOSE);
126   if (b == NULL) {
127     OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB);
128     return NULL;
129   }
130   void *ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u);
131   BIO_free(b);
132   return ret;
133 }
134 
check_pem(const char * nm,const char * name)135 static int check_pem(const char *nm, const char *name) {
136   // Normal matching nm and name
137   if (!strcmp(nm, name)) {
138     return 1;
139   }
140 
141   // Make PEM_STRING_EVP_PKEY match any private key
142 
143   if (!strcmp(name, PEM_STRING_EVP_PKEY)) {
144     return !strcmp(nm, PEM_STRING_PKCS8) || !strcmp(nm, PEM_STRING_PKCS8INF) ||
145            !strcmp(nm, PEM_STRING_RSA) || !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 
155   if (!strcmp(nm, PEM_STRING_X509_REQ_OLD) &&
156       !strcmp(name, PEM_STRING_X509_REQ)) {
157     return 1;
158   }
159 
160   // Allow normal certs to be read as trusted certs
161   if (!strcmp(nm, PEM_STRING_X509) && !strcmp(name, PEM_STRING_X509_TRUSTED)) {
162     return 1;
163   }
164 
165   if (!strcmp(nm, PEM_STRING_X509_OLD) &&
166       !strcmp(name, PEM_STRING_X509_TRUSTED)) {
167     return 1;
168   }
169 
170   // Some CAs use PKCS#7 with CERTIFICATE headers
171   if (!strcmp(nm, PEM_STRING_X509) && !strcmp(name, PEM_STRING_PKCS7)) {
172     return 1;
173   }
174 
175   if (!strcmp(nm, PEM_STRING_PKCS7_SIGNED) && !strcmp(name, PEM_STRING_PKCS7)) {
176     return 1;
177   }
178 
179 #ifndef OPENSSL_NO_CMS
180   if (!strcmp(nm, PEM_STRING_X509) && !strcmp(name, PEM_STRING_CMS)) {
181     return 1;
182   }
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   }
187 #endif
188 
189   return 0;
190 }
191 
cipher_by_name(const char * name)192 static const EVP_CIPHER *cipher_by_name(const char *name) {
193   // This is similar to the (deprecated) function |EVP_get_cipherbyname|. Note
194   // the PEM code assumes that ciphers have at least 8 bytes of IV, at most 20
195   // bytes of overhead and generally behave like CBC mode.
196   if (0 == strcmp(name, SN_des_cbc)) {
197     return EVP_des_cbc();
198   } else if (0 == strcmp(name, SN_des_ede3_cbc)) {
199     return EVP_des_ede3_cbc();
200   } else if (0 == strcmp(name, SN_aes_128_cbc)) {
201     return EVP_aes_128_cbc();
202   } else if (0 == strcmp(name, SN_aes_192_cbc)) {
203     return EVP_aes_192_cbc();
204   } else if (0 == strcmp(name, SN_aes_256_cbc)) {
205     return EVP_aes_256_cbc();
206   } else {
207     return NULL;
208   }
209 }
210 
PEM_bytes_read_bio(unsigned char ** pdata,long * plen,char ** pnm,const char * name,BIO * bp,pem_password_cb * cb,void * u)211 int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
212                        const char *name, BIO *bp, pem_password_cb *cb,
213                        void *u) {
214   EVP_CIPHER_INFO cipher;
215   char *nm = NULL, *header = NULL;
216   unsigned char *data = NULL;
217   long len;
218   int ret = 0;
219 
220   for (;;) {
221     if (!PEM_read_bio(bp, &nm, &header, &data, &len)) {
222       uint32_t error = ERR_peek_error();
223       if (ERR_GET_LIB(error) == ERR_LIB_PEM &&
224           ERR_GET_REASON(error) == PEM_R_NO_START_LINE) {
225         ERR_add_error_data(2, "Expecting: ", name);
226       }
227       return 0;
228     }
229     if (check_pem(nm, name)) {
230       break;
231     }
232     OPENSSL_free(nm);
233     OPENSSL_free(header);
234     OPENSSL_free(data);
235   }
236   if (!PEM_get_EVP_CIPHER_INFO(header, &cipher)) {
237     goto err;
238   }
239   if (!PEM_do_header(&cipher, data, &len, cb, u)) {
240     goto err;
241   }
242 
243   *pdata = data;
244   *plen = len;
245 
246   if (pnm) {
247     *pnm = nm;
248   }
249 
250   ret = 1;
251 
252 err:
253   if (!ret || !pnm) {
254     OPENSSL_free(nm);
255   }
256   OPENSSL_free(header);
257   if (!ret) {
258     OPENSSL_free(data);
259   }
260   return ret;
261 }
262 
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)263 int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp, void *x,
264                    const EVP_CIPHER *enc, unsigned char *kstr, int klen,
265                    pem_password_cb *callback, void *u) {
266   BIO *b = BIO_new_fp(fp, BIO_NOCLOSE);
267   if (b == NULL) {
268     OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB);
269     return 0;
270   }
271   int ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u);
272   BIO_free(b);
273   return ret;
274 }
275 
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)276 int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp, void *x,
277                        const EVP_CIPHER *enc, unsigned char *kstr, int klen,
278                        pem_password_cb *callback, void *u) {
279   EVP_CIPHER_CTX ctx;
280   int dsize = 0, i, j, ret = 0;
281   unsigned char *p, *data = NULL;
282   const char *objstr = NULL;
283   char buf[PEM_BUFSIZE];
284   unsigned char key[EVP_MAX_KEY_LENGTH];
285   unsigned char iv[EVP_MAX_IV_LENGTH];
286 
287   if (enc != NULL) {
288     objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc));
289     if (objstr == NULL || cipher_by_name(objstr) == NULL ||
290         EVP_CIPHER_iv_length(enc) < 8) {
291       OPENSSL_PUT_ERROR(PEM, PEM_R_UNSUPPORTED_CIPHER);
292       goto err;
293     }
294   }
295 
296   if ((dsize = i2d(x, NULL)) < 0) {
297     OPENSSL_PUT_ERROR(PEM, ERR_R_ASN1_LIB);
298     dsize = 0;
299     goto err;
300   }
301   // dzise + 8 bytes are needed
302   // actually it needs the cipher block size extra...
303   data = (unsigned char *)OPENSSL_malloc((unsigned int)dsize + 20);
304   if (data == NULL) {
305     goto err;
306   }
307   p = data;
308   i = i2d(x, &p);
309 
310   if (enc != NULL) {
311     const unsigned iv_len = EVP_CIPHER_iv_length(enc);
312 
313     if (kstr == NULL) {
314       klen = 0;
315       if (!callback) {
316         callback = PEM_def_callback;
317       }
318       klen = (*callback)(buf, PEM_BUFSIZE, 1, u);
319       if (klen <= 0) {
320         OPENSSL_PUT_ERROR(PEM, PEM_R_READ_KEY);
321         goto err;
322       }
323       kstr = (unsigned char *)buf;
324     }
325     assert(iv_len <= sizeof(iv));
326     if (!RAND_bytes(iv, iv_len)) {  // Generate a salt
327       goto err;
328     }
329     // The 'iv' is used as the iv and as a salt.  It is NOT taken from
330     // the BytesToKey function
331     if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1, key, NULL)) {
332       goto err;
333     }
334 
335     if (kstr == (unsigned char *)buf) {
336       OPENSSL_cleanse(buf, PEM_BUFSIZE);
337     }
338 
339     assert(strlen(objstr) + 23 + 2 * iv_len + 13 <= sizeof(buf));
340 
341     buf[0] = '\0';
342     PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
343     PEM_dek_info(buf, objstr, iv_len, (char *)iv);
344     // k=strlen(buf);
345 
346     EVP_CIPHER_CTX_init(&ctx);
347     ret = 1;
348     if (!EVP_EncryptInit_ex(&ctx, enc, NULL, key, iv) ||
349         !EVP_EncryptUpdate(&ctx, data, &j, data, i) ||
350         !EVP_EncryptFinal_ex(&ctx, &(data[j]), &i)) {
351       ret = 0;
352     } else {
353       i += j;
354     }
355     EVP_CIPHER_CTX_cleanup(&ctx);
356     if (ret == 0) {
357       goto err;
358     }
359   } else {
360     ret = 1;
361     buf[0] = '\0';
362   }
363   i = PEM_write_bio(bp, name, buf, data, i);
364   if (i <= 0) {
365     ret = 0;
366   }
367 err:
368   OPENSSL_cleanse(key, sizeof(key));
369   OPENSSL_cleanse(iv, sizeof(iv));
370   OPENSSL_cleanse((char *)&ctx, sizeof(ctx));
371   OPENSSL_cleanse(buf, PEM_BUFSIZE);
372   OPENSSL_free(data);
373   return ret;
374 }
375 
PEM_do_header(EVP_CIPHER_INFO * cipher,unsigned char * data,long * plen,pem_password_cb * callback,void * u)376 int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
377                   pem_password_cb *callback, void *u) {
378   int i = 0, j, o, klen;
379   long len;
380   EVP_CIPHER_CTX ctx;
381   unsigned char key[EVP_MAX_KEY_LENGTH];
382   char buf[PEM_BUFSIZE];
383 
384   len = *plen;
385 
386   if (cipher->cipher == NULL) {
387     return 1;
388   }
389 
390   klen = 0;
391   if (!callback) {
392     callback = PEM_def_callback;
393   }
394   klen = callback(buf, PEM_BUFSIZE, 0, u);
395   if (klen <= 0) {
396     OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_PASSWORD_READ);
397     return 0;
398   }
399 
400   if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
401                       (unsigned char *)buf, klen, 1, key, NULL)) {
402     return 0;
403   }
404 
405   j = (int)len;
406   EVP_CIPHER_CTX_init(&ctx);
407   o = EVP_DecryptInit_ex(&ctx, cipher->cipher, NULL, key, &(cipher->iv[0]));
408   if (o) {
409     o = EVP_DecryptUpdate(&ctx, data, &i, data, j);
410   }
411   if (o) {
412     o = EVP_DecryptFinal_ex(&ctx, &(data[i]), &j);
413   }
414   EVP_CIPHER_CTX_cleanup(&ctx);
415   OPENSSL_cleanse((char *)buf, sizeof(buf));
416   OPENSSL_cleanse((char *)key, sizeof(key));
417   if (!o) {
418     OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_DECRYPT);
419     return 0;
420   }
421   j += i;
422   *plen = j;
423   return 1;
424 }
425 
PEM_get_EVP_CIPHER_INFO(char * header,EVP_CIPHER_INFO * cipher)426 int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher) {
427   const EVP_CIPHER *enc = NULL;
428   char *p, c;
429   char **header_pp = &header;
430 
431   cipher->cipher = NULL;
432   OPENSSL_memset(cipher->iv, 0, sizeof(cipher->iv));
433   if ((header == NULL) || (*header == '\0') || (*header == '\n')) {
434     return 1;
435   }
436   if (strncmp(header, "Proc-Type: ", 11) != 0) {
437     OPENSSL_PUT_ERROR(PEM, PEM_R_NOT_PROC_TYPE);
438     return 0;
439   }
440   header += 11;
441   if (*header != '4') {
442     return 0;
443   }
444   header++;
445   if (*header != ',') {
446     return 0;
447   }
448   header++;
449   if (strncmp(header, "ENCRYPTED", 9) != 0) {
450     OPENSSL_PUT_ERROR(PEM, PEM_R_NOT_ENCRYPTED);
451     return 0;
452   }
453   for (; (*header != '\n') && (*header != '\0'); header++) {
454     ;
455   }
456   if (*header == '\0') {
457     OPENSSL_PUT_ERROR(PEM, PEM_R_SHORT_HEADER);
458     return 0;
459   }
460   header++;
461   if (strncmp(header, "DEK-Info: ", 10) != 0) {
462     OPENSSL_PUT_ERROR(PEM, PEM_R_NOT_DEK_INFO);
463     return 0;
464   }
465   header += 10;
466 
467   p = header;
468   for (;;) {
469     c = *header;
470     if (!((c >= 'A' && c <= 'Z') || c == '-' ||
471           OPENSSL_isdigit(c))) {
472       break;
473     }
474     header++;
475   }
476   *header = '\0';
477   cipher->cipher = enc = cipher_by_name(p);
478   *header = c;
479   header++;
480 
481   if (enc == NULL) {
482     OPENSSL_PUT_ERROR(PEM, PEM_R_UNSUPPORTED_ENCRYPTION);
483     return 0;
484   }
485   // The IV parameter must be at least 8 bytes long to be used as the salt in
486   // the KDF. (This should not happen given |cipher_by_name|.)
487   if (EVP_CIPHER_iv_length(enc) < 8) {
488     assert(0);
489     OPENSSL_PUT_ERROR(PEM, PEM_R_UNSUPPORTED_ENCRYPTION);
490     return 0;
491   }
492   if (!load_iv(header_pp, &(cipher->iv[0]), EVP_CIPHER_iv_length(enc))) {
493     return 0;
494   }
495 
496   return 1;
497 }
498 
load_iv(char ** fromp,unsigned char * to,size_t num)499 static int load_iv(char **fromp, unsigned char *to, size_t num) {
500   uint8_t v;
501   char *from;
502 
503   from = *fromp;
504   for (size_t i = 0; i < num; i++) {
505     to[i] = 0;
506   }
507   num *= 2;
508   for (size_t i = 0; i < num; i++) {
509     if (!OPENSSL_fromxdigit(&v, *from)) {
510       OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_IV_CHARS);
511       return 0;
512     }
513     from++;
514     to[i / 2] |= v << (!(i & 1)) * 4;
515   }
516 
517   *fromp = from;
518   return 1;
519 }
520 
PEM_write(FILE * fp,const char * name,const char * header,const unsigned char * data,long len)521 int PEM_write(FILE *fp, const char *name, const char *header,
522               const unsigned char *data, long len) {
523   BIO *b = BIO_new_fp(fp, BIO_NOCLOSE);
524   if (b == NULL) {
525     OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB);
526     return 0;
527   }
528   int ret = PEM_write_bio(b, name, header, data, len);
529   BIO_free(b);
530   return ret;
531 }
532 
PEM_write_bio(BIO * bp,const char * name,const char * header,const unsigned char * data,long len)533 int PEM_write_bio(BIO *bp, const char *name, const char *header,
534                   const unsigned char *data, long len) {
535   int nlen, n, i, j, outl;
536   unsigned char *buf = NULL;
537   EVP_ENCODE_CTX ctx;
538   int reason = ERR_R_BUF_LIB;
539 
540   EVP_EncodeInit(&ctx);
541   nlen = strlen(name);
542 
543   if ((BIO_write(bp, "-----BEGIN ", 11) != 11) ||
544       (BIO_write(bp, name, nlen) != nlen) ||
545       (BIO_write(bp, "-----\n", 6) != 6)) {
546     goto err;
547   }
548 
549   i = strlen(header);
550   if (i > 0) {
551     if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1)) {
552       goto err;
553     }
554   }
555 
556   buf = OPENSSL_malloc(PEM_BUFSIZE * 8);
557   if (buf == NULL) {
558     goto err;
559   }
560 
561   i = j = 0;
562   while (len > 0) {
563     n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
564     EVP_EncodeUpdate(&ctx, buf, &outl, &(data[j]), n);
565     if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl)) {
566       goto err;
567     }
568     i += outl;
569     len -= n;
570     j += n;
571   }
572   EVP_EncodeFinal(&ctx, buf, &outl);
573   if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl)) {
574     goto err;
575   }
576   OPENSSL_free(buf);
577   buf = NULL;
578   if ((BIO_write(bp, "-----END ", 9) != 9) ||
579       (BIO_write(bp, name, nlen) != nlen) ||
580       (BIO_write(bp, "-----\n", 6) != 6)) {
581     goto err;
582   }
583   return i + outl;
584 err:
585   if (buf) {
586     OPENSSL_free(buf);
587   }
588   OPENSSL_PUT_ERROR(PEM, reason);
589   return 0;
590 }
591 
PEM_read(FILE * fp,char ** name,char ** header,unsigned char ** data,long * len)592 int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
593              long *len) {
594   BIO *b = BIO_new_fp(fp, BIO_NOCLOSE);
595   if (b == NULL) {
596     OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB);
597     return 0;
598   }
599   int ret = PEM_read_bio(b, name, header, data, len);
600   BIO_free(b);
601   return ret;
602 }
603 
PEM_read_bio(BIO * bp,char ** name,char ** header,unsigned char ** data,long * len)604 int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
605                  long *len) {
606   EVP_ENCODE_CTX ctx;
607   int end = 0, i, k, bl = 0, hl = 0, nohead = 0;
608   char buf[256];
609   BUF_MEM *nameB;
610   BUF_MEM *headerB;
611   BUF_MEM *dataB, *tmpB;
612 
613   nameB = BUF_MEM_new();
614   headerB = BUF_MEM_new();
615   dataB = BUF_MEM_new();
616   if ((nameB == NULL) || (headerB == NULL) || (dataB == NULL)) {
617     BUF_MEM_free(nameB);
618     BUF_MEM_free(headerB);
619     BUF_MEM_free(dataB);
620     return 0;
621   }
622 
623   buf[254] = '\0';
624   for (;;) {
625     i = BIO_gets(bp, buf, 254);
626 
627     if (i <= 0) {
628       OPENSSL_PUT_ERROR(PEM, PEM_R_NO_START_LINE);
629       goto err;
630     }
631 
632     while ((i >= 0) && (buf[i] <= ' ')) {
633       i--;
634     }
635     buf[++i] = '\n';
636     buf[++i] = '\0';
637 
638     if (strncmp(buf, "-----BEGIN ", 11) == 0) {
639       i = strlen(&(buf[11]));
640 
641       if (strncmp(&(buf[11 + i - 6]), "-----\n", 6) != 0) {
642         continue;
643       }
644       if (!BUF_MEM_grow(nameB, i + 9)) {
645         goto err;
646       }
647       OPENSSL_memcpy(nameB->data, &(buf[11]), i - 6);
648       nameB->data[i - 6] = '\0';
649       break;
650     }
651   }
652   hl = 0;
653   if (!BUF_MEM_grow(headerB, 256)) {
654     goto err;
655   }
656   headerB->data[0] = '\0';
657   for (;;) {
658     i = BIO_gets(bp, buf, 254);
659     if (i <= 0) {
660       break;
661     }
662 
663     while ((i >= 0) && (buf[i] <= ' ')) {
664       i--;
665     }
666     buf[++i] = '\n';
667     buf[++i] = '\0';
668 
669     if (buf[0] == '\n') {
670       break;
671     }
672     if (!BUF_MEM_grow(headerB, hl + i + 9)) {
673       goto err;
674     }
675     if (strncmp(buf, "-----END ", 9) == 0) {
676       nohead = 1;
677       break;
678     }
679     OPENSSL_memcpy(&(headerB->data[hl]), buf, i);
680     headerB->data[hl + i] = '\0';
681     hl += i;
682   }
683 
684   bl = 0;
685   if (!BUF_MEM_grow(dataB, 1024)) {
686     goto err;
687   }
688   dataB->data[0] = '\0';
689   if (!nohead) {
690     for (;;) {
691       i = BIO_gets(bp, buf, 254);
692       if (i <= 0) {
693         break;
694       }
695 
696       while ((i >= 0) && (buf[i] <= ' ')) {
697         i--;
698       }
699       buf[++i] = '\n';
700       buf[++i] = '\0';
701 
702       if (i != 65) {
703         end = 1;
704       }
705       if (strncmp(buf, "-----END ", 9) == 0) {
706         break;
707       }
708       if (i > 65) {
709         break;
710       }
711       if (!BUF_MEM_grow_clean(dataB, i + bl + 9)) {
712         goto err;
713       }
714       OPENSSL_memcpy(&(dataB->data[bl]), buf, i);
715       dataB->data[bl + i] = '\0';
716       bl += i;
717       if (end) {
718         buf[0] = '\0';
719         i = BIO_gets(bp, buf, 254);
720         if (i <= 0) {
721           break;
722         }
723 
724         while ((i >= 0) && (buf[i] <= ' ')) {
725           i--;
726         }
727         buf[++i] = '\n';
728         buf[++i] = '\0';
729 
730         break;
731       }
732     }
733   } else {
734     tmpB = headerB;
735     headerB = dataB;
736     dataB = tmpB;
737     bl = hl;
738   }
739   i = strlen(nameB->data);
740   if ((strncmp(buf, "-----END ", 9) != 0) ||
741       (strncmp(nameB->data, &(buf[9]), i) != 0) ||
742       (strncmp(&(buf[9 + i]), "-----\n", 6) != 0)) {
743     OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_END_LINE);
744     goto err;
745   }
746 
747   EVP_DecodeInit(&ctx);
748   i = EVP_DecodeUpdate(&ctx, (unsigned char *)dataB->data, &bl,
749                        (unsigned char *)dataB->data, bl);
750   if (i < 0) {
751     OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_BASE64_DECODE);
752     goto err;
753   }
754   i = EVP_DecodeFinal(&ctx, (unsigned char *)&(dataB->data[bl]), &k);
755   if (i < 0) {
756     OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_BASE64_DECODE);
757     goto err;
758   }
759   bl += k;
760 
761   if (bl == 0) {
762     goto err;
763   }
764   *name = nameB->data;
765   *header = headerB->data;
766   *data = (unsigned char *)dataB->data;
767   *len = bl;
768   OPENSSL_free(nameB);
769   OPENSSL_free(headerB);
770   OPENSSL_free(dataB);
771   return 1;
772 err:
773   BUF_MEM_free(nameB);
774   BUF_MEM_free(headerB);
775   BUF_MEM_free(dataB);
776   return 0;
777 }
778 
PEM_def_callback(char * buf,int size,int rwflag,void * userdata)779 int PEM_def_callback(char *buf, int size, int rwflag, void *userdata) {
780   if (!buf || !userdata || size < 0) {
781     return 0;
782   }
783   size_t len = strlen((char *)userdata);
784   if (len >= (size_t)size) {
785     return 0;
786   }
787   OPENSSL_strlcpy(buf, userdata, (size_t)size);
788   return (int)len;
789 }
790