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