Skip to content

Commit

Permalink
pem: avoid segfault if PKEY is NULL in PEM_write_bio_PrivateKey
Browse files Browse the repository at this point in the history
Make the code more robust and correctly handle EVP_PKEY set to NULL
instead of dereferencing null pointer.

Signed-off-by: Milan Broz <gmazyland@gmail.com>

Reviewed-by: Dmitry Belyavskiy <beldmit@gmail.com>
Reviewed-by: Tomas Mraz <tomas@openssl.org>
(Merged from #19536)

(cherry picked from commit 373d901)
  • Loading branch information
mbroz authored and t8m committed Nov 10, 2022
1 parent 60d391b commit 2fee530
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
5 changes: 4 additions & 1 deletion crypto/pem/pem_pkey.c
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ PEM_write_cb_ex_fnsig(PrivateKey, EVP_PKEY, BIO, write_bio)
IMPLEMENT_PEM_provided_write_body_main(pkey, bio);

legacy:
if (x->ameth == NULL || x->ameth->priv_encode != NULL)
if (x != NULL && (x->ameth == NULL || x->ameth->priv_encode != NULL))
return PEM_write_bio_PKCS8PrivateKey(out, x, enc,
(const char *)kstr, klen, cb, u);
return PEM_write_bio_PrivateKey_traditional(out, x, enc, kstr, klen, cb, u);
Expand All @@ -336,6 +336,9 @@ int PEM_write_bio_PrivateKey_traditional(BIO *bp, const EVP_PKEY *x,
EVP_PKEY *copy = NULL;
int ret;

if (x == NULL)
return 0;

if (evp_pkey_is_assigned(x)
&& evp_pkey_is_provided(x)
&& evp_pkey_copy_downgraded(&copy, x))
Expand Down
7 changes: 6 additions & 1 deletion test/evp_pkey_provided_test.c
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,12 @@ static int test_print_key_using_pem(const char *alg, const EVP_PKEY *pk)
/* Unencrypted private key in PEM form */
|| !TEST_true(PEM_write_bio_PrivateKey(membio, pk,
NULL, NULL, 0, NULL, NULL))
|| !TEST_true(compare_with_file(alg, PRIV_PEM, membio)))
|| !TEST_true(compare_with_file(alg, PRIV_PEM, membio))
/* NULL key */
|| !TEST_false(PEM_write_bio_PrivateKey(membio, NULL,
NULL, NULL, 0, NULL, NULL))
|| !TEST_false(PEM_write_bio_PrivateKey_traditional(membio, NULL,
NULL, NULL, 0, NULL, NULL)))
goto err;

ret = 1;
Expand Down

0 comments on commit 2fee530

Please sign in to comment.