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
//! SSH transport key exchange methods.

pub use encoding::digest;
pub use rand_core;

#[cfg(feature = "mlkem768x25519-sha256")]
pub mod mlkem768x25519;

#[cfg(feature = "mlkem768x25519-sha256")]
pub use mlkem768x25519::MlKem768X25519;

use core::fmt;
use digest::{Digest, Output};
use encoding::{Decode, DigestWriter, Encode};
use rand_core::CryptoRng;

/// An SSH key exchange with one client initiation and one server reply.
///
/// The method-specific fields must encode exactly as received. Implementations that accept
/// multiple representations of a public key must retain the original encoding for the hash.
///
/// Implement this trait on the client's ephemeral state. The server calls
/// [`respond`][Self::respond] to generate its reply and shared secret in one step.
/// The transport handles method negotiation, packet framing, and host authentication.
/// DH group exchange (RFC 4419) requires additional negotiation and transcript fields.
pub trait Kex: Sized {
    /// SSH method name to advertise in `SSH_MSG_KEXINIT`.
    const NAME: &'static str;

    /// Hash used for the exchange hash and SSH key derivation.
    type Hash: Digest;

    /// Client's method-specific field, including its SSH wire framing.
    type Init: Decode<Error = encoding::Error> + Encode;

    /// Server's method-specific field, including its SSH wire framing.
    type Reply: Decode<Error = encoding::Error> + Encode;

    /// Shared secret `K`. `AsRef` borrows the raw bytes. `Encode` writes the method's
    /// complete SSH representation for hashing and key derivation (e.g. `string` or `mpint`).
    type Secret: AsRef<[u8]> + Encode;

    /// Error from key generation or peer key validation.
    type Error: core::error::Error;

    /// Generate a fresh client state and the public field to send.
    ///
    /// # Errors
    /// Returns a method-specific error if key generation fails.
    fn start<R: CryptoRng + ?Sized>(rng: &mut R) -> Result<(Self, Self::Init), Self::Error>;

    /// Process the client's public field and generate the server's reply and shared secret.
    ///
    /// # Errors
    /// Returns a method-specific error if key generation or peer key validation fails.
    fn respond<R: CryptoRng + ?Sized>(
        rng: &mut R,
        init: &Self::Init,
    ) -> Result<(Self::Reply, Self::Secret), Self::Error>;

    /// Consume the client state and derive the shared secret from the server's public field.
    /// The client authenticates the server by checking its host key and signature over `H`.
    ///
    /// # Errors
    /// Returns a method-specific error if key agreement fails.
    fn finish(self, reply: &Self::Reply) -> Result<Self::Secret, Self::Error>;
}

/// SSH exchange transcript. Only the digest state is retained across the network round trip.
pub struct Transcript<K: Kex>(K::Hash);

impl<K: Kex> Transcript<K> {
    /// Hash the identification strings (without CR/LF) and the original KEXINIT payloads
    /// (including the message number). Their packet buffers may then be reused.
    ///
    /// # Errors
    /// Returns an error if a field exceeds the SSH string length limit.
    pub fn new(
        client_id: &[u8],
        server_id: &[u8],
        client_kexinit: &[u8],
        server_kexinit: &[u8],
    ) -> encoding::Result<Self> {
        let mut hash = K::Hash::new();
        let mut writer = DigestWriter(&mut hash);

        for field in [client_id, server_id, client_kexinit, server_kexinit] {
            field.encode(&mut writer)?;
        }

        Ok(Self(hash))
    }

    /// Hash the original host-key or certificate blob (without its outer string length),
    /// the two method-specific public fields, and the shared secret. Returns the hash `H`
    /// that the server signs.
    ///
    /// # Errors
    /// Returns an error if an SSH field cannot be encoded.
    pub fn finish(
        mut self,
        server_host_key: &[u8],
        init: &K::Init,
        reply: &K::Reply,
        secret: &K::Secret,
    ) -> encoding::Result<Output<K::Hash>> {
        let mut writer = DigestWriter(&mut self.0);
        server_host_key.encode(&mut writer)?;
        init.encode(&mut writer)?;
        reply.encode(&mut writer)?;
        secret.encode(&mut writer)?;
        Ok(self.0.finalize())
    }
}

impl<K: Kex> fmt::Debug for Transcript<K> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Transcript")
            .field("method", &K::NAME)
            .finish_non_exhaustive()
    }
}