ssh-protocol 0.4.0

Pure Rust implementation of the SSH protocol as described in RFC4251/RFC4253 as well as OpenSSH-specific extensions (WIP)
Documentation
//! `mlkem768x25519-sha256` hybrid key exchange ([RFC 10042]).
//!
//! [RFC 10042]: https://www.rfc-editor.org/rfc/rfc10042.html

use super::Kex;
use core::fmt;
use encoding::{Decode, Encode};
use ml_kem::{
    Decapsulate, Encapsulate, Generate, KeyExport,
    ml_kem_768::{DecapsulationKey, EncapsulationKey},
};
use rand_core::CryptoRng;
use sha2::{Digest, Sha256};
use x25519_dalek::{EphemeralSecret, PublicKey};
use zeroize::{Zeroize, Zeroizing};

/// Client ephemeral public keys (`C_INIT`), encoded together as one SSH string.
#[derive(Clone, Debug, Decode, Encode, Eq, PartialEq)]
#[ssh(crate = encoding, length_prefixed)]
pub struct Init {
    mlkem: [u8; 1184],
    x25519: [u8; 32],
}

/// Server ciphertext and ephemeral public key (`S_REPLY`), encoded together as one SSH string.
#[derive(Clone, Debug, Decode, Encode, Eq, PartialEq)]
#[ssh(crate = encoding, length_prefixed)]
pub struct Reply {
    mlkem: [u8; 1088],
    x25519: [u8; 32],
}

/// ML-KEM-768 with X25519 and SHA-256. An instance holds the client's one-use secrets.
pub struct MlKem768X25519 {
    mlkem: DecapsulationKey,
    x25519: EphemeralSecret,
}

impl Kex for MlKem768X25519 {
    const NAME: &'static str = "mlkem768x25519-sha256";

    type Hash = Sha256;
    type Init = Init;
    type Reply = Reply;
    type Secret = Secret;
    type Error = Error;

    fn start<R: CryptoRng + ?Sized>(rng: &mut R) -> Result<(Self, Init), Error> {
        let mlkem = DecapsulationKey::generate_from_rng(rng);
        let x25519 = EphemeralSecret::random_from_rng(rng);
        let init = Init {
            mlkem: mlkem.encapsulation_key().to_bytes().into(),
            x25519: PublicKey::from(&x25519).to_bytes(),
        };
        Ok((Self { mlkem, x25519 }, init))
    }

    fn respond<R: CryptoRng + ?Sized>(rng: &mut R, init: &Init) -> Result<(Reply, Secret), Error> {
        let ek = EncapsulationKey::new((&init.mlkem).into())
            .map_err(|_| Error::InvalidEncapsulationKey)?;
        let (ciphertext, mlkem) = ek.encapsulate_with_rng(rng);
        let mlkem = Zeroizing::new(mlkem);
        let secret = EphemeralSecret::random_from_rng(rng);
        let public = PublicKey::from(&secret);
        let x25519 = agree(secret, init.x25519)?;
        let reply = Reply {
            mlkem: ciphertext.into(),
            x25519: public.to_bytes(),
        };
        Ok((reply, Secret::combine(&mlkem, &x25519)))
    }

    fn finish(self, reply: &Reply) -> Result<Secret, Error> {
        let x25519 = agree(self.x25519, reply.x25519)?;
        let mlkem = Zeroizing::new(self.mlkem.decapsulate((&reply.mlkem).into()));
        Ok(Secret::combine(&mlkem, &x25519))
    }
}

impl fmt::Debug for MlKem768X25519 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MlKem768X25519").finish_non_exhaustive()
    }
}

fn agree(secret: EphemeralSecret, peer: [u8; 32]) -> Result<x25519_dalek::SharedSecret, Error> {
    let shared = secret.diffie_hellman(&PublicKey::from(peer));
    if shared.was_contributory() {
        Ok(shared)
    } else {
        Err(Error::NonContributory)
    }
}

/// The combined shared secret `K`. [`Encode`] writes it as a 32-byte SSH string.
#[derive(Encode)]
#[ssh(crate = encoding, length_prefixed)]
pub struct Secret([u8; 32]);

impl Secret {
    fn combine(mlkem: &ml_kem::SharedKey, x25519: &x25519_dalek::SharedSecret) -> Self {
        Self(
            Sha256::new()
                .chain_update(mlkem)
                .chain_update(x25519.as_bytes())
                .finalize()
                .into(),
        )
    }
}

impl AsRef<[u8]> for Secret {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl fmt::Debug for Secret {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Secret").finish_non_exhaustive()
    }
}

impl Drop for Secret {
    fn drop(&mut self) {
        self.0.zeroize();
    }
}

/// Key agreement errors. Abort the SSH key exchange on either error.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Error {
    /// The client's ML-KEM encapsulation key failed the FIPS 203 public-key check.
    InvalidEncapsulationKey,

    /// X25519 produced the all-zero shared secret.
    NonContributory,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::InvalidEncapsulationKey => "invalid ML-KEM-768 encapsulation key",
            Self::NonContributory => "non-contributory X25519 key exchange",
        })
    }
}

impl core::error::Error for Error {}