Skip to content

#12520 Add support for mlkem768x25519-sha256 for server-side connections using cryptography. - #12730

Merged
adiroiban merged 25 commits into
trunkfrom
12520-finnrg-conch-ssh-mlkem-take2
Sep 10, 2026
Merged

adiroiban merged 25 commits into
trunkfrom
12520-finnrg-conch-ssh-mlkem-take2

Conversation

@adiroiban

@adiroiban adiroiban commented Jul 22, 2026 •

Copy link
Copy Markdown
Member

Scope and purpose

Fixes #12520

This is based on the initial code from @FinnRG from #12621

99% is the code from Finn. I only converted to cryptography, updated the naming conventions, enabled a few more tests, add strict checks in new tests.

I did some refactoring while validating the implementation against the RFC and coverted variable names to Twisted standard

I have updated the code to use the Python cryptography library, rather than a separate library.

This will need cryptography 48.0 or newer and Twisted should just don't advertise support for MLKEM on older cryptography

I have also enabled the end to end KEX tests with OpenSSH on Ubuntu 26.04

Contributor Checklist:

This process applies to all pull requests - no matter how small.
Have a look at our developer documentation before submitting your Pull Request.

Below is a non-exhaustive list (as a reminder):

  • The title of the PR should describe the changes and starts with the associated issue number, like “#9782 Remove twisted.news. #1234 Brief description”.
  • A release notes news fragment file was create in src/twisted/newsfragments/ (see: Release notes fragments docs.)
  • The automated tests were updated.
  • Once all checks are green, request a review by leaving a comment that contains exactly the string please review.
    Our bot will trigger the review process, by applying the pending review label
    and requesting a review from the Twisted dev team.

@codspeed

codspeed Bot commented Jul 22, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 36 untouched benchmarks


Comparing 12520-finnrg-conch-ssh-mlkem-take2 (47dda61) with trunk (ac919a6)

Open in CodSpeed

@adiroiban
adiroiban marked this pull request as ready for review July 22, 2026 15:19
@chevah-robot
chevah-robot requested a review from a team July 22, 2026 15:20

@gudnimg gudnimg left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me. Just minor nitpicks about type annotation :)

Comment thread src/twisted/conch/test/test_conch.py Outdated
Comment on lines +635 to +645
def test_CURVE25519_SHA256(self):
"""
The curve25519-sha256 key exchange algorithm is compatible with OpenSSH.
"""
return self.assertExecuteWithKexAlgorithm("curve25519-sha256")

def test_MLKEM768X25519_SHA256(self):
"""
The mlkem768x25519-sha256 key exchange algorithm is compatible with OpenSSH.
"""
return self.assertExecuteWithKexAlgorithm("mlkem768x25519-sha256")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider adding type annotation for new code. assertExecuteWithKexAlgorithm returns Deferred[Any] as far as I can tell.

Suggested change
def test_CURVE25519_SHA256(self):
"""
The curve25519-sha256 key exchange algorithm is compatible with OpenSSH.
"""
return self.assertExecuteWithKexAlgorithm("curve25519-sha256")
def test_MLKEM768X25519_SHA256(self):
"""
The mlkem768x25519-sha256 key exchange algorithm is compatible with OpenSSH.
"""
return self.assertExecuteWithKexAlgorithm("mlkem768x25519-sha256")
def test_CURVE25519_SHA256(self) -> Deferred[Any]:
"""
The curve25519-sha256 key exchange algorithm is compatible with OpenSSH.
"""
return self.assertExecuteWithKexAlgorithm("curve25519-sha256")
def test_MLKEM768X25519_SHA256(self) -> Deferred[Any]:
"""
The mlkem768x25519-sha256 key exchange algorithm is compatible with OpenSSH.
"""
return self.assertExecuteWithKexAlgorithm("mlkem768x25519-sha256")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very much second this. If we're not going to have any type annotations we should at least have a brief review of why it's too much work.

"""

# These variables don't comply with Twisted naming convention.
# The names are kept to match the RFC.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe a dumb comment, but would it be useful to have a specific number for this RFC in the comment? Just as a source of reference if anyone needs to look it up.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a RFC link somewhere else in the docs.
I didn't want to add a specific RFC reference here...since the current version is still draft... and I was trying to avoid having this reference invalid in the future.

The type-annotation comments are valid... unless mypy complains about it, I most probably will forget to add them again in the future.

I don't use type annotation for Python on my day to day job, but I agree that type annotation are helpful to read the Twisted code.

"""

def checkDisconnected(self, kind=None):
def checkDisconnected(self, kind=None, description=None):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be nice to add type annotation here. But not a blocker imo.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same - is this hard to type check?

@adiroiban

Copy link
Copy Markdown
Member Author

Thanks for the review.

I hope @FinnRG will have some time to take a look at the changes.

I would like to get this merge, then implement client-side support and then do a release

@glyph glyph left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are some cleanups here, but the only blockers are:

  1. except Exception
  2. type annotations themselves aren't required, but we should at least have some demonstrative error output to show that it's actually difficult to try.

I am going with a "request changes" because we seem to have had a few issues with accidental auto-merges going through after a "make some changes and land" approve goes through? (I don't have any examples to hand, forgive me if those weren't actually on Twisted, I get way too much email right now.) But the changes required should be pretty trivial.

Maybe a feature to add to the bot, to allow it to do an approve after a self-review for PRs in that state?

Comment thread src/twisted/conch/ssh/_kex.py Outdated
import cryptography.hazmat.primitives.hpke # noqa: F401
except ImportError:
# Most probably we have cryptography older than 48.0
is_ml_kem_supported = False

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
is_ml_kem_supported = False
cryptographyHasMLKEM = False

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know it's a private namespace, but let's stick with coding-standard compliant names.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

np. it's ok. I don't use this convention for my other project, so I kind of forget to use the Twisted coding convention.

Comment thread src/twisted/conch/ssh/_kex.py Resolved
from cryptography.hazmat.primitives.asymmetric.mlkem import MLKEM768PrivateKey


def skipWithoutMLKEM(f):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

docstirng & type annotation please? I don't want to implicitly lose type coverage for every test this decorates

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to add anotation... not sure if this is the right way... I went a bit down a small rabbit hole :P

"""

def checkDisconnected(self, kind=None):
def checkDisconnected(self, kind=None, description=None):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same - is this hard to type check?

Comment thread src/twisted/conch/ssh/factory.py Outdated
kexAlgorithm
for kexAlgorithm in t.supportedKeyExchanges
if _kex.isFixedGroup(kexAlgorithm) or _kex.isEllipticCurve(kexAlgorithm)
if not _kex.isNonFixedGroup(kexAlgorithm)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Glad to have contributors qualified to understand if this is valid or not because I do not understand the math :)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:) I tried to rename it. thanks for the feedback.

Comment on lines +1591 to +1598
try:
peerKey = x25519.X25519PublicKey.from_public_bytes(c_pk1)
traditionalExchange = ourKey.exchange(peerKey)
except Exception:
self.sendDisconnect(
DISCONNECT_KEY_EXCHANGE_FAILED, "Invalid peer X25519 public key"
)
return

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yikes! Never catch Exception and then return without any kind of report. Please catch a specific exception type here, or use failuresHandled if this is a place a traceback should be reported. (I think that this is actually just a specific exception type issue, unless I'm misunderstanding; I don't think exchange is potentially arbitrary application code)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will catch the specific exception and guard only the required code.
This was lazy coding :)

I don't think that we need to log this.
The reporting is done via the SSH process.


Here the peer sends us junk/invalid data.
The remote SSH peer might be just send us invalid data hoping for a security error.

Comment on lines +1601 to +1609
try:
# encapsulate returns (ciphertext, shared_secret)
peerMLKEM = mlkem.MLKEM768PublicKey.from_public_bytes(c_pk2)
primitiveSharedSecret, ciperText = peerMLKEM.encapsulate()
except Exception:
self.sendDisconnect(
DISCONNECT_KEY_EXCHANGE_FAILED, "Invalid peer ML-KEM public key"
)
return

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Once again, please catch specific exceptions here.


isClient = True

# FIXME https://github.com/twisted/twisted/issues/12624

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for filing this as a separate issue.

Comment thread src/twisted/conch/test/test_conch.py Outdated
Comment on lines +635 to +645
def test_CURVE25519_SHA256(self):
"""
The curve25519-sha256 key exchange algorithm is compatible with OpenSSH.
"""
return self.assertExecuteWithKexAlgorithm("curve25519-sha256")

def test_MLKEM768X25519_SHA256(self):
"""
The mlkem768x25519-sha256 key exchange algorithm is compatible with OpenSSH.
"""
return self.assertExecuteWithKexAlgorithm("mlkem768x25519-sha256")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very much second this. If we're not going to have any type annotations we should at least have a brief review of why it's too much work.

@adiroiban

adiroiban commented Sep 9, 2026 •

Copy link
Copy Markdown
Member Author

Thanks for the great review.

I hope that I have addressed all the comments.

This should be ready for another review.


Some tests are failding due to some Ubuntu package mirrors

Fetched 9436 kB in 1s (8692 kB/s)
Reading package lists...
E: Failed to fetch https://dl.google.com/linux/chrome-stable/deb/dists/stable/main/binary-amd64/Packages.gz  Hash Sum mismatch

@adiroiban
adiroiban requested a review from a team September 9, 2026 18:05
@adiroiban
adiroiban requested a review from glyph September 9, 2026 18:05

@glyph glyph left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we can address the coverage gap I think it's ready to go.

Comment thread src/twisted/conch/test/test_conch.py Outdated
kexAlgorithms = []
openSSHPath = which("ssh")
if not openSSHPath:
raise SkipTest("ssh client not found")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

coverage gap: this test can be done at import time and use the @skipIf decorator to avoid having this branch actually in the code.

Comment thread src/twisted/conch/test/test_conch.py Outdated
except BaseException:

kexAlgorithms = output.decode("utf-8").split()
except Exception:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it looks like this just … never fails? can we just remove the whole try/except, then? no point in having this if it's not actually a supported environment

Comment on lines +19 to +22
skip: str | None = zi.Attribute(
"The reason why this test case should be skipped, or C{None} to not skip."
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

interesting drive-by typing, but glad to have it! :)

"""


ITestCaseVar = TypeVar("ITestCaseVar", bound=Union[ITestCase, type[ITestCase]])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we keep this private just to avoid exposing soon-to-be-obsolete TypeVar objects?

Suggested change
ITestCaseVar = TypeVar("ITestCaseVar", bound=Union[ITestCase, type[ITestCase]])
_ITestCaseVar = TypeVar("_ITestCaseVar", bound=Union[ITestCase, type[ITestCase]])

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review.

Agree.. this, together with the "skip" update in the interface were cause by adding type annotation to the skipif decorator. I will make it private.

I will refactor and send back for review

@adiroiban
adiroiban requested a review from glyph September 10, 2026 07:17
@adiroiban

Copy link
Copy Markdown
Member Author

Thanks for there review. COverage is done without any exceptions. I used skipf

@glyph glyph left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, thanks!

@adiroiban
adiroiban merged commit fa958e5 into trunk Sep 10, 2026
31 checks passed
@adiroiban
adiroiban deleted the 12520-finnrg-conch-ssh-mlkem-take2 branch September 10, 2026 15:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Post quantum key agreement algorithms (mlkem768x25519-sha256)

5 participants