2 * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
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
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>
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);
31 int PEM_def_callback(char *buf, int num, int w, void *key)
38 i = (i > num) ? num : i;
43 prompt = EVP_get_pw_prompt();
45 prompt = "Enter PEM pass phrase:";
49 * We assume that w == 0 means decryption,
50 * while w == 1 means encryption
52 int min_len = w ? MIN_LENGTH : 0;
54 i = EVP_read_pw_string_min(buf, min_len, num, prompt, w);
56 PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
57 memset(buf, 0, (unsigned int)num);
61 if (min_len && j < min_len) {
63 "phrase is too short, needs to be at least %d chars\n",
71 void PEM_proc_type(char *buf, int type)
75 if (type == PEM_TYPE_ENCRYPTED)
77 else if (type == PEM_TYPE_MIC_CLEAR)
79 else if (type == PEM_TYPE_MIC_ONLY)
84 strcat(buf, "Proc-Type: 4,");
89 void PEM_dek_info(char *buf, const char *type, int len, char *str)
91 static const unsigned char map[17] = "0123456789ABCDEF";
95 strcat(buf, "DEK-Info: ");
99 for (i = 0; i < len; i++) {
100 buf[j + i * 2] = map[(str[i] >> 4) & 0x0f];
101 buf[j + i * 2 + 1] = map[(str[i]) & 0x0f];
103 buf[j + i * 2] = '\n';
104 buf[j + i * 2 + 1] = '\0';
107 #ifndef OPENSSL_NO_STDIO
108 void *PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x,
109 pem_password_cb *cb, void *u)
114 if ((b = BIO_new(BIO_s_file())) == NULL) {
115 PEMerr(PEM_F_PEM_ASN1_READ, ERR_R_BUF_LIB);
118 BIO_set_fp(b, fp, BIO_NOCLOSE);
119 ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u);
125 static int check_pem(const char *nm, const char *name)
127 /* Normal matching nm and name */
128 if (strcmp(nm, name) == 0)
131 /* Make PEM_STRING_EVP_PKEY match any private key */
133 if (strcmp(name, PEM_STRING_EVP_PKEY) == 0) {
135 const EVP_PKEY_ASN1_METHOD *ameth;
136 if (strcmp(nm, PEM_STRING_PKCS8) == 0)
138 if (strcmp(nm, PEM_STRING_PKCS8INF) == 0)
140 slen = pem_check_suffix(nm, "PRIVATE KEY");
143 * NB: ENGINE implementations won't contain a deprecated old
144 * private key decode function so don't look for them.
146 ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen);
147 if (ameth && ameth->old_priv_decode)
153 if (strcmp(name, PEM_STRING_PARAMETERS) == 0) {
155 const EVP_PKEY_ASN1_METHOD *ameth;
156 slen = pem_check_suffix(nm, "PARAMETERS");
159 ameth = EVP_PKEY_asn1_find_str(&e, nm, slen);
162 if (ameth->param_decode)
166 #ifndef OPENSSL_NO_ENGINE
174 /* If reading DH parameters handle X9.42 DH format too */
175 if (strcmp(nm, PEM_STRING_DHXPARAMS) == 0
176 && strcmp(name, PEM_STRING_DHPARAMS) == 0)
179 /* Permit older strings */
181 if (strcmp(nm, PEM_STRING_X509_OLD) == 0
182 && strcmp(name, PEM_STRING_X509) == 0)
185 if (strcmp(nm, PEM_STRING_X509_REQ_OLD) == 0
186 && strcmp(name, PEM_STRING_X509_REQ) == 0)
189 /* Allow normal certs to be read as trusted certs */
190 if (strcmp(nm, PEM_STRING_X509) == 0
191 && strcmp(name, PEM_STRING_X509_TRUSTED) == 0)
194 if (strcmp(nm, PEM_STRING_X509_OLD) == 0
195 && strcmp(name, PEM_STRING_X509_TRUSTED) == 0)
198 /* Some CAs use PKCS#7 with CERTIFICATE headers */
199 if (strcmp(nm, PEM_STRING_X509) == 0
200 && strcmp(name, PEM_STRING_PKCS7) == 0)
203 if (strcmp(nm, PEM_STRING_PKCS7_SIGNED) == 0
204 && strcmp(name, PEM_STRING_PKCS7) == 0)
207 #ifndef OPENSSL_NO_CMS
208 if (strcmp(nm, PEM_STRING_X509) == 0
209 && strcmp(name, PEM_STRING_CMS) == 0)
211 /* Allow CMS to be read from PKCS#7 headers */
212 if (strcmp(nm, PEM_STRING_PKCS7) == 0
213 && strcmp(name, PEM_STRING_CMS) == 0)
220 static void pem_free(void *p, unsigned int flags)
222 if (flags & PEM_FLAG_SECURE)
223 OPENSSL_secure_free(p);
228 static void *pem_malloc(int num, unsigned int flags)
230 return (flags & PEM_FLAG_SECURE) ? OPENSSL_secure_malloc(num)
231 : OPENSSL_malloc(num);
234 static int pem_bytes_read_bio_flags(unsigned char **pdata, long *plen,
235 char **pnm, const char *name, BIO *bp,
236 pem_password_cb *cb, void *u,
239 EVP_CIPHER_INFO cipher;
240 char *nm = NULL, *header = NULL;
241 unsigned char *data = NULL;
247 pem_free(header, flags);
248 pem_free(data, flags);
249 if (!PEM_read_bio_ex(bp, &nm, &header, &data, &len, flags)) {
250 if (ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE)
251 ERR_add_error_data(2, "Expecting: ", name);
254 } while (!check_pem(nm, name));
255 if (!PEM_get_EVP_CIPHER_INFO(header, &cipher))
257 if (!PEM_do_header(&cipher, data, &len, cb, u))
269 if (!ret || pnm == NULL)
271 pem_free(header, flags);
273 pem_free(data, flags);
277 int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
278 const char *name, BIO *bp, pem_password_cb *cb,
280 return pem_bytes_read_bio_flags(pdata, plen, pnm, name, bp, cb, u,
281 PEM_FLAG_EAY_COMPATIBLE);
284 int PEM_bytes_read_bio_secmem(unsigned char **pdata, long *plen, char **pnm,
285 const char *name, BIO *bp, pem_password_cb *cb,
287 return pem_bytes_read_bio_flags(pdata, plen, pnm, name, bp, cb, u,
288 PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE);
291 #ifndef OPENSSL_NO_STDIO
292 int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp,
293 void *x, const EVP_CIPHER *enc, unsigned char *kstr,
294 int klen, pem_password_cb *callback, void *u)
299 if ((b = BIO_new(BIO_s_file())) == NULL) {
300 PEMerr(PEM_F_PEM_ASN1_WRITE, ERR_R_BUF_LIB);
303 BIO_set_fp(b, fp, BIO_NOCLOSE);
304 ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u);
310 int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp,
311 void *x, const EVP_CIPHER *enc, unsigned char *kstr,
312 int klen, pem_password_cb *callback, void *u)
314 EVP_CIPHER_CTX *ctx = NULL;
315 int dsize = 0, i = 0, j = 0, ret = 0;
316 unsigned char *p, *data = NULL;
317 const char *objstr = NULL;
318 char buf[PEM_BUFSIZE];
319 unsigned char key[EVP_MAX_KEY_LENGTH];
320 unsigned char iv[EVP_MAX_IV_LENGTH];
323 objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc));
324 if (objstr == NULL || EVP_CIPHER_iv_length(enc) == 0) {
325 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_UNSUPPORTED_CIPHER);
330 if ((dsize = i2d(x, NULL)) < 0) {
331 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_ASN1_LIB);
335 /* dsize + 8 bytes are needed */
336 /* actually it needs the cipher block size extra... */
337 data = OPENSSL_malloc((unsigned int)dsize + 20);
339 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_MALLOC_FAILURE);
347 if (callback == NULL)
348 klen = PEM_def_callback(buf, PEM_BUFSIZE, 1, u);
350 klen = (*callback) (buf, PEM_BUFSIZE, 1, u);
352 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_READ_KEY);
355 #ifdef CHARSET_EBCDIC
356 /* Convert the pass phrase from EBCDIC */
357 ebcdic2ascii(buf, buf, klen);
359 kstr = (unsigned char *)buf;
361 RAND_add(data, i, 0); /* put in the RSA key. */
362 OPENSSL_assert(EVP_CIPHER_iv_length(enc) <= (int)sizeof(iv));
363 if (RAND_bytes(iv, EVP_CIPHER_iv_length(enc)) <= 0) /* Generate a salt */
366 * The 'iv' is used as the iv and as a salt. It is NOT taken from
367 * the BytesToKey function
369 if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1, key, NULL))
372 if (kstr == (unsigned char *)buf)
373 OPENSSL_cleanse(buf, PEM_BUFSIZE);
375 OPENSSL_assert(strlen(objstr) + 23 + 2 * EVP_CIPHER_iv_length(enc) + 13
379 PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
380 PEM_dek_info(buf, objstr, EVP_CIPHER_iv_length(enc), (char *)iv);
384 if ((ctx = EVP_CIPHER_CTX_new()) == NULL
385 || !EVP_EncryptInit_ex(ctx, enc, NULL, key, iv)
386 || !EVP_EncryptUpdate(ctx, data, &j, data, i)
387 || !EVP_EncryptFinal_ex(ctx, &(data[j]), &i))
396 i = PEM_write_bio(bp, name, buf, data, i);
400 OPENSSL_cleanse(key, sizeof(key));
401 OPENSSL_cleanse(iv, sizeof(iv));
402 EVP_CIPHER_CTX_free(ctx);
403 OPENSSL_cleanse(buf, PEM_BUFSIZE);
404 OPENSSL_clear_free(data, (unsigned int)dsize);
408 int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
409 pem_password_cb *callback, void *u)
414 int ilen = (int) len; /* EVP_DecryptUpdate etc. take int lengths */
416 unsigned char key[EVP_MAX_KEY_LENGTH];
417 char buf[PEM_BUFSIZE];
419 #if LONG_MAX > INT_MAX
420 /* Check that we did not truncate the length */
422 PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_HEADER_TOO_LONG);
427 if (cipher->cipher == NULL)
429 if (callback == NULL)
430 keylen = PEM_def_callback(buf, PEM_BUFSIZE, 0, u);
432 keylen = callback(buf, PEM_BUFSIZE, 0, u);
434 PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_PASSWORD_READ);
437 #ifdef CHARSET_EBCDIC
438 /* Convert the pass phrase from EBCDIC */
439 ebcdic2ascii(buf, buf, keylen);
442 if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
443 (unsigned char *)buf, keylen, 1, key, NULL))
446 ctx = EVP_CIPHER_CTX_new();
450 ok = EVP_DecryptInit_ex(ctx, cipher->cipher, NULL, key, &(cipher->iv[0]));
452 ok = EVP_DecryptUpdate(ctx, data, &ilen, data, ilen);
454 /* Squirrel away the length of data decrypted so far. */
456 ok = EVP_DecryptFinal_ex(ctx, &(data[ilen]), &ilen);
461 PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_DECRYPT);
463 EVP_CIPHER_CTX_free(ctx);
464 OPENSSL_cleanse((char *)buf, sizeof(buf));
465 OPENSSL_cleanse((char *)key, sizeof(key));
470 * This implements a very limited PEM header parser that does not support the
471 * full grammar of rfc1421. In particular, folded headers are not supported,
472 * nor is additional whitespace.
474 * A robust implementation would make use of a library that turns the headers
475 * into a BIO from which one folded line is read at a time, and is then split
476 * into a header label and content. We would then parse the content of the
477 * headers we care about. This is overkill for just this limited use-case, but
478 * presumably we also parse rfc822-style headers for S/MIME, so a common
479 * abstraction might well be more generally useful.
481 int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
483 static const char ProcType[] = "Proc-Type:";
484 static const char ENCRYPTED[] = "ENCRYPTED";
485 static const char DEKInfo[] = "DEK-Info:";
486 const EVP_CIPHER *enc = NULL;
488 char *dekinfostart, c;
490 cipher->cipher = NULL;
491 if ((header == NULL) || (*header == '\0') || (*header == '\n'))
494 if (strncmp(header, ProcType, sizeof(ProcType)-1) != 0) {
495 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_PROC_TYPE);
498 header += sizeof(ProcType)-1;
499 header += strspn(header, " \t");
501 if (*header++ != '4' || *header++ != ',')
503 header += strspn(header, " \t");
505 /* We expect "ENCRYPTED" followed by optional white-space + line break */
506 if (strncmp(header, ENCRYPTED, sizeof(ENCRYPTED)-1) != 0 ||
507 strspn(header+sizeof(ENCRYPTED)-1, " \t\r\n") == 0) {
508 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_ENCRYPTED);
511 header += sizeof(ENCRYPTED)-1;
512 header += strspn(header, " \t\r");
513 if (*header++ != '\n') {
514 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_SHORT_HEADER);
519 * https://tools.ietf.org/html/rfc1421#section-4.6.1.3
520 * We expect "DEK-Info: algo[,hex-parameters]"
522 if (strncmp(header, DEKInfo, sizeof(DEKInfo)-1) != 0) {
523 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_DEK_INFO);
526 header += sizeof(DEKInfo)-1;
527 header += strspn(header, " \t");
530 * DEK-INFO is a comma-separated combination of algorithm name and optional
533 dekinfostart = header;
534 header += strcspn(header, " \t,");
537 cipher->cipher = enc = EVP_get_cipherbyname(dekinfostart);
539 header += strspn(header, " \t");
542 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_UNSUPPORTED_ENCRYPTION);
545 ivlen = EVP_CIPHER_iv_length(enc);
546 if (ivlen > 0 && *header++ != ',') {
547 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_MISSING_DEK_IV);
549 } else if (ivlen == 0 && *header == ',') {
550 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_UNEXPECTED_DEK_IV);
554 if (!load_iv(&header, cipher->iv, EVP_CIPHER_iv_length(enc)))
560 static int load_iv(char **fromp, unsigned char *to, int num)
566 for (i = 0; i < num; i++)
569 for (i = 0; i < num; i++) {
570 v = OPENSSL_hexchar2int(*from);
572 PEMerr(PEM_F_LOAD_IV, PEM_R_BAD_IV_CHARS);
576 to[i / 2] |= v << (long)((!(i & 1)) * 4);
583 #ifndef OPENSSL_NO_STDIO
584 int PEM_write(FILE *fp, const char *name, const char *header,
585 const unsigned char *data, long len)
590 if ((b = BIO_new(BIO_s_file())) == NULL) {
591 PEMerr(PEM_F_PEM_WRITE, ERR_R_BUF_LIB);
594 BIO_set_fp(b, fp, BIO_NOCLOSE);
595 ret = PEM_write_bio(b, name, header, data, len);
601 int PEM_write_bio(BIO *bp, const char *name, const char *header,
602 const unsigned char *data, long len)
604 int nlen, n, i, j, outl;
605 unsigned char *buf = NULL;
606 EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new();
607 int reason = ERR_R_BUF_LIB;
610 reason = ERR_R_MALLOC_FAILURE;
617 if ((BIO_write(bp, "-----BEGIN ", 11) != 11) ||
618 (BIO_write(bp, name, nlen) != nlen) ||
619 (BIO_write(bp, "-----\n", 6) != 6))
624 if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1))
628 buf = OPENSSL_malloc(PEM_BUFSIZE * 8);
630 reason = ERR_R_MALLOC_FAILURE;
636 n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
637 if (!EVP_EncodeUpdate(ctx, buf, &outl, &(data[j]), n))
639 if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl))
645 EVP_EncodeFinal(ctx, buf, &outl);
646 if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl))
648 if ((BIO_write(bp, "-----END ", 9) != 9) ||
649 (BIO_write(bp, name, nlen) != nlen) ||
650 (BIO_write(bp, "-----\n", 6) != 6))
652 OPENSSL_clear_free(buf, PEM_BUFSIZE * 8);
653 EVP_ENCODE_CTX_free(ctx);
656 OPENSSL_clear_free(buf, PEM_BUFSIZE * 8);
657 EVP_ENCODE_CTX_free(ctx);
658 PEMerr(PEM_F_PEM_WRITE_BIO, reason);
662 #ifndef OPENSSL_NO_STDIO
663 int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
669 if ((b = BIO_new(BIO_s_file())) == NULL) {
670 PEMerr(PEM_F_PEM_READ, ERR_R_BUF_LIB);
673 BIO_set_fp(b, fp, BIO_NOCLOSE);
674 ret = PEM_read_bio(b, name, header, data, len);
680 /* Some helpers for PEM_read_bio_ex(). */
682 #define isb64(c) (isalnum(c) || (c) == '+' || (c) == '/' || (c) == '=')
684 static int sanitize_line(char *linebuf, int len, unsigned int flags)
688 if (flags & PEM_FLAG_EAY_COMPATIBLE) {
689 /* Strip trailing whitespace */
690 while ((len >= 0) && (linebuf[len] <= ' '))
692 /* Go back to whitespace before applying uniform line ending. */
694 } else if (flags & PEM_FLAG_ONLY_B64) {
695 for (i = 0; i < len; ++i) {
696 if (!isb64(linebuf[i]) || linebuf[i] == '\n' || linebuf[i] == '\r')
701 /* EVP_DecodeBlock strips leading and trailing whitespace, so just strip
702 * control characters in-place and let everything through. */
703 for (i = 0; i < len; ++i) {
704 if (linebuf[i] == '\n' || linebuf[i] == '\r')
706 if (iscntrl(linebuf[i]))
711 /* The caller allocated LINESIZE+1, so this is safe. */
712 linebuf[len++] = '\n';
718 /* Note trailing spaces for begin and end. */
719 static const char beginstr[] = "-----BEGIN ";
720 static const char endstr[] = "-----END ";
721 static const char tailstr[] = "-----\n";
722 #define BEGINLEN (sizeof(beginstr) - 1)
723 #define ENDLEN (sizeof(endstr) - 1)
724 #define TAILLEN (sizeof(tailstr) - 1)
725 static int get_name(BIO *bp, char **name, unsigned int flags)
732 * Need to hold trailing NUL (accounted for by BIO_gets() and the newline
733 * that will be added by sanitize_line() (the extra '1').
735 linebuf = pem_malloc(LINESIZE + 1, flags);
736 if (linebuf == NULL) {
737 PEMerr(PEM_F_GET_NAME, ERR_R_MALLOC_FAILURE);
742 len = BIO_gets(bp, linebuf, LINESIZE);
745 PEMerr(PEM_F_GET_NAME, PEM_R_NO_START_LINE);
749 /* Strip trailing garbage and standardize ending. */
750 len = sanitize_line(linebuf, len, flags & ~PEM_FLAG_ONLY_B64);
752 /* Allow leading empty or non-matching lines. */
753 } while (strncmp(linebuf, beginstr, BEGINLEN) != 0
755 || strncmp(linebuf + len - TAILLEN, tailstr, TAILLEN) != 0);
756 linebuf[len - TAILLEN] = '\0';
757 len = len - BEGINLEN - TAILLEN + 1;
758 *name = pem_malloc(len, flags);
760 PEMerr(PEM_F_GET_NAME, ERR_R_MALLOC_FAILURE);
763 memcpy(*name, linebuf + BEGINLEN, len);
767 pem_free(linebuf, flags);
771 /* Keep track of how much of a header we've seen. */
779 * Extract the optional PEM header, with details on the type of content and
780 * any encryption used on the contents, and the bulk of the data from the bio.
781 * The end of the header is marked by a blank line; if the end-of-input marker
782 * is reached prior to a blank line, there is no header.
784 * The header and data arguments are BIO** since we may have to swap them
785 * if there is no header, for efficiency.
787 * We need the name of the PEM-encoded type to verify the end string.
789 static int get_header_and_data(BIO *bp, BIO **header, BIO **data, char *name,
794 int len, line, ret = 0, end = 0;
795 /* 0 if not seen (yet), 1 if reading header, 2 if finished header */
796 enum header_status got_header = MAYBE_HEADER;
797 unsigned int flags_mask;
800 /* Need to hold trailing NUL (accounted for by BIO_gets() and the newline
801 * that will be added by sanitize_line() (the extra '1'). */
802 linebuf = pem_malloc(LINESIZE + 1, flags);
803 if (linebuf == NULL) {
804 PEMerr(PEM_F_GET_HEADER_AND_DATA, ERR_R_MALLOC_FAILURE);
808 for (line = 0; ; line++) {
810 len = BIO_gets(bp, linebuf, LINESIZE);
812 PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_SHORT_HEADER);
816 if (got_header == MAYBE_HEADER) {
817 if (memchr(linebuf, ':', len) != NULL)
818 got_header = IN_HEADER;
820 if (!strncmp(linebuf, endstr, ENDLEN) || got_header == IN_HEADER)
821 flags_mask &= ~PEM_FLAG_ONLY_B64;
822 len = sanitize_line(linebuf, len, flags & flags_mask);
824 /* Check for end of header. */
825 if (linebuf[0] == '\n') {
826 if (got_header == POST_HEADER) {
827 /* Another blank line is an error. */
828 PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_BAD_END_LINE);
831 got_header = POST_HEADER;
836 /* Check for end of stream (which means there is no header). */
837 if (strncmp(linebuf, endstr, ENDLEN) == 0) {
838 p = linebuf + ENDLEN;
839 namelen = strlen(name);
840 if (strncmp(p, name, namelen) != 0 ||
841 strncmp(p + namelen, tailstr, TAILLEN) != 0) {
842 PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_BAD_END_LINE);
845 if (got_header == MAYBE_HEADER) {
851 /* Malformed input; short line not at end of data. */
852 PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_BAD_END_LINE);
856 * Else, a line of text -- could be header or data; we don't
857 * know yet. Just pass it through.
859 BIO_puts(tmp, linebuf);
861 * Only encrypted files need the line length check applied.
863 if (got_header == POST_HEADER) {
864 /* 65 includes the trailing newline */
874 pem_free(linebuf, flags);
879 * Read in PEM-formatted data from the given BIO.
881 * By nature of the PEM format, all content must be printable ASCII (except
882 * for line endings). Other characters, or lines that are longer than 80
883 * characters, are malformed input and will be rejected.
885 int PEM_read_bio_ex(BIO *bp, char **name_out, char **header,
886 unsigned char **data, long *len_out, unsigned int flags)
888 EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new();
889 const BIO_METHOD *bmeth;
890 BIO *headerB = NULL, *dataB = NULL;
892 int len, taillen, headerlen, ret = 0;
896 PEMerr(PEM_F_PEM_READ_BIO_EX, ERR_R_MALLOC_FAILURE);
901 *name_out = *header = NULL;
903 if ((flags & PEM_FLAG_EAY_COMPATIBLE) && (flags & PEM_FLAG_ONLY_B64)) {
904 /* These two are mutually incompatible; bail out. */
905 PEMerr(PEM_F_PEM_READ_BIO_EX, ERR_R_PASSED_INVALID_ARGUMENT);
908 bmeth = (flags & PEM_FLAG_SECURE) ? BIO_s_secmem() : BIO_s_mem();
910 headerB = BIO_new(bmeth);
911 dataB = BIO_new(bmeth);
912 if (headerB == NULL || dataB == NULL) {
913 PEMerr(PEM_F_PEM_READ_BIO_EX, ERR_R_MALLOC_FAILURE);
917 if (!get_name(bp, &name, flags))
919 if (!get_header_and_data(bp, &headerB, &dataB, name, flags))
923 BIO_get_mem_ptr(dataB, &buf_mem);
924 len = buf_mem->length;
925 if (EVP_DecodeUpdate(ctx, (unsigned char*)buf_mem->data, &len,
926 (unsigned char*)buf_mem->data, len) < 0
927 || EVP_DecodeFinal(ctx, (unsigned char*)&(buf_mem->data[len]),
929 PEMerr(PEM_F_PEM_READ_BIO_EX, PEM_R_BAD_BASE64_DECODE);
933 buf_mem->length = len;
935 /* There was no data in the PEM file; avoid malloc(0). */
938 headerlen = BIO_get_mem_data(headerB, NULL);
939 *header = pem_malloc(headerlen + 1, flags);
940 *data = pem_malloc(len, flags);
941 if (*header == NULL || *data == NULL) {
942 pem_free(*header, flags);
943 pem_free(*data, flags);
946 BIO_read(headerB, *header, headerlen);
947 (*header)[headerlen] = '\0';
948 BIO_read(dataB, *data, len);
955 EVP_ENCODE_CTX_free(ctx);
956 pem_free(name, flags);
962 int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
965 return PEM_read_bio_ex(bp, name, header, data, len, PEM_FLAG_EAY_COMPATIBLE);
969 * Check pem string and return prefix length. If for example the pem_str ==
970 * "RSA PRIVATE KEY" and suffix = "PRIVATE KEY" the return value is 3 for the
974 int pem_check_suffix(const char *pem_str, const char *suffix)
976 int pem_len = strlen(pem_str);
977 int suffix_len = strlen(suffix);
979 if (suffix_len + 1 >= pem_len)
981 p = pem_str + pem_len - suffix_len;
982 if (strcmp(p, suffix))