3be12d661a162e419e4af7e058123609151456e1
[openssl.git] / crypto / pem / pem_lib.c
1 /*
2  * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include "internal/ctype.h"
12 #include <string.h>
13 #include "internal/cryptlib.h"
14 #include <openssl/buffer.h>
15 #include <openssl/objects.h>
16 #include <openssl/evp.h>
17 #include <openssl/rand.h>
18 #include <openssl/x509.h>
19 #include <openssl/pem.h>
20 #include <openssl/pkcs12.h>
21 #include "internal/asn1_int.h"
22 #include <openssl/des.h>
23 #include <openssl/engine.h>
24
25 #define MIN_LENGTH      4
26
27 static int load_iv(char **fromp, unsigned char *to, int num);
28 static int check_pem(const char *nm, const char *name);
29 int pem_check_suffix(const char *pem_str, const char *suffix);
30
31 int PEM_def_callback(char *buf, int num, int w, void *key)
32 {
33     int i, min_len;
34     const char *prompt;
35
36     if (key) {
37         i = strlen(key);
38         i = (i > num) ? num : i;
39         memcpy(buf, key, i);
40         return i;
41     }
42
43     prompt = EVP_get_pw_prompt();
44     if (prompt == NULL)
45         prompt = "Enter PEM pass phrase:";
46
47     /*
48      * We assume that w == 0 means decryption,
49      * while w == 1 means encryption
50      */
51     min_len = w ? MIN_LENGTH : 0;
52
53     i = EVP_read_pw_string_min(buf, min_len, num, prompt, w);
54     if (i != 0) {
55         PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
56         memset(buf, 0, (unsigned int)num);
57         return -1;
58     }
59     return strlen(buf);
60 }
61
62 void PEM_proc_type(char *buf, int type)
63 {
64     const char *str;
65     char *p = buf + strlen(buf);
66
67     if (type == PEM_TYPE_ENCRYPTED)
68         str = "ENCRYPTED";
69     else if (type == PEM_TYPE_MIC_CLEAR)
70         str = "MIC-CLEAR";
71     else if (type == PEM_TYPE_MIC_ONLY)
72         str = "MIC-ONLY";
73     else
74         str = "BAD-TYPE";
75
76     BIO_snprintf(p, PEM_BUFSIZE - (size_t)(p - buf), "Proc-Type: 4,%s\n", str);
77 }
78
79 void PEM_dek_info(char *buf, const char *type, int len, char *str)
80 {
81     long i;
82     char *p = buf + strlen(buf);
83     int j = PEM_BUFSIZE - (size_t)(p - buf), n;
84
85     n = BIO_snprintf(p, j, "DEK-Info: %s,", type);
86     if (n > 0) {
87         j -= n;
88         p += n;
89         for (i = 0; i < len; i++) {
90             n = BIO_snprintf(p, j, "%02X", 0xff & str[i]);
91             if (n <= 0)
92                 return;
93             j -= n;
94             p += n;
95         }
96         if (j > 1)
97             strcpy(p, "\n");
98     }
99 }
100
101 #ifndef OPENSSL_NO_STDIO
102 void *PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x,
103                     pem_password_cb *cb, void *u)
104 {
105     BIO *b;
106     void *ret;
107
108     if ((b = BIO_new(BIO_s_file())) == NULL) {
109         PEMerr(PEM_F_PEM_ASN1_READ, ERR_R_BUF_LIB);
110         return 0;
111     }
112     BIO_set_fp(b, fp, BIO_NOCLOSE);
113     ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u);
114     BIO_free(b);
115     return ret;
116 }
117 #endif
118
119 static int check_pem(const char *nm, const char *name)
120 {
121     /* Normal matching nm and name */
122     if (strcmp(nm, name) == 0)
123         return 1;
124
125     /* Make PEM_STRING_EVP_PKEY match any private key */
126
127     if (strcmp(name, PEM_STRING_EVP_PKEY) == 0) {
128         int slen;
129         const EVP_PKEY_ASN1_METHOD *ameth;
130         if (strcmp(nm, PEM_STRING_PKCS8) == 0)
131             return 1;
132         if (strcmp(nm, PEM_STRING_PKCS8INF) == 0)
133             return 1;
134         slen = pem_check_suffix(nm, "PRIVATE KEY");
135         if (slen > 0) {
136             /*
137              * NB: ENGINE implementations won't contain a deprecated old
138              * private key decode function so don't look for them.
139              */
140             ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen);
141             if (ameth && ameth->old_priv_decode)
142                 return 1;
143         }
144         return 0;
145     }
146
147     if (strcmp(name, PEM_STRING_PARAMETERS) == 0) {
148         int slen;
149         const EVP_PKEY_ASN1_METHOD *ameth;
150         slen = pem_check_suffix(nm, "PARAMETERS");
151         if (slen > 0) {
152             ENGINE *e;
153             ameth = EVP_PKEY_asn1_find_str(&e, nm, slen);
154             if (ameth) {
155                 int r;
156                 if (ameth->param_decode)
157                     r = 1;
158                 else
159                     r = 0;
160 #ifndef OPENSSL_NO_ENGINE
161                 ENGINE_finish(e);
162 #endif
163                 return r;
164             }
165         }
166         return 0;
167     }
168     /* If reading DH parameters handle X9.42 DH format too */
169     if (strcmp(nm, PEM_STRING_DHXPARAMS) == 0
170         && strcmp(name, PEM_STRING_DHPARAMS) == 0)
171         return 1;
172
173     /* Permit older strings */
174
175     if (strcmp(nm, PEM_STRING_X509_OLD) == 0
176         && strcmp(name, PEM_STRING_X509) == 0)
177         return 1;
178
179     if (strcmp(nm, PEM_STRING_X509_REQ_OLD) == 0
180         && strcmp(name, PEM_STRING_X509_REQ) == 0)
181         return 1;
182
183     /* Allow normal certs to be read as trusted certs */
184     if (strcmp(nm, PEM_STRING_X509) == 0
185         && strcmp(name, PEM_STRING_X509_TRUSTED) == 0)
186         return 1;
187
188     if (strcmp(nm, PEM_STRING_X509_OLD) == 0
189         && strcmp(name, PEM_STRING_X509_TRUSTED) == 0)
190         return 1;
191
192     /* Some CAs use PKCS#7 with CERTIFICATE headers */
193     if (strcmp(nm, PEM_STRING_X509) == 0
194         && strcmp(name, PEM_STRING_PKCS7) == 0)
195         return 1;
196
197     if (strcmp(nm, PEM_STRING_PKCS7_SIGNED) == 0
198         && strcmp(name, PEM_STRING_PKCS7) == 0)
199         return 1;
200
201 #ifndef OPENSSL_NO_CMS
202     if (strcmp(nm, PEM_STRING_X509) == 0
203         && strcmp(name, PEM_STRING_CMS) == 0)
204         return 1;
205     /* Allow CMS to be read from PKCS#7 headers */
206     if (strcmp(nm, PEM_STRING_PKCS7) == 0
207         && strcmp(name, PEM_STRING_CMS) == 0)
208         return 1;
209 #endif
210
211     return 0;
212 }
213
214 static void pem_free(void *p, unsigned int flags, size_t num)
215 {
216     if (flags & PEM_FLAG_SECURE)
217         OPENSSL_secure_clear_free(p, num);
218     else
219         OPENSSL_free(p);
220 }
221
222 static void *pem_malloc(int num, unsigned int flags)
223 {
224     return (flags & PEM_FLAG_SECURE) ? OPENSSL_secure_malloc(num)
225                                      : OPENSSL_malloc(num);
226 }
227
228 static int pem_bytes_read_bio_flags(unsigned char **pdata, long *plen,
229                                     char **pnm, const char *name, BIO *bp,
230                                     pem_password_cb *cb, void *u,
231                                     unsigned int flags)
232 {
233     EVP_CIPHER_INFO cipher;
234     char *nm = NULL, *header = NULL;
235     unsigned char *data = NULL;
236     long len = 0;
237     int ret = 0;
238
239     do {
240         pem_free(nm, flags, 0);
241         pem_free(header, flags, 0);
242         pem_free(data, flags, len);
243         if (!PEM_read_bio_ex(bp, &nm, &header, &data, &len, flags)) {
244             if (ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE)
245                 ERR_add_error_data(2, "Expecting: ", name);
246             return 0;
247         }
248     } while (!check_pem(nm, name));
249     if (!PEM_get_EVP_CIPHER_INFO(header, &cipher))
250         goto err;
251     if (!PEM_do_header(&cipher, data, &len, cb, u))
252         goto err;
253
254     *pdata = data;
255     *plen = len;
256
257     if (pnm != NULL)
258         *pnm = nm;
259
260     ret = 1;
261
262  err:
263     if (!ret || pnm == NULL)
264         pem_free(nm, flags, 0);
265     pem_free(header, flags, 0);
266     if (!ret)
267         pem_free(data, flags, len);
268     return ret;
269 }
270
271 int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
272                        const char *name, BIO *bp, pem_password_cb *cb,
273                        void *u) {
274     return pem_bytes_read_bio_flags(pdata, plen, pnm, name, bp, cb, u,
275                                     PEM_FLAG_EAY_COMPATIBLE);
276 }
277
278 int PEM_bytes_read_bio_secmem(unsigned char **pdata, long *plen, char **pnm,
279                               const char *name, BIO *bp, pem_password_cb *cb,
280                               void *u) {
281     return pem_bytes_read_bio_flags(pdata, plen, pnm, name, bp, cb, u,
282                                     PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE);
283 }
284
285 #ifndef OPENSSL_NO_STDIO
286 int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp,
287                    void *x, const EVP_CIPHER *enc, unsigned char *kstr,
288                    int klen, pem_password_cb *callback, void *u)
289 {
290     BIO *b;
291     int ret;
292
293     if ((b = BIO_new(BIO_s_file())) == NULL) {
294         PEMerr(PEM_F_PEM_ASN1_WRITE, ERR_R_BUF_LIB);
295         return 0;
296     }
297     BIO_set_fp(b, fp, BIO_NOCLOSE);
298     ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u);
299     BIO_free(b);
300     return ret;
301 }
302 #endif
303
304 int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp,
305                        void *x, const EVP_CIPHER *enc, unsigned char *kstr,
306                        int klen, pem_password_cb *callback, void *u)
307 {
308     EVP_CIPHER_CTX *ctx = NULL;
309     int dsize = 0, i = 0, j = 0, ret = 0;
310     unsigned char *p, *data = NULL;
311     const char *objstr = NULL;
312     char buf[PEM_BUFSIZE];
313     unsigned char key[EVP_MAX_KEY_LENGTH];
314     unsigned char iv[EVP_MAX_IV_LENGTH];
315
316     if (enc != NULL) {
317         objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc));
318         if (objstr == NULL || EVP_CIPHER_iv_length(enc) == 0
319                 || EVP_CIPHER_iv_length(enc) > (int)sizeof(iv)
320                    /*
321                     * Check "Proc-Type: 4,Encrypted\nDEK-Info: objstr,hex-iv\n"
322                     * fits into buf
323                     */
324                 || (strlen(objstr) + 23 + 2 * EVP_CIPHER_iv_length(enc) + 13)
325                    > sizeof(buf)) {
326             PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_UNSUPPORTED_CIPHER);
327             goto err;
328         }
329     }
330
331     if ((dsize = i2d(x, NULL)) < 0) {
332         PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_ASN1_LIB);
333         dsize = 0;
334         goto err;
335     }
336     /* dsize + 8 bytes are needed */
337     /* actually it needs the cipher block size extra... */
338     data = OPENSSL_malloc((unsigned int)dsize + 20);
339     if (data == NULL) {
340         PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_MALLOC_FAILURE);
341         goto err;
342     }
343     p = data;
344     i = i2d(x, &p);
345
346     if (enc != NULL) {
347         if (kstr == NULL) {
348             if (callback == NULL)
349                 klen = PEM_def_callback(buf, PEM_BUFSIZE, 1, u);
350             else
351                 klen = (*callback) (buf, PEM_BUFSIZE, 1, u);
352             if (klen <= 0) {
353                 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_READ_KEY);
354                 goto err;
355             }
356 #ifdef CHARSET_EBCDIC
357             /* Convert the pass phrase from EBCDIC */
358             ebcdic2ascii(buf, buf, klen);
359 #endif
360             kstr = (unsigned char *)buf;
361         }
362         if (RAND_bytes(iv, EVP_CIPHER_iv_length(enc)) <= 0) /* Generate a salt */
363             goto err;
364         /*
365          * The 'iv' is used as the iv and as a salt.  It is NOT taken from
366          * the BytesToKey function
367          */
368         if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1, key, NULL))
369             goto err;
370
371         if (kstr == (unsigned char *)buf)
372             OPENSSL_cleanse(buf, PEM_BUFSIZE);
373
374         buf[0] = '\0';
375         PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
376         PEM_dek_info(buf, objstr, EVP_CIPHER_iv_length(enc), (char *)iv);
377         /* k=strlen(buf); */
378
379         ret = 1;
380         if ((ctx = EVP_CIPHER_CTX_new()) == NULL
381             || !EVP_EncryptInit_ex(ctx, enc, NULL, key, iv)
382             || !EVP_EncryptUpdate(ctx, data, &j, data, i)
383             || !EVP_EncryptFinal_ex(ctx, &(data[j]), &i))
384             ret = 0;
385         if (ret == 0)
386             goto err;
387         i += j;
388     } else {
389         ret = 1;
390         buf[0] = '\0';
391     }
392     i = PEM_write_bio(bp, name, buf, data, i);
393     if (i <= 0)
394         ret = 0;
395  err:
396     OPENSSL_cleanse(key, sizeof(key));
397     OPENSSL_cleanse(iv, sizeof(iv));
398     EVP_CIPHER_CTX_free(ctx);
399     OPENSSL_cleanse(buf, PEM_BUFSIZE);
400     OPENSSL_clear_free(data, (unsigned int)dsize);
401     return ret;
402 }
403
404 int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
405                   pem_password_cb *callback, void *u)
406 {
407     int ok;
408     int keylen;
409     long len = *plen;
410     int ilen = (int) len;       /* EVP_DecryptUpdate etc. take int lengths */
411     EVP_CIPHER_CTX *ctx;
412     unsigned char key[EVP_MAX_KEY_LENGTH];
413     char buf[PEM_BUFSIZE];
414
415 #if LONG_MAX > INT_MAX
416     /* Check that we did not truncate the length */
417     if (len > INT_MAX) {
418         PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_HEADER_TOO_LONG);
419         return 0;
420     }
421 #endif
422
423     if (cipher->cipher == NULL)
424         return 1;
425     if (callback == NULL)
426         keylen = PEM_def_callback(buf, PEM_BUFSIZE, 0, u);
427     else
428         keylen = callback(buf, PEM_BUFSIZE, 0, u);
429     if (keylen <= 0) {
430         PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_PASSWORD_READ);
431         return 0;
432     }
433 #ifdef CHARSET_EBCDIC
434     /* Convert the pass phrase from EBCDIC */
435     ebcdic2ascii(buf, buf, keylen);
436 #endif
437
438     if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
439                         (unsigned char *)buf, keylen, 1, key, NULL))
440         return 0;
441
442     ctx = EVP_CIPHER_CTX_new();
443     if (ctx == NULL)
444         return 0;
445
446     ok = EVP_DecryptInit_ex(ctx, cipher->cipher, NULL, key, &(cipher->iv[0]));
447     if (ok)
448         ok = EVP_DecryptUpdate(ctx, data, &ilen, data, ilen);
449     if (ok) {
450         /* Squirrel away the length of data decrypted so far. */
451         *plen = ilen;
452         ok = EVP_DecryptFinal_ex(ctx, &(data[ilen]), &ilen);
453     }
454     if (ok)
455         *plen += ilen;
456     else
457         PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_DECRYPT);
458
459     EVP_CIPHER_CTX_free(ctx);
460     OPENSSL_cleanse((char *)buf, sizeof(buf));
461     OPENSSL_cleanse((char *)key, sizeof(key));
462     return ok;
463 }
464
465 /*
466  * This implements a very limited PEM header parser that does not support the
467  * full grammar of rfc1421.  In particular, folded headers are not supported,
468  * nor is additional whitespace.
469  *
470  * A robust implementation would make use of a library that turns the headers
471  * into a BIO from which one folded line is read at a time, and is then split
472  * into a header label and content.  We would then parse the content of the
473  * headers we care about.  This is overkill for just this limited use-case, but
474  * presumably we also parse rfc822-style headers for S/MIME, so a common
475  * abstraction might well be more generally useful.
476  */
477 int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
478 {
479     static const char ProcType[] = "Proc-Type:";
480     static const char ENCRYPTED[] = "ENCRYPTED";
481     static const char DEKInfo[] = "DEK-Info:";
482     const EVP_CIPHER *enc = NULL;
483     int ivlen;
484     char *dekinfostart, c;
485
486     cipher->cipher = NULL;
487     if ((header == NULL) || (*header == '\0') || (*header == '\n'))
488         return 1;
489
490     if (strncmp(header, ProcType, sizeof(ProcType)-1) != 0) {
491         PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_PROC_TYPE);
492         return 0;
493     }
494     header += sizeof(ProcType)-1;
495     header += strspn(header, " \t");
496
497     if (*header++ != '4' || *header++ != ',')
498         return 0;
499     header += strspn(header, " \t");
500
501     /* We expect "ENCRYPTED" followed by optional white-space + line break */
502     if (strncmp(header, ENCRYPTED, sizeof(ENCRYPTED)-1) != 0 ||
503         strspn(header+sizeof(ENCRYPTED)-1, " \t\r\n") == 0) {
504         PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_ENCRYPTED);
505         return 0;
506     }
507     header += sizeof(ENCRYPTED)-1;
508     header += strspn(header, " \t\r");
509     if (*header++ != '\n') {
510         PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_SHORT_HEADER);
511         return 0;
512     }
513
514     /*-
515      * https://tools.ietf.org/html/rfc1421#section-4.6.1.3
516      * We expect "DEK-Info: algo[,hex-parameters]"
517      */
518     if (strncmp(header, DEKInfo, sizeof(DEKInfo)-1) != 0) {
519         PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_DEK_INFO);
520         return 0;
521     }
522     header += sizeof(DEKInfo)-1;
523     header += strspn(header, " \t");
524
525     /*
526      * DEK-INFO is a comma-separated combination of algorithm name and optional
527      * parameters.
528      */
529     dekinfostart = header;
530     header += strcspn(header, " \t,");
531     c = *header;
532     *header = '\0';
533     cipher->cipher = enc = EVP_get_cipherbyname(dekinfostart);
534     *header = c;
535     header += strspn(header, " \t");
536
537     if (enc == NULL) {
538         PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_UNSUPPORTED_ENCRYPTION);
539         return 0;
540     }
541     ivlen = EVP_CIPHER_iv_length(enc);
542     if (ivlen > 0 && *header++ != ',') {
543         PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_MISSING_DEK_IV);
544         return 0;
545     } else if (ivlen == 0 && *header == ',') {
546         PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_UNEXPECTED_DEK_IV);
547         return 0;
548     }
549
550     if (!load_iv(&header, cipher->iv, EVP_CIPHER_iv_length(enc)))
551         return 0;
552
553     return 1;
554 }
555
556 static int load_iv(char **fromp, unsigned char *to, int num)
557 {
558     int v, i;
559     char *from;
560
561     from = *fromp;
562     for (i = 0; i < num; i++)
563         to[i] = 0;
564     num *= 2;
565     for (i = 0; i < num; i++) {
566         v = OPENSSL_hexchar2int(*from);
567         if (v < 0) {
568             PEMerr(PEM_F_LOAD_IV, PEM_R_BAD_IV_CHARS);
569             return 0;
570         }
571         from++;
572         to[i / 2] |= v << (long)((!(i & 1)) * 4);
573     }
574
575     *fromp = from;
576     return 1;
577 }
578
579 #ifndef OPENSSL_NO_STDIO
580 int PEM_write(FILE *fp, const char *name, const char *header,
581               const unsigned char *data, long len)
582 {
583     BIO *b;
584     int ret;
585
586     if ((b = BIO_new(BIO_s_file())) == NULL) {
587         PEMerr(PEM_F_PEM_WRITE, ERR_R_BUF_LIB);
588         return 0;
589     }
590     BIO_set_fp(b, fp, BIO_NOCLOSE);
591     ret = PEM_write_bio(b, name, header, data, len);
592     BIO_free(b);
593     return ret;
594 }
595 #endif
596
597 int PEM_write_bio(BIO *bp, const char *name, const char *header,
598                   const unsigned char *data, long len)
599 {
600     int nlen, n, i, j, outl;
601     unsigned char *buf = NULL;
602     EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new();
603     int reason = ERR_R_BUF_LIB;
604     int retval = 0;
605
606     if (ctx == NULL) {
607         reason = ERR_R_MALLOC_FAILURE;
608         goto err;
609     }
610
611     EVP_EncodeInit(ctx);
612     nlen = strlen(name);
613
614     if ((BIO_write(bp, "-----BEGIN ", 11) != 11) ||
615         (BIO_write(bp, name, nlen) != nlen) ||
616         (BIO_write(bp, "-----\n", 6) != 6))
617         goto err;
618
619     i = strlen(header);
620     if (i > 0) {
621         if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1))
622             goto err;
623     }
624
625     buf = OPENSSL_malloc(PEM_BUFSIZE * 8);
626     if (buf == NULL) {
627         reason = ERR_R_MALLOC_FAILURE;
628         goto err;
629     }
630
631     i = j = 0;
632     while (len > 0) {
633         n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
634         if (!EVP_EncodeUpdate(ctx, buf, &outl, &(data[j]), n))
635             goto err;
636         if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl))
637             goto err;
638         i += outl;
639         len -= n;
640         j += n;
641     }
642     EVP_EncodeFinal(ctx, buf, &outl);
643     if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl))
644         goto err;
645     if ((BIO_write(bp, "-----END ", 9) != 9) ||
646         (BIO_write(bp, name, nlen) != nlen) ||
647         (BIO_write(bp, "-----\n", 6) != 6))
648         goto err;
649     retval = i + outl;
650
651  err:
652     if (retval == 0)
653         PEMerr(PEM_F_PEM_WRITE_BIO, reason);
654     EVP_ENCODE_CTX_free(ctx);
655     OPENSSL_clear_free(buf, PEM_BUFSIZE * 8);
656     return retval;
657 }
658
659 #ifndef OPENSSL_NO_STDIO
660 int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
661              long *len)
662 {
663     BIO *b;
664     int ret;
665
666     if ((b = BIO_new(BIO_s_file())) == NULL) {
667         PEMerr(PEM_F_PEM_READ, ERR_R_BUF_LIB);
668         return 0;
669     }
670     BIO_set_fp(b, fp, BIO_NOCLOSE);
671     ret = PEM_read_bio(b, name, header, data, len);
672     BIO_free(b);
673     return ret;
674 }
675 #endif
676
677 /* Some helpers for PEM_read_bio_ex(). */
678 static int sanitize_line(char *linebuf, int len, unsigned int flags)
679 {
680     int i;
681
682     if (flags & PEM_FLAG_EAY_COMPATIBLE) {
683         /* Strip trailing whitespace */
684         while ((len >= 0) && (linebuf[len] <= ' '))
685             len--;
686         /* Go back to whitespace before applying uniform line ending. */
687         len++;
688     } else if (flags & PEM_FLAG_ONLY_B64) {
689         for (i = 0; i < len; ++i) {
690             if (!ossl_isbase64(linebuf[i]) || linebuf[i] == '\n'
691                 || linebuf[i] == '\r')
692                 break;
693         }
694         len = i;
695     } else {
696         /* EVP_DecodeBlock strips leading and trailing whitespace, so just strip
697          * control characters in-place and let everything through. */
698         for (i = 0; i < len; ++i) {
699             if (linebuf[i] == '\n' || linebuf[i] == '\r')
700                 break;
701             if (ossl_iscntrl(linebuf[i]))
702                 linebuf[i] = ' ';
703         }
704         len = i;
705     }
706     /* The caller allocated LINESIZE+1, so this is safe. */
707     linebuf[len++] = '\n';
708     linebuf[len] = '\0';
709     return len;
710 }
711
712 #define LINESIZE 255
713 /* Note trailing spaces for begin and end. */
714 static const char beginstr[] = "-----BEGIN ";
715 static const char endstr[] = "-----END ";
716 static const char tailstr[] = "-----\n";
717 #define BEGINLEN ((int)(sizeof(beginstr) - 1))
718 #define ENDLEN ((int)(sizeof(endstr) - 1))
719 #define TAILLEN ((int)(sizeof(tailstr) - 1))
720 static int get_name(BIO *bp, char **name, unsigned int flags)
721 {
722     char *linebuf;
723     int ret = 0;
724     int len;
725
726     /*
727      * Need to hold trailing NUL (accounted for by BIO_gets() and the newline
728      * that will be added by sanitize_line() (the extra '1').
729      */
730     linebuf = pem_malloc(LINESIZE + 1, flags);
731     if (linebuf == NULL) {
732         PEMerr(PEM_F_GET_NAME, ERR_R_MALLOC_FAILURE);
733         return 0;
734     }
735
736     do {
737         len = BIO_gets(bp, linebuf, LINESIZE);
738
739         if (len <= 0) {
740             PEMerr(PEM_F_GET_NAME, PEM_R_NO_START_LINE);
741             goto err;
742         }
743
744         /* Strip trailing garbage and standardize ending. */
745         len = sanitize_line(linebuf, len, flags & ~PEM_FLAG_ONLY_B64);
746
747         /* Allow leading empty or non-matching lines. */
748     } while (strncmp(linebuf, beginstr, BEGINLEN) != 0
749              || len < TAILLEN
750              || strncmp(linebuf + len - TAILLEN, tailstr, TAILLEN) != 0);
751     linebuf[len - TAILLEN] = '\0';
752     len = len - BEGINLEN - TAILLEN + 1;
753     *name = pem_malloc(len, flags);
754     if (*name == NULL) {
755         PEMerr(PEM_F_GET_NAME, ERR_R_MALLOC_FAILURE);
756         goto err;
757     }
758     memcpy(*name, linebuf + BEGINLEN, len);
759     ret = 1;
760
761 err:
762     pem_free(linebuf, flags, LINESIZE + 1);
763     return ret;
764 }
765
766 /* Keep track of how much of a header we've seen. */
767 enum header_status {
768     MAYBE_HEADER,
769     IN_HEADER,
770     POST_HEADER
771 };
772
773 /**
774  * Extract the optional PEM header, with details on the type of content and
775  * any encryption used on the contents, and the bulk of the data from the bio.
776  * The end of the header is marked by a blank line; if the end-of-input marker
777  * is reached prior to a blank line, there is no header.
778  *
779  * The header and data arguments are BIO** since we may have to swap them
780  * if there is no header, for efficiency.
781  *
782  * We need the name of the PEM-encoded type to verify the end string.
783  */
784 static int get_header_and_data(BIO *bp, BIO **header, BIO **data, char *name,
785                                unsigned int flags)
786 {
787     BIO *tmp = *header;
788     char *linebuf, *p;
789     int len, line, ret = 0, end = 0;
790     /* 0 if not seen (yet), 1 if reading header, 2 if finished header */
791     enum header_status got_header = MAYBE_HEADER;
792     unsigned int flags_mask;
793     size_t namelen;
794
795     /* Need to hold trailing NUL (accounted for by BIO_gets() and the newline
796      * that will be added by sanitize_line() (the extra '1'). */
797     linebuf = pem_malloc(LINESIZE + 1, flags);
798     if (linebuf == NULL) {
799         PEMerr(PEM_F_GET_HEADER_AND_DATA, ERR_R_MALLOC_FAILURE);
800         return 0;
801     }
802
803     for (line = 0; ; line++) {
804         flags_mask = ~0u;
805         len = BIO_gets(bp, linebuf, LINESIZE);
806         if (len <= 0) {
807             PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_SHORT_HEADER);
808             goto err;
809         }
810
811         if (got_header == MAYBE_HEADER) {
812             if (memchr(linebuf, ':', len) != NULL)
813                 got_header = IN_HEADER;
814         }
815         if (!strncmp(linebuf, endstr, ENDLEN) || got_header == IN_HEADER)
816             flags_mask &= ~PEM_FLAG_ONLY_B64;
817         len = sanitize_line(linebuf, len, flags & flags_mask);
818
819         /* Check for end of header. */
820         if (linebuf[0] == '\n') {
821             if (got_header == POST_HEADER) {
822                 /* Another blank line is an error. */
823                 PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_BAD_END_LINE);
824                 goto err;
825             }
826             got_header = POST_HEADER;
827             tmp = *data;
828             continue;
829         }
830
831         /* Check for end of stream (which means there is no header). */
832         if (strncmp(linebuf, endstr, ENDLEN) == 0) {
833             p = linebuf + ENDLEN;
834             namelen = strlen(name);
835             if (strncmp(p, name, namelen) != 0 ||
836                 strncmp(p + namelen, tailstr, TAILLEN) != 0) {
837                 PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_BAD_END_LINE);
838                 goto err;
839             }
840             if (got_header == MAYBE_HEADER) {
841                 *header = *data;
842                 *data = tmp;
843             }
844             break;
845         } else if (end) {
846             /* Malformed input; short line not at end of data. */
847             PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_BAD_END_LINE);
848             goto err;
849         }
850         /*
851          * Else, a line of text -- could be header or data; we don't
852          * know yet.  Just pass it through.
853          */
854         if (BIO_puts(tmp, linebuf) < 0)
855             goto err;
856         /*
857          * Only encrypted files need the line length check applied.
858          */
859         if (got_header == POST_HEADER) {
860             /* 65 includes the trailing newline */
861             if (len > 65)
862                 goto err;
863             if (len < 65)
864                 end = 1;
865         }
866     }
867
868     ret = 1;
869 err:
870     pem_free(linebuf, flags, LINESIZE + 1);
871     return ret;
872 }
873
874 /**
875  * Read in PEM-formatted data from the given BIO.
876  *
877  * By nature of the PEM format, all content must be printable ASCII (except
878  * for line endings).  Other characters, or lines that are longer than 80
879  * characters, are malformed input and will be rejected.
880  */
881 int PEM_read_bio_ex(BIO *bp, char **name_out, char **header,
882                     unsigned char **data, long *len_out, unsigned int flags)
883 {
884     EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new();
885     const BIO_METHOD *bmeth;
886     BIO *headerB = NULL, *dataB = NULL;
887     char *name = NULL;
888     int len, taillen, headerlen, ret = 0;
889     BUF_MEM * buf_mem;
890
891     if (ctx == NULL) {
892         PEMerr(PEM_F_PEM_READ_BIO_EX, ERR_R_MALLOC_FAILURE);
893         return 0;
894     }
895
896     *len_out = 0;
897     *name_out = *header = NULL;
898     *data = NULL;
899     if ((flags & PEM_FLAG_EAY_COMPATIBLE) && (flags & PEM_FLAG_ONLY_B64)) {
900         /* These two are mutually incompatible; bail out. */
901         PEMerr(PEM_F_PEM_READ_BIO_EX, ERR_R_PASSED_INVALID_ARGUMENT);
902         goto end;
903     }
904     bmeth = (flags & PEM_FLAG_SECURE) ? BIO_s_secmem() : BIO_s_mem();
905
906     headerB = BIO_new(bmeth);
907     dataB = BIO_new(bmeth);
908     if (headerB == NULL || dataB == NULL) {
909         PEMerr(PEM_F_PEM_READ_BIO_EX, ERR_R_MALLOC_FAILURE);
910         goto end;
911     }
912
913     if (!get_name(bp, &name, flags))
914         goto end;
915     if (!get_header_and_data(bp, &headerB, &dataB, name, flags))
916         goto end;
917
918     EVP_DecodeInit(ctx);
919     BIO_get_mem_ptr(dataB, &buf_mem);
920     len = buf_mem->length;
921     if (EVP_DecodeUpdate(ctx, (unsigned char*)buf_mem->data, &len,
922                          (unsigned char*)buf_mem->data, len) < 0
923             || EVP_DecodeFinal(ctx, (unsigned char*)&(buf_mem->data[len]),
924                                &taillen) < 0) {
925         PEMerr(PEM_F_PEM_READ_BIO_EX, PEM_R_BAD_BASE64_DECODE);
926         goto end;
927     }
928     len += taillen;
929     buf_mem->length = len;
930
931     /* There was no data in the PEM file; avoid malloc(0). */
932     if (len == 0)
933         goto end;
934     headerlen = BIO_get_mem_data(headerB, NULL);
935     *header = pem_malloc(headerlen + 1, flags);
936     *data = pem_malloc(len, flags);
937     if (*header == NULL || *data == NULL) {
938         pem_free(*header, flags, 0);
939         pem_free(*data, flags, 0);
940         goto end;
941     }
942     BIO_read(headerB, *header, headerlen);
943     (*header)[headerlen] = '\0';
944     BIO_read(dataB, *data, len);
945     *len_out = len;
946     *name_out = name;
947     name = NULL;
948     ret = 1;
949
950 end:
951     EVP_ENCODE_CTX_free(ctx);
952     pem_free(name, flags, 0);
953     BIO_free(headerB);
954     BIO_free(dataB);
955     return ret;
956 }
957
958 int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
959                  long *len)
960 {
961     return PEM_read_bio_ex(bp, name, header, data, len, PEM_FLAG_EAY_COMPATIBLE);
962 }
963
964 /*
965  * Check pem string and return prefix length. If for example the pem_str ==
966  * "RSA PRIVATE KEY" and suffix = "PRIVATE KEY" the return value is 3 for the
967  * string "RSA".
968  */
969
970 int pem_check_suffix(const char *pem_str, const char *suffix)
971 {
972     int pem_len = strlen(pem_str);
973     int suffix_len = strlen(suffix);
974     const char *p;
975     if (suffix_len + 1 >= pem_len)
976         return 0;
977     p = pem_str + pem_len - suffix_len;
978     if (strcmp(p, suffix))
979         return 0;
980     p--;
981     if (*p != ' ')
982         return 0;
983     return p - pem_str;
984 }