Skip to content

Commit a84ea53

Browse files
committed
pkey: use OSSL_DECODER to load encrypted PEM on OpenSSL 3.0
OpenSSL 3.0 has rewritten routines to load pkeys (PEM_read_bio_* and d2i_* functions) around the newly introduced OSSL_DECODER API. This comes with a slight behavior change. They now decrypt and parse each encountered PEM block, then check the kind of the block. This used to be the reverse: they checked the PEM header to see the kind, and then decrypted the content. This means that the password callback may now be called repeatedly. Let's use the OSSL_DECODER API directly on OpenSSL 3.0 so that the return value from the password callback will be reused automatically.
1 parent 8c185e0 commit a84ea53

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Diff for: ext/openssl/ossl_pkey.c

+40
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,45 @@ ossl_pkey_new(EVP_PKEY *pkey)
7979
return obj;
8080
}
8181

82+
#if OSSL_OPENSSL_PREREQ(3, 0, 0)
83+
# include <openssl/decoder.h>
84+
85+
EVP_PKEY *
86+
ossl_pkey_read_generic(BIO *bio, VALUE pass)
87+
{
88+
void *ppass = (void *)pass;
89+
OSSL_DECODER_CTX *dctx;
90+
EVP_PKEY *pkey = NULL;
91+
int pos = 0, pos2;
92+
93+
dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "DER", NULL, NULL, 0, NULL, NULL);
94+
if (!dctx)
95+
goto out;
96+
if (OSSL_DECODER_CTX_set_pem_password_cb(dctx, ossl_pem_passwd_cb, ppass) != 1)
97+
goto out;
98+
99+
/* First check DER */
100+
if (OSSL_DECODER_from_bio(dctx, bio) == 1)
101+
goto out;
102+
103+
/* Then check PEM; multiple OSSL_DECODER_from_bio() calls may be needed */
104+
OSSL_BIO_reset(bio);
105+
if (OSSL_DECODER_CTX_set_input_type(dctx, "PEM") != 1)
106+
goto out;
107+
while (OSSL_DECODER_from_bio(dctx, bio) != 1) {
108+
if (BIO_eof(bio))
109+
goto out;
110+
pos2 = BIO_tell(bio);
111+
if (pos2 < 0 || pos2 <= pos)
112+
goto out;
113+
pos = pos2;
114+
}
115+
116+
out:
117+
OSSL_DECODER_CTX_free(dctx);
118+
return pkey;
119+
}
120+
#else
82121
EVP_PKEY *
83122
ossl_pkey_read_generic(BIO *bio, VALUE pass)
84123
{
@@ -107,6 +146,7 @@ ossl_pkey_read_generic(BIO *bio, VALUE pass)
107146
out:
108147
return pkey;
109148
}
149+
#endif
110150

111151
/*
112152
* call-seq:

0 commit comments

Comments
 (0)