Skip to main content

ssh_protocol/kex/
mlkem768x25519.rs

1//! `mlkem768x25519-sha256` hybrid key exchange ([RFC 10042]).
2//!
3//! [RFC 10042]: https://www.rfc-editor.org/rfc/rfc10042.html
4
5use super::Kex;
6use core::fmt;
7use encoding::{Decode, Encode};
8use ml_kem::{
9    Decapsulate, Encapsulate, Generate, KeyExport,
10    ml_kem_768::{DecapsulationKey, EncapsulationKey},
11};
12use rand_core::CryptoRng;
13use sha2::{Digest, Sha256};
14use x25519_dalek::{EphemeralSecret, PublicKey};
15use zeroize::{Zeroize, Zeroizing};
16
17/// Client ephemeral public keys (`C_INIT`), encoded together as one SSH string.
18#[derive(Clone, Debug, Decode, Encode, Eq, PartialEq)]
19#[ssh(crate = encoding, length_prefixed)]
20pub struct Init {
21    mlkem: [u8; 1184],
22    x25519: [u8; 32],
23}
24
25/// Server ciphertext and ephemeral public key (`S_REPLY`), encoded together as one SSH string.
26#[derive(Clone, Debug, Decode, Encode, Eq, PartialEq)]
27#[ssh(crate = encoding, length_prefixed)]
28pub struct Reply {
29    mlkem: [u8; 1088],
30    x25519: [u8; 32],
31}
32
33/// ML-KEM-768 with X25519 and SHA-256. An instance holds the client's one-use secrets.
34pub struct MlKem768X25519 {
35    mlkem: DecapsulationKey,
36    x25519: EphemeralSecret,
37}
38
39impl Kex for MlKem768X25519 {
40    const NAME: &'static str = "mlkem768x25519-sha256";
41
42    type Hash = Sha256;
43    type Init = Init;
44    type Reply = Reply;
45    type Secret = Secret;
46    type Error = Error;
47
48    fn start<R: CryptoRng + ?Sized>(rng: &mut R) -> Result<(Self, Init), Error> {
49        let mlkem = DecapsulationKey::generate_from_rng(rng);
50        let x25519 = EphemeralSecret::random_from_rng(rng);
51        let init = Init {
52            mlkem: mlkem.encapsulation_key().to_bytes().into(),
53            x25519: PublicKey::from(&x25519).to_bytes(),
54        };
55        Ok((Self { mlkem, x25519 }, init))
56    }
57
58    fn respond<R: CryptoRng + ?Sized>(rng: &mut R, init: &Init) -> Result<(Reply, Secret), Error> {
59        let ek = EncapsulationKey::new((&init.mlkem).into())
60            .map_err(|_| Error::InvalidEncapsulationKey)?;
61        let (ciphertext, mlkem) = ek.encapsulate_with_rng(rng);
62        let mlkem = Zeroizing::new(mlkem);
63        let secret = EphemeralSecret::random_from_rng(rng);
64        let public = PublicKey::from(&secret);
65        let x25519 = agree(secret, init.x25519)?;
66        let reply = Reply {
67            mlkem: ciphertext.into(),
68            x25519: public.to_bytes(),
69        };
70        Ok((reply, Secret::combine(&mlkem, &x25519)))
71    }
72
73    fn finish(self, reply: &Reply) -> Result<Secret, Error> {
74        let x25519 = agree(self.x25519, reply.x25519)?;
75        let mlkem = Zeroizing::new(self.mlkem.decapsulate((&reply.mlkem).into()));
76        Ok(Secret::combine(&mlkem, &x25519))
77    }
78}
79
80impl fmt::Debug for MlKem768X25519 {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        f.debug_struct("MlKem768X25519").finish_non_exhaustive()
83    }
84}
85
86fn agree(secret: EphemeralSecret, peer: [u8; 32]) -> Result<x25519_dalek::SharedSecret, Error> {
87    let shared = secret.diffie_hellman(&PublicKey::from(peer));
88    if shared.was_contributory() {
89        Ok(shared)
90    } else {
91        Err(Error::NonContributory)
92    }
93}
94
95/// The combined shared secret `K`. [`Encode`] writes it as a 32-byte SSH string.
96#[derive(Encode)]
97#[ssh(crate = encoding, length_prefixed)]
98pub struct Secret([u8; 32]);
99
100impl Secret {
101    fn combine(mlkem: &ml_kem::SharedKey, x25519: &x25519_dalek::SharedSecret) -> Self {
102        Self(
103            Sha256::new()
104                .chain_update(mlkem)
105                .chain_update(x25519.as_bytes())
106                .finalize()
107                .into(),
108        )
109    }
110}
111
112impl AsRef<[u8]> for Secret {
113    fn as_ref(&self) -> &[u8] {
114        &self.0
115    }
116}
117
118impl fmt::Debug for Secret {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        f.debug_struct("Secret").finish_non_exhaustive()
121    }
122}
123
124impl Drop for Secret {
125    fn drop(&mut self) {
126        self.0.zeroize();
127    }
128}
129
130/// Key agreement errors. Abort the SSH key exchange on either error.
131#[derive(Clone, Copy, Debug, Eq, PartialEq)]
132#[non_exhaustive]
133pub enum Error {
134    /// The client's ML-KEM encapsulation key failed the FIPS 203 public-key check.
135    InvalidEncapsulationKey,
136
137    /// X25519 produced the all-zero shared secret.
138    NonContributory,
139}
140
141impl fmt::Display for Error {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        f.write_str(match self {
144            Self::InvalidEncapsulationKey => "invalid ML-KEM-768 encapsulation key",
145            Self::NonContributory => "non-contributory X25519 key exchange",
146        })
147    }
148}
149
150impl core::error::Error for Error {}