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