passalong-ssh 0.3.0

SSH/SFTP storage backend for passalong
Documentation
//! Strict server host key pinning: the server's key must equal the
//! configured one. There is no trust-on-first-use and no `known_hosts`
//! fallback.

use russh::keys::{HashAlg, PublicKey};

use crate::error::SshError;

/// The server public key from `server.ssh.host_key`.
#[derive(Debug, Clone)]
pub struct PinnedHostKey {
    key: PublicKey,
}

impl PinnedHostKey {
    /// Parses an OpenSSH public key line such as `ssh-ed25519 AAAA… comment`.
    /// A leading host field, as printed by `ssh-keyscan`, is tolerated.
    ///
    /// # Errors
    ///
    /// [`SshError::InvalidHostKey`] when no public key can be read.
    pub fn parse(line: &str) -> Result<Self, SshError> {
        let line = line.trim();
        let key = PublicKey::from_openssh(line)
            .or_else(|first| match line.split_once(char::is_whitespace) {
                Some((_, rest)) if !rest.trim().is_empty() => {
                    PublicKey::from_openssh(rest.trim()).map_err(|_| first)
                }
                _ => Err(first),
            })
            .map_err(|err| {
                SshError::InvalidHostKey(format!(
                    "expected an OpenSSH public key such as `ssh-ed25519 AAAA...` ({err})"
                ))
            })?;
        #[cfg(not(feature = "rsa"))]
        if key.algorithm().is_rsa() {
            return Err(SshError::RsaUnsupported {
                what: "server.ssh.host_key".to_owned(),
            });
        }
        Ok(Self { key })
    }

    /// Whether `presented` is this key. Comments are ignored.
    pub fn matches(&self, presented: &PublicKey) -> bool {
        self.key.key_data() == presented.key_data()
    }

    /// The key's SHA-256 fingerprint, as `ssh-keygen -l` prints it.
    pub fn fingerprint(&self) -> String {
        fingerprint(&self.key)
    }
}

/// SHA-256 fingerprint of any public key.
pub(crate) fn fingerprint(key: &PublicKey) -> String {
    key.fingerprint(HashAlg::Sha256).to_string()
}

/// A server host key seen during discovery, not yet trusted.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscoveredKey {
    /// The key as an OpenSSH `type base64` line, ready for
    /// `server.ssh.host_key`.
    pub openssh_line: String,
    /// SHA-256 fingerprint, as `ssh-keygen -l` prints it.
    pub fingerprint: String,
    /// Algorithm name, such as `ssh-ed25519`.
    pub algorithm: String,
}

impl DiscoveredKey {
    pub(crate) fn from_key(key: &PublicKey) -> Result<Self, SshError> {
        let line = key.to_openssh().map_err(|err| {
            SshError::InvalidHostKey(format!("cannot encode the server's key: {err}"))
        })?;
        // Keep `type base64` only; a comment is meaningless for a host key.
        let openssh_line = line
            .split_whitespace()
            .take(2)
            .collect::<Vec<_>>()
            .join(" ");
        Ok(Self {
            openssh_line,
            fingerprint: fingerprint(key),
            algorithm: key.algorithm().as_str().to_owned(),
        })
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::error::SshError;

    // Throwaway public keys generated for these tests; public keys are not secrets.
    pub const KEY_A: &str = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIF2M9DqIpW9GMebpvjNg+bobwAbQKRBqPVMatyvyI4gq passalong-test-a";
    pub const KEY_B: &str = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMKy9BQGg0B6NYvYwyrJzGCOHCXKQBj7E/5jvWJSEDCi passalong-test-b";
    pub const KEY_C: &str = "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBDjE+RqfPVU1q3oRZ0A7kEGVjiycIFrzmrvdTMY9XxA5RwiwmWJ1Ra9XgfC5jOjwYXCvbge0k6d0MwNVN8fH/Rg= passalong-test-c";
    const KEY_A_FINGERPRINT: &str = "SHA256:5Si4lWKPwa0+I2wCQf3eOtcF8jWo30BWybHoXLTxABo";
    pub const KEY_RSA: &str = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCc20+WNqOOyD5NLL1a8IdPRt24TG6uZkCYiCtewTNxHslQawoxE/Z0njaK8Xs2Bqsd0eEGhw2cnnMqXHlNVfWHQ3NhfBe5BXGZSin2dEVZw2nlEfI5Y2uEEVBFTir7EodMI/pJwqPEFZELPC4nm70XjDRDXBvwZDEwrzF1S/5NXZ6Xa4LG/9UOsq05C5bIlqR32/GBBfLWi8PThy1LTg6u4EJE1ovHz4xWQBGCLc/eFnwxePRrMSI1RYQzZ3u6RuCiGXmCsKba7BxaRt5/lEb1PKTPTyi50Y03mcrG4kxA2NXGFH4FAp4T7ICw9JL1z6yXwdWreWjKq9mERVctMLcL passalong-test-rsa";
    #[cfg(feature = "rsa")]
    const KEY_RSA_FINGERPRINT: &str = "SHA256:LY/lOwQzQWODS5oQTLX9+HhSPwqy6sX7OY+mTMZV+2w";

    fn public(line: &str) -> russh::keys::PublicKey {
        russh::keys::PublicKey::from_openssh(line).unwrap()
    }

    #[test]
    fn parses_openssh_key_lines_with_or_without_a_comment() {
        let pinned = PinnedHostKey::parse(KEY_A).unwrap();
        assert_eq!(pinned.fingerprint(), KEY_A_FINGERPRINT);
        let bare = KEY_A.rsplit_once(' ').unwrap().0;
        assert_eq!(
            PinnedHostKey::parse(bare).unwrap().fingerprint(),
            KEY_A_FINGERPRINT
        );
        assert_eq!(
            PinnedHostKey::parse(&format!("  {bare}\n"))
                .unwrap()
                .fingerprint(),
            KEY_A_FINGERPRINT
        );
    }

    #[test]
    fn accepts_ssh_keyscan_output_with_its_host_prefix() {
        let line = format!("[192.168.1.10]:2222 {KEY_A}");
        assert_eq!(
            PinnedHostKey::parse(&line).unwrap().fingerprint(),
            KEY_A_FINGERPRINT
        );
        let line = format!("192.168.1.10 {}", KEY_C);
        assert!(PinnedHostKey::parse(&line).is_ok());
    }

    #[test]
    fn matches_only_the_same_key_whatever_its_comment() {
        let pinned = PinnedHostKey::parse(KEY_A).unwrap();
        let recommented = KEY_A.replace("passalong-test-a", "someone@else");
        assert!(pinned.matches(&public(&recommented)));
        assert!(!pinned.matches(&public(KEY_B)), "different ed25519 key");
        assert!(!pinned.matches(&public(KEY_C)), "different key type");
    }

    #[test]
    fn rejects_anything_that_is_not_a_public_key() {
        for bad in [
            "",
            "   ",
            "ssh-ed25519",
            "ssh-ed25519 not*base64",
            "AAAAC3NzaC1lZDI1NTE5",
            "host ssh-ed25519",
            "a b c d",
        ] {
            match PinnedHostKey::parse(bad) {
                Err(SshError::InvalidHostKey(_)) => {}
                other => panic!("{bad:?}: {other:?}"),
            }
        }
    }

    #[test]
    fn a_discovered_key_carries_its_line_fingerprint_and_algorithm() {
        let found = DiscoveredKey::from_key(&public(KEY_A)).unwrap();
        assert_eq!(found.fingerprint, KEY_A_FINGERPRINT);
        assert_eq!(found.algorithm, "ssh-ed25519");
        assert!(
            found.openssh_line.starts_with("ssh-ed25519 AAAA"),
            "{}",
            found.openssh_line
        );
        assert_eq!(
            PinnedHostKey::parse(&found.openssh_line)
                .unwrap()
                .fingerprint(),
            KEY_A_FINGERPRINT
        );
        let ecdsa = DiscoveredKey::from_key(&public(KEY_C)).unwrap();
        assert_eq!(ecdsa.algorithm, "ecdsa-sha2-nistp256");
    }

    #[cfg(not(feature = "rsa"))]
    #[test]
    fn rsa_host_keys_need_the_rsa_feature() {
        match PinnedHostKey::parse(KEY_RSA) {
            Err(err @ SshError::RsaUnsupported { .. }) => {
                let message = err.to_string();
                assert!(message.starts_with("server.ssh.host_key: "), "{message}");
                assert!(message.contains("--features rsa"), "{message}");
            }
            other => panic!("unexpected {other:?}"),
        }
    }

    #[cfg(feature = "rsa")]
    #[test]
    fn rsa_host_keys_parse_with_the_rsa_feature() {
        assert_eq!(
            PinnedHostKey::parse(KEY_RSA).unwrap().fingerprint(),
            KEY_RSA_FINGERPRINT
        );
    }
}