Skip to contentSkip to conversation

lib/crypto: ML-DSA verification support

PATCH Superseded Eric Biggers 6 participants 27 messages Nov 20, 2025 – Nov 30, 2025

Subsystems (3)

v1 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

Eric Biggers

author maintainer
#0 lore raw

cover lib/crypto: ML-DSA verification support

This series is targeting libcrypto-next. It can also be retrieved from:

git fetch https://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/linux.git mldsa-v1

This series adds support for verifying ML-DSA signatures to lib/crypto/. Patch 1 is the ML-DSA implementation itself. See that for full details.

Patches 2-4 are the KUnit tests, which still need some more work.

Sending this out now as requested by David. I'd like some more time to work on writing proper tests and making sure that everything is correct.

This is just the lib/crypto/ part. On top of this, we'll want to make public_key_verify_signature() call mldsa_verify() to support ML-DSA. (No need for the redundant crypto_sig abstraction layer.)

David Howells (1):
lib/crypto: tests: Add KUnit tests for ML-DSA

Eric Biggers (3):
lib/crypto: Add ML-DSA verification support
lib/crypto: tests: Add ML-DSA-65 test cases
lib/crypto: tests: Add ML-DSA-87 test cases

 include/crypto/mldsa.h                        |   51 +
 lib/crypto/Kconfig                            |    7 +
 lib/crypto/Makefile                           |    5 +
 lib/crypto/mldsa.c                            |  566 ++
 lib/crypto/tests/Kconfig                      |   10 +
 lib/crypto/tests/Makefile                     |    1 +
 lib/crypto/tests/mldsa_kunit.c                |  124 +
 .../tests/mldsa_pure_rejection_vectors_44.h   |  489 ++
 .../tests/mldsa_pure_rejection_vectors_65.h   | 4702 ++++++++++++
 .../tests/mldsa_pure_rejection_vectors_87.h   | 6390 +++++++++++++++++
 10 files changed, 12345 insertions(+)
 create mode 100644 include/crypto/mldsa.h
 create mode 100644 lib/crypto/mldsa.c
 create mode 100644 lib/crypto/tests/mldsa_kunit.c
 create mode 100644 lib/crypto/tests/mldsa_pure_rejection_vectors_44.h
 create mode 100644 lib/crypto/tests/mldsa_pure_rejection_vectors_65.h
 create mode 100644 lib/crypto/tests/mldsa_pure_rejection_vectors_87.h

base-commit: 10a1140107e0b98bd67d37ae7af72989dd7df00b

Signature · 1 line
2.51.2
author maintainer
#1 lore raw

PATCH 1/4 lib/crypto: Add ML-DSA verification support

Add support for verifying ML-DSA signatures.

ML-DSA (Module-Lattice-Based Digital Signature Algorithm) is specified in FIPS 204 and is the standard version of Dilithium. Unlike RSA and elliptic-curve cryptography, ML-DSA is believed to be secure even against adversaries in possession of a large-scale quantum computer.

Compared to the earlier patch
(https://lore.kernel.org/r/[email protected]/)
that was based on "leancrypto", this implementation:

- Is about 600 lines of source code instead of 4800.
- Generates about 4 KB of object code instead of 28 KB.
- Uses 9-13 KB of memory to verify a signature instead of 31-84 KB.
- Is 3-5% faster, depending on the ML-DSA parameter set.

The API just consists of a single function mldsa_verify(), supporting the standard parameter sets (ML-DSA-44, ML-DSA-65, and ML-DSA-87) as selected by an enum. That's all that's actually needed.

HashML-DSA, incremental message hashing, and nonempty contexts aren't supported, as they aren't needed yet. Likewise, only verification support is included, since it's all the kernel needs. It's much simpler than full keygen+sign+verify support, and it means that constant-time code isn't needed either. (I've still used constant-time patterns in some places anyway, but technically it's not needed. And some steps in ML-DSA verification are inherently variable-time anyway.)

Note that mldsa_verify() allocates memory, so it can sleep and can fail with ENOMEM. Unfortunately we don't have much choice about that, since ML-DSA needs a lot of memory. At least callers have to check for errors anyway, since the signature could be invalid.

---
 include/crypto/mldsa.h |  51 ++++
 lib/crypto/Kconfig     |   7 +
 lib/crypto/Makefile    |   5 +
 lib/crypto/mldsa.c     | 566 +++++++++++++++++++++++++++++++++++++++++
 4 files changed, 629 insertions(+)
 create mode 100644 include/crypto/mldsa.h
 create mode 100644 lib/crypto/mldsa.c
include/crypto/mldsa.h new file +51 -0
new file mode 100644
index 000000000000..f0c212e9e4f1
@@ -0,0 +1,51 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+/*
+ * Support for verifying ML-DSA signatures
+ *
+ * Copyright 2025 Google LLC
+ */
+#ifndef _CRYPTO_MLDSA_H
+#define _CRYPTO_MLDSA_H
+
+#include <linux/types.h>
+
+/* Identifier for an ML-DSA parameter set */
+enum mldsa_alg {
+	MLDSA44, /* ML-DSA-44 */
+	MLDSA65, /* ML-DSA-65 */
+	MLDSA87, /* ML-DSA-87 */
+};
+
+/* Lengths of ML-DSA public keys and signatures in bytes */
+#define MLDSA44_PUBLIC_KEY_SIZE 1312
+#define MLDSA65_PUBLIC_KEY_SIZE 1952
+#define MLDSA87_PUBLIC_KEY_SIZE 2592
+#define MLDSA44_SIGNATURE_SIZE 2420
+#define MLDSA65_SIGNATURE_SIZE 3309
+#define MLDSA87_SIGNATURE_SIZE 4627
+
+/**
+ * mldsa_verify() - Verify an ML-DSA signature
+ * @alg: The ML-DSA parameter set to use
+ * @sig: The signature
+ * @sig_len: Length of the signature in bytes.  Should match the
+ *	     MLDSA*_SIGNATURE_SIZE constant associated with @alg,
+ *	     otherwise -EBADMSG will be returned right away.
+ * @msg: The message
+ * @msg_len: Length of the message in bytes
+ * @pk: The public key
+ * @pk_len: Length of the public key in bytes.  Should match the
+ *	    MLDSA*_PUBLIC_KEY_SIZE constant associated with @alg,
+ *	    otherwise -EBADMSG will be returned right away.
+ *
+ * This verifies an ML-DSA signature using the specified ML-DSA parameter set.
+ * The context string is assumed to be empty.
+ *
+ * Context: Might sleep
+ * Return: 0 if the signature is valid, -EBADMSG if the signature is invalid, or
+ *	   -ENOMEM if out of memory so the validity of the signature is unknown
+ */
+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);
+
+#endif /* _CRYPTO_MLDSA_H */
lib/crypto/Kconfig +7 -0
index 9d04b3771ce2..51ac3186ebc2 100644
@@ -98,10 +98,17 @@ config CRYPTO_LIB_MD5_ARCH
 	depends on CRYPTO_LIB_MD5 && !UML
 	default y if MIPS && CPU_CAVIUM_OCTEON
 	default y if PPC
 	default y if SPARC64
 
+config CRYPTO_LIB_MLDSA
+	tristate
+	select CRYPTO_LIB_SHA3
+	help
+	  The ML-DSA library functions.  Select this if your module uses any of
+	  the functions from <crypto/mldsa.h>.
+
 config CRYPTO_LIB_POLY1305
 	tristate
 	help
 	  The Poly1305 library functions.  Select this if your module uses any
 	  of the functions from <crypto/poly1305.h>.
lib/crypto/Makefile +5 -0
index 6580991f8e12..fb83ec480ec0 100644
@@ -125,10 +125,15 @@ libmd5-$(CONFIG_PPC) += powerpc/md5-asm.o
 libmd5-$(CONFIG_SPARC) += sparc/md5_asm.o
 endif # CONFIG_CRYPTO_LIB_MD5_ARCH
 
 ################################################################################
 
+obj-$(CONFIG_CRYPTO_LIB_MLDSA) += libmldsa.o
+libmldsa-y := mldsa.o
+
+################################################################################
+
 obj-$(CONFIG_CRYPTO_LIB_POLY1305) += libpoly1305.o
 libpoly1305-y := poly1305.o
 ifeq ($(CONFIG_ARCH_SUPPORTS_INT128),y)
 libpoly1305-$(CONFIG_CRYPTO_LIB_POLY1305_GENERIC) += poly1305-donna64.o
 else
lib/crypto/mldsa.c new file +566 -0

566 lines not on this page · raw message

Signature · 1 line
2.51.2
author maintainer
#21 lore raw

PATCH 2/4 lib/crypto: tests: Add KUnit tests for ML-DSA

In reply to Eric Biggers

From: David Howells <[email protected]>

Add a KUnit test suite for ML-DSA, including:

- The ML-DSA-44 "Pure rejection tests" from Stephan Mueller's Leancrypto
- An ML-DSA-44 benchmark

Later patches will add test cases for ML-DSA-65 and ML-DSA-87.

(This needs some work. For one, there are no negative tests yet.)

---
 lib/crypto/tests/Kconfig                      |  10 +
 lib/crypto/tests/Makefile                     |   1 +
 lib/crypto/tests/mldsa_kunit.c                |  92 ++++
 .../tests/mldsa_pure_rejection_vectors_44.h   | 489 ++++++++++++++++++
 4 files changed, 592 insertions(+)
 create mode 100644 lib/crypto/tests/mldsa_kunit.c
 create mode 100644 lib/crypto/tests/mldsa_pure_rejection_vectors_44.h
lib/crypto/tests/Kconfig +10 -0
index 61d435c450bb..214c23d994e6 100644
@@ -36,10 +36,20 @@ config CRYPTO_LIB_MD5_KUNIT_TEST
 	select CRYPTO_LIB_MD5
 	help
 	  KUnit tests for the MD5 cryptographic hash function and its
 	  corresponding HMAC.
 
+config CRYPTO_LIB_MLDSA_KUNIT_TEST
+	tristate "KUnit tests for ML-DSA" if !KUNIT_ALL_TESTS
+	depends on KUNIT
+	default KUNIT_ALL_TESTS || CRYPTO_SELFTESTS
+	select CRYPTO_LIB_BENCHMARK_VISIBLE
+	select CRYPTO_LIB_MLDSA
+	help
+	  KUnit tests for ML-DSA (Module-Lattice-Based Digital Signature
+	  Algorithm).
+
 config CRYPTO_LIB_POLY1305_KUNIT_TEST
 	tristate "KUnit tests for Poly1305" if !KUNIT_ALL_TESTS
 	depends on KUNIT
 	default KUNIT_ALL_TESTS || CRYPTO_SELFTESTS
 	select CRYPTO_LIB_BENCHMARK_VISIBLE
lib/crypto/tests/Makefile +1 -0
index 5109a0651925..3dde0b40b2c5 100644
@@ -2,10 +2,11 @@
 
 obj-$(CONFIG_CRYPTO_LIB_BLAKE2B_KUNIT_TEST) += blake2b_kunit.o
 obj-$(CONFIG_CRYPTO_LIB_BLAKE2S_KUNIT_TEST) += blake2s_kunit.o
 obj-$(CONFIG_CRYPTO_LIB_CURVE25519_KUNIT_TEST) += curve25519_kunit.o
 obj-$(CONFIG_CRYPTO_LIB_MD5_KUNIT_TEST) += md5_kunit.o
+obj-$(CONFIG_CRYPTO_LIB_MLDSA_KUNIT_TEST) += mldsa_kunit.o
 obj-$(CONFIG_CRYPTO_LIB_POLY1305_KUNIT_TEST) += poly1305_kunit.o
 obj-$(CONFIG_CRYPTO_LIB_POLYVAL_KUNIT_TEST) += polyval_kunit.o
 obj-$(CONFIG_CRYPTO_LIB_SHA1_KUNIT_TEST) += sha1_kunit.o
 obj-$(CONFIG_CRYPTO_LIB_SHA256_KUNIT_TEST) += sha224_kunit.o sha256_kunit.o
 obj-$(CONFIG_CRYPTO_LIB_SHA512_KUNIT_TEST) += sha384_kunit.o sha512_kunit.o
lib/crypto/tests/mldsa_kunit.c new file +92 -0

92 lines not on this page · raw message

lib/crypto/tests/mldsa_pure_rejection_vectors_44.h new file +489 -0

489 lines not on this page · raw message

Signature · 1 line
2.51.2
author maintainer
#23 lore raw

PATCH 3/4 lib/crypto: tests: Add ML-DSA-65 test cases

In reply to Eric Biggers

Add test vectors and test cases for ML-DSA-65.

(This needs some work. For one, there are no negative tests yet.)

---
 lib/crypto/tests/mldsa_kunit.c                |   16 +
 .../tests/mldsa_pure_rejection_vectors_65.h   | 4702 +++++++++++++++++
 2 files changed, 4718 insertions(+)
 create mode 100644 lib/crypto/tests/mldsa_pure_rejection_vectors_65.h
lib/crypto/tests/mldsa_kunit.c +16 -0
index 836555bd0096..3d4abda9ba67 100644
@@ -23,10 +23,13 @@ struct mldsa_testvector {
  * as generated with the mldsa_edge_case_tester.
  */
 static const struct mldsa_testvector mldsa_44_testvectors[] = {
 #include "mldsa_pure_rejection_vectors_44.h"
 };
+static const struct mldsa_testvector mldsa_65_testvectors[] = {
+#include "mldsa_pure_rejection_vectors_65.h"
+};
 
 static void do_mldsa_and_assert_success(struct kunit *test, enum mldsa_alg alg,
 					const struct mldsa_testvector *tv)
 {
 	int err = mldsa_verify(alg, tv->sig, tv->sig_len, tv->msg, tv->msg_len,
@@ -45,10 +48,16 @@ static void test_mldsa44(struct kunit *test)
 {
 	test_mldsa(test, MLDSA44, mldsa_44_testvectors,
 		   ARRAY_SIZE(mldsa_44_testvectors));
 }
 
+static void test_mldsa65(struct kunit *test)
+{
+	test_mldsa(test, MLDSA65, mldsa_65_testvectors,
+		   ARRAY_SIZE(mldsa_65_testvectors));
+}
+
 static void benchmark_mldsa(struct kunit *test, enum mldsa_alg alg,
 			    const struct mldsa_testvector *tv)
 {
 	const int warmup_niter = 200;
 	const int benchmark_niter = 200;
@@ -73,13 +82,20 @@ static void benchmark_mldsa(struct kunit *test, enum mldsa_alg alg,
 static void benchmark_mldsa44(struct kunit *test)
 {
 	benchmark_mldsa(test, MLDSA44, &mldsa_44_testvectors[0]);
 }
 
+static void benchmark_mldsa65(struct kunit *test)
+{
+	benchmark_mldsa(test, MLDSA65, &mldsa_65_testvectors[0]);
+}
+
 static struct kunit_case mldsa_kunit_cases[] = {
 	KUNIT_CASE(test_mldsa44),
+	KUNIT_CASE(test_mldsa65),
 	KUNIT_CASE(benchmark_mldsa44),
+	KUNIT_CASE(benchmark_mldsa65),
 	{},
 };
 
 static struct kunit_suite mldsa_kunit_suite = {
 	.name = "mldsa",
lib/crypto/tests/mldsa_pure_rejection_vectors_65.h new file +4702 -0

2,951 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.51.2

Part of the diff is not shown here. View the raw message.

author maintainer
#24 lore raw

PATCH 4/4 lib/crypto: tests: Add ML-DSA-87 test cases

In reply to Eric Biggers

Add test vectors and test cases for ML-DSA-87.

(This needs some work. For one, there are no negative tests yet.)

---
 lib/crypto/tests/mldsa_kunit.c                |   16 +
 .../tests/mldsa_pure_rejection_vectors_87.h   | 6390 +++++++++++++++++
 2 files changed, 6406 insertions(+)
 create mode 100644 lib/crypto/tests/mldsa_pure_rejection_vectors_87.h
lib/crypto/tests/mldsa_kunit.c +16 -0
index 3d4abda9ba67..4727134cf97e 100644
@@ -26,10 +26,13 @@ static const struct mldsa_testvector mldsa_44_testvectors[] = {
 #include "mldsa_pure_rejection_vectors_44.h"
 };
 static const struct mldsa_testvector mldsa_65_testvectors[] = {
 #include "mldsa_pure_rejection_vectors_65.h"
 };
+static const struct mldsa_testvector mldsa_87_testvectors[] = {
+#include "mldsa_pure_rejection_vectors_87.h"
+};
 
 static void do_mldsa_and_assert_success(struct kunit *test, enum mldsa_alg alg,
 					const struct mldsa_testvector *tv)
 {
 	int err = mldsa_verify(alg, tv->sig, tv->sig_len, tv->msg, tv->msg_len,
@@ -54,10 +57,16 @@ static void test_mldsa65(struct kunit *test)
 {
 	test_mldsa(test, MLDSA65, mldsa_65_testvectors,
 		   ARRAY_SIZE(mldsa_65_testvectors));
 }
 
+static void test_mldsa87(struct kunit *test)
+{
+	test_mldsa(test, MLDSA87, mldsa_87_testvectors,
+		   ARRAY_SIZE(mldsa_87_testvectors));
+}
+
 static void benchmark_mldsa(struct kunit *test, enum mldsa_alg alg,
 			    const struct mldsa_testvector *tv)
 {
 	const int warmup_niter = 200;
 	const int benchmark_niter = 200;
@@ -87,15 +96,22 @@ static void benchmark_mldsa44(struct kunit *test)
 static void benchmark_mldsa65(struct kunit *test)
 {
 	benchmark_mldsa(test, MLDSA65, &mldsa_65_testvectors[0]);
 }
 
+static void benchmark_mldsa87(struct kunit *test)
+{
+	benchmark_mldsa(test, MLDSA87, &mldsa_87_testvectors[0]);
+}
+
 static struct kunit_case mldsa_kunit_cases[] = {
 	KUNIT_CASE(test_mldsa44),
 	KUNIT_CASE(test_mldsa65),
+	KUNIT_CASE(test_mldsa87),
 	KUNIT_CASE(benchmark_mldsa44),
 	KUNIT_CASE(benchmark_mldsa65),
+	KUNIT_CASE(benchmark_mldsa87),
 	{},
 };
 
 static struct kunit_suite mldsa_kunit_suite = {
 	.name = "mldsa",
lib/crypto/tests/mldsa_pure_rejection_vectors_87.h new file +6390 -0

2,949 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.51.2

Part of the diff is not shown here. View the raw message.

#22 lore raw

RE: [PATCH 2/4] lib/crypto: tests: Add KUnit tests for ML-DSA

In reply to Eric Biggers
Quoted 5 lines

-----Original Message-----
From: Eric Biggers <[email protected]>
Subject: [PATCH 2/4] lib/crypto: tests: Add KUnit tests for ML-DSA

...

Quoted 15 lines

From: David Howells <[email protected]>

Add a KUnit test suite for ML-DSA, including:

- The ML-DSA-44 "Pure rejection tests" from Stephan Mueller's Leancrypto
- An ML-DSA-44 benchmark

Later patches will add test cases for ML-DSA-65 and ML-DSA-87.

(This needs some work. For one, there are no negative tests yet.)

...

lib/crypto/tests/mldsa_pure_rejection_vectors_44.h line 4

Quoted 6 lines

+++ b/lib/crypto/tests/mldsa_pure_rejection_vectors_44.h

lib/crypto/tests/mldsa_pure_rejection_vectors_44.h new file +4 -0
@@ -0,0 +1,489 @@
+/* SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause */
+	{
+		.what = "pure rejection vector",
+		.algo = "ml-dsa44",

Either no dashes or all dashes might be easier to handle:
mldsa44
mldsa-44
ml-dsa44
ml-dsa-44

maintainer
#2 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

In reply to Eric Biggers

You need to add something like:

#include <linux/module.h>
...
MODULE_DESCRIPTION("ML-DSA signature verification"); MODULE_LICENSE("GPL");

David

maintainer
#4 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

In reply to Eric Biggers
Quoted 1 line · Eric Biggers

- Is about 600 lines of source code instead of 4800.

There's less shareable code for other algos that I'm sure people are going to ask for, but that's probably fine.

Quoted 2 lines

- Generates about 4 KB of object code instead of 28 KB.
- Uses 9-13 KB of memory to verify a signature instead of 31-84 KB.

That's definitely good.

Quoted 1 line

- Is 3-5% faster, depending on the ML-DSA parameter set.

That's not quite what I see. For Leancrypto:

    # benchmark_mldsa44: 8672 ops/s
    # benchmark_mldsa65: 5470 ops/s
    # benchmark_mldsa87: 3350 ops/s

For your implementation:

    # benchmark_mldsa44: 8707 ops/s
    # benchmark_mldsa65: 5423 ops/s
    # benchmark_mldsa87: 3352 ops/s

This may reflect differences in CPU (mine's an i3-4170).

The numbers are pretty stable with the cpu frequency governor set to performance and without rebooting betweentimes.

Interesting that your mldsa44 is consistently faster, but your mldsa65 is consistently slower. mldsa87 is consistently about the same.

I don't think the time differences are particularly significant.

David

maintainer Reviewed-by on v1 1/4
#6 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

In reply to Eric Biggers

lib/crypto/mldsa.c line 170

Quoted 2 lines · Eric Biggers
lib/crypto/mldsa.c new file +2 -0
+	/* Compute d = (c mod 2^32) * (q^-1 mod 2^32). */
+	s32 d = (s32)c * QINV_MOD_R;

Hmmm... is "(s32)c" actually "(c mod 2^32)"? Should that be:

	u32 d = (u32)c * QINV_MOD_R;

This is followed up by casting 'd' to "s64". I don't think that should sign-extend it, but...

lib/crypto/mldsa.c line 195

Quoted 1 line
lib/crypto/mldsa.c new file +1 -0
+	for (int m = 0, len = 128; len >= 1; len /= 2) {

Can you put "int m = 0" outside of the for-statement? I know putting it inside saves a line or two, but 'm' is not the loop counter - which it seems like it should be by virtue of being listed first.

lib/crypto/mldsa.c line 221

Quoted 1 line
lib/crypto/mldsa.c new file +1 -0
+	for (int m = 256, len = 1; len < 256; len *= 2) {

Ditto.

lib/crypto/mldsa.c line 248

Quoted 2 lines
lib/crypto/mldsa.c new file +2 -0
+static const u8 *decode_t1_elem(struct mldsa_ring_elem *out,
+				const u8 *t1_encoded)

I think this is (more or less) pkDecode()? Can you put something like:

* Decode the vector 't1' from the public key.
* Reference: FIPS 204 Algorithm 23, sigDecode.

in the comment before it?

lib/crypto/mldsa.c line 344

Quoted 6 lines
lib/crypto/mldsa.c new file +6 -0
+/*
+ * Use @seed to generate a ring element @c with coefficients in {-1, 0, 1},
+ * exactly @tau of them nonzero.  Reference: FIPS 204 Algorithm 29, SampleInBall
+ */
+static void sample_in_ball(struct mldsa_ring_elem *c, const u8 *seed,
+			   size_t seed_len, int tau, struct shake_ctx *shake)

Should "seed" actually be labelled "rho"? I know a seed is what it is, but the algo description has a different label - and the caller passes it ctilde, not rho:-/.

lib/crypto/mldsa.c line 455

Quoted 2 lines
lib/crypto/mldsa.c new file +2 -0
+	u8 (*h)[N]; /* The signer's hint vector, length k */
+	h = (u8 (*)[N])&ws->z[l];

C is weird sometimes.

lib/crypto/mldsa.c line 528

Quoted 1 line
lib/crypto/mldsa.c new file +1 -0
+		/* Reduce to [0, q), then tmp = w'_1 = UseHint(h, w'_Approx) */

Bracket mismatch. "[0, q]"

lib/crypto/mldsa.c line 535

Quoted 3 lines
lib/crypto/mldsa.c new file +2 -0
+		/* w1Encode(w'_1) */
+		w1_pos = 0;
...

Given you put the decode functions into helpers, don't you want to do that with this?

lib/crypto/mldsa.c line 562

Quoted 2 lines
lib/crypto/mldsa.c new file +2 -0
+	if (memcmp(ws->ctildeprime, ctilde, params->ctilde_len) != 0)
+		return -EBADMSG;

Actually, this should return -EKEYREJECTED, not -EBADMSG.

I guess you don't need to use crypto_memneq() as timing doesn't matter.

The maths look okay, I think. You can add:

David

author maintainer
#5 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

In reply to David Howells
Quoted 6 lines · David Howells
Quoted 1 line · Eric Biggers

- Is about 600 lines of source code instead of 4800.

There's less shareable code for other algos that I'm sure people are going to ask for, but that's probably fine.

The "advanced" verification features that people could conceivably want in the future (public key preloading, nonempty contexts, HashML-DSA, external mu, incremental message hashing) would all be fairly straightforward to add, in the event that that they ever become needed.

Signing support would of course be challenging. But that's expected, and we should try to keep that out of the kernel anyway.

Quoted 21 lines
Quoted 2 lines

- Generates about 4 KB of object code instead of 28 KB.
- Uses 9-13 KB of memory to verify a signature instead of 31-84 KB.

That's definitely good.

Quoted 1 line

- Is 3-5% faster, depending on the ML-DSA parameter set.

That's not quite what I see. For Leancrypto:

    # benchmark_mldsa44: 8672 ops/s
    # benchmark_mldsa65: 5470 ops/s
    # benchmark_mldsa87: 3350 ops/s

For your implementation:

    # benchmark_mldsa44: 8707 ops/s
    # benchmark_mldsa65: 5423 ops/s
    # benchmark_mldsa87: 3352 ops/s

This may reflect differences in CPU (mine's an i3-4170).

Quoted 7 lines

The numbers are pretty stable with the cpu frequency governor set to performance and without rebooting betweentimes.

Interesting that your mldsa44 is consistently faster, but your mldsa65 is consistently slower. mldsa87 is consistently about the same.

I don't think the time differences are particularly significant.

Sure, I had just tested one CPU. Slightly different results on different CPUs are expected. It's also expected that the ops/s for verification in a loop is still in roughly the same ballpark as your integration of leancrypto (or the Dilithium reference code which leancrypto seems to be based on, for that matter). There aren't too many ways to implement the most time-consuming parts. Generally, arch-optimized code would be needed to do significantly better.

Of course, the greatly reduced icache and dcache usage is much more important for performance. But that doesn't show up in the "just verify the same signature in a loop repeatedly" benchmark.

I'll clarify that part of the commit message accordingly.

- Eric

author maintainer
#7 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

In reply to David Howells
Quoted 11 lines · David Howells

lib/crypto/mldsa.c line 170

Quoted 2 lines · Eric Biggers
lib/crypto/mldsa.c new file +2 -0
+	/* Compute d = (c mod 2^32) * (q^-1 mod 2^32). */
+	s32 d = (s32)c * QINV_MOD_R;

Hmmm... is "(s32)c" actually "(c mod 2^32)"? Should that be:

	u32 d = (u32)c * QINV_MOD_R;

This is followed up by casting 'd' to "s64". I don't think that should sign-extend it, but...

It selects the representative in the range [INT32_MIN, INT32_MAX], rather than the representative in the range [0, UINT32_MAX]. The sign extension is intentional. This makes the reduction more symmetric so that the range of supported unreduced products is roughly symmetric. I'll update the comments to clarify this.

Quoted 9 lines

lib/crypto/mldsa.c line 195

Quoted 1 line
lib/crypto/mldsa.c new file +1 -0
+	for (int m = 0, len = 128; len >= 1; len /= 2) {

Can you put "int m = 0" outside of the for-statement? I know putting it inside saves a line or two, but 'm' is not the loop counter - which it seems like it should be by virtue of being listed first.

lib/crypto/mldsa.c line 221

Quoted 1 line
lib/crypto/mldsa.c new file +1 -0
+	for (int m = 256, len = 1; len < 256; len *= 2) {

Ditto.

Sure.

Quoted 10 lines

lib/crypto/mldsa.c line 248

Quoted 3 lines
lib/crypto/mldsa.c new file +2 -0
+static const u8 *decode_t1_elem(struct mldsa_ring_elem *out,
+				const u8 *t1_encoded)

I think this is (more or less) pkDecode()? Can you put something like:

* Decode the vector 't1' from the public key.
* Reference: FIPS 204 Algorithm 23, sigDecode.

in the comment before it?

Sure.

Quoted 10 lines

lib/crypto/mldsa.c line 344

Quoted 6 lines
lib/crypto/mldsa.c new file +6 -0
+/*
+ * Use @seed to generate a ring element @c with coefficients in {-1, 0, 1},
+ * exactly @tau of them nonzero.  Reference: FIPS 204 Algorithm 29, SampleInBall
+ */
+static void sample_in_ball(struct mldsa_ring_elem *c, const u8 *seed,
+			   size_t seed_len, int tau, struct shake_ctx *shake)

Should "seed" actually be labelled "rho"? I know a seed is what it is, but the algo description has a different label - and the caller passes it ctilde, not rho:-/.

FIPS 204 Algorithm 29 SampleInBall uses the variable rho for the seed, while also calling it a "seed" in the descriptive text. However, elsewhere rho refers specifically to the public key's random seed. I think just calling it "seed" makes sense here.

Quoted 4 lines

lib/crypto/mldsa.c line 455

Quoted 2 lines
lib/crypto/mldsa.c new file +2 -0
+	u8 (*h)[N]; /* The signer's hint vector, length k */
+	h = (u8 (*)[N])&ws->z[l];

C is weird sometimes.

We could make it a 'u8 *', but then we'd have to use array indices like h[i*k + j] rather than h[i][j]. May be worth it anyway, to avoid the slightly-unusual syntax.

Quoted 3 lines

lib/crypto/mldsa.c line 528

Quoted 1 line
lib/crypto/mldsa.c new file +1 -0
+		/* Reduce to [0, q), then tmp = w'_1 = UseHint(h, w'_Approx) */

Bracket mismatch. "[0, q]"

It's intentional, since it denotes a mathematical range. Elsewhere I used the words "the range" explicitly, so I'll add that above too. (Or maybe reword it differently.)

Quoted 7 lines

lib/crypto/mldsa.c line 535

Quoted 4 lines
lib/crypto/mldsa.c new file +2 -0
+		/* w1Encode(w'_1) */
+		w1_pos = 0;
...

Given you put the decode functions into helpers, don't you want to do that with this?

Sure, I'll move the w1Encode part into a helper function.

Quoted 4 lines

lib/crypto/mldsa.c line 562

Quoted 2 lines
lib/crypto/mldsa.c new file +2 -0
+	if (memcmp(ws->ctildeprime, ctilde, params->ctilde_len) != 0)
+		return -EBADMSG;

Actually, this should return -EKEYREJECTED, not -EBADMSG.

Who/what decided that? A lot of the crypto code uses -EBADMSG already. crypto_aead uses it, for example.

Quoted 1 line

I guess you don't need to use crypto_memneq() as timing doesn't matter.

Correct.

Quoted 3 lines

The maths look okay, I think. You can add:

Thanks,

- Eric

author maintainer
#3 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

In reply to David Howells
Quoted 8 lines · David Howells

You need to add something like:

#include <linux/module.h>
...
MODULE_DESCRIPTION("ML-DSA signature verification"); MODULE_LICENSE("GPL");

David

Yep. Sorry, I usually build my test kernels with CONFIG_MODULES=n because it's easier.

- Eric

author maintainer
#26 lore raw
In reply to David Howells
Quoted 2 lines · David Howells

Note that your emailed patches seem corrupt somehow, but I can fetch the git branch.

Works for me:

git checkout -d 10a1140107e0b98bd67d37ae7af72989dd7df00b b4 am [email protected]
git am ./20251119_ebiggers_lib_crypto_ml_dsa_verification_support.mbx

10a1140107e0b98bd67d37ae7af72989dd7df00b is the base-commit listed in the cover letter, via the --base option to 'git format-patch'. It's the current head of libcrypto-next and is also in linux-next. Maybe you tried applying the series to a different commit.

Anyway, using the git repo is fine too. This sort of stuff is exactly why I usually provide a git link too.

- Eric

maintainer
#8 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

In reply to Eric Biggers
Quoted 8 lines · Eric Biggers
Quoted 7 lines · David Howells

lib/crypto/mldsa.c line 170

Quoted 2 lines · Eric Biggers
lib/crypto/mldsa.c new file +2 -0
+	/* Compute d = (c mod 2^32) * (q^-1 mod 2^32). */
+	s32 d = (s32)c * QINV_MOD_R;

Hmmm... is "(s32)c" actually "(c mod 2^32)"? Should that be:

Quoted 8 lines
Quoted 4 lines
	u32 d = (u32)c * QINV_MOD_R;

This is followed up by casting 'd' to "s64". I don't think that should sign-extend it, but...

It selects the representative in the range [INT32_MIN, INT32_MAX], rather than the representative in the range [0, UINT32_MAX]. The sign extension is intentional.

I'm concerned about the basis on which it becomes positive or negative. It looks like the sign bit ends up being chosen arbitrarily.

Quoted 7 lines
Quoted 3 lines

lib/crypto/mldsa.c line 528

Quoted 1 line
lib/crypto/mldsa.c new file +1 -0
+		/* Reduce to [0, q), then tmp = w'_1 = UseHint(h, w'_Approx) */

Bracket mismatch. "[0, q]"

It's intentional, since it denotes a mathematical range. Elsewhere I used the words "the range" explicitly, so I'll add that above too. (Or maybe reword it differently.)

I meant you have an opening square bracket and a closing round bracket in "[0, q)".

David

author maintainer
#9 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

Quoted 15 lines · David Howells
Quoted 13 lines · Eric Biggers
Quoted 11 lines · David Howells

lib/crypto/mldsa.c line 170

Quoted 2 lines · Eric Biggers
lib/crypto/mldsa.c new file +2 -0
+	/* Compute d = (c mod 2^32) * (q^-1 mod 2^32). */
+	s32 d = (s32)c * QINV_MOD_R;

Hmmm... is "(s32)c" actually "(c mod 2^32)"? Should that be:

	u32 d = (u32)c * QINV_MOD_R;

This is followed up by casting 'd' to "s64". I don't think that should sign-extend it, but...

Quoted 6 lines
Quoted 3 lines

It selects the representative in the range [INT32_MIN, INT32_MAX], rather than the representative in the range [0, UINT32_MAX]. The sign extension is intentional.

I'm concerned about the basis on which it becomes positive or negative. It looks like the sign bit ends up being chosen arbitrarily.

Right, it's unrelated to the sign of the s64 value, unless the s64 value happens to fit in a s32. And that's okay: the worst-case analysis, which considers the largest possible absolute value that can be built up, assumes the signs happen to match repeatedly.

By the way, lest you think I'd doing anything particularly novel here, the Dilithium reference code also uses this same (very-nearly-symmetric) Montgomery reduction formula including the sign extension, where it made its way into leancrypto and your patchset too. It also appears in FIPS 204 as Algorithm 49, MontgomeryReduce. There are other ways to implement this stuff, but they would be less efficient.

However, unfortunately neither source explains it properly, and they actually provide incorrect information. The comment in the reference code says the the input can be in "-2^{31}Q <= a <= Q*2^31", which isn't quite correct; the upper bound is actually exclusive. In my code, I correctly document the upper bound as being exclusive.

FIPS 204 documents the same incorrect interval, but then sort of gets around it by only claiming that the output is less than 2q in absolute value (rather than q) and also by not clarifying whether sign extension is done. They may have thought that sign extension shouldn't be done, as you seem to have thought. Either way, their explanation is misleading. The very-nearly-symmetric version that produces an output less than q in absolute value is the logical version when working with signed values, and it seems to be what the Dilithium authors intended.

Anyway, it's clear that my code comments still didn't explain it properly either, so I'll work on that.

Quoted 10 lines
Quoted 7 lines
Quoted 3 lines

lib/crypto/mldsa.c line 528

Quoted 1 line
lib/crypto/mldsa.c new file +1 -0
+		/* Reduce to [0, q), then tmp = w'_1 = UseHint(h, w'_Approx) */

Bracket mismatch. "[0, q]"

It's intentional, since it denotes a mathematical range. Elsewhere I used the words "the range" explicitly, so I'll add that above too. (Or maybe reword it differently.)

I meant you have an opening square bracket and a closing round bracket in "[0, q)".

That means the lower end is inclusive and the upper end is exclusive. We're taking mod q, so we do *not* want q to be included.

I could write it another way that wouldn't assume familiarity with open interval notation, like [0, q - 1] or 0 <= val < q.

- Eric

maintainer
#10 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

Quoted 2 lines · Eric Biggers

I could write it another way that wouldn't assume familiarity with open interval notation, like [0, q - 1] or 0 <= val < q.

"[0, q-1]" would be less prone to confusion, thanks - and editors flagging the bracket mismatch.

David

maintainer
#12 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

In reply to Eric Biggers
Quoted 6 lines · Eric Biggers
Quoted 4 lines

lib/crypto/mldsa.c line 562

Quoted 2 lines
lib/crypto/mldsa.c new file +2 -0
+	if (memcmp(ws->ctildeprime, ctilde, params->ctilde_len) != 0)
+		return -EBADMSG;

Actually, this should return -EKEYREJECTED, not -EBADMSG.

Who/what decided that?

I did. When I added RSA support in 2012 for module signing. Note that it was originally added as part of crypto/asymmetric_keys/ and was not covered by a crypto API. The RSA code has since been moved to crypto/ and is now accessed through the crypto API, but it has retained this error code and this is also used by other public key algos.

Quoted 2 lines

A lot of the crypto code uses -EBADMSG already.
crypto_aead uses it, for example.

ecdsa.c:60: return -EKEYREJECTED;
ecrdsa.c:111: return -EKEYREJECTED;
ecrdsa.c:139: return -EKEYREJECTED;
ecrdsa.c:239: return -EKEYREJECTED;
rsassa-pkcs1.c:293: return -EKEYREJECTED;
rsassa-pkcs1.c:295: return -EKEYREJECTED;

David

author maintainer
#13 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

Quoted 18 lines · David Howells
Quoted 6 lines · Eric Biggers
Quoted 4 lines

lib/crypto/mldsa.c line 562

Quoted 2 lines
lib/crypto/mldsa.c new file +2 -0
+	if (memcmp(ws->ctildeprime, ctilde, params->ctilde_len) != 0)
+		return -EBADMSG;

Actually, this should return -EKEYREJECTED, not -EBADMSG.

Who/what decided that?

I did. When I added RSA support in 2012 for module signing. Note that it was originally added as part of crypto/asymmetric_keys/ and was not covered by a crypto API. The RSA code has since been moved to crypto/ and is now accessed through the crypto API, but it has retained this error code and this is also used by other public key algos.

Quoted 2 lines

A lot of the crypto code uses -EBADMSG already.
crypto_aead uses it, for example.

Quoted 6 lines

ecdsa.c:60: return -EKEYREJECTED;
ecrdsa.c:111: return -EKEYREJECTED;
ecrdsa.c:139: return -EKEYREJECTED;
ecrdsa.c:239: return -EKEYREJECTED;
rsassa-pkcs1.c:293: return -EKEYREJECTED;
rsassa-pkcs1.c:295: return -EKEYREJECTED;

crypto/aegis128-core.c:442: return -EBADMSG;
crypto/aegis128-core.c:499: return -EBADMSG;
crypto/algif_aead.c:313: if (err == -EIOCBQUEUED || err == -EBADMSG || !ret)
crypto/authenc.c:223: return -EBADMSG;
crypto/authencesn.c:220: return -EBADMSG;
crypto/ccm.c:336: err = -EBADMSG;
crypto/ccm.c:384: return -EBADMSG;
crypto/chacha20poly1305.c:90: return -EBADMSG;
crypto/dh.c:207: ret = -EBADMSG;
crypto/dh.c:221: ret = -EBADMSG;

crypto/dh.c:242:                ret = -EBADMSG;
crypto/ecdsa.c:37:              return -EBADMSG;
crypto/ecrdsa.c:101:            return -EBADMSG;
crypto/gcm.c:471:       return crypto_memneq(iauth_tag, auth_tag, authsize) ? -EBADMSG : 0;
crypto/krb5enc.c:259:           return -EBADMSG;
crypto/rsa.c:150:               ret = -EBADMSG;
crypto/rsa.c:189:               ret = -EBADMSG;
crypto/rsassa-pkcs1.c:275:              return -EBADMSG;
crypto/rsassa-pkcs1.c:282:              return -EBADMSG;
crypto/rsassa-pkcs1.c:286:              return -EBADMSG;
crypto/rsassa-pkcs1.c:288:              return -EBADMSG;

crypto/testmgr.c:90: * algorithm might result in EINVAL rather than EBADMSG, due to other
crypto/testmgr.c:2179: (err != vec->crypt_error && !(err == -EBADMSG && vec->novrfy))) {
crypto/testmgr.c:2183: vec->crypt_error != 0 && vec->crypt_error != -EBADMSG)
crypto/testmgr.c:2184: sprintf(expected_error, "-EBADMSG or %d",
crypto/testmgr.c:2187: sprintf(expected_error, "-EBADMSG");
include/crypto/aead.h:37: * operation is that the caller should explicitly check for -EBADMSG of the include/crypto/aead.h:39: * a breach in the integrity of the message. In essence, that -EBADMSG error include/crypto/aead.h:375: * Return: 0 if the cipher operation was successful; -EBADMSG: The AEAD

That list actually includes the same three files that use -EKEYREJECTED. It looks like if the signature verification fails "early" it's -EBADMSG, whereas if it fails "late" it's -EKEYREJECTED? I'm skeptical that that's a meaningful difference. And it's not like this is documented either; crypto_sig_verify() just says "error code in case of error".

- Eric

#14 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

Quoted 3 lines · Eric Biggers

That list actually includes the same three files that use -EKEYREJECTED. It looks like if the signature verification fails "early" it's -EBADMSG, whereas if it fails "late" it's -EKEYREJECTED?

-EBADMSG denotes malformed data (e.g. incorrectly formatted ASN.1 payload).

-EKEYREJECTED denotes a well-formed, but incorrect signature (e.g. made by a wrong key).

I think it's important and useful to be able to differentiate that.

Thanks,

Lukas

author maintainer
#15 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

Quoted 11 lines · Lukas Wunner
Quoted 3 lines · Eric Biggers

That list actually includes the same three files that use -EKEYREJECTED. It looks like if the signature verification fails "early" it's -EBADMSG, whereas if it fails "late" it's -EKEYREJECTED?

(quoted diff) +0 -2
-EBADMSG denotes malformed data (e.g. incorrectly formatted ASN.1 payload).
 
-EKEYREJECTED denotes a well-formed, but incorrect signature (e.g. made

by a wrong key).

I think it's important and useful to be able to differentiate that.

I guess. The pseudocode in the ML-DSA specification is clear that signature verification returns a boolean, regardless of whether the signature is invalid due to the ctilde check, the coefficients of the reponse vector being out of range, or the encoded hint vector being malformed. But if we really think it's useful we could disregard that and use EKEYREJECTED for the ctilde check and EBADMSG for the other cases. I think that would align with what you're suggesting. This is inconsistent with the kernel's symmetric crypto code, but oh well.

- Eric

author maintainer
#11 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

In reply to Eric Biggers
Quoted 5 lines · Eric Biggers

However, unfortunately neither source explains it properly, and they actually provide incorrect information. The comment in the reference code says the the input can be in "-2^{31}Q <= a <= Q*2^31", which isn't quite correct; the upper bound is actually exclusive. In my code, I correctly document the upper bound as being exclusive.

I opened https://github.com/pq-crystals/dilithium/issues/108 against the reference implementation. So hopefully that comment will get fixed.

Quoted 8 lines

FIPS 204 documents the same incorrect interval, but then sort of gets around it by only claiming that the output is less than 2q in absolute value (rather than q) and also by not clarifying whether sign extension is done. They may have thought that sign extension shouldn't be done, as you seem to have thought. Either way, their explanation is misleading. The very-nearly-symmetric version that produces an output less than q in absolute value is the logical version when working with signed values, and it seems to be what the Dilithium authors intended.

I'm collecting the mistakes that I've found in FIPS 204 into a list, which I'll send in to NIST as an errata request at some point...

- Eric

#16 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

In reply to Eric Biggers

It looks like this may be close, but for the record:

The LF has a dedicated project for ML-DSA: https://github.com/pq-code-package/mldsa-native (part of the Post-Quantum Cryptography Alliance). It's derived from the reference implementation and adds automatically verified memory-safety + type-safety (= bounds-tracking) and a uniform backend interface for assembly optimizations; see the README for more details. It's licensed under Apache-2.0 OR MIT OR ISC.

If you are sure that the kernel will never need sign/keygen support, or support for optimized assembly, the current ad-hoc patch may be fine. Otherwise, the challenges are likely just delayed, e.g. how to safely re-use parts of the current code for the timing-sensitive signing, or in contexts with other bounds assumptions, or how to integrate assembly optimizations. It may not seem so, but this is difficult to get right and where maintainability gets challenging.

Verification here is a vehicle for maintainability: If you change any arithmetic code -- say you decide to do less modular reduction for performance -- you currently need very careful review that the bounds still check out in the worst case. In mldsa-native, this is re-checked automatically.

mldsa-native is production-ready and in the process of being integrated into Amazon's AWS-LC crypto library; the sibling-project mlkem-native https://github.com/pq-code-package/mlkem-native already has been. mldsa-native is not yet a drop-in for the kernel, however. At the least, memory usage needs to be brought down and allocation be made flexible. We're working on it, and if the kernel community was interested in it, it'd give impetus to accelerate the work.

This is just so you're aware. If mldsa-native is of interest, let us know -- it would be great to collaborate across the LF instead of duplicating efforts.

Thanks,
Hanno & Matthias (maintainers of mldsa-native)

author maintainer
#17 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

Quoted 6 lines · Hanno

It looks like this may be close, but for the record:

The LF has a dedicated project for ML-DSA: https://github.com/pq-code-package/mldsa-native (part of the Post-Quantum Cryptography Alliance). It's derived from the reference implementation and adds automatically verified memory-safety + type-safety (= bounds-tracking) and a uniform backend interface for assembly optimizations; see the README for more details. It's licensed under Apache-2.0 OR MIT OR ISC.

If you are sure that the kernel will never need sign/keygen support, or support for optimized assembly, the current ad-hoc patch may be fine. Otherwise, the challenges are likely just delayed, e.g. how to safely re-use parts of the current code for the timing-sensitive signing, or in contexts with other bounds assumptions, or how to integrate assembly optimizations. It may not seem so, but this is difficult to get right and where maintainability gets challenging.

Quoted 8 lines

Verification here is a vehicle for maintainability: If you change any arithmetic code -- say you decide to do less modular reduction for performance -- you currently need very careful review that the bounds still check out in the worst case. In mldsa-native, this is re-checked automatically.

mldsa-native is production-ready and in the process of being integrated into Amazon's AWS-LC crypto library; the sibling-project mlkem-native https://github.com/pq-code-package/mlkem-native already has been. mldsa-native is not yet a drop-in for the kernel, however. At the least, memory usage needs to be brought down and allocation be made flexible. We're working on it, and if the kernel community was interested in it, it'd give impetus to accelerate the work.

This is just so you're aware. If mldsa-native is of interest, let us know -- it would be great to collaborate across the LF instead of duplicating efforts.

Thanks,
Hanno & Matthias (maintainers of mldsa-native)

(Side note: this patch series is up to v2. See
https://lore.kernel.org/linux-crypto/[email protected]/
for the latest version as of this writing)

For context, this is at least the third different userspace project that's been suggested to borrow ML-DSA code from, and not the first that is a fork of the Dilithium reference code.

ML-DSA is also just one of dozens of algorithms the kernel supports. In none of them has the kernel community been successful with integrating a project wholesale, vs. just taking individual files.

So while mldsa-native looks like a great project, for the task in question (adding basic ML-DSA verification support to the kernel) I'm not sure it brings much new to the table. Of course, there's also no corresponding kernel patch that proposes integrating mldsa-native into the kernel, so it's a bit hypothetical at this point too. The leancrypto proposal at least had a patch, so it was more concrete.

I think you may be underestimating how much the requirements of the kernel differ from userspace. Consider the following:

- Kernel stack is 8 KB to 16 KB. mldsa-native's signature verification code starts out by allocating ~100KB of memory on the stack. If that code was built into the kernel, it would immediately write out of bounds. Oops. So much for the formal verification of memory bounds.

- Vector registers (e.g. AVX) can be used in the kernel only in some contexts, and only when they are explicitly saved and restored. So we have to do our own integration of any code that uses them anyway. There is also more overhead to each vector-optimized function than there is in userspace, so very fine-grained optimization (e.g. as is used in the Dilithium reference code) doesn't work too well.

- The vector intrinsics like <immintrin.h> can't be used in the kernel, as they depend on userspace headers. Thus, vector instructions can generally be used only in assembly code. I believe this problem is solvable with a combination of changes to GCC, clang, and the kernel, and I'd like to see that happen. But someone would need to do it.

Note that the kernel already has optimized Keccak code. That already covers the most performance-critical part of ML-DSA. Besides that part, I think we're fine with a portable implementation of ML-DSA. Consider that that's always been what we've done for RSA, for example. Signature verification performance just isn't that important in the kernel.

But even if we decide the kernel needs optimized ML-DSA ring operations later, I don't think we get any free lunch. Userspace libraries aren't directly usable in the kernel anyway, for the reasons I outlined above. And we can always borrow things piecemeal, as we've always done.

Microbenchmark throughput also isn't everything: memory usage and code size is very important too, often even more important. I haven't seen a proposal that even comes close to my mldsa_verify() on those metrics.

We can't be 100% sure that the kernel will never need ML-DSA signing support. But it's not needed now, it's something that architecturally doesn't make much sense, and we'd prefer to avoid adding it. We shouldn't overengineer things around requirements that don't exist.

Anyway, we also aren't stuck with one implementation forever. If someone can actually do ML-DSA better, whether that's for verification-only right now or for everything during a hypothetical future addition of signing support, we can replace my lib/crypto/mldsa.c with something else. *Usually* kernel code evolves incrementally, but not always. Especially with the crypto algorithms, there are examples where we've entirely swapped out an implementation.

- Eric

#18 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

Hi Hanno,

Just to add to what Eric said...

Quoted 2 lines · Eric Biggers

I think you may be underestimating how much the requirements of the kernel differ from userspace. Consider the following:

I've added a bit of formally verified code to the kernel, and also ported some userspace crypto. In these cases, I wound up working with the authors of the code to make it more suitable to the requirements of kernel space -- even down to the formatting level. For example, the HACL* project needed some changes to KReMLin to make the variety of code fit into what the kernel expected. Andy Polyakov's code needed some internal functions exposed so that the kernel could do cpu capability based dispatch. And so on and so forth. There's always _something_.

I'd love to have a formally verified ML-DSA implementation (if we're to have ML-DSA in the kernel anyhow, but it looks like that's happening). But I almost guarantee that it's going to be some work to do. If those are efforts you'd consider undertaking seriously, I'd be happy to assist or help guide the considerations.

There's also another approach, which would be to formally verify Eric's code, perhaps even using the same techniques as your own project, via CBMC and such. In this case, the name of the game is usually to port the kernel code to userspace. That generally winds up being a matter of shimming out some headers and adding a few typedefs. There's a decent amount of kernel test code or kernel tool code that does this, and lots of shim headers already in the kernel that can be borrowed for this. But usually, at least for crypto code, you can figure it out pretty quickly by just trying to compile it and plugging the missing headers and types as they come up.

The model checking might be more work with this latter approach, since it's not already done like it is for the former, but the porting work is probably much less arduous.

Anyway, the bigger picture is that I'm very enthusiastic about getting formally verified crypto in the kernel, so these types of efforts are really very appreciated and welcomed. But it just takes a bit more work than usual.

Jason

#19 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

Eric, Jason,

Thanks for the fast replies!

Quoted 2 lines · On 30/11/2025, 00:22, "Eric Biggers" <[email protected]…

I think you may be underestimating how much the requirements of the kernel differ from userspace.

There is no doubt this is the case -- I am not a kernel guy -- so the points you raise are very valuable.

Equally, you may be underestimating how much work it is to go from a static verification-only code to something that the community will be able to work with and extend in the future.

There's clearly opportunity to learn from each other here. If this patch forms the 'mldsa-v1' for the kernel, it would be great to work together to see if 'mldsa-v2' could come from mldsa-native.

Quoted 2 lines

In none of them has the kernel community been successful with integrating a project wholesale, vs. just taking individual files.

I take that as a challenge. With AWS-LC we were also told that mlkem-native would never be able to integrate wholesale -- and now it is. It's a matter of goodwill and collaboration, and not a binary yes/no -- if selected but minimal patches are needed, that's still better than an entirely separate implementation, in my mind.

Quoted 1 line

- Kernel stack is 8 KB to 16 KB. ...

Yes, as mentioned we started working on a) bringing the memory usage down, and b) making the use of heap/stack configurable.

Quoted 6 lines

- Vector registers (e.g. AVX) can be used in the kernel only in some contexts, and only when they are explicitly saved and restored. So we have to do our own integration of any code that uses them anyway. There is also more overhead to each vector-optimized function than there is in userspace, so very fine-grained optimization (e.g. as is used in the Dilithium reference code) doesn't work too well.

That's very useful, can you say more? Would one want some sort of configurable preamble/postamble in the top-level API which takes care of the necessary save/restore logic?

What is the per-function overhead?

Quoted 6 lines

- The vector intrinsics like <immintrin.h> can't be used in the kernel, as they depend on userspace headers. Thus, vector instructions can generally be used only in assembly code. I believe this problem is solvable with a combination of changes to GCC, clang, and the kernel, and I'd like to see that happen. But someone would need to do it.

The use of intrinsics is on the way out; the kernel isn't the only project who can't use them.

Using assembly is also more suitable for our optimization and verification approach in mlkem-native and mldsa-native: We superoptimize some assembly using SLOTHY (https://github.com/slothy-optimizer/slothy/)
and then do 'post-hoc' verification of the final object code using the HOL-Light/s2n-bignum (https://github.com/awslabs/s2n-bignum/)
infrastructure. In mlkem-native, all AArch64 assembly is developed and verified in this way; in mldsa-native, we just completed the verification of the AVX2 assembly for the base multiplication and the NTT.

Quoted 2 lines

Note that the kernel already has optimized Keccak code. That already covers the most performance-critical part of ML-DSA.

No, this would need _batched_ Keccak. An ML-DSA implementation using only 1x-Keccak will never have competitive performance. See
https://github.com/pq-code-package/mldsa-native/pull/754 for the performance loss from using unbatched Keccak only, on a variety of platforms; it's >2x for some.

In turn, if you want to integrate batched Keccak -- but perhaps only on some platforms? -- you need to rewrite your entire code to make use of it. That's not a simple change, and part of what I mean when I say that the challenges are just deferred. Note that the official reference and AVX2 implementations duck this problem by duplicating the code and adjusting it, rather than looking for a common structure that could host both 'plain' and batched Keccak. I assume the amount of code duplication this brings would be unacceptable.

Quoted 9 lines · On 30/11/2025, 01:06, "Jason A. Donenfeld" <[email protected]…

I've added a bit of formally verified code to the kernel, and also ported some userspace crypto. In these cases, I wound up working with the authors of the code to make it more suitable to the requirements of kernel space -- even down to the formatting level. For example, the HACL* project needed some changes to KReMLin to make the variety of code fit into what the kernel expected. Andy Polyakov's code needed some internal functions exposed so that the kernel could do cpu capability based dispatch. And so on and so forth. There's always _something_.

100%. This is where we need support from someone in the kernel to even know what needs doing. The caveat regarding SIMD usage Eric mentioned is a good example. The CPU capability based dispatch, for example, was something we flushed out when we did the AWS-LC integration: dispatch is now configurable.

Quoted 2 lines

If those are efforts you'd consider undertaking seriously, I'd be happy to assist or help guide the considerations.

We are taking mlkem/mldsa-native seriously and want to make them as usable as possible. So, regardless of whether they'd ultimately end up in the kernel, any support of the form "If you wanted to integrate this in environment XXX [like the kernel], then you would need ..." is very useful and we'd be grateful for it.

I don't expect this to be something we can rush through in a couple of days, but something that's achieved with steady progress and collaboration.

Quoted 4 lines

Anyway, the bigger picture is that I'm very enthusiastic about getting formally verified crypto in the kernel, so these types of efforts are really very appreciated and welcomed. But it just takes a bit more work than usual.

Thank you, Jason, this is great to hear, and if you had time to work with us, we'd really appreciate it.

Thanks,
Hanno & Matthias

author maintainer
#20 lore raw

Re: [PATCH 1/4] lib/crypto: Add ML-DSA verification support

Quoted 7 lines · Hanno
Quoted 6 lines

- Vector registers (e.g. AVX) can be used in the kernel only in some contexts, and only when they are explicitly saved and restored. So we have to do our own integration of any code that uses them anyway. There is also more overhead to each vector-optimized function than there is in userspace, so very fine-grained optimization (e.g. as is used in the Dilithium reference code) doesn't work too well.

Quoted 5 lines

That's very useful, can you say more? Would one want some sort of configurable preamble/postamble in the top-level API which takes care of the necessary save/restore logic?

What is the per-function overhead?

It varies by architecture, but usually it looks something like:

    if (irq_fpu_usable()) {
            kernel_fpu_begin();
            avx_function();
            kernel_fpu_end();
    } else {
            generic_function();
    }

The overhead varies significantly by CPU, kernel config options, and whether it's the first use since the current task last entered the kernel. But it can be up to a few hundred cycles.

Quoted 9 lines
Quoted 2 lines

Note that the kernel already has optimized Keccak code. That already covers the most performance-critical part of ML-DSA.

No, this would need _batched_ Keccak. An ML-DSA implementation using only 1x-Keccak will never have competitive performance. See
https://github.com/pq-code-package/mldsa-native/pull/754 for the performance loss from using unbatched Keccak only, on a variety of platforms; it's >2x for some.

Quoted 8 lines

In turn, if you want to integrate batched Keccak -- but perhaps only on some platforms? -- you need to rewrite your entire code to make use of it. That's not a simple change, and part of what I mean when I say that the challenges are just deferred. Note that the official reference and AVX2 implementations duck this problem by duplicating the code and adjusting it, rather than looking for a common structure that could host both 'plain' and batched Keccak. I assume the amount of code duplication this brings would be unacceptable.

At least in my code, only the matrix expansion code would need to change to take advantage of interleaved Keccak. The fact that other implementations apparently are having trouble with this actually suggests to me that perhaps they're not good implementations to use.

Anyway, no one has said they want this particular optimization in the kernel anyway. And hopefully the future is native Keccak support anyway; s390 already has it, and (at least) RISC-V is working on it.

- Eric