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
12 #include "internal/cryptlib.h"
13 #include <openssl/buffer.h>
14 #include <openssl/objects.h>
15 #include <openssl/evp.h>
16 #include <openssl/rand.h>
17 #include <openssl/x509.h>
18 #include <openssl/pem.h>
19 #include <openssl/pkcs12.h>
20 #include "internal/asn1_int.h"
21 #include <openssl/des.h>
22 #include <openssl/engine.h>
26 static int load_iv(char **fromp, unsigned char *to, int num);
27 static int check_pem(const char *nm, const char *name);
28 int pem_check_suffix(const char *pem_str, const char *suffix);
30 int PEM_def_callback(char *buf, int num, int w, void *key)
32 #if defined(OPENSSL_NO_STDIO) || defined(OPENSSL_NO_UI)
34 * We should not ever call the default callback routine from windows.
36 PEMerr(PEM_F_PEM_DEF_CALLBACK, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
43 i = (i > num) ? num : i;
48 prompt = EVP_get_pw_prompt();
50 prompt = "Enter PEM pass phrase:";
54 * We assume that w == 0 means decryption,
55 * while w == 1 means encryption
57 int min_len = w ? MIN_LENGTH : 0;
59 i = EVP_read_pw_string_min(buf, min_len, num, prompt, w);
61 PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
62 memset(buf, 0, (unsigned int)num);
66 if (min_len && j < min_len) {
68 "phrase is too short, needs to be at least %d chars\n",
77 void PEM_proc_type(char *buf, int type)
81 if (type == PEM_TYPE_ENCRYPTED)
83 else if (type == PEM_TYPE_MIC_CLEAR)
85 else if (type == PEM_TYPE_MIC_ONLY)
90 OPENSSL_strlcat(buf, "Proc-Type: 4,", PEM_BUFSIZE);
91 OPENSSL_strlcat(buf, str, PEM_BUFSIZE);
92 OPENSSL_strlcat(buf, "\n", PEM_BUFSIZE);
95 void PEM_dek_info(char *buf, const char *type, int len, char *str)
97 static const unsigned char map[17] = "0123456789ABCDEF";
101 OPENSSL_strlcat(buf, "DEK-Info: ", PEM_BUFSIZE);
102 OPENSSL_strlcat(buf, type, PEM_BUFSIZE);
103 OPENSSL_strlcat(buf, ",", PEM_BUFSIZE);
105 if (j + (len * 2) + 1 > PEM_BUFSIZE)
107 for (i = 0; i < len; i++) {
108 buf[j + i * 2] = map[(str[i] >> 4) & 0x0f];
109 buf[j + i * 2 + 1] = map[(str[i]) & 0x0f];
111 buf[j + i * 2] = '\n';
112 buf[j + i * 2 + 1] = '\0';
115 #ifndef OPENSSL_NO_STDIO
116 void *PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x,
117 pem_password_cb *cb, void *u)
122 if ((b = BIO_new(BIO_s_file())) == NULL) {
123 PEMerr(PEM_F_PEM_ASN1_READ, ERR_R_BUF_LIB);
126 BIO_set_fp(b, fp, BIO_NOCLOSE);
127 ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u);
133 static int check_pem(const char *nm, const char *name)
135 /* Normal matching nm and name */
136 if (strcmp(nm, name) == 0)
139 /* Make PEM_STRING_EVP_PKEY match any private key */
141 if (strcmp(name, PEM_STRING_EVP_PKEY) == 0) {
143 const EVP_PKEY_ASN1_METHOD *ameth;
144 if (strcmp(nm, PEM_STRING_PKCS8) == 0)
146 if (strcmp(nm, PEM_STRING_PKCS8INF) == 0)
148 slen = pem_check_suffix(nm, "PRIVATE KEY");
151 * NB: ENGINE implementations wont contain a deprecated old
152 * private key decode function so don't look for them.
154 ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen);
155 if (ameth && ameth->old_priv_decode)
161 if (strcmp(name, PEM_STRING_PARAMETERS) == 0) {
163 const EVP_PKEY_ASN1_METHOD *ameth;
164 slen = pem_check_suffix(nm, "PARAMETERS");
167 ameth = EVP_PKEY_asn1_find_str(&e, nm, slen);
170 if (ameth->param_decode)
174 #ifndef OPENSSL_NO_ENGINE
182 /* If reading DH parameters handle X9.42 DH format too */
183 if (strcmp(nm, PEM_STRING_DHXPARAMS) == 0
184 && strcmp(name, PEM_STRING_DHPARAMS) == 0)
187 /* Permit older strings */
189 if (strcmp(nm, PEM_STRING_X509_OLD) == 0
190 && strcmp(name, PEM_STRING_X509) == 0)
193 if (strcmp(nm, PEM_STRING_X509_REQ_OLD) == 0
194 && strcmp(name, PEM_STRING_X509_REQ) == 0)
197 /* Allow normal certs to be read as trusted certs */
198 if (strcmp(nm, PEM_STRING_X509) == 0
199 && strcmp(name, PEM_STRING_X509_TRUSTED) == 0)
202 if (strcmp(nm, PEM_STRING_X509_OLD) == 0
203 && strcmp(name, PEM_STRING_X509_TRUSTED) == 0)
206 /* Some CAs use PKCS#7 with CERTIFICATE headers */
207 if (strcmp(nm, PEM_STRING_X509) == 0
208 && strcmp(name, PEM_STRING_PKCS7) == 0)
211 if (strcmp(nm, PEM_STRING_PKCS7_SIGNED) == 0
212 && strcmp(name, PEM_STRING_PKCS7) == 0)
215 #ifndef OPENSSL_NO_CMS
216 if (strcmp(nm, PEM_STRING_X509) == 0
217 && strcmp(name, PEM_STRING_CMS) == 0)
219 /* Allow CMS to be read from PKCS#7 headers */
220 if (strcmp(nm, PEM_STRING_PKCS7) == 0
221 && strcmp(name, PEM_STRING_CMS) == 0)
228 int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
229 const char *name, BIO *bp, pem_password_cb *cb,
232 EVP_CIPHER_INFO cipher;
233 char *nm = NULL, *header = NULL;
234 unsigned char *data = NULL;
239 if (!PEM_read_bio(bp, &nm, &header, &data, &len)) {
240 if (ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE)
241 ERR_add_error_data(2, "Expecting: ", name);
244 if (check_pem(nm, name))
247 OPENSSL_free(header);
250 if (!PEM_get_EVP_CIPHER_INFO(header, &cipher))
252 if (!PEM_do_header(&cipher, data, &len, cb, u))
266 OPENSSL_free(header);
272 #ifndef OPENSSL_NO_STDIO
273 int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp,
274 void *x, const EVP_CIPHER *enc, unsigned char *kstr,
275 int klen, pem_password_cb *callback, void *u)
280 if ((b = BIO_new(BIO_s_file())) == NULL) {
281 PEMerr(PEM_F_PEM_ASN1_WRITE, ERR_R_BUF_LIB);
284 BIO_set_fp(b, fp, BIO_NOCLOSE);
285 ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u);
291 int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp,
292 void *x, const EVP_CIPHER *enc, unsigned char *kstr,
293 int klen, pem_password_cb *callback, void *u)
295 EVP_CIPHER_CTX *ctx = NULL;
296 int dsize = 0, i = 0, j = 0, ret = 0;
297 unsigned char *p, *data = NULL;
298 const char *objstr = NULL;
299 char buf[PEM_BUFSIZE];
300 unsigned char key[EVP_MAX_KEY_LENGTH];
301 unsigned char iv[EVP_MAX_IV_LENGTH];
304 objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc));
305 if (objstr == NULL || EVP_CIPHER_iv_length(enc) == 0) {
306 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_UNSUPPORTED_CIPHER);
311 if ((dsize = i2d(x, NULL)) < 0) {
312 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_ASN1_LIB);
316 /* dzise + 8 bytes are needed */
317 /* actually it needs the cipher block size extra... */
318 data = OPENSSL_malloc((unsigned int)dsize + 20);
320 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_MALLOC_FAILURE);
328 if (callback == NULL)
329 klen = PEM_def_callback(buf, PEM_BUFSIZE, 1, u);
331 klen = (*callback) (buf, PEM_BUFSIZE, 1, u);
333 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_READ_KEY);
336 #ifdef CHARSET_EBCDIC
337 /* Convert the pass phrase from EBCDIC */
338 ebcdic2ascii(buf, buf, klen);
340 kstr = (unsigned char *)buf;
342 RAND_add(data, i, 0); /* put in the RSA key. */
343 OPENSSL_assert(EVP_CIPHER_iv_length(enc) <= (int)sizeof(iv));
344 if (RAND_bytes(iv, EVP_CIPHER_iv_length(enc)) <= 0) /* Generate a salt */
347 * The 'iv' is used as the iv and as a salt. It is NOT taken from
348 * the BytesToKey function
350 if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1, key, NULL))
353 if (kstr == (unsigned char *)buf)
354 OPENSSL_cleanse(buf, PEM_BUFSIZE);
356 OPENSSL_assert(strlen(objstr) + 23 + 2 * EVP_CIPHER_iv_length(enc) + 13
360 PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
361 PEM_dek_info(buf, objstr, EVP_CIPHER_iv_length(enc), (char *)iv);
365 if ((ctx = EVP_CIPHER_CTX_new()) == NULL
366 || !EVP_EncryptInit_ex(ctx, enc, NULL, key, iv)
367 || !EVP_EncryptUpdate(ctx, data, &j, data, i)
368 || !EVP_EncryptFinal_ex(ctx, &(data[j]), &i))
377 i = PEM_write_bio(bp, name, buf, data, i);
381 OPENSSL_cleanse(key, sizeof(key));
382 OPENSSL_cleanse(iv, sizeof(iv));
383 EVP_CIPHER_CTX_free(ctx);
384 OPENSSL_cleanse(buf, PEM_BUFSIZE);
385 OPENSSL_clear_free(data, (unsigned int)dsize);
389 int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
390 pem_password_cb *callback, void *u)
392 int i = 0, j, o, klen;
395 unsigned char key[EVP_MAX_KEY_LENGTH];
396 char buf[PEM_BUFSIZE];
400 if (cipher->cipher == NULL)
402 if (callback == NULL)
403 klen = PEM_def_callback(buf, PEM_BUFSIZE, 0, u);
405 klen = callback(buf, PEM_BUFSIZE, 0, u);
407 PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_PASSWORD_READ);
410 #ifdef CHARSET_EBCDIC
411 /* Convert the pass phrase from EBCDIC */
412 ebcdic2ascii(buf, buf, klen);
415 if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
416 (unsigned char *)buf, klen, 1, key, NULL))
420 ctx = EVP_CIPHER_CTX_new();
423 o = EVP_DecryptInit_ex(ctx, cipher->cipher, NULL, key, &(cipher->iv[0]));
425 o = EVP_DecryptUpdate(ctx, data, &i, data, j);
427 o = EVP_DecryptFinal_ex(ctx, &(data[i]), &j);
428 EVP_CIPHER_CTX_free(ctx);
429 OPENSSL_cleanse((char *)buf, sizeof(buf));
430 OPENSSL_cleanse((char *)key, sizeof(key));
434 PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_DECRYPT);
441 int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
443 const EVP_CIPHER *enc = NULL;
444 char *dekinfostart, c;
446 cipher->cipher = NULL;
447 if ((header == NULL) || (*header == '\0') || (*header == '\n'))
449 if (strncmp(header, "Proc-Type: ", 11) != 0) {
450 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_PROC_TYPE);
460 if (strncmp(header, "ENCRYPTED", 9) != 0) {
461 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_ENCRYPTED);
464 for (; (*header != '\n') && (*header != '\0'); header++) ;
465 if (*header == '\0') {
466 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_SHORT_HEADER);
470 if (strncmp(header, "DEK-Info: ", 10) != 0) {
471 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_DEK_INFO);
476 dekinfostart = header;
479 #ifndef CHARSET_EBCDIC
480 if (!(((c >= 'A') && (c <= 'Z')) || (c == '-') ||
481 ((c >= '0') && (c <= '9'))))
484 if (!(isupper(c) || (c == '-') || isdigit(c)))
490 cipher->cipher = enc = EVP_get_cipherbyname(dekinfostart);
494 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_UNSUPPORTED_ENCRYPTION);
497 if (!load_iv(&header, cipher->iv, EVP_CIPHER_iv_length(enc)))
503 static int load_iv(char **fromp, unsigned char *to, int num)
509 for (i = 0; i < num; i++)
512 for (i = 0; i < num; i++) {
513 v = OPENSSL_hexchar2int(*from);
515 PEMerr(PEM_F_LOAD_IV, PEM_R_BAD_IV_CHARS);
519 to[i / 2] |= v << (long)((!(i & 1)) * 4);
526 #ifndef OPENSSL_NO_STDIO
527 int PEM_write(FILE *fp, const char *name, const char *header,
528 const unsigned char *data, long len)
533 if ((b = BIO_new(BIO_s_file())) == NULL) {
534 PEMerr(PEM_F_PEM_WRITE, ERR_R_BUF_LIB);
537 BIO_set_fp(b, fp, BIO_NOCLOSE);
538 ret = PEM_write_bio(b, name, header, data, len);
544 int PEM_write_bio(BIO *bp, const char *name, const char *header,
545 const unsigned char *data, long len)
547 int nlen, n, i, j, outl;
548 unsigned char *buf = NULL;
549 EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new();
550 int reason = ERR_R_BUF_LIB;
553 reason = ERR_R_MALLOC_FAILURE;
560 if ((BIO_write(bp, "-----BEGIN ", 11) != 11) ||
561 (BIO_write(bp, name, nlen) != nlen) ||
562 (BIO_write(bp, "-----\n", 6) != 6))
567 if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1))
571 buf = OPENSSL_malloc(PEM_BUFSIZE * 8);
573 reason = ERR_R_MALLOC_FAILURE;
579 n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
580 EVP_EncodeUpdate(ctx, buf, &outl, &(data[j]), n);
581 if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl))
587 EVP_EncodeFinal(ctx, buf, &outl);
588 if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl))
590 if ((BIO_write(bp, "-----END ", 9) != 9) ||
591 (BIO_write(bp, name, nlen) != nlen) ||
592 (BIO_write(bp, "-----\n", 6) != 6))
594 OPENSSL_clear_free(buf, PEM_BUFSIZE * 8);
595 EVP_ENCODE_CTX_free(ctx);
598 OPENSSL_clear_free(buf, PEM_BUFSIZE * 8);
599 EVP_ENCODE_CTX_free(ctx);
600 PEMerr(PEM_F_PEM_WRITE_BIO, reason);
604 #ifndef OPENSSL_NO_STDIO
605 int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
611 if ((b = BIO_new(BIO_s_file())) == NULL) {
612 PEMerr(PEM_F_PEM_READ, ERR_R_BUF_LIB);
615 BIO_set_fp(b, fp, BIO_NOCLOSE);
616 ret = PEM_read_bio(b, name, header, data, len);
622 int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
625 EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new();
626 int end = 0, i, k, bl = 0, hl = 0, nohead = 0;
630 BUF_MEM *dataB, *tmpB;
633 PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
637 nameB = BUF_MEM_new();
638 headerB = BUF_MEM_new();
639 dataB = BUF_MEM_new();
640 if ((nameB == NULL) || (headerB == NULL) || (dataB == NULL)) {
646 i = BIO_gets(bp, buf, 254);
649 PEMerr(PEM_F_PEM_READ_BIO, PEM_R_NO_START_LINE);
653 while ((i >= 0) && (buf[i] <= ' '))
658 if (strncmp(buf, "-----BEGIN ", 11) == 0) {
659 i = strlen(&(buf[11]));
661 if (strncmp(&(buf[11 + i - 6]), "-----\n", 6) != 0)
663 if (!BUF_MEM_grow(nameB, i + 9)) {
664 PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
667 memcpy(nameB->data, &(buf[11]), i - 6);
668 nameB->data[i - 6] = '\0';
673 if (!BUF_MEM_grow(headerB, 256)) {
674 PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
677 headerB->data[0] = '\0';
679 i = BIO_gets(bp, buf, 254);
683 while ((i >= 0) && (buf[i] <= ' '))
690 if (!BUF_MEM_grow(headerB, hl + i + 9)) {
691 PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
694 if (strncmp(buf, "-----END ", 9) == 0) {
698 memcpy(&(headerB->data[hl]), buf, i);
699 headerB->data[hl + i] = '\0';
704 if (!BUF_MEM_grow(dataB, 1024)) {
705 PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
708 dataB->data[0] = '\0';
711 i = BIO_gets(bp, buf, 254);
715 while ((i >= 0) && (buf[i] <= ' '))
722 if (strncmp(buf, "-----END ", 9) == 0)
726 if (!BUF_MEM_grow_clean(dataB, i + bl + 9)) {
727 PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
730 memcpy(&(dataB->data[bl]), buf, i);
731 dataB->data[bl + i] = '\0';
735 i = BIO_gets(bp, buf, 254);
739 while ((i >= 0) && (buf[i] <= ' '))
753 i = strlen(nameB->data);
754 if ((strncmp(buf, "-----END ", 9) != 0) ||
755 (strncmp(nameB->data, &(buf[9]), i) != 0) ||
756 (strncmp(&(buf[9 + i]), "-----\n", 6) != 0)) {
757 PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_END_LINE);
762 i = EVP_DecodeUpdate(ctx,
763 (unsigned char *)dataB->data, &bl,
764 (unsigned char *)dataB->data, bl);
766 PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_BASE64_DECODE);
769 i = EVP_DecodeFinal(ctx, (unsigned char *)&(dataB->data[bl]), &k);
771 PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_BASE64_DECODE);
779 *header = headerB->data;
780 *data = (unsigned char *)dataB->data;
783 OPENSSL_free(headerB);
785 EVP_ENCODE_CTX_free(ctx);
789 BUF_MEM_free(headerB);
791 EVP_ENCODE_CTX_free(ctx);
796 * Check pem string and return prefix length. If for example the pem_str ==
797 * "RSA PRIVATE KEY" and suffix = "PRIVATE KEY" the return value is 3 for the
801 int pem_check_suffix(const char *pem_str, const char *suffix)
803 int pem_len = strlen(pem_str);
804 int suffix_len = strlen(suffix);
806 if (suffix_len + 1 >= pem_len)
808 p = pem_str + pem_len - suffix_len;
809 if (strcmp(p, suffix))