xref: /aosp_15_r20/external/boringssl/src/crypto/pem/pem_lib.c (revision 8fb009dc861624b67b6cdb62ea21f0f22d0c584b)
1 /* Copyright (C) 1995-1998 Eric Young ([email protected])
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young ([email protected]).
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 ([email protected]).
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 ([email protected])"
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 ([email protected])"
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,const unsigned char * pass,int pass_len,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, const unsigned char *pass,
265                    int pass_len, 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 =
272       PEM_ASN1_write_bio(i2d, name, b, x, enc, pass, pass_len, callback, u);
273   BIO_free(b);
274   return ret;
275 }
276 
PEM_ASN1_write_bio(i2d_of_void * i2d,const char * name,BIO * bp,void * x,const EVP_CIPHER * enc,const unsigned char * pass,int pass_len,pem_password_cb * callback,void * u)277 int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp, void *x,
278                        const EVP_CIPHER *enc, const unsigned char *pass,
279                        int pass_len, pem_password_cb *callback, void *u) {
280   EVP_CIPHER_CTX ctx;
281   int dsize = 0, i, j, ret = 0;
282   unsigned char *p, *data = NULL;
283   const char *objstr = NULL;
284   char buf[PEM_BUFSIZE];
285   unsigned char key[EVP_MAX_KEY_LENGTH];
286   unsigned char iv[EVP_MAX_IV_LENGTH];
287 
288   if (enc != NULL) {
289     objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc));
290     if (objstr == NULL || cipher_by_name(objstr) == NULL ||
291         EVP_CIPHER_iv_length(enc) < 8) {
292       OPENSSL_PUT_ERROR(PEM, PEM_R_UNSUPPORTED_CIPHER);
293       goto err;
294     }
295   }
296 
297   if ((dsize = i2d(x, NULL)) < 0) {
298     OPENSSL_PUT_ERROR(PEM, ERR_R_ASN1_LIB);
299     dsize = 0;
300     goto err;
301   }
302   // dzise + 8 bytes are needed
303   // actually it needs the cipher block size extra...
304   data = (unsigned char *)OPENSSL_malloc((unsigned int)dsize + 20);
305   if (data == NULL) {
306     goto err;
307   }
308   p = data;
309   i = i2d(x, &p);
310 
311   if (enc != NULL) {
312     const unsigned iv_len = EVP_CIPHER_iv_length(enc);
313 
314     if (pass == NULL) {
315       pass_len = 0;
316       if (!callback) {
317         callback = PEM_def_callback;
318       }
319       pass_len = (*callback)(buf, PEM_BUFSIZE, 1, u);
320       if (pass_len <= 0) {
321         OPENSSL_PUT_ERROR(PEM, PEM_R_READ_KEY);
322         goto err;
323       }
324       pass = (const unsigned char *)buf;
325     }
326     assert(iv_len <= sizeof(iv));
327     if (!RAND_bytes(iv, iv_len)) {  // Generate a salt
328       goto err;
329     }
330     // The 'iv' is used as the iv and as a salt.  It is NOT taken from
331     // the BytesToKey function
332     if (!EVP_BytesToKey(enc, EVP_md5(), iv, pass, pass_len, 1, key, NULL)) {
333       goto err;
334     }
335 
336     if (pass == (const unsigned char *)buf) {
337       OPENSSL_cleanse(buf, PEM_BUFSIZE);
338     }
339 
340     assert(strlen(objstr) + 23 + 2 * iv_len + 13 <= sizeof(buf));
341 
342     buf[0] = '\0';
343     PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
344     PEM_dek_info(buf, objstr, iv_len, (char *)iv);
345     // k=strlen(buf);
346 
347     EVP_CIPHER_CTX_init(&ctx);
348     ret = 1;
349     if (!EVP_EncryptInit_ex(&ctx, enc, NULL, key, iv) ||
350         !EVP_EncryptUpdate(&ctx, data, &j, data, i) ||
351         !EVP_EncryptFinal_ex(&ctx, &(data[j]), &i)) {
352       ret = 0;
353     } else {
354       i += j;
355     }
356     EVP_CIPHER_CTX_cleanup(&ctx);
357     if (ret == 0) {
358       goto err;
359     }
360   } else {
361     ret = 1;
362     buf[0] = '\0';
363   }
364   i = PEM_write_bio(bp, name, buf, data, i);
365   if (i <= 0) {
366     ret = 0;
367   }
368 err:
369   OPENSSL_cleanse(key, sizeof(key));
370   OPENSSL_cleanse(iv, sizeof(iv));
371   OPENSSL_cleanse((char *)&ctx, sizeof(ctx));
372   OPENSSL_cleanse(buf, PEM_BUFSIZE);
373   OPENSSL_free(data);
374   return ret;
375 }
376 
PEM_do_header(EVP_CIPHER_INFO * cipher,unsigned char * data,long * plen,pem_password_cb * callback,void * u)377 int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
378                   pem_password_cb *callback, void *u) {
379   int i = 0, j, o, pass_len;
380   long len;
381   EVP_CIPHER_CTX ctx;
382   unsigned char key[EVP_MAX_KEY_LENGTH];
383   char buf[PEM_BUFSIZE];
384 
385   len = *plen;
386 
387   if (cipher->cipher == NULL) {
388     return 1;
389   }
390 
391   pass_len = 0;
392   if (!callback) {
393     callback = PEM_def_callback;
394   }
395   pass_len = callback(buf, PEM_BUFSIZE, 0, u);
396   if (pass_len <= 0) {
397     OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_PASSWORD_READ);
398     return 0;
399   }
400 
401   if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
402                       (unsigned char *)buf, pass_len, 1, key, NULL)) {
403     return 0;
404   }
405 
406   j = (int)len;
407   EVP_CIPHER_CTX_init(&ctx);
408   o = EVP_DecryptInit_ex(&ctx, cipher->cipher, NULL, key, &(cipher->iv[0]));
409   if (o) {
410     o = EVP_DecryptUpdate(&ctx, data, &i, data, j);
411   }
412   if (o) {
413     o = EVP_DecryptFinal_ex(&ctx, &(data[i]), &j);
414   }
415   EVP_CIPHER_CTX_cleanup(&ctx);
416   OPENSSL_cleanse((char *)buf, sizeof(buf));
417   OPENSSL_cleanse((char *)key, sizeof(key));
418   if (!o) {
419     OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_DECRYPT);
420     return 0;
421   }
422   j += i;
423   *plen = j;
424   return 1;
425 }
426 
PEM_get_EVP_CIPHER_INFO(char * header,EVP_CIPHER_INFO * cipher)427 int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher) {
428   const EVP_CIPHER *enc = NULL;
429   char *p, c;
430   char **header_pp = &header;
431 
432   cipher->cipher = NULL;
433   OPENSSL_memset(cipher->iv, 0, sizeof(cipher->iv));
434   if ((header == NULL) || (*header == '\0') || (*header == '\n')) {
435     return 1;
436   }
437   if (strncmp(header, "Proc-Type: ", 11) != 0) {
438     OPENSSL_PUT_ERROR(PEM, PEM_R_NOT_PROC_TYPE);
439     return 0;
440   }
441   header += 11;
442   if (*header != '4') {
443     return 0;
444   }
445   header++;
446   if (*header != ',') {
447     return 0;
448   }
449   header++;
450   if (strncmp(header, "ENCRYPTED", 9) != 0) {
451     OPENSSL_PUT_ERROR(PEM, PEM_R_NOT_ENCRYPTED);
452     return 0;
453   }
454   for (; (*header != '\n') && (*header != '\0'); header++) {
455     ;
456   }
457   if (*header == '\0') {
458     OPENSSL_PUT_ERROR(PEM, PEM_R_SHORT_HEADER);
459     return 0;
460   }
461   header++;
462   if (strncmp(header, "DEK-Info: ", 10) != 0) {
463     OPENSSL_PUT_ERROR(PEM, PEM_R_NOT_DEK_INFO);
464     return 0;
465   }
466   header += 10;
467 
468   p = header;
469   for (;;) {
470     c = *header;
471     if (!((c >= 'A' && c <= 'Z') || c == '-' ||
472           OPENSSL_isdigit(c))) {
473       break;
474     }
475     header++;
476   }
477   *header = '\0';
478   cipher->cipher = enc = cipher_by_name(p);
479   *header = c;
480   header++;
481 
482   if (enc == NULL) {
483     OPENSSL_PUT_ERROR(PEM, PEM_R_UNSUPPORTED_ENCRYPTION);
484     return 0;
485   }
486   // The IV parameter must be at least 8 bytes long to be used as the salt in
487   // the KDF. (This should not happen given |cipher_by_name|.)
488   if (EVP_CIPHER_iv_length(enc) < 8) {
489     assert(0);
490     OPENSSL_PUT_ERROR(PEM, PEM_R_UNSUPPORTED_ENCRYPTION);
491     return 0;
492   }
493   if (!load_iv(header_pp, &(cipher->iv[0]), EVP_CIPHER_iv_length(enc))) {
494     return 0;
495   }
496 
497   return 1;
498 }
499 
load_iv(char ** fromp,unsigned char * to,size_t num)500 static int load_iv(char **fromp, unsigned char *to, size_t num) {
501   uint8_t v;
502   char *from;
503 
504   from = *fromp;
505   for (size_t i = 0; i < num; i++) {
506     to[i] = 0;
507   }
508   num *= 2;
509   for (size_t i = 0; i < num; i++) {
510     if (!OPENSSL_fromxdigit(&v, *from)) {
511       OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_IV_CHARS);
512       return 0;
513     }
514     from++;
515     to[i / 2] |= v << (!(i & 1)) * 4;
516   }
517 
518   *fromp = from;
519   return 1;
520 }
521 
PEM_write(FILE * fp,const char * name,const char * header,const unsigned char * data,long len)522 int PEM_write(FILE *fp, const char *name, const char *header,
523               const unsigned char *data, long len) {
524   BIO *b = BIO_new_fp(fp, BIO_NOCLOSE);
525   if (b == NULL) {
526     OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB);
527     return 0;
528   }
529   int ret = PEM_write_bio(b, name, header, data, len);
530   BIO_free(b);
531   return ret;
532 }
533 
PEM_write_bio(BIO * bp,const char * name,const char * header,const unsigned char * data,long len)534 int PEM_write_bio(BIO *bp, const char *name, const char *header,
535                   const unsigned char *data, long len) {
536   int nlen, n, i, j, outl;
537   unsigned char *buf = NULL;
538   EVP_ENCODE_CTX ctx;
539   int reason = ERR_R_BUF_LIB;
540 
541   EVP_EncodeInit(&ctx);
542   nlen = strlen(name);
543 
544   if ((BIO_write(bp, "-----BEGIN ", 11) != 11) ||
545       (BIO_write(bp, name, nlen) != nlen) ||
546       (BIO_write(bp, "-----\n", 6) != 6)) {
547     goto err;
548   }
549 
550   i = strlen(header);
551   if (i > 0) {
552     if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1)) {
553       goto err;
554     }
555   }
556 
557   buf = OPENSSL_malloc(PEM_BUFSIZE * 8);
558   if (buf == NULL) {
559     goto err;
560   }
561 
562   i = j = 0;
563   while (len > 0) {
564     n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
565     EVP_EncodeUpdate(&ctx, buf, &outl, &(data[j]), n);
566     if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl)) {
567       goto err;
568     }
569     i += outl;
570     len -= n;
571     j += n;
572   }
573   EVP_EncodeFinal(&ctx, buf, &outl);
574   if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl)) {
575     goto err;
576   }
577   OPENSSL_free(buf);
578   buf = NULL;
579   if ((BIO_write(bp, "-----END ", 9) != 9) ||
580       (BIO_write(bp, name, nlen) != nlen) ||
581       (BIO_write(bp, "-----\n", 6) != 6)) {
582     goto err;
583   }
584   return i + outl;
585 err:
586   if (buf) {
587     OPENSSL_free(buf);
588   }
589   OPENSSL_PUT_ERROR(PEM, reason);
590   return 0;
591 }
592 
PEM_read(FILE * fp,char ** name,char ** header,unsigned char ** data,long * len)593 int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
594              long *len) {
595   BIO *b = BIO_new_fp(fp, BIO_NOCLOSE);
596   if (b == NULL) {
597     OPENSSL_PUT_ERROR(PEM, ERR_R_BUF_LIB);
598     return 0;
599   }
600   int ret = PEM_read_bio(b, name, header, data, len);
601   BIO_free(b);
602   return ret;
603 }
604 
PEM_read_bio(BIO * bp,char ** name,char ** header,unsigned char ** data,long * len)605 int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
606                  long *len) {
607   EVP_ENCODE_CTX ctx;
608   int end = 0, i, k, bl = 0, hl = 0, nohead = 0;
609   char buf[256];
610   BUF_MEM *nameB;
611   BUF_MEM *headerB;
612   BUF_MEM *dataB, *tmpB;
613 
614   nameB = BUF_MEM_new();
615   headerB = BUF_MEM_new();
616   dataB = BUF_MEM_new();
617   if ((nameB == NULL) || (headerB == NULL) || (dataB == NULL)) {
618     BUF_MEM_free(nameB);
619     BUF_MEM_free(headerB);
620     BUF_MEM_free(dataB);
621     return 0;
622   }
623 
624   buf[254] = '\0';
625   for (;;) {
626     i = BIO_gets(bp, buf, 254);
627 
628     if (i <= 0) {
629       OPENSSL_PUT_ERROR(PEM, PEM_R_NO_START_LINE);
630       goto err;
631     }
632 
633     while ((i >= 0) && (buf[i] <= ' ')) {
634       i--;
635     }
636     buf[++i] = '\n';
637     buf[++i] = '\0';
638 
639     if (strncmp(buf, "-----BEGIN ", 11) == 0) {
640       i = strlen(&(buf[11]));
641 
642       if (strncmp(&(buf[11 + i - 6]), "-----\n", 6) != 0) {
643         continue;
644       }
645       if (!BUF_MEM_grow(nameB, i + 9)) {
646         goto err;
647       }
648       OPENSSL_memcpy(nameB->data, &(buf[11]), i - 6);
649       nameB->data[i - 6] = '\0';
650       break;
651     }
652   }
653   hl = 0;
654   if (!BUF_MEM_grow(headerB, 256)) {
655     goto err;
656   }
657   headerB->data[0] = '\0';
658   for (;;) {
659     i = BIO_gets(bp, buf, 254);
660     if (i <= 0) {
661       break;
662     }
663 
664     while ((i >= 0) && (buf[i] <= ' ')) {
665       i--;
666     }
667     buf[++i] = '\n';
668     buf[++i] = '\0';
669 
670     if (buf[0] == '\n') {
671       break;
672     }
673     if (!BUF_MEM_grow(headerB, hl + i + 9)) {
674       goto err;
675     }
676     if (strncmp(buf, "-----END ", 9) == 0) {
677       nohead = 1;
678       break;
679     }
680     OPENSSL_memcpy(&(headerB->data[hl]), buf, i);
681     headerB->data[hl + i] = '\0';
682     hl += i;
683   }
684 
685   bl = 0;
686   if (!BUF_MEM_grow(dataB, 1024)) {
687     goto err;
688   }
689   dataB->data[0] = '\0';
690   if (!nohead) {
691     for (;;) {
692       i = BIO_gets(bp, buf, 254);
693       if (i <= 0) {
694         break;
695       }
696 
697       while ((i >= 0) && (buf[i] <= ' ')) {
698         i--;
699       }
700       buf[++i] = '\n';
701       buf[++i] = '\0';
702 
703       if (i != 65) {
704         end = 1;
705       }
706       if (strncmp(buf, "-----END ", 9) == 0) {
707         break;
708       }
709       if (i > 65) {
710         break;
711       }
712       if (!BUF_MEM_grow_clean(dataB, i + bl + 9)) {
713         goto err;
714       }
715       OPENSSL_memcpy(&(dataB->data[bl]), buf, i);
716       dataB->data[bl + i] = '\0';
717       bl += i;
718       if (end) {
719         buf[0] = '\0';
720         i = BIO_gets(bp, buf, 254);
721         if (i <= 0) {
722           break;
723         }
724 
725         while ((i >= 0) && (buf[i] <= ' ')) {
726           i--;
727         }
728         buf[++i] = '\n';
729         buf[++i] = '\0';
730 
731         break;
732       }
733     }
734   } else {
735     tmpB = headerB;
736     headerB = dataB;
737     dataB = tmpB;
738     bl = hl;
739   }
740   i = strlen(nameB->data);
741   if ((strncmp(buf, "-----END ", 9) != 0) ||
742       (strncmp(nameB->data, &(buf[9]), i) != 0) ||
743       (strncmp(&(buf[9 + i]), "-----\n", 6) != 0)) {
744     OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_END_LINE);
745     goto err;
746   }
747 
748   EVP_DecodeInit(&ctx);
749   i = EVP_DecodeUpdate(&ctx, (unsigned char *)dataB->data, &bl,
750                        (unsigned char *)dataB->data, bl);
751   if (i < 0) {
752     OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_BASE64_DECODE);
753     goto err;
754   }
755   i = EVP_DecodeFinal(&ctx, (unsigned char *)&(dataB->data[bl]), &k);
756   if (i < 0) {
757     OPENSSL_PUT_ERROR(PEM, PEM_R_BAD_BASE64_DECODE);
758     goto err;
759   }
760   bl += k;
761 
762   if (bl == 0) {
763     goto err;
764   }
765   *name = nameB->data;
766   *header = headerB->data;
767   *data = (unsigned char *)dataB->data;
768   *len = bl;
769   OPENSSL_free(nameB);
770   OPENSSL_free(headerB);
771   OPENSSL_free(dataB);
772   return 1;
773 err:
774   BUF_MEM_free(nameB);
775   BUF_MEM_free(headerB);
776   BUF_MEM_free(dataB);
777   return 0;
778 }
779 
PEM_def_callback(char * buf,int size,int rwflag,void * userdata)780 int PEM_def_callback(char *buf, int size, int rwflag, void *userdata) {
781   if (!buf || !userdata || size < 0) {
782     return 0;
783   }
784   size_t len = strlen((char *)userdata);
785   if (len >= (size_t)size) {
786     return 0;
787   }
788   OPENSSL_strlcpy(buf, userdata, (size_t)size);
789   return (int)len;
790 }
791