From f7df4e1e002a8cc85901cf31c1c61c547d206eba Mon Sep 17 00:00:00 2001 From: Karel Miko Date: Tue, 17 Nov 2026 17:11:24 +0100 Subject: [PATCH] ecc_import_pkcs8: reject malformed explicit curve parameters and free the key on error --- src/pk/ecc/ecc_import_pkcs8.c | 5 ++++- tests/ecc_test.c | 11 +++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/pk/ecc/ecc_import_pkcs8.c b/src/pk/ecc/ecc_import_pkcs8.c index ad32fa07d..b8ea5355e 100644 --- a/src/pk/ecc/ecc_import_pkcs8.c +++ b/src/pk/ecc/ecc_import_pkcs8.c @@ -69,6 +69,7 @@ int ecc_import_pkcs8_asn1(ltc_asn1_list *alg_id, ltc_asn1_list *priv_key, ecc_ke */ if (ltc_mp_cmp_d(version->data, 1) != LTC_MP_EQ) { + err = CRYPT_INVALID_PACKET; goto LBL_DONE; } cofactor = ltc_mp_get_int(p_cofactor->data); @@ -91,6 +92,9 @@ int ecc_import_pkcs8_asn1(ltc_asn1_list *alg_id, ltc_asn1_list *priv_key, ecc_ke if ((err = ecc_set_curve_from_mpis(a, b, prime->data, order->data, gx, gy, cofactor, key)) != CRYPT_OK) { goto LBL_DONE; } + } else { + err = CRYPT_INVALID_PACKET; + goto LBL_DONE; } } else { err = CRYPT_INVALID_PACKET; @@ -115,7 +119,6 @@ int ecc_import_pkcs8_asn1(ltc_asn1_list *alg_id, ltc_asn1_list *priv_key, ecc_ke } } err = CRYPT_INVALID_PACKET; - goto LBL_DONE; LBL_ECCFREE: ecc_free(key); diff --git a/tests/ecc_test.c b/tests/ecc_test.c index 5247734a8..5f7575997 100644 --- a/tests/ecc_test.c +++ b/tests/ecc_test.c @@ -2277,6 +2277,17 @@ static int s_ecc_import_export(void) { DO(ecc_key_cmp(PK_PRIVATE, &pri, &key)); ecc_free(&key); + /* import - private PKCS8 format - malformed explicit curve parameters or private key */ + XMEMCPY(out, long_pri_pkcs8, sizeof(long_pri_pkcs8)); + out[24] = 0x02; /* ECParameters version 2 */ + SHOULD_FAIL(ecc_import_pkcs8(out, sizeof(long_pri_pkcs8), NULL, &key)); + XMEMCPY(out, long_pri_pkcs8, sizeof(long_pri_pkcs8)); + out[73] = 0x02; /* curve A as INTEGER instead of OCTET STRING */ + SHOULD_FAIL(ecc_import_pkcs8(out, sizeof(long_pri_pkcs8), NULL, &key)); + XMEMCPY(out, long_pri_pkcs8, sizeof(long_pri_pkcs8)); + out[186] = 0x31; /* ECPrivateKey as SET instead of SEQUENCE, the already set curve has to be freed */ + SHOULD_FAIL(ecc_import_pkcs8(out, sizeof(long_pri_pkcs8), NULL, &key)); + /* import - private PKCS8 format - password protected (PBES1 algorithms) */ #ifdef LTC_MD2 DO(ecc_import_pkcs8(long_pri_pkcs8_pbe_md2_des, sizeof(long_pri_pkcs8_pbe_md2_des), &pw_ctx, &key));