9d8ad35ad39ff55600368f830a9bc84328bc7f7e
[openssl.git] / crypto / pem / pem_lib.c
1 /*
2  * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 /* We need to use some engine deprecated APIs */
11 #define OPENSSL_SUPPRESS_DEPRECATED
12
13 #include <stdio.h>
14 #include "crypto/ctype.h"
15 #include <string.h>
16 #include "internal/cryptlib.h"
17 #include <openssl/buffer.h>
18 #include <openssl/objects.h>
19 #include <openssl/evp.h>
20 #include <openssl/rand.h>
21 #include <openssl/x509.h>
22 #include <openssl/pem.h>
23 #include <openssl/pkcs12.h>
24 #include "crypto/asn1.h"
25 #include <openssl/des.h>
26 #include <openssl/engine.h>
27
28 #define MIN_LENGTH      4
29
30 static int load_iv(char **fromp, unsigned char *to, int num);
31 static int check_pem(const char *nm, const char *name);
32 int ossl_pem_check_suffix(const char *pem_str, const char *suffix);
33
34 int PEM_def_callback(char *buf, int num, int rwflag, void *userdata)
35 {
36     int i, min_len;
37     const char *prompt;
38
39     /* We assume that the user passes a default password as userdata */
40     if (userdata) {
41         i = strlen(userdata);
42         i = (i > num) ? num : i;
43         memcpy(buf, userdata, i);
44         return i;
45     }
46
47     prompt = EVP_get_pw_prompt();
48     if (prompt == NULL)
49         prompt = "Enter PEM pass phrase:";
50
51     /*
52      * rwflag == 0 means decryption
53      * rwflag == 1 means encryption
54      *
55      * We assume that for encryption, we want a minimum length, while for
56      * decryption, we cannot know any minimum length, so we assume zero.
57      */
58     min_len = rwflag ? MIN_LENGTH : 0;
59
60     i = EVP_read_pw_string_min(buf, min_len, num, prompt, rwflag);
61     if (i != 0) {
62         ERR_raise(ERR_LIB_PEM, PEM_R_PROBLEMS_GETTING_PASSWORD);
63         memset(buf, 0, (unsigned int)num);
64         return -1;
65     }
66     return strlen(buf);
67 }
68
69 void PEM_proc_type(char *buf, int type)
70 {
71     const char *str;
72     char *p = buf + strlen(buf);
73
74     if (type == PEM_TYPE_ENCRYPTED)
75         str = "ENCRYPTED";
76     else if (type == PEM_TYPE_MIC_CLEAR)
77         str = "MIC-CLEAR";
78     else if (type == PEM_TYPE_MIC_ONLY)
79         str = "MIC-ONLY";
80     else
81         str = "BAD-TYPE";
82
83     BIO_snprintf(p, PEM_BUFSIZE - (size_t)(p - buf), "Proc-Type: 4,%s\n", str);
84 }
85
86 void PEM_dek_info(char *buf, const char *type, int len, const char *str)
87 {
88     long i;
89     char *p = buf + strlen(buf);
90     int j = PEM_BUFSIZE - (size_t)(p - buf), n;
91
92     n = BIO_snprintf(p, j, "DEK-Info: %s,", type);
93     if (n > 0) {
94         j -= n;
95         p += n;
96         for (i = 0; i < len; i++) {
97             n = BIO_snprintf(p, j, "%02X", 0xff & str[i]);
98             if (n <= 0)
99                 return;
100             j -= n;
101             p += n;
102         }
103         if (j > 1)
104             strcpy(p, "\n");
105     }
106 }
107
108 #ifndef OPENSSL_NO_STDIO
109 void *PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x,
110                     pem_password_cb *cb, void *u)
111 {
112     BIO *b;
113     void *ret;
114
115     if ((b = BIO_new(BIO_s_file())) == NULL) {
116         ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
117         return 0;
118     }
119     BIO_set_fp(b, fp, BIO_NOCLOSE);
120     ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u);
121     BIO_free(b);
122     return ret;
123 }
124 #endif
125
126 static int check_pem(const char *nm, const char *name)
127 {
128     /* Normal matching nm and name */
129     if (strcmp(nm, name) == 0)
130         return 1;
131
132     /* Make PEM_STRING_EVP_PKEY match any private key */
133
134     if (strcmp(name, PEM_STRING_EVP_PKEY) == 0) {
135         int slen;
136         const EVP_PKEY_ASN1_METHOD *ameth;
137         if (strcmp(nm, PEM_STRING_PKCS8) == 0)
138             return 1;
139         if (strcmp(nm, PEM_STRING_PKCS8INF) == 0)
140             return 1;
141         slen = ossl_pem_check_suffix(nm, "PRIVATE KEY");
142         if (slen > 0) {
143             /*
144              * NB: ENGINE implementations won't contain a deprecated old
145              * private key decode function so don't look for them.
146              */
147             ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen);
148             if (ameth && ameth->old_priv_decode)
149                 return 1;
150         }
151         return 0;
152     }
153
154     if (strcmp(name, PEM_STRING_PARAMETERS) == 0) {
155         int slen;
156         const EVP_PKEY_ASN1_METHOD *ameth;
157         slen = ossl_pem_check_suffix(nm, "PARAMETERS");
158         if (slen > 0) {
159             ENGINE *e;
160             ameth = EVP_PKEY_asn1_find_str(&e, nm, slen);
161             if (ameth) {
162                 int r;
163                 if (ameth->param_decode)
164                     r = 1;
165                 else
166                     r = 0;
167 #ifndef OPENSSL_NO_ENGINE
168                 ENGINE_finish(e);
169 #endif
170                 return r;
171             }
172         }
173         return 0;
174     }
175     /* If reading DH parameters handle X9.42 DH format too */
176     if (strcmp(nm, PEM_STRING_DHXPARAMS) == 0
177         && strcmp(name, PEM_STRING_DHPARAMS) == 0)
178         return 1;
179
180     /* Permit older strings */
181
182     if (strcmp(nm, PEM_STRING_X509_OLD) == 0
183         && strcmp(name, PEM_STRING_X509) == 0)
184         return 1;
185
186     if (strcmp(nm, PEM_STRING_X509_REQ_OLD) == 0
187         && strcmp(name, PEM_STRING_X509_REQ) == 0)
188         return 1;
189
190     /* Allow normal certs to be read as trusted certs */
191     if (strcmp(nm, PEM_STRING_X509) == 0
192         && strcmp(name, PEM_STRING_X509_TRUSTED) == 0)
193         return 1;
194
195     if (strcmp(nm, PEM_STRING_X509_OLD) == 0
196         && strcmp(name, PEM_STRING_X509_TRUSTED) == 0)
197         return 1;
198
199     /* Some CAs use PKCS#7 with CERTIFICATE headers */
200     if (strcmp(nm, PEM_STRING_X509) == 0
201         && strcmp(name, PEM_STRING_PKCS7) == 0)
202         return 1;
203
204     if (strcmp(nm, PEM_STRING_PKCS7_SIGNED) == 0
205         && strcmp(name, PEM_STRING_PKCS7) == 0)
206         return 1;
207
208 #ifndef OPENSSL_NO_CMS
209     if (strcmp(nm, PEM_STRING_X509) == 0
210         && strcmp(name, PEM_STRING_CMS) == 0)
211         return 1;
212     /* Allow CMS to be read from PKCS#7 headers */
213     if (strcmp(nm, PEM_STRING_PKCS7) == 0
214         && strcmp(name, PEM_STRING_CMS) == 0)
215         return 1;
216 #endif
217
218     return 0;
219 }
220
221 #define PEM_FREE(p, flags, num)                                 \
222     pem_free((p), (flags), (num), OPENSSL_FILE, OPENSSL_LINE)
223 static void pem_free(void *p, unsigned int flags, size_t num,
224                      const char *file, int line)
225 {
226     if (flags & PEM_FLAG_SECURE)
227         CRYPTO_secure_clear_free(p, num, file, line);
228     else
229         CRYPTO_free(p, file, line);
230 }
231
232 #define PEM_MALLOC(num, flags)                                  \
233     pem_malloc((num), (flags), OPENSSL_FILE, OPENSSL_LINE)
234 static void *pem_malloc(int num, unsigned int flags,
235                         const char *file, int line)
236 {
237     return (flags & PEM_FLAG_SECURE) ? CRYPTO_secure_malloc(num, file, line)
238                                      : CRYPTO_malloc(num, file, line);
239
240 }
241
242 static int pem_bytes_read_bio_flags(unsigned char **pdata, long *plen,
243                                     char **pnm, const char *name, BIO *bp,
244                                     pem_password_cb *cb, void *u,
245                                     unsigned int flags)
246 {
247     EVP_CIPHER_INFO cipher;
248     char *nm = NULL, *header = NULL;
249     unsigned char *data = NULL;
250     long len = 0;
251     int ret = 0;
252
253     do {
254         PEM_FREE(nm, flags, 0);
255         PEM_FREE(header, flags, 0);
256         PEM_FREE(data, flags, len);
257         if (!PEM_read_bio_ex(bp, &nm, &header, &data, &len, flags)) {
258             if (ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE)
259                 ERR_add_error_data(2, "Expecting: ", name);
260             return 0;
261         }
262     } while (!check_pem(nm, name));
263     if (!PEM_get_EVP_CIPHER_INFO(header, &cipher))
264         goto err;
265     if (!PEM_do_header(&cipher, data, &len, cb, u))
266         goto err;
267
268     *pdata = data;
269     *plen = len;
270
271     if (pnm != NULL)
272         *pnm = nm;
273
274     ret = 1;
275
276  err:
277     if (!ret || pnm == NULL)
278         PEM_FREE(nm, flags, 0);
279     PEM_FREE(header, flags, 0);
280     if (!ret)
281         PEM_FREE(data, flags, len);
282     return ret;
283 }
284
285 int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
286                        const char *name, BIO *bp, pem_password_cb *cb,
287                        void *u) {
288     return pem_bytes_read_bio_flags(pdata, plen, pnm, name, bp, cb, u,
289                                     PEM_FLAG_EAY_COMPATIBLE);
290 }
291
292 int PEM_bytes_read_bio_secmem(unsigned char **pdata, long *plen, char **pnm,
293                               const char *name, BIO *bp, pem_password_cb *cb,
294                               void *u) {
295     return pem_bytes_read_bio_flags(pdata, plen, pnm, name, bp, cb, u,
296                                     PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE);
297 }
298
299 #ifndef OPENSSL_NO_STDIO
300 int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp,
301                    const void *x, const EVP_CIPHER *enc,
302                    const unsigned char *kstr, int klen,
303                    pem_password_cb *callback, void *u)
304 {
305     BIO *b;
306     int ret;
307
308     if ((b = BIO_new(BIO_s_file())) == NULL) {
309         ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
310         return 0;
311     }
312     BIO_set_fp(b, fp, BIO_NOCLOSE);
313     ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u);
314     BIO_free(b);
315     return ret;
316 }
317 #endif
318
319 int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp,
320                        const void *x, const EVP_CIPHER *enc,
321                        const unsigned char *kstr, int klen,
322                        pem_password_cb *callback, void *u)
323 {
324     EVP_CIPHER_CTX *ctx = NULL;
325     int dsize = 0, i = 0, j = 0, ret = 0;
326     unsigned char *p, *data = NULL;
327     const char *objstr = NULL;
328     char buf[PEM_BUFSIZE];
329     unsigned char key[EVP_MAX_KEY_LENGTH];
330     unsigned char iv[EVP_MAX_IV_LENGTH];
331
332     if (enc != NULL) {
333         objstr = EVP_CIPHER_get0_name(enc);
334         if (objstr == NULL || EVP_CIPHER_get_iv_length(enc) == 0
335                 || EVP_CIPHER_get_iv_length(enc) > (int)sizeof(iv)
336                    /*
337                     * Check "Proc-Type: 4,Encrypted\nDEK-Info: objstr,hex-iv\n"
338                     * fits into buf
339                     */
340                 || strlen(objstr) + 23 + 2 * EVP_CIPHER_get_iv_length(enc) + 13
341                    > sizeof(buf)) {
342             ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_CIPHER);
343             goto err;
344         }
345     }
346
347     if ((dsize = i2d(x, NULL)) <= 0) {
348         ERR_raise(ERR_LIB_PEM, ERR_R_ASN1_LIB);
349         dsize = 0;
350         goto err;
351     }
352     /* dsize + 8 bytes are needed */
353     /* actually it needs the cipher block size extra... */
354     data = OPENSSL_malloc((unsigned int)dsize + 20);
355     if (data == NULL)
356         goto err;
357     p = data;
358     i = i2d(x, &p);
359
360     if (enc != NULL) {
361         if (kstr == NULL) {
362             if (callback == NULL)
363                 klen = PEM_def_callback(buf, PEM_BUFSIZE, 1, u);
364             else
365                 klen = (*callback) (buf, PEM_BUFSIZE, 1, u);
366             if (klen <= 0) {
367                 ERR_raise(ERR_LIB_PEM, PEM_R_READ_KEY);
368                 goto err;
369             }
370 #ifdef CHARSET_EBCDIC
371             /* Convert the pass phrase from EBCDIC */
372             ebcdic2ascii(buf, buf, klen);
373 #endif
374             kstr = (unsigned char *)buf;
375         }
376         /* Generate a salt */
377         if (RAND_bytes(iv, EVP_CIPHER_get_iv_length(enc)) <= 0)
378             goto err;
379         /*
380          * The 'iv' is used as the iv and as a salt.  It is NOT taken from
381          * the BytesToKey function
382          */
383         if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1, key, NULL))
384             goto err;
385
386         if (kstr == (unsigned char *)buf)
387             OPENSSL_cleanse(buf, PEM_BUFSIZE);
388
389         buf[0] = '\0';
390         PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
391         PEM_dek_info(buf, objstr, EVP_CIPHER_get_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         ERR_raise(ERR_LIB_PEM, 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         ERR_raise(ERR_LIB_PEM, 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         ERR_raise(ERR_LIB_PEM, 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 #define PROC_TYPE "Proc-Type:"
493 #define ENCRYPTED "ENCRYPTED"
494 #define DEK_INFO "DEK-Info:"
495 int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
496 {
497     const EVP_CIPHER *enc = NULL;
498     int ivlen;
499     char *dekinfostart, c;
500
501     cipher->cipher = NULL;
502     memset(cipher->iv, 0, sizeof(cipher->iv));
503     if ((header == NULL) || (*header == '\0') || (*header == '\n'))
504         return 1;
505
506     if (!CHECK_AND_SKIP_PREFIX(header, PROC_TYPE)) {
507         ERR_raise(ERR_LIB_PEM, PEM_R_NOT_PROC_TYPE);
508         return 0;
509     }
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 (!CHECK_AND_SKIP_PREFIX(header, ENCRYPTED) ||
518         strspn(header, " \t\r\n") == 0) {
519         ERR_raise(ERR_LIB_PEM, PEM_R_NOT_ENCRYPTED);
520         return 0;
521     }
522     header += strspn(header, " \t\r");
523     if (*header++ != '\n') {
524         ERR_raise(ERR_LIB_PEM, PEM_R_SHORT_HEADER);
525         return 0;
526     }
527
528     /*-
529      * https://tools.ietf.org/html/rfc1421#section-4.6.1.3
530      * We expect "DEK-Info: algo[,hex-parameters]"
531      */
532     if (!CHECK_AND_SKIP_PREFIX(header, DEK_INFO)) {
533         ERR_raise(ERR_LIB_PEM, PEM_R_NOT_DEK_INFO);
534         return 0;
535     }
536     header += strspn(header, " \t");
537
538     /*
539      * DEK-INFO is a comma-separated combination of algorithm name and optional
540      * parameters.
541      */
542     dekinfostart = header;
543     header += strcspn(header, " \t,");
544     c = *header;
545     *header = '\0';
546     cipher->cipher = enc = EVP_get_cipherbyname(dekinfostart);
547     *header = c;
548     header += strspn(header, " \t");
549
550     if (enc == NULL) {
551         ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_ENCRYPTION);
552         return 0;
553     }
554     ivlen = EVP_CIPHER_get_iv_length(enc);
555     if (ivlen > 0 && *header++ != ',') {
556         ERR_raise(ERR_LIB_PEM, PEM_R_MISSING_DEK_IV);
557         return 0;
558     } else if (ivlen == 0 && *header == ',') {
559         ERR_raise(ERR_LIB_PEM, PEM_R_UNEXPECTED_DEK_IV);
560         return 0;
561     }
562
563     if (!load_iv(&header, cipher->iv, EVP_CIPHER_get_iv_length(enc)))
564         return 0;
565
566     return 1;
567 }
568
569 static int load_iv(char **fromp, unsigned char *to, int num)
570 {
571     int v, i;
572     char *from;
573
574     from = *fromp;
575     for (i = 0; i < num; i++)
576         to[i] = 0;
577     num *= 2;
578     for (i = 0; i < num; i++) {
579         v = OPENSSL_hexchar2int(*from);
580         if (v < 0) {
581             ERR_raise(ERR_LIB_PEM, PEM_R_BAD_IV_CHARS);
582             return 0;
583         }
584         from++;
585         to[i / 2] |= v << (long)((!(i & 1)) * 4);
586     }
587
588     *fromp = from;
589     return 1;
590 }
591
592 #ifndef OPENSSL_NO_STDIO
593 int PEM_write(FILE *fp, const char *name, const char *header,
594               const unsigned char *data, long len)
595 {
596     BIO *b;
597     int ret;
598
599     if ((b = BIO_new(BIO_s_file())) == NULL) {
600         ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
601         return 0;
602     }
603     BIO_set_fp(b, fp, BIO_NOCLOSE);
604     ret = PEM_write_bio(b, name, header, data, len);
605     BIO_free(b);
606     return ret;
607 }
608 #endif
609
610 int PEM_write_bio(BIO *bp, const char *name, const char *header,
611                   const unsigned char *data, long len)
612 {
613     int nlen, n, i, j, outl;
614     unsigned char *buf = NULL;
615     EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new();
616     int reason = 0;
617     int retval = 0;
618
619     if (ctx == NULL) {
620         reason = ERR_R_EVP_LIB;
621         goto err;
622     }
623
624     EVP_EncodeInit(ctx);
625     nlen = strlen(name);
626
627     if ((BIO_write(bp, "-----BEGIN ", 11) != 11) ||
628         (BIO_write(bp, name, nlen) != nlen) ||
629         (BIO_write(bp, "-----\n", 6) != 6)) {
630         reason = ERR_R_BIO_LIB;
631         goto err;
632     }
633
634     i = header != NULL ? strlen(header) : 0;
635     if (i > 0) {
636         if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1)) {
637             reason = ERR_R_BIO_LIB;
638             goto err;
639         }
640     }
641
642     buf = OPENSSL_malloc(PEM_BUFSIZE * 8);
643     if (buf == NULL)
644         goto err;
645
646     i = j = 0;
647     while (len > 0) {
648         n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
649         if (!EVP_EncodeUpdate(ctx, buf, &outl, &(data[j]), n)) {
650             reason = ERR_R_EVP_LIB;
651             goto err;
652         }
653         if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl)) {
654             reason = ERR_R_BIO_LIB;
655             goto err;
656         }
657         i += outl;
658         len -= n;
659         j += n;
660     }
661     EVP_EncodeFinal(ctx, buf, &outl);
662     if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl)) {
663         reason = ERR_R_BIO_LIB;
664         goto err;
665     }
666     if ((BIO_write(bp, "-----END ", 9) != 9) ||
667         (BIO_write(bp, name, nlen) != nlen) ||
668         (BIO_write(bp, "-----\n", 6) != 6)) {
669         reason = ERR_R_BIO_LIB;
670         goto err;
671     }
672     retval = i + outl;
673
674  err:
675     if (retval == 0 && reason != 0)
676         ERR_raise(ERR_LIB_PEM, reason);
677     EVP_ENCODE_CTX_free(ctx);
678     OPENSSL_clear_free(buf, PEM_BUFSIZE * 8);
679     return retval;
680 }
681
682 #ifndef OPENSSL_NO_STDIO
683 int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
684              long *len)
685 {
686     BIO *b;
687     int ret;
688
689     if ((b = BIO_new(BIO_s_file())) == NULL) {
690         ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
691         return 0;
692     }
693     BIO_set_fp(b, fp, BIO_NOCLOSE);
694     ret = PEM_read_bio(b, name, header, data, len);
695     BIO_free(b);
696     return ret;
697 }
698 #endif
699
700 /* Some helpers for PEM_read_bio_ex(). */
701 static int sanitize_line(char *linebuf, int len, unsigned int flags, int first_call)
702 {
703     int i;
704     if (first_call) {
705         /* Other BOMs imply unsupported multibyte encoding,
706          * so don't strip them and let the error raise */
707         const unsigned char utf8_bom[3] = {0xEF, 0xBB, 0xBF};
708
709         if (len > 3 && memcmp(linebuf, utf8_bom, 3) == 0) {
710             memmove(linebuf, linebuf + 3, len - 3);
711             linebuf[len - 3] = 0;
712             len -= 3;
713         }
714     }
715
716     if (flags & PEM_FLAG_EAY_COMPATIBLE) {
717         /* Strip trailing whitespace */
718         while ((len >= 0) && (linebuf[len] <= ' '))
719             len--;
720         /* Go back to whitespace before applying uniform line ending. */
721         len++;
722     } else if (flags & PEM_FLAG_ONLY_B64) {
723         for (i = 0; i < len; ++i) {
724             if (!ossl_isbase64(linebuf[i]) || linebuf[i] == '\n'
725                 || linebuf[i] == '\r')
726                 break;
727         }
728         len = i;
729     } else {
730         /* EVP_DecodeBlock strips leading and trailing whitespace, so just strip
731          * control characters in-place and let everything through. */
732         for (i = 0; i < len; ++i) {
733             if (linebuf[i] == '\n' || linebuf[i] == '\r')
734                 break;
735             if (ossl_iscntrl(linebuf[i]))
736                 linebuf[i] = ' ';
737         }
738         len = i;
739     }
740     /* The caller allocated LINESIZE+1, so this is safe. */
741     linebuf[len++] = '\n';
742     linebuf[len] = '\0';
743     return len;
744 }
745
746 #define LINESIZE 255
747 /* Note trailing spaces for begin and end. */
748 #define BEGINSTR "-----BEGIN "
749 #define ENDSTR "-----END "
750 #define TAILSTR "-----\n"
751 #define BEGINLEN ((int)(sizeof(BEGINSTR) - 1))
752 #define ENDLEN ((int)(sizeof(ENDSTR) - 1))
753 #define TAILLEN ((int)(sizeof(TAILSTR) - 1))
754 static int get_name(BIO *bp, char **name, unsigned int flags)
755 {
756     char *linebuf;
757     int ret = 0;
758     int len;
759     int first_call = 1;
760
761     /*
762      * Need to hold trailing NUL (accounted for by BIO_gets() and the newline
763      * that will be added by sanitize_line() (the extra '1').
764      */
765     linebuf = PEM_MALLOC(LINESIZE + 1, flags);
766     if (linebuf == NULL)
767         return 0;
768
769     do {
770         len = BIO_gets(bp, linebuf, LINESIZE);
771
772         if (len <= 0) {
773             ERR_raise(ERR_LIB_PEM, PEM_R_NO_START_LINE);
774             goto err;
775         }
776
777         /* Strip trailing garbage and standardize ending. */
778         len = sanitize_line(linebuf, len, flags & ~PEM_FLAG_ONLY_B64, first_call);
779         first_call = 0;
780
781         /* Allow leading empty or non-matching lines. */
782     } while (!HAS_PREFIX(linebuf, BEGINSTR)
783              || len < TAILLEN
784              || !HAS_PREFIX(linebuf + len - TAILLEN, TAILSTR));
785     linebuf[len - TAILLEN] = '\0';
786     len = len - BEGINLEN - TAILLEN + 1;
787     *name = PEM_MALLOC(len, flags);
788     if (*name == NULL)
789         goto err;
790     memcpy(*name, linebuf + BEGINLEN, len);
791     ret = 1;
792
793 err:
794     PEM_FREE(linebuf, flags, LINESIZE + 1);
795     return ret;
796 }
797
798 /* Keep track of how much of a header we've seen. */
799 enum header_status {
800     MAYBE_HEADER,
801     IN_HEADER,
802     POST_HEADER
803 };
804
805 /**
806  * Extract the optional PEM header, with details on the type of content and
807  * any encryption used on the contents, and the bulk of the data from the bio.
808  * The end of the header is marked by a blank line; if the end-of-input marker
809  * is reached prior to a blank line, there is no header.
810  *
811  * The header and data arguments are BIO** since we may have to swap them
812  * if there is no header, for efficiency.
813  *
814  * We need the name of the PEM-encoded type to verify the end string.
815  */
816 static int get_header_and_data(BIO *bp, BIO **header, BIO **data, char *name,
817                                unsigned int flags)
818 {
819     BIO *tmp = *header;
820     char *linebuf, *p;
821     int len, ret = 0, end = 0, prev_partial_line_read = 0, partial_line_read = 0;
822     /* 0 if not seen (yet), 1 if reading header, 2 if finished header */
823     enum header_status got_header = MAYBE_HEADER;
824     unsigned int flags_mask;
825     size_t namelen;
826
827     /* Need to hold trailing NUL (accounted for by BIO_gets() and the newline
828      * that will be added by sanitize_line() (the extra '1'). */
829     linebuf = PEM_MALLOC(LINESIZE + 1, flags);
830     if (linebuf == NULL)
831         return 0;
832
833     while(1) {
834         flags_mask = ~0u;
835         len = BIO_gets(bp, linebuf, LINESIZE);
836         if (len <= 0) {
837             ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
838             goto err;
839         }
840
841         /*
842          * Check if line has been read completely or if only part of the line
843          * has been read. Keep the previous value to ignore newlines that
844          * appear due to reading a line up until the char before the newline.
845          */
846         prev_partial_line_read = partial_line_read;
847         partial_line_read = len == LINESIZE-1 && linebuf[LINESIZE-2] != '\n';
848
849         if (got_header == MAYBE_HEADER) {
850             if (memchr(linebuf, ':', len) != NULL)
851                 got_header = IN_HEADER;
852         }
853         if (HAS_PREFIX(linebuf, ENDSTR) || got_header == IN_HEADER)
854             flags_mask &= ~PEM_FLAG_ONLY_B64;
855         len = sanitize_line(linebuf, len, flags & flags_mask, 0);
856
857         /* Check for end of header. */
858         if (linebuf[0] == '\n') {
859             /*
860              * If previous line has been read only partially this newline is a
861              * regular newline at the end of a line and not an empty line.
862              */
863             if (!prev_partial_line_read) {
864                 if (got_header == POST_HEADER) {
865                     /* Another blank line is an error. */
866                     ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
867                     goto err;
868                 }
869                 got_header = POST_HEADER;
870                 tmp = *data;
871             }
872             continue;
873         }
874
875         /* Check for end of stream (which means there is no header). */
876         p = linebuf;
877         if (CHECK_AND_SKIP_PREFIX(p, ENDSTR)) {
878             namelen = strlen(name);
879             if (strncmp(p, name, namelen) != 0 ||
880                 !HAS_PREFIX(p + namelen, TAILSTR)) {
881                 ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
882                 goto err;
883             }
884             if (got_header == MAYBE_HEADER) {
885                 *header = *data;
886                 *data = tmp;
887             }
888             break;
889         } else if (end) {
890             /* Malformed input; short line not at end of data. */
891             ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
892             goto err;
893         }
894         /*
895          * Else, a line of text -- could be header or data; we don't
896          * know yet.  Just pass it through.
897          */
898         if (BIO_puts(tmp, linebuf) < 0)
899             goto err;
900         /*
901          * Only encrypted files need the line length check applied.
902          */
903         if (got_header == POST_HEADER) {
904             /* 65 includes the trailing newline */
905             if (len > 65)
906                 goto err;
907             if (len < 65)
908                 end = 1;
909         }
910     }
911
912     ret = 1;
913 err:
914     PEM_FREE(linebuf, flags, LINESIZE + 1);
915     return ret;
916 }
917
918 /**
919  * Read in PEM-formatted data from the given BIO.
920  *
921  * By nature of the PEM format, all content must be printable ASCII (except
922  * for line endings).  Other characters are malformed input and will be rejected.
923  */
924 int PEM_read_bio_ex(BIO *bp, char **name_out, char **header,
925                     unsigned char **data, long *len_out, unsigned int flags)
926 {
927     EVP_ENCODE_CTX *ctx = NULL;
928     const BIO_METHOD *bmeth;
929     BIO *headerB = NULL, *dataB = NULL;
930     char *name = NULL;
931     int len, taillen, headerlen, ret = 0;
932     BUF_MEM *buf_mem;
933
934     *len_out = 0;
935     *name_out = *header = NULL;
936     *data = NULL;
937     if ((flags & PEM_FLAG_EAY_COMPATIBLE) && (flags & PEM_FLAG_ONLY_B64)) {
938         /* These two are mutually incompatible; bail out. */
939         ERR_raise(ERR_LIB_PEM, ERR_R_PASSED_INVALID_ARGUMENT);
940         goto end;
941     }
942     bmeth = (flags & PEM_FLAG_SECURE) ? BIO_s_secmem() : BIO_s_mem();
943
944     headerB = BIO_new(bmeth);
945     dataB = BIO_new(bmeth);
946     if (headerB == NULL || dataB == NULL) {
947         ERR_raise(ERR_LIB_PEM, ERR_R_BIO_LIB);
948         goto end;
949     }
950
951     if (!get_name(bp, &name, flags))
952         goto end;
953     if (!get_header_and_data(bp, &headerB, &dataB, name, flags))
954         goto end;
955
956     BIO_get_mem_ptr(dataB, &buf_mem);
957     len = buf_mem->length;
958
959     /* There was no data in the PEM file */
960     if (len == 0)
961         goto end;
962
963     ctx = EVP_ENCODE_CTX_new();
964     if (ctx == NULL) {
965         ERR_raise(ERR_LIB_PEM, ERR_R_EVP_LIB);
966         goto end;
967     }
968
969     EVP_DecodeInit(ctx);
970     if (EVP_DecodeUpdate(ctx, (unsigned char*)buf_mem->data, &len,
971                          (unsigned char*)buf_mem->data, len) < 0
972             || EVP_DecodeFinal(ctx, (unsigned char*)&(buf_mem->data[len]),
973                                &taillen) < 0) {
974         ERR_raise(ERR_LIB_PEM, PEM_R_BAD_BASE64_DECODE);
975         goto end;
976     }
977     len += taillen;
978     buf_mem->length = len;
979
980     headerlen = BIO_get_mem_data(headerB, NULL);
981     *header = PEM_MALLOC(headerlen + 1, flags);
982     *data = PEM_MALLOC(len, flags);
983     if (*header == NULL || *data == NULL)
984         goto out_free;
985     if (headerlen != 0 && BIO_read(headerB, *header, headerlen) != headerlen)
986         goto out_free;
987     (*header)[headerlen] = '\0';
988     if (BIO_read(dataB, *data, len) != len)
989         goto out_free;
990     *len_out = len;
991     *name_out = name;
992     name = NULL;
993     ret = 1;
994     goto end;
995
996 out_free:
997     PEM_FREE(*header, flags, 0);
998     *header = NULL;
999     PEM_FREE(*data, flags, 0);
1000     *data = NULL;
1001 end:
1002     EVP_ENCODE_CTX_free(ctx);
1003     PEM_FREE(name, flags, 0);
1004     BIO_free(headerB);
1005     BIO_free(dataB);
1006     return ret;
1007 }
1008
1009 int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
1010                  long *len)
1011 {
1012     return PEM_read_bio_ex(bp, name, header, data, len, PEM_FLAG_EAY_COMPATIBLE);
1013 }
1014
1015 /*
1016  * Check pem string and return prefix length. If for example the pem_str ==
1017  * "RSA PRIVATE KEY" and suffix = "PRIVATE KEY" the return value is 3 for the
1018  * string "RSA".
1019  */
1020
1021 int ossl_pem_check_suffix(const char *pem_str, const char *suffix)
1022 {
1023     int pem_len = strlen(pem_str);
1024     int suffix_len = strlen(suffix);
1025     const char *p;
1026     if (suffix_len + 1 >= pem_len)
1027         return 0;
1028     p = pem_str + pem_len - suffix_len;
1029     if (strcmp(p, suffix))
1030         return 0;
1031     p--;
1032     if (*p != ' ')
1033         return 0;
1034     return p - pem_str;
1035 }