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)
33 #if defined(OPENSSL_NO_STDIO) || defined(OPENSSL_NO_UI)
35 * We should not ever call the default callback routine from windows.
37 PEMerr(PEM_F_PEM_DEF_CALLBACK, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
44 i = (i > num) ? num : i;
49 prompt = EVP_get_pw_prompt();
51 prompt = "Enter PEM pass phrase:";
55 * We assume that w == 0 means decryption,
56 * while w == 1 means encryption
58 int min_len = w ? MIN_LENGTH : 0;
60 i = EVP_read_pw_string_min(buf, min_len, num, prompt, w);
62 PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
63 memset(buf, 0, (unsigned int)num);
67 if (min_len && j < min_len) {
69 "phrase is too short, needs to be at least %d chars\n",
78 void PEM_proc_type(char *buf, int type)
82 if (type == PEM_TYPE_ENCRYPTED)
84 else if (type == PEM_TYPE_MIC_CLEAR)
86 else if (type == PEM_TYPE_MIC_ONLY)
91 OPENSSL_strlcat(buf, "Proc-Type: 4,", PEM_BUFSIZE);
92 OPENSSL_strlcat(buf, str, PEM_BUFSIZE);
93 OPENSSL_strlcat(buf, "\n", PEM_BUFSIZE);
96 void PEM_dek_info(char *buf, const char *type, int len, char *str)
98 static const unsigned char map[17] = "0123456789ABCDEF";
102 OPENSSL_strlcat(buf, "DEK-Info: ", PEM_BUFSIZE);
103 OPENSSL_strlcat(buf, type, PEM_BUFSIZE);
104 OPENSSL_strlcat(buf, ",", PEM_BUFSIZE);
106 if (j + (len * 2) + 1 > PEM_BUFSIZE)
108 for (i = 0; i < len; i++) {
109 buf[j + i * 2] = map[(str[i] >> 4) & 0x0f];
110 buf[j + i * 2 + 1] = map[(str[i]) & 0x0f];
112 buf[j + i * 2] = '\n';
113 buf[j + i * 2 + 1] = '\0';
116 #ifndef OPENSSL_NO_STDIO
117 void *PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x,
118 pem_password_cb *cb, void *u)
123 if ((b = BIO_new(BIO_s_file())) == NULL) {
124 PEMerr(PEM_F_PEM_ASN1_READ, ERR_R_BUF_LIB);
127 BIO_set_fp(b, fp, BIO_NOCLOSE);
128 ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u);
134 static int check_pem(const char *nm, const char *name)
136 /* Normal matching nm and name */
137 if (strcmp(nm, name) == 0)
140 /* Make PEM_STRING_EVP_PKEY match any private key */
142 if (strcmp(name, PEM_STRING_EVP_PKEY) == 0) {
144 const EVP_PKEY_ASN1_METHOD *ameth;
145 if (strcmp(nm, PEM_STRING_PKCS8) == 0)
147 if (strcmp(nm, PEM_STRING_PKCS8INF) == 0)
149 slen = pem_check_suffix(nm, "PRIVATE KEY");
152 * NB: ENGINE implementations wont contain a deprecated old
153 * private key decode function so don't look for them.
155 ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen);
156 if (ameth && ameth->old_priv_decode)
162 if (strcmp(name, PEM_STRING_PARAMETERS) == 0) {
164 const EVP_PKEY_ASN1_METHOD *ameth;
165 slen = pem_check_suffix(nm, "PARAMETERS");
168 ameth = EVP_PKEY_asn1_find_str(&e, nm, slen);
171 if (ameth->param_decode)
175 #ifndef OPENSSL_NO_ENGINE
183 /* If reading DH parameters handle X9.42 DH format too */
184 if (strcmp(nm, PEM_STRING_DHXPARAMS) == 0
185 && strcmp(name, PEM_STRING_DHPARAMS) == 0)
188 /* Permit older strings */
190 if (strcmp(nm, PEM_STRING_X509_OLD) == 0
191 && strcmp(name, PEM_STRING_X509) == 0)
194 if (strcmp(nm, PEM_STRING_X509_REQ_OLD) == 0
195 && strcmp(name, PEM_STRING_X509_REQ) == 0)
198 /* Allow normal certs to be read as trusted certs */
199 if (strcmp(nm, PEM_STRING_X509) == 0
200 && strcmp(name, PEM_STRING_X509_TRUSTED) == 0)
203 if (strcmp(nm, PEM_STRING_X509_OLD) == 0
204 && strcmp(name, PEM_STRING_X509_TRUSTED) == 0)
207 /* Some CAs use PKCS#7 with CERTIFICATE headers */
208 if (strcmp(nm, PEM_STRING_X509) == 0
209 && strcmp(name, PEM_STRING_PKCS7) == 0)
212 if (strcmp(nm, PEM_STRING_PKCS7_SIGNED) == 0
213 && strcmp(name, PEM_STRING_PKCS7) == 0)
216 #ifndef OPENSSL_NO_CMS
217 if (strcmp(nm, PEM_STRING_X509) == 0
218 && strcmp(name, PEM_STRING_CMS) == 0)
220 /* Allow CMS to be read from PKCS#7 headers */
221 if (strcmp(nm, PEM_STRING_PKCS7) == 0
222 && strcmp(name, PEM_STRING_CMS) == 0)
229 int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
230 const char *name, BIO *bp, pem_password_cb *cb,
233 EVP_CIPHER_INFO cipher;
234 char *nm = NULL, *header = NULL;
235 unsigned char *data = NULL;
240 if (!PEM_read_bio(bp, &nm, &header, &data, &len)) {
241 if (ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE)
242 ERR_add_error_data(2, "Expecting: ", name);
245 if (check_pem(nm, name))
248 OPENSSL_free(header);
251 if (!PEM_get_EVP_CIPHER_INFO(header, &cipher))
253 if (!PEM_do_header(&cipher, data, &len, cb, u))
267 OPENSSL_free(header);
273 #ifndef OPENSSL_NO_STDIO
274 int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp,
275 void *x, const EVP_CIPHER *enc, unsigned char *kstr,
276 int klen, pem_password_cb *callback, void *u)
281 if ((b = BIO_new(BIO_s_file())) == NULL) {
282 PEMerr(PEM_F_PEM_ASN1_WRITE, ERR_R_BUF_LIB);
285 BIO_set_fp(b, fp, BIO_NOCLOSE);
286 ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u);
292 int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp,
293 void *x, const EVP_CIPHER *enc, unsigned char *kstr,
294 int klen, pem_password_cb *callback, void *u)
296 EVP_CIPHER_CTX *ctx = NULL;
297 int dsize = 0, i = 0, j = 0, ret = 0;
298 unsigned char *p, *data = NULL;
299 const char *objstr = NULL;
300 char buf[PEM_BUFSIZE];
301 unsigned char key[EVP_MAX_KEY_LENGTH];
302 unsigned char iv[EVP_MAX_IV_LENGTH];
305 objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc));
306 if (objstr == NULL || EVP_CIPHER_iv_length(enc) == 0) {
307 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_UNSUPPORTED_CIPHER);
312 if ((dsize = i2d(x, NULL)) < 0) {
313 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_ASN1_LIB);
317 /* dzise + 8 bytes are needed */
318 /* actually it needs the cipher block size extra... */
319 data = OPENSSL_malloc((unsigned int)dsize + 20);
321 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_MALLOC_FAILURE);
329 if (callback == NULL)
330 klen = PEM_def_callback(buf, PEM_BUFSIZE, 1, u);
332 klen = (*callback) (buf, PEM_BUFSIZE, 1, u);
334 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_READ_KEY);
337 #ifdef CHARSET_EBCDIC
338 /* Convert the pass phrase from EBCDIC */
339 ebcdic2ascii(buf, buf, klen);
341 kstr = (unsigned char *)buf;
343 RAND_add(data, i, 0); /* put in the RSA key. */
344 OPENSSL_assert(EVP_CIPHER_iv_length(enc) <= (int)sizeof(iv));
345 if (RAND_bytes(iv, EVP_CIPHER_iv_length(enc)) <= 0) /* Generate a salt */
348 * The 'iv' is used as the iv and as a salt. It is NOT taken from
349 * the BytesToKey function
351 if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1, key, NULL))
354 if (kstr == (unsigned char *)buf)
355 OPENSSL_cleanse(buf, PEM_BUFSIZE);
357 OPENSSL_assert(strlen(objstr) + 23 + 2 * EVP_CIPHER_iv_length(enc) + 13
361 PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
362 PEM_dek_info(buf, objstr, EVP_CIPHER_iv_length(enc), (char *)iv);
366 if ((ctx = EVP_CIPHER_CTX_new()) == NULL
367 || !EVP_EncryptInit_ex(ctx, enc, NULL, key, iv)
368 || !EVP_EncryptUpdate(ctx, data, &j, data, i)
369 || !EVP_EncryptFinal_ex(ctx, &(data[j]), &i))
378 i = PEM_write_bio(bp, name, buf, data, i);
382 OPENSSL_cleanse(key, sizeof(key));
383 OPENSSL_cleanse(iv, sizeof(iv));
384 EVP_CIPHER_CTX_free(ctx);
385 OPENSSL_cleanse(buf, PEM_BUFSIZE);
386 OPENSSL_clear_free(data, (unsigned int)dsize);
390 int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
391 pem_password_cb *callback, void *u)
396 int ilen = (int) len; /* EVP_DecryptUpdate etc. take int lengths */
398 unsigned char key[EVP_MAX_KEY_LENGTH];
399 char buf[PEM_BUFSIZE];
401 #if LONG_MAX > INT_MAX
402 /* Check that we did not truncate the length */
404 PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_HEADER_TOO_LONG);
409 if (cipher->cipher == NULL)
411 if (callback == NULL)
412 keylen = PEM_def_callback(buf, PEM_BUFSIZE, 0, u);
414 keylen = callback(buf, PEM_BUFSIZE, 0, u);
416 PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_PASSWORD_READ);
419 #ifdef CHARSET_EBCDIC
420 /* Convert the pass phrase from EBCDIC */
421 ebcdic2ascii(buf, buf, keylen);
424 if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
425 (unsigned char *)buf, keylen, 1, key, NULL))
428 ctx = EVP_CIPHER_CTX_new();
432 ok = EVP_DecryptInit_ex(ctx, cipher->cipher, NULL, key, &(cipher->iv[0]));
434 ok = EVP_DecryptUpdate(ctx, data, &ilen, data, ilen);
436 /* Squirrel away the length of data decrypted so far. */
438 ok = EVP_DecryptFinal_ex(ctx, &(data[ilen]), &ilen);
443 PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_DECRYPT);
445 EVP_CIPHER_CTX_free(ctx);
446 OPENSSL_cleanse((char *)buf, sizeof(buf));
447 OPENSSL_cleanse((char *)key, sizeof(key));
452 * This implements a very limited PEM header parser that does not support the
453 * full grammar of rfc1421. In particular, folded headers are not supported,
454 * nor is additional whitespace.
456 * A robust implementation would make use of a library that turns the headers
457 * into a BIO from which one folded line is read at a time, and is then split
458 * into a header label and content. We would then parse the content of the
459 * headers we care about. This is overkill for just this limited use-case, but
460 * presumably we also parse rfc822-style headers for S/MIME, so a common
461 * abstraction might well be more generally useful.
463 int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
465 static const char ProcType[] = "Proc-Type:";
466 static const char ENCRYPTED[] = "ENCRYPTED";
467 static const char DEKInfo[] = "DEK-Info:";
468 const EVP_CIPHER *enc = NULL;
470 char *dekinfostart, c;
472 cipher->cipher = NULL;
473 if ((header == NULL) || (*header == '\0') || (*header == '\n'))
476 if (strncmp(header, ProcType, sizeof(ProcType)-1) != 0) {
477 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_PROC_TYPE);
480 header += sizeof(ProcType)-1;
481 header += strspn(header, " \t");
483 if (*header++ != '4' || *header++ != ',')
485 header += strspn(header, " \t");
487 /* We expect "ENCRYPTED" followed by optional white-space + line break */
488 if (strncmp(header, ENCRYPTED, sizeof(ENCRYPTED)-1) != 0 ||
489 strspn(header+sizeof(ENCRYPTED)-1, " \t\r\n") == 0) {
490 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_ENCRYPTED);
493 header += sizeof(ENCRYPTED)-1;
494 header += strspn(header, " \t\r");
495 if (*header++ != '\n') {
496 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_SHORT_HEADER);
501 * https://tools.ietf.org/html/rfc1421#section-4.6.1.3
502 * We expect "DEK-Info: algo[,hex-parameters]"
504 if (strncmp(header, DEKInfo, sizeof(DEKInfo)-1) != 0) {
505 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_DEK_INFO);
508 header += sizeof(DEKInfo)-1;
509 header += strspn(header, " \t");
512 * DEK-INFO is a comma-separated combination of algorithm name and optional
515 dekinfostart = header;
516 header += strcspn(header, " \t,");
519 cipher->cipher = enc = EVP_get_cipherbyname(dekinfostart);
521 header += strspn(header, " \t");
524 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_UNSUPPORTED_ENCRYPTION);
527 ivlen = EVP_CIPHER_iv_length(enc);
528 if (ivlen > 0 && *header++ != ',') {
529 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_MISSING_DEK_IV);
531 } else if (ivlen == 0 && *header == ',') {
532 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_UNEXPECTED_DEK_IV);
536 if (!load_iv(&header, cipher->iv, EVP_CIPHER_iv_length(enc)))
542 static int load_iv(char **fromp, unsigned char *to, int num)
548 for (i = 0; i < num; i++)
551 for (i = 0; i < num; i++) {
552 v = OPENSSL_hexchar2int(*from);
554 PEMerr(PEM_F_LOAD_IV, PEM_R_BAD_IV_CHARS);
558 to[i / 2] |= v << (long)((!(i & 1)) * 4);
565 #ifndef OPENSSL_NO_STDIO
566 int PEM_write(FILE *fp, const char *name, const char *header,
567 const unsigned char *data, long len)
572 if ((b = BIO_new(BIO_s_file())) == NULL) {
573 PEMerr(PEM_F_PEM_WRITE, ERR_R_BUF_LIB);
576 BIO_set_fp(b, fp, BIO_NOCLOSE);
577 ret = PEM_write_bio(b, name, header, data, len);
583 int PEM_write_bio(BIO *bp, const char *name, const char *header,
584 const unsigned char *data, long len)
586 int nlen, n, i, j, outl;
587 unsigned char *buf = NULL;
588 EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new();
589 int reason = ERR_R_BUF_LIB;
592 reason = ERR_R_MALLOC_FAILURE;
599 if ((BIO_write(bp, "-----BEGIN ", 11) != 11) ||
600 (BIO_write(bp, name, nlen) != nlen) ||
601 (BIO_write(bp, "-----\n", 6) != 6))
606 if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1))
610 buf = OPENSSL_malloc(PEM_BUFSIZE * 8);
612 reason = ERR_R_MALLOC_FAILURE;
618 n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
619 EVP_EncodeUpdate(ctx, buf, &outl, &(data[j]), n);
620 if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl))
626 EVP_EncodeFinal(ctx, buf, &outl);
627 if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl))
629 if ((BIO_write(bp, "-----END ", 9) != 9) ||
630 (BIO_write(bp, name, nlen) != nlen) ||
631 (BIO_write(bp, "-----\n", 6) != 6))
633 OPENSSL_clear_free(buf, PEM_BUFSIZE * 8);
634 EVP_ENCODE_CTX_free(ctx);
637 OPENSSL_clear_free(buf, PEM_BUFSIZE * 8);
638 EVP_ENCODE_CTX_free(ctx);
639 PEMerr(PEM_F_PEM_WRITE_BIO, reason);
643 #ifndef OPENSSL_NO_STDIO
644 int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
650 if ((b = BIO_new(BIO_s_file())) == NULL) {
651 PEMerr(PEM_F_PEM_READ, ERR_R_BUF_LIB);
654 BIO_set_fp(b, fp, BIO_NOCLOSE);
655 ret = PEM_read_bio(b, name, header, data, len);
661 int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
664 EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new();
665 int end = 0, i, k, bl = 0, hl = 0, nohead = 0;
669 BUF_MEM *dataB, *tmpB;
672 PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
676 nameB = BUF_MEM_new();
677 headerB = BUF_MEM_new();
678 dataB = BUF_MEM_new();
679 if ((nameB == NULL) || (headerB == NULL) || (dataB == NULL)) {
685 i = BIO_gets(bp, buf, 254);
688 PEMerr(PEM_F_PEM_READ_BIO, PEM_R_NO_START_LINE);
692 while ((i >= 0) && (buf[i] <= ' '))
697 if (strncmp(buf, "-----BEGIN ", 11) == 0) {
698 i = strlen(&(buf[11]));
700 if (strncmp(&(buf[11 + i - 6]), "-----\n", 6) != 0)
702 if (!BUF_MEM_grow(nameB, i + 9)) {
703 PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
706 memcpy(nameB->data, &(buf[11]), i - 6);
707 nameB->data[i - 6] = '\0';
712 if (!BUF_MEM_grow(headerB, 256)) {
713 PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
716 headerB->data[0] = '\0';
718 i = BIO_gets(bp, buf, 254);
722 while ((i >= 0) && (buf[i] <= ' '))
729 if (!BUF_MEM_grow(headerB, hl + i + 9)) {
730 PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
733 if (strncmp(buf, "-----END ", 9) == 0) {
737 memcpy(&(headerB->data[hl]), buf, i);
738 headerB->data[hl + i] = '\0';
743 if (!BUF_MEM_grow(dataB, 1024)) {
744 PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
747 dataB->data[0] = '\0';
750 i = BIO_gets(bp, buf, 254);
754 while ((i >= 0) && (buf[i] <= ' '))
761 if (strncmp(buf, "-----END ", 9) == 0)
765 if (!BUF_MEM_grow_clean(dataB, i + bl + 9)) {
766 PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
769 memcpy(&(dataB->data[bl]), buf, i);
770 dataB->data[bl + i] = '\0';
774 i = BIO_gets(bp, buf, 254);
778 while ((i >= 0) && (buf[i] <= ' '))
792 i = strlen(nameB->data);
793 if ((strncmp(buf, "-----END ", 9) != 0) ||
794 (strncmp(nameB->data, &(buf[9]), i) != 0) ||
795 (strncmp(&(buf[9 + i]), "-----\n", 6) != 0)) {
796 PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_END_LINE);
801 i = EVP_DecodeUpdate(ctx,
802 (unsigned char *)dataB->data, &bl,
803 (unsigned char *)dataB->data, bl);
805 PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_BASE64_DECODE);
808 i = EVP_DecodeFinal(ctx, (unsigned char *)&(dataB->data[bl]), &k);
810 PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_BASE64_DECODE);
818 *header = headerB->data;
819 *data = (unsigned char *)dataB->data;
822 OPENSSL_free(headerB);
824 EVP_ENCODE_CTX_free(ctx);
828 BUF_MEM_free(headerB);
830 EVP_ENCODE_CTX_free(ctx);
835 * Check pem string and return prefix length. If for example the pem_str ==
836 * "RSA PRIVATE KEY" and suffix = "PRIVATE KEY" the return value is 3 for the
840 int pem_check_suffix(const char *pem_str, const char *suffix)
842 int pem_len = strlen(pem_str);
843 int suffix_len = strlen(suffix);
845 if (suffix_len + 1 >= pem_len)
847 p = pem_str + pem_len - suffix_len;
848 if (strcmp(p, suffix))