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