2 * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
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
10 /* We need to use some engine deprecated APIs */
11 #define OPENSSL_SUPPRESS_DEPRECATED
14 #include "crypto/ctype.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>
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 pem_check_suffix(const char *pem_str
, const char *suffix
);
34 int PEM_def_callback(char *buf
, int num
, int rwflag
, void *userdata
)
39 /* We assume that the user passes a default password as userdata */
42 i
= (i
> num
) ? num
: i
;
43 memcpy(buf
, userdata
, i
);
47 prompt
= EVP_get_pw_prompt();
49 prompt
= "Enter PEM pass phrase:";
52 * rwflag == 0 means decryption
53 * rwflag == 1 means encryption
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.
58 min_len
= rwflag
? MIN_LENGTH
: 0;
60 i
= EVP_read_pw_string_min(buf
, min_len
, num
, prompt
, rwflag
);
62 ERR_raise(ERR_LIB_PEM
, PEM_R_PROBLEMS_GETTING_PASSWORD
);
63 memset(buf
, 0, (unsigned int)num
);
69 void PEM_proc_type(char *buf
, int type
)
72 char *p
= buf
+ strlen(buf
);
74 if (type
== PEM_TYPE_ENCRYPTED
)
76 else if (type
== PEM_TYPE_MIC_CLEAR
)
78 else if (type
== PEM_TYPE_MIC_ONLY
)
83 BIO_snprintf(p
, PEM_BUFSIZE
- (size_t)(p
- buf
), "Proc-Type: 4,%s\n", str
);
86 void PEM_dek_info(char *buf
, const char *type
, int len
, const char *str
)
89 char *p
= buf
+ strlen(buf
);
90 int j
= PEM_BUFSIZE
- (size_t)(p
- buf
), n
;
92 n
= BIO_snprintf(p
, j
, "DEK-Info: %s,", type
);
96 for (i
= 0; i
< len
; i
++) {
97 n
= BIO_snprintf(p
, j
, "%02X", 0xff & str
[i
]);
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
)
115 if ((b
= BIO_new(BIO_s_file())) == NULL
) {
116 ERR_raise(ERR_LIB_PEM
, ERR_R_BUF_LIB
);
119 BIO_set_fp(b
, fp
, BIO_NOCLOSE
);
120 ret
= PEM_ASN1_read_bio(d2i
, name
, b
, x
, cb
, u
);
126 static int check_pem(const char *nm
, const char *name
)
128 /* Normal matching nm and name */
129 if (strcmp(nm
, name
) == 0)
132 /* Make PEM_STRING_EVP_PKEY match any private key */
134 if (strcmp(name
, PEM_STRING_EVP_PKEY
) == 0) {
136 const EVP_PKEY_ASN1_METHOD
*ameth
;
137 if (strcmp(nm
, PEM_STRING_PKCS8
) == 0)
139 if (strcmp(nm
, PEM_STRING_PKCS8INF
) == 0)
141 slen
= pem_check_suffix(nm
, "PRIVATE KEY");
144 * NB: ENGINE implementations won't contain a deprecated old
145 * private key decode function so don't look for them.
147 ameth
= EVP_PKEY_asn1_find_str(NULL
, nm
, slen
);
148 if (ameth
&& ameth
->old_priv_decode
)
154 if (strcmp(name
, PEM_STRING_PARAMETERS
) == 0) {
156 const EVP_PKEY_ASN1_METHOD
*ameth
;
157 slen
= pem_check_suffix(nm
, "PARAMETERS");
160 ameth
= EVP_PKEY_asn1_find_str(&e
, nm
, slen
);
163 if (ameth
->param_decode
)
167 #ifndef OPENSSL_NO_ENGINE
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)
180 /* Permit older strings */
182 if (strcmp(nm
, PEM_STRING_X509_OLD
) == 0
183 && strcmp(name
, PEM_STRING_X509
) == 0)
186 if (strcmp(nm
, PEM_STRING_X509_REQ_OLD
) == 0
187 && strcmp(name
, PEM_STRING_X509_REQ
) == 0)
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)
195 if (strcmp(nm
, PEM_STRING_X509_OLD
) == 0
196 && strcmp(name
, PEM_STRING_X509_TRUSTED
) == 0)
199 /* Some CAs use PKCS#7 with CERTIFICATE headers */
200 if (strcmp(nm
, PEM_STRING_X509
) == 0
201 && strcmp(name
, PEM_STRING_PKCS7
) == 0)
204 if (strcmp(nm
, PEM_STRING_PKCS7_SIGNED
) == 0
205 && strcmp(name
, PEM_STRING_PKCS7
) == 0)
208 #ifndef OPENSSL_NO_CMS
209 if (strcmp(nm
, PEM_STRING_X509
) == 0
210 && strcmp(name
, PEM_STRING_CMS
) == 0)
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)
221 static void pem_free(void *p
, unsigned int flags
, size_t num
)
223 if (flags
& PEM_FLAG_SECURE
)
224 OPENSSL_secure_clear_free(p
, num
);
229 static void *pem_malloc(int num
, unsigned int flags
)
231 return (flags
& PEM_FLAG_SECURE
) ? OPENSSL_secure_malloc(num
)
232 : OPENSSL_malloc(num
);
235 static int pem_bytes_read_bio_flags(unsigned char **pdata
, long *plen
,
236 char **pnm
, const char *name
, BIO
*bp
,
237 pem_password_cb
*cb
, void *u
,
240 EVP_CIPHER_INFO cipher
;
241 char *nm
= NULL
, *header
= NULL
;
242 unsigned char *data
= NULL
;
247 pem_free(nm
, flags
, 0);
248 pem_free(header
, flags
, 0);
249 pem_free(data
, flags
, len
);
250 if (!PEM_read_bio_ex(bp
, &nm
, &header
, &data
, &len
, flags
)) {
251 if (ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE
)
252 ERR_add_error_data(2, "Expecting: ", name
);
255 } while (!check_pem(nm
, name
));
256 if (!PEM_get_EVP_CIPHER_INFO(header
, &cipher
))
258 if (!PEM_do_header(&cipher
, data
, &len
, cb
, u
))
270 if (!ret
|| pnm
== NULL
)
271 pem_free(nm
, flags
, 0);
272 pem_free(header
, flags
, 0);
274 pem_free(data
, flags
, len
);
278 int PEM_bytes_read_bio(unsigned char **pdata
, long *plen
, char **pnm
,
279 const char *name
, BIO
*bp
, pem_password_cb
*cb
,
281 return pem_bytes_read_bio_flags(pdata
, plen
, pnm
, name
, bp
, cb
, u
,
282 PEM_FLAG_EAY_COMPATIBLE
);
285 int PEM_bytes_read_bio_secmem(unsigned char **pdata
, long *plen
, char **pnm
,
286 const char *name
, BIO
*bp
, pem_password_cb
*cb
,
288 return pem_bytes_read_bio_flags(pdata
, plen
, pnm
, name
, bp
, cb
, u
,
289 PEM_FLAG_SECURE
| PEM_FLAG_EAY_COMPATIBLE
);
292 #ifndef OPENSSL_NO_STDIO
293 int PEM_ASN1_write(i2d_of_void
*i2d
, const char *name
, FILE *fp
,
294 const void *x
, const EVP_CIPHER
*enc
,
295 const unsigned char *kstr
, int klen
,
296 pem_password_cb
*callback
, void *u
)
301 if ((b
= BIO_new(BIO_s_file())) == NULL
) {
302 ERR_raise(ERR_LIB_PEM
, ERR_R_BUF_LIB
);
305 BIO_set_fp(b
, fp
, BIO_NOCLOSE
);
306 ret
= PEM_ASN1_write_bio(i2d
, name
, b
, x
, enc
, kstr
, klen
, callback
, u
);
312 int PEM_ASN1_write_bio(i2d_of_void
*i2d
, const char *name
, BIO
*bp
,
313 const void *x
, const EVP_CIPHER
*enc
,
314 const unsigned char *kstr
, int klen
,
315 pem_password_cb
*callback
, void *u
)
317 EVP_CIPHER_CTX
*ctx
= NULL
;
318 int dsize
= 0, i
= 0, j
= 0, ret
= 0;
319 unsigned char *p
, *data
= NULL
;
320 const char *objstr
= NULL
;
321 char buf
[PEM_BUFSIZE
];
322 unsigned char key
[EVP_MAX_KEY_LENGTH
];
323 unsigned char iv
[EVP_MAX_IV_LENGTH
];
326 objstr
= OBJ_nid2sn(EVP_CIPHER_nid(enc
));
327 if (objstr
== NULL
|| EVP_CIPHER_iv_length(enc
) == 0
328 || EVP_CIPHER_iv_length(enc
) > (int)sizeof(iv
)
330 * Check "Proc-Type: 4,Encrypted\nDEK-Info: objstr,hex-iv\n"
333 || (strlen(objstr
) + 23 + 2 * EVP_CIPHER_iv_length(enc
) + 13)
335 ERR_raise(ERR_LIB_PEM
, PEM_R_UNSUPPORTED_CIPHER
);
340 if ((dsize
= i2d(x
, NULL
)) <= 0) {
341 ERR_raise(ERR_LIB_PEM
, ERR_R_ASN1_LIB
);
345 /* dsize + 8 bytes are needed */
346 /* actually it needs the cipher block size extra... */
347 data
= OPENSSL_malloc((unsigned int)dsize
+ 20);
349 ERR_raise(ERR_LIB_PEM
, ERR_R_MALLOC_FAILURE
);
357 if (callback
== NULL
)
358 klen
= PEM_def_callback(buf
, PEM_BUFSIZE
, 1, u
);
360 klen
= (*callback
) (buf
, PEM_BUFSIZE
, 1, u
);
362 ERR_raise(ERR_LIB_PEM
, PEM_R_READ_KEY
);
365 #ifdef CHARSET_EBCDIC
366 /* Convert the pass phrase from EBCDIC */
367 ebcdic2ascii(buf
, buf
, klen
);
369 kstr
= (unsigned char *)buf
;
371 if (RAND_bytes(iv
, EVP_CIPHER_iv_length(enc
)) <= 0) /* Generate a salt */
374 * The 'iv' is used as the iv and as a salt. It is NOT taken from
375 * the BytesToKey function
377 if (!EVP_BytesToKey(enc
, EVP_md5(), iv
, kstr
, klen
, 1, key
, NULL
))
380 if (kstr
== (unsigned char *)buf
)
381 OPENSSL_cleanse(buf
, PEM_BUFSIZE
);
384 PEM_proc_type(buf
, PEM_TYPE_ENCRYPTED
);
385 PEM_dek_info(buf
, objstr
, EVP_CIPHER_iv_length(enc
), (char *)iv
);
389 if ((ctx
= EVP_CIPHER_CTX_new()) == NULL
390 || !EVP_EncryptInit_ex(ctx
, enc
, NULL
, key
, iv
)
391 || !EVP_EncryptUpdate(ctx
, data
, &j
, data
, i
)
392 || !EVP_EncryptFinal_ex(ctx
, &(data
[j
]), &i
))
401 i
= PEM_write_bio(bp
, name
, buf
, data
, i
);
405 OPENSSL_cleanse(key
, sizeof(key
));
406 OPENSSL_cleanse(iv
, sizeof(iv
));
407 EVP_CIPHER_CTX_free(ctx
);
408 OPENSSL_cleanse(buf
, PEM_BUFSIZE
);
409 OPENSSL_clear_free(data
, (unsigned int)dsize
);
413 int PEM_do_header(EVP_CIPHER_INFO
*cipher
, unsigned char *data
, long *plen
,
414 pem_password_cb
*callback
, void *u
)
419 int ilen
= (int) len
; /* EVP_DecryptUpdate etc. take int lengths */
421 unsigned char key
[EVP_MAX_KEY_LENGTH
];
422 char buf
[PEM_BUFSIZE
];
424 #if LONG_MAX > INT_MAX
425 /* Check that we did not truncate the length */
427 ERR_raise(ERR_LIB_PEM
, PEM_R_HEADER_TOO_LONG
);
432 if (cipher
->cipher
== NULL
)
434 if (callback
== NULL
)
435 keylen
= PEM_def_callback(buf
, PEM_BUFSIZE
, 0, u
);
437 keylen
= callback(buf
, PEM_BUFSIZE
, 0, u
);
439 ERR_raise(ERR_LIB_PEM
, PEM_R_BAD_PASSWORD_READ
);
442 #ifdef CHARSET_EBCDIC
443 /* Convert the pass phrase from EBCDIC */
444 ebcdic2ascii(buf
, buf
, keylen
);
447 if (!EVP_BytesToKey(cipher
->cipher
, EVP_md5(), &(cipher
->iv
[0]),
448 (unsigned char *)buf
, keylen
, 1, key
, NULL
))
451 ctx
= EVP_CIPHER_CTX_new();
455 ok
= EVP_DecryptInit_ex(ctx
, cipher
->cipher
, NULL
, key
, &(cipher
->iv
[0]));
457 ok
= EVP_DecryptUpdate(ctx
, data
, &ilen
, data
, ilen
);
459 /* Squirrel away the length of data decrypted so far. */
461 ok
= EVP_DecryptFinal_ex(ctx
, &(data
[ilen
]), &ilen
);
466 ERR_raise(ERR_LIB_PEM
, PEM_R_BAD_DECRYPT
);
468 EVP_CIPHER_CTX_free(ctx
);
469 OPENSSL_cleanse((char *)buf
, sizeof(buf
));
470 OPENSSL_cleanse((char *)key
, sizeof(key
));
475 * This implements a very limited PEM header parser that does not support the
476 * full grammar of rfc1421. In particular, folded headers are not supported,
477 * nor is additional whitespace.
479 * A robust implementation would make use of a library that turns the headers
480 * into a BIO from which one folded line is read at a time, and is then split
481 * into a header label and content. We would then parse the content of the
482 * headers we care about. This is overkill for just this limited use-case, but
483 * presumably we also parse rfc822-style headers for S/MIME, so a common
484 * abstraction might well be more generally useful.
486 int PEM_get_EVP_CIPHER_INFO(char *header
, EVP_CIPHER_INFO
*cipher
)
488 static const char ProcType
[] = "Proc-Type:";
489 static const char ENCRYPTED
[] = "ENCRYPTED";
490 static const char DEKInfo
[] = "DEK-Info:";
491 const EVP_CIPHER
*enc
= NULL
;
493 char *dekinfostart
, c
;
495 cipher
->cipher
= NULL
;
496 memset(cipher
->iv
, 0, sizeof(cipher
->iv
));
497 if ((header
== NULL
) || (*header
== '\0') || (*header
== '\n'))
500 if (strncmp(header
, ProcType
, sizeof(ProcType
)-1) != 0) {
501 ERR_raise(ERR_LIB_PEM
, PEM_R_NOT_PROC_TYPE
);
504 header
+= sizeof(ProcType
)-1;
505 header
+= strspn(header
, " \t");
507 if (*header
++ != '4' || *header
++ != ',')
509 header
+= strspn(header
, " \t");
511 /* We expect "ENCRYPTED" followed by optional white-space + line break */
512 if (strncmp(header
, ENCRYPTED
, sizeof(ENCRYPTED
)-1) != 0 ||
513 strspn(header
+sizeof(ENCRYPTED
)-1, " \t\r\n") == 0) {
514 ERR_raise(ERR_LIB_PEM
, PEM_R_NOT_ENCRYPTED
);
517 header
+= sizeof(ENCRYPTED
)-1;
518 header
+= strspn(header
, " \t\r");
519 if (*header
++ != '\n') {
520 ERR_raise(ERR_LIB_PEM
, PEM_R_SHORT_HEADER
);
525 * https://tools.ietf.org/html/rfc1421#section-4.6.1.3
526 * We expect "DEK-Info: algo[,hex-parameters]"
528 if (strncmp(header
, DEKInfo
, sizeof(DEKInfo
)-1) != 0) {
529 ERR_raise(ERR_LIB_PEM
, PEM_R_NOT_DEK_INFO
);
532 header
+= sizeof(DEKInfo
)-1;
533 header
+= strspn(header
, " \t");
536 * DEK-INFO is a comma-separated combination of algorithm name and optional
539 dekinfostart
= header
;
540 header
+= strcspn(header
, " \t,");
543 cipher
->cipher
= enc
= EVP_get_cipherbyname(dekinfostart
);
545 header
+= strspn(header
, " \t");
548 ERR_raise(ERR_LIB_PEM
, PEM_R_UNSUPPORTED_ENCRYPTION
);
551 ivlen
= EVP_CIPHER_iv_length(enc
);
552 if (ivlen
> 0 && *header
++ != ',') {
553 ERR_raise(ERR_LIB_PEM
, PEM_R_MISSING_DEK_IV
);
555 } else if (ivlen
== 0 && *header
== ',') {
556 ERR_raise(ERR_LIB_PEM
, PEM_R_UNEXPECTED_DEK_IV
);
560 if (!load_iv(&header
, cipher
->iv
, EVP_CIPHER_iv_length(enc
)))
566 static int load_iv(char **fromp
, unsigned char *to
, int num
)
572 for (i
= 0; i
< num
; i
++)
575 for (i
= 0; i
< num
; i
++) {
576 v
= OPENSSL_hexchar2int(*from
);
578 ERR_raise(ERR_LIB_PEM
, PEM_R_BAD_IV_CHARS
);
582 to
[i
/ 2] |= v
<< (long)((!(i
& 1)) * 4);
589 #ifndef OPENSSL_NO_STDIO
590 int PEM_write(FILE *fp
, const char *name
, const char *header
,
591 const unsigned char *data
, long len
)
596 if ((b
= BIO_new(BIO_s_file())) == NULL
) {
597 ERR_raise(ERR_LIB_PEM
, ERR_R_BUF_LIB
);
600 BIO_set_fp(b
, fp
, BIO_NOCLOSE
);
601 ret
= PEM_write_bio(b
, name
, header
, data
, len
);
607 int PEM_write_bio(BIO
*bp
, const char *name
, const char *header
,
608 const unsigned char *data
, long len
)
610 int nlen
, n
, i
, j
, outl
;
611 unsigned char *buf
= NULL
;
612 EVP_ENCODE_CTX
*ctx
= EVP_ENCODE_CTX_new();
613 int reason
= ERR_R_BUF_LIB
;
617 reason
= ERR_R_MALLOC_FAILURE
;
624 if ((BIO_write(bp
, "-----BEGIN ", 11) != 11) ||
625 (BIO_write(bp
, name
, nlen
) != nlen
) ||
626 (BIO_write(bp
, "-----\n", 6) != 6))
631 if ((BIO_write(bp
, header
, i
) != i
) || (BIO_write(bp
, "\n", 1) != 1))
635 buf
= OPENSSL_malloc(PEM_BUFSIZE
* 8);
637 reason
= ERR_R_MALLOC_FAILURE
;
643 n
= (int)((len
> (PEM_BUFSIZE
* 5)) ? (PEM_BUFSIZE
* 5) : len
);
644 if (!EVP_EncodeUpdate(ctx
, buf
, &outl
, &(data
[j
]), n
))
646 if ((outl
) && (BIO_write(bp
, (char *)buf
, outl
) != outl
))
652 EVP_EncodeFinal(ctx
, buf
, &outl
);
653 if ((outl
> 0) && (BIO_write(bp
, (char *)buf
, outl
) != outl
))
655 if ((BIO_write(bp
, "-----END ", 9) != 9) ||
656 (BIO_write(bp
, name
, nlen
) != nlen
) ||
657 (BIO_write(bp
, "-----\n", 6) != 6))
663 ERR_raise(ERR_LIB_PEM
, reason
);
664 EVP_ENCODE_CTX_free(ctx
);
665 OPENSSL_clear_free(buf
, PEM_BUFSIZE
* 8);
669 #ifndef OPENSSL_NO_STDIO
670 int PEM_read(FILE *fp
, char **name
, char **header
, unsigned char **data
,
676 if ((b
= BIO_new(BIO_s_file())) == NULL
) {
677 ERR_raise(ERR_LIB_PEM
, ERR_R_BUF_LIB
);
680 BIO_set_fp(b
, fp
, BIO_NOCLOSE
);
681 ret
= PEM_read_bio(b
, name
, header
, data
, len
);
687 /* Some helpers for PEM_read_bio_ex(). */
688 static int sanitize_line(char *linebuf
, int len
, unsigned int flags
, int first_call
)
692 /* Other BOMs imply unsupported multibyte encoding,
693 * so don't strip them and let the error raise */
694 const unsigned char utf8_bom
[3] = {0xEF, 0xBB, 0xBF};
696 if (len
> 3 && memcmp(linebuf
, utf8_bom
, 3) == 0) {
697 memmove(linebuf
, linebuf
+ 3, len
- 3);
698 linebuf
[len
- 3] = 0;
703 if (flags
& PEM_FLAG_EAY_COMPATIBLE
) {
704 /* Strip trailing whitespace */
705 while ((len
>= 0) && (linebuf
[len
] <= ' '))
707 /* Go back to whitespace before applying uniform line ending. */
709 } else if (flags
& PEM_FLAG_ONLY_B64
) {
710 for (i
= 0; i
< len
; ++i
) {
711 if (!ossl_isbase64(linebuf
[i
]) || linebuf
[i
] == '\n'
712 || linebuf
[i
] == '\r')
717 /* EVP_DecodeBlock strips leading and trailing whitespace, so just strip
718 * control characters in-place and let everything through. */
719 for (i
= 0; i
< len
; ++i
) {
720 if (linebuf
[i
] == '\n' || linebuf
[i
] == '\r')
722 if (ossl_iscntrl(linebuf
[i
]))
727 /* The caller allocated LINESIZE+1, so this is safe. */
728 linebuf
[len
++] = '\n';
734 /* Note trailing spaces for begin and end. */
735 static const char beginstr
[] = "-----BEGIN ";
736 static const char endstr
[] = "-----END ";
737 static const char tailstr
[] = "-----\n";
738 #define BEGINLEN ((int)(sizeof(beginstr) - 1))
739 #define ENDLEN ((int)(sizeof(endstr) - 1))
740 #define TAILLEN ((int)(sizeof(tailstr) - 1))
741 static int get_name(BIO
*bp
, char **name
, unsigned int flags
)
749 * Need to hold trailing NUL (accounted for by BIO_gets() and the newline
750 * that will be added by sanitize_line() (the extra '1').
752 linebuf
= pem_malloc(LINESIZE
+ 1, flags
);
753 if (linebuf
== NULL
) {
754 ERR_raise(ERR_LIB_PEM
, ERR_R_MALLOC_FAILURE
);
759 len
= BIO_gets(bp
, linebuf
, LINESIZE
);
762 ERR_raise(ERR_LIB_PEM
, PEM_R_NO_START_LINE
);
766 /* Strip trailing garbage and standardize ending. */
767 len
= sanitize_line(linebuf
, len
, flags
& ~PEM_FLAG_ONLY_B64
, first_call
);
770 /* Allow leading empty or non-matching lines. */
771 } while (strncmp(linebuf
, beginstr
, BEGINLEN
) != 0
773 || strncmp(linebuf
+ len
- TAILLEN
, tailstr
, TAILLEN
) != 0);
774 linebuf
[len
- TAILLEN
] = '\0';
775 len
= len
- BEGINLEN
- TAILLEN
+ 1;
776 *name
= pem_malloc(len
, flags
);
778 ERR_raise(ERR_LIB_PEM
, ERR_R_MALLOC_FAILURE
);
781 memcpy(*name
, linebuf
+ BEGINLEN
, len
);
785 pem_free(linebuf
, flags
, LINESIZE
+ 1);
789 /* Keep track of how much of a header we've seen. */
797 * Extract the optional PEM header, with details on the type of content and
798 * any encryption used on the contents, and the bulk of the data from the bio.
799 * The end of the header is marked by a blank line; if the end-of-input marker
800 * is reached prior to a blank line, there is no header.
802 * The header and data arguments are BIO** since we may have to swap them
803 * if there is no header, for efficiency.
805 * We need the name of the PEM-encoded type to verify the end string.
807 static int get_header_and_data(BIO
*bp
, BIO
**header
, BIO
**data
, char *name
,
812 int len
, line
, ret
= 0, end
= 0, prev_partial_line_read
= 0, partial_line_read
= 0;
813 /* 0 if not seen (yet), 1 if reading header, 2 if finished header */
814 enum header_status got_header
= MAYBE_HEADER
;
815 unsigned int flags_mask
;
818 /* Need to hold trailing NUL (accounted for by BIO_gets() and the newline
819 * that will be added by sanitize_line() (the extra '1'). */
820 linebuf
= pem_malloc(LINESIZE
+ 1, flags
);
821 if (linebuf
== NULL
) {
822 ERR_raise(ERR_LIB_PEM
, ERR_R_MALLOC_FAILURE
);
826 for (line
= 0; ; line
++) {
828 len
= BIO_gets(bp
, linebuf
, LINESIZE
);
830 ERR_raise(ERR_LIB_PEM
, PEM_R_BAD_END_LINE
);
835 * Check if line has been read completely or if only part of the line
836 * has been read. Keep the previous value to ignore newlines that
837 * appear due to reading a line up until the char before the newline.
839 prev_partial_line_read
= partial_line_read
;
840 partial_line_read
= len
== LINESIZE
-1 && linebuf
[LINESIZE
-2] != '\n';
842 if (got_header
== MAYBE_HEADER
) {
843 if (memchr(linebuf
, ':', len
) != NULL
)
844 got_header
= IN_HEADER
;
846 if (!strncmp(linebuf
, endstr
, ENDLEN
) || got_header
== IN_HEADER
)
847 flags_mask
&= ~PEM_FLAG_ONLY_B64
;
848 len
= sanitize_line(linebuf
, len
, flags
& flags_mask
, 0);
850 /* Check for end of header. */
851 if (linebuf
[0] == '\n') {
853 * If previous line has been read only partially this newline is a
854 * regular newline at the end of a line and not an empty line.
856 if (!prev_partial_line_read
) {
857 if (got_header
== POST_HEADER
) {
858 /* Another blank line is an error. */
859 ERR_raise(ERR_LIB_PEM
, PEM_R_BAD_END_LINE
);
862 got_header
= POST_HEADER
;
868 /* Check for end of stream (which means there is no header). */
869 if (strncmp(linebuf
, endstr
, ENDLEN
) == 0) {
870 p
= linebuf
+ ENDLEN
;
871 namelen
= strlen(name
);
872 if (strncmp(p
, name
, namelen
) != 0 ||
873 strncmp(p
+ namelen
, tailstr
, TAILLEN
) != 0) {
874 ERR_raise(ERR_LIB_PEM
, PEM_R_BAD_END_LINE
);
877 if (got_header
== MAYBE_HEADER
) {
883 /* Malformed input; short line not at end of data. */
884 ERR_raise(ERR_LIB_PEM
, PEM_R_BAD_END_LINE
);
888 * Else, a line of text -- could be header or data; we don't
889 * know yet. Just pass it through.
891 if (BIO_puts(tmp
, linebuf
) < 0)
894 * Only encrypted files need the line length check applied.
896 if (got_header
== POST_HEADER
) {
897 /* 65 includes the trailing newline */
907 pem_free(linebuf
, flags
, LINESIZE
+ 1);
912 * Read in PEM-formatted data from the given BIO.
914 * By nature of the PEM format, all content must be printable ASCII (except
915 * for line endings). Other characters are malformed input and will be rejected.
917 int PEM_read_bio_ex(BIO
*bp
, char **name_out
, char **header
,
918 unsigned char **data
, long *len_out
, unsigned int flags
)
920 EVP_ENCODE_CTX
*ctx
= NULL
;
921 const BIO_METHOD
*bmeth
;
922 BIO
*headerB
= NULL
, *dataB
= NULL
;
924 int len
, taillen
, headerlen
, ret
= 0;
928 *name_out
= *header
= NULL
;
930 if ((flags
& PEM_FLAG_EAY_COMPATIBLE
) && (flags
& PEM_FLAG_ONLY_B64
)) {
931 /* These two are mutually incompatible; bail out. */
932 ERR_raise(ERR_LIB_PEM
, ERR_R_PASSED_INVALID_ARGUMENT
);
935 bmeth
= (flags
& PEM_FLAG_SECURE
) ? BIO_s_secmem() : BIO_s_mem();
937 headerB
= BIO_new(bmeth
);
938 dataB
= BIO_new(bmeth
);
939 if (headerB
== NULL
|| dataB
== NULL
) {
940 ERR_raise(ERR_LIB_PEM
, ERR_R_MALLOC_FAILURE
);
944 if (!get_name(bp
, &name
, flags
))
946 if (!get_header_and_data(bp
, &headerB
, &dataB
, name
, flags
))
949 BIO_get_mem_ptr(dataB
, &buf_mem
);
950 len
= buf_mem
->length
;
952 /* There was no data in the PEM file */
956 ctx
= EVP_ENCODE_CTX_new();
958 ERR_raise(ERR_LIB_PEM
, ERR_R_MALLOC_FAILURE
);
963 if (EVP_DecodeUpdate(ctx
, (unsigned char*)buf_mem
->data
, &len
,
964 (unsigned char*)buf_mem
->data
, len
) < 0
965 || EVP_DecodeFinal(ctx
, (unsigned char*)&(buf_mem
->data
[len
]),
967 ERR_raise(ERR_LIB_PEM
, PEM_R_BAD_BASE64_DECODE
);
971 buf_mem
->length
= len
;
973 headerlen
= BIO_get_mem_data(headerB
, NULL
);
974 *header
= pem_malloc(headerlen
+ 1, flags
);
975 *data
= pem_malloc(len
, flags
);
976 if (*header
== NULL
|| *data
== NULL
) {
977 pem_free(*header
, flags
, 0);
978 pem_free(*data
, flags
, 0);
981 BIO_read(headerB
, *header
, headerlen
);
982 (*header
)[headerlen
] = '\0';
983 BIO_read(dataB
, *data
, len
);
990 EVP_ENCODE_CTX_free(ctx
);
991 pem_free(name
, flags
, 0);
997 int PEM_read_bio(BIO
*bp
, char **name
, char **header
, unsigned char **data
,
1000 return PEM_read_bio_ex(bp
, name
, header
, data
, len
, PEM_FLAG_EAY_COMPATIBLE
);
1004 * Check pem string and return prefix length. If for example the pem_str ==
1005 * "RSA PRIVATE KEY" and suffix = "PRIVATE KEY" the return value is 3 for the
1009 int pem_check_suffix(const char *pem_str
, const char *suffix
)
1011 int pem_len
= strlen(pem_str
);
1012 int suffix_len
= strlen(suffix
);
1014 if (suffix_len
+ 1 >= pem_len
)
1016 p
= pem_str
+ pem_len
- suffix_len
;
1017 if (strcmp(p
, suffix
))