From 0bd57c6657dcc22878debfe15918c1d2a351a425 Mon Sep 17 00:00:00 2001 From: tb <> Date: Mon, 28 Oct 2024 17:58:18 +0000 Subject: d2i_ECPrivateKey: split parameter setting into a helper In order to decode a private key, the group must be known in some way. Typically, the group is encoded in the EC domain parameters, preferably as a named curve (this is mandatory in PKIX per RFC 5480). However, the group could be absent because the domain parameters are OPTIONAL in the ECPrivateKey SEQUENCE. In that case the code falls back to the group that may already be set on the EC_KEY. Now there is no way to tell whether that group is the right one... In any case. Split this thing out of the body of d2i_ECPrivateKey() to make that function a bit less of an eyesore. ok jsing --- src/lib/libcrypto/ec/ec_asn1.c | 34 ++++++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) (limited to 'src/lib/libcrypto') diff --git a/src/lib/libcrypto/ec/ec_asn1.c b/src/lib/libcrypto/ec/ec_asn1.c index 842089f813..1ba1e36435 100644 --- a/src/lib/libcrypto/ec/ec_asn1.c +++ b/src/lib/libcrypto/ec/ec_asn1.c @@ -1,4 +1,4 @@ -/* $OpenBSD: ec_asn1.c,v 1.89 2024/10/28 17:40:46 tb Exp $ */ +/* $OpenBSD: ec_asn1.c,v 1.90 2024/10/28 17:58:18 tb Exp $ */ /* * Written by Nils Larsch for the OpenSSL project. */ @@ -1089,6 +1089,30 @@ i2d_ECPKParameters(const EC_GROUP *group, unsigned char **out_der) } LCRYPTO_ALIAS(i2d_ECPKParameters); +static int +ec_key_set_group_from_parameters(EC_KEY *ec_key, const ECPKPARAMETERS *params) +{ + EC_GROUP *group = NULL; + int ret = 0; + + /* Use group in parameters, if any. Fall back to existing group. */ + if (params != NULL) { + if ((group = ec_asn1_pkparameters2group(params)) == NULL) + goto err; + if (!EC_KEY_set_group(ec_key, group)) + goto err; + } + if (ec_key->group == NULL) + goto err; + + ret = 1; + + err: + EC_GROUP_free(group); + + return ret; +} + EC_KEY * d2i_ECPrivateKey(EC_KEY **out_ec_key, const unsigned char **in, long len) { @@ -1106,14 +1130,8 @@ d2i_ECPrivateKey(EC_KEY **out_ec_key, const unsigned char **in, long len) } ec_key->version = ec_privatekey->version; - if (ec_privatekey->parameters) { - EC_GROUP_free(ec_key->group); - ec_key->group = ec_asn1_pkparameters2group(ec_privatekey->parameters); - } - if (ec_key->group == NULL) { - ECerror(ERR_R_EC_LIB); + if (!ec_key_set_group_from_parameters(ec_key, ec_privatekey->parameters)) goto err; - } if (ec_privatekey->privateKey) { ec_key->priv_key = BN_bin2bn( -- cgit v1.2.3-55-g6feb