Skip to main content

ssh_protocol/
kex.rs

1//! SSH transport key exchange methods.
2
3pub use encoding::digest;
4pub use rand_core;
5
6#[cfg(feature = "mlkem768x25519-sha256")]
7pub mod mlkem768x25519;
8
9#[cfg(feature = "mlkem768x25519-sha256")]
10pub use mlkem768x25519::MlKem768X25519;
11
12use core::fmt;
13use digest::{Digest, Output};
14use encoding::{Decode, DigestWriter, Encode};
15use rand_core::CryptoRng;
16
17/// An SSH key exchange with one client initiation and one server reply.
18///
19/// The method-specific fields must encode exactly as received. Implementations that accept
20/// multiple representations of a public key must retain the original encoding for the hash.
21///
22/// Implement this trait on the client's ephemeral state. The server calls
23/// [`respond`][Self::respond] to generate its reply and shared secret in one step.
24/// The transport handles method negotiation, packet framing, and host authentication.
25/// DH group exchange (RFC 4419) requires additional negotiation and transcript fields.
26pub trait Kex: Sized {
27    /// SSH method name to advertise in `SSH_MSG_KEXINIT`.
28    const NAME: &'static str;
29
30    /// Hash used for the exchange hash and SSH key derivation.
31    type Hash: Digest;
32
33    /// Client's method-specific field, including its SSH wire framing.
34    type Init: Decode<Error = encoding::Error> + Encode;
35
36    /// Server's method-specific field, including its SSH wire framing.
37    type Reply: Decode<Error = encoding::Error> + Encode;
38
39    /// Shared secret `K`. `AsRef` borrows the raw bytes. `Encode` writes the method's
40    /// complete SSH representation for hashing and key derivation (e.g. `string` or `mpint`).
41    type Secret: AsRef<[u8]> + Encode;
42
43    /// Error from key generation or peer key validation.
44    type Error: core::error::Error;
45
46    /// Generate a fresh client state and the public field to send.
47    ///
48    /// # Errors
49    /// Returns a method-specific error if key generation fails.
50    fn start<R: CryptoRng + ?Sized>(rng: &mut R) -> Result<(Self, Self::Init), Self::Error>;
51
52    /// Process the client's public field and generate the server's reply and shared secret.
53    ///
54    /// # Errors
55    /// Returns a method-specific error if key generation or peer key validation fails.
56    fn respond<R: CryptoRng + ?Sized>(
57        rng: &mut R,
58        init: &Self::Init,
59    ) -> Result<(Self::Reply, Self::Secret), Self::Error>;
60
61    /// Consume the client state and derive the shared secret from the server's public field.
62    /// The client authenticates the server by checking its host key and signature over `H`.
63    ///
64    /// # Errors
65    /// Returns a method-specific error if key agreement fails.
66    fn finish(self, reply: &Self::Reply) -> Result<Self::Secret, Self::Error>;
67}
68
69/// SSH exchange transcript. Only the digest state is retained across the network round trip.
70pub struct Transcript<K: Kex>(K::Hash);
71
72impl<K: Kex> Transcript<K> {
73    /// Hash the identification strings (without CR/LF) and the original KEXINIT payloads
74    /// (including the message number). Their packet buffers may then be reused.
75    ///
76    /// # Errors
77    /// Returns an error if a field exceeds the SSH string length limit.
78    pub fn new(
79        client_id: &[u8],
80        server_id: &[u8],
81        client_kexinit: &[u8],
82        server_kexinit: &[u8],
83    ) -> encoding::Result<Self> {
84        let mut hash = K::Hash::new();
85        let mut writer = DigestWriter(&mut hash);
86
87        for field in [client_id, server_id, client_kexinit, server_kexinit] {
88            field.encode(&mut writer)?;
89        }
90
91        Ok(Self(hash))
92    }
93
94    /// Hash the original host-key or certificate blob (without its outer string length),
95    /// the two method-specific public fields, and the shared secret. Returns the hash `H`
96    /// that the server signs.
97    ///
98    /// # Errors
99    /// Returns an error if an SSH field cannot be encoded.
100    pub fn finish(
101        mut self,
102        server_host_key: &[u8],
103        init: &K::Init,
104        reply: &K::Reply,
105        secret: &K::Secret,
106    ) -> encoding::Result<Output<K::Hash>> {
107        let mut writer = DigestWriter(&mut self.0);
108        server_host_key.encode(&mut writer)?;
109        init.encode(&mut writer)?;
110        reply.encode(&mut writer)?;
111        secret.encode(&mut writer)?;
112        Ok(self.0.finalize())
113    }
114}
115
116impl<K: Kex> fmt::Debug for Transcript<K> {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.debug_struct("Transcript")
119            .field("method", &K::NAME)
120            .finish_non_exhaustive()
121    }
122}