lib/crypto: mldsa: Explicitly check that 'alg' is a valid value

C doesn't guarantee at the language level that an enum actually has one
of the declared values.

For robustness, make mldsa_verify() handle invalid values of 'alg'.

No effect on current callers, who always pass a valid value for 'alg'.
(Except for the KUnit test case that this commit adds.)

Fixes: 64edccea59 ("lib/crypto: Add ML-DSA verification support")
Cc: [email protected]
Reviewed-by: Ard Biesheuvel <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Eric Biggers <[email protected]>
This commit is contained in:
Eric Biggers
2026-10-29 10:12:08 -07:00
parent 5c140c8700
commit efb621a57d
3 changed files with 18 additions and 2 deletions
+1
View File
@@ -48,6 +48,7 @@ enum mldsa_alg {
* Return:
* * 0 if the signature is valid
* * -EBADMSG if the signature and/or public key is malformed
* * -EINVAL if @alg is not a valid value
* * -EKEYREJECTED if the signature is invalid but otherwise well-formed
* * -ENOMEM if out of memory so the validity of the signature is unknown
*/
+8 -2
View File
@@ -528,8 +528,8 @@ static size_t encode_w1(u8 out[MAX_W1_ENCODED_LEN],
int mldsa_verify(enum mldsa_alg alg, const u8 *sig, size_t sig_len,
const u8 *msg, size_t msg_len, const u8 *pk, size_t pk_len)
{
const struct mldsa_parameter_set *params = &mldsa_parameter_sets[alg];
const int k = params->k, l = params->l;
const struct mldsa_parameter_set *params;
int k, l;
/* For now this just does pure ML-DSA with an empty context string. */
static const u8 msg_prefix[2] = { /* dom_sep= */ 0, /* ctx_len= */ 0 };
const u8 *ctilde; /* The signer's commitment hash */
@@ -537,6 +537,12 @@ int mldsa_verify(enum mldsa_alg alg, const u8 *sig, size_t sig_len,
u8 *h; /* The signer's hint vector, length k * N */
size_t w1_enc_len;
if (alg != MLDSA44 && alg != MLDSA65 && alg != MLDSA87)
return -EINVAL;
params = &mldsa_parameter_sets[alg];
k = params->k;
l = params->l;
/* Validate the public key and signature lengths. */
if (pk_len != params->pk_len || sig_len != params->sig_len)
return -EBADMSG;
+9
View File
@@ -372,6 +372,14 @@ static void test_mldsa_use_hint(struct kunit *test)
}
}
static void test_mldsa_invalid_alg(struct kunit *test)
{
KUNIT_ASSERT_EQ(test, -EINVAL,
mldsa_verify(MLDSA44 - 1, NULL, 0, NULL, 0, NULL, 0));
KUNIT_ASSERT_EQ(test, -EINVAL,
mldsa_verify(MLDSA87 + 1, NULL, 0, NULL, 0, NULL, 0));
}
static void benchmark_mldsa(struct kunit *test,
const struct mldsa_testvector *tv)
{
@@ -414,6 +422,7 @@ static struct kunit_case mldsa_kunit_cases[] = {
KUNIT_CASE(test_mldsa65),
KUNIT_CASE(test_mldsa87),
KUNIT_CASE(test_mldsa_use_hint),
KUNIT_CASE(test_mldsa_invalid_alg),
KUNIT_CASE(benchmark_mldsa44),
KUNIT_CASE(benchmark_mldsa65),
KUNIT_CASE(benchmark_mldsa87),