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
//! Exercise the public KEX trait with a downstream method and no built-in algorithms.

use chacha20::{ChaCha20Rng, rand_core::SeedableRng};
use sha2::Sha384;
use ssh_protocol::{
    Encode, Writer, encoding,
    kex::{Kex, Transcript, digest::Digest, rand_core::CryptoRng},
};

struct Magnitude([u8; 1]);

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

impl Encode for Magnitude {
    fn encoded_len(&self) -> encoding::Result<usize> {
        encoding::MpintRef::from_bytes(&self.0)?.encoded_len()
    }

    fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
        encoding::MpintRef::from_bytes(&self.0)?.encode(writer)
    }
}

// Fixed public fields and secret for testing the transcript format only.
struct Fixture;

impl Kex for Fixture {
    const NAME: &'static str = "fixture@example.com";
    type Hash = Sha384;
    type Init = [u8; 5];
    type Reply = [u8; 6];
    type Secret = Magnitude;
    type Error = encoding::Error;

    fn start<R: CryptoRng + ?Sized>(_: &mut R) -> encoding::Result<(Self, Self::Init)> {
        Ok((Self, *b"\0\0\0\x01Q"))
    }

    fn respond<R: CryptoRng + ?Sized>(
        _: &mut R,
        _: &Self::Init,
    ) -> encoding::Result<(Self::Reply, Magnitude)> {
        Ok((*b"\0\0\0\x02RS", Magnitude([0x80])))
    }

    fn finish(self, _: &Self::Reply) -> encoding::Result<Magnitude> {
        Ok(Magnitude([0x80]))
    }
}

#[test]
fn method_selects_digest_and_secret_encoding() -> encoding::Result<()> {
    let mut rng = ChaCha20Rng::from_seed([0; 32]);
    let (client, init) = Fixture::start(&mut rng)?;
    let (reply, server_k) = Fixture::respond(&mut rng, &init)?;
    let k = client.finish(&reply)?;
    assert_eq!(server_k.as_ref(), &[0x80]);
    let mut encoded_k = [0; 6];
    k.encode(&mut encoded_k.as_mut_slice())?;
    assert_eq!(&encoded_k, b"\0\0\0\x02\0\x80");

    let transcript = Transcript::<Fixture>::new(b"c", b"s", b"\x14a", b"\x14b")?;
    let wire = b"\0\0\0\x01c\0\0\0\x01s\
                 \0\0\0\x02\x14a\0\0\0\x02\x14b\
                 \0\0\0\x01h\0\0\0\x01Q\0\0\0\x02RS\
                 \0\0\0\x02\0\x80";
    assert_eq!(
        transcript.finish(b"h", &init, &reply, &k)?,
        Sha384::digest(wire),
    );
    Ok(())
}