use md5::Md5;
use russh::client;
use russh::keys;
use russh::keys::ssh_key::HashAlg;
use russh::{cipher, compression};
use sha1::Digest as Sha1Digest;
use sha1::Sha1;
use std::borrow::Cow;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tracing::{debug, info};
mod error;
mod options;
#[cfg(test)]
mod tests;
pub use error::SshError;
pub use options::{HostKeyCheckingMode, SshOptions};
#[cfg(test)]
use crate::sftp::packet::{SSH_FXP_INIT, SSH_FXP_VERSION};
fn matches_fingerprint(key: &russh::keys::ssh_key::PublicKey, expected: &str) -> bool {
let Some((algorithm, digest)) = expected.split_once('=') else {
return key.fingerprint(HashAlg::Sha256).to_string() == expected;
};
let Ok(bytes) = key.to_bytes() else {
return false;
};
let algorithm = algorithm.to_ascii_lowercase();
let digest = digest.trim();
match algorithm.as_str() {
"md5" => hex::encode(Md5::digest(&bytes)).eq_ignore_ascii_case(&digest.replace(':', "")),
"sha-1" | "sha1" => {
hex::encode(Sha1::digest(&bytes)).eq_ignore_ascii_case(&digest.replace(':', ""))
}
"sha-256" | "sha256" => {
let actual = key.fingerprint(HashAlg::Sha256).to_string();
actual.eq_ignore_ascii_case(digest)
|| actual
.strip_prefix("SHA256:")
.is_some_and(|value| value.eq_ignore_ascii_case(digest))
}
"sha-512" | "sha512" => {
let actual = key.fingerprint(HashAlg::Sha512).to_string();
actual.eq_ignore_ascii_case(digest)
|| actual
.strip_prefix("SHA512:")
.is_some_and(|value| value.eq_ignore_ascii_case(digest))
}
_ => false,
}
}
fn verify_server_key(
options: &SshOptions,
server_key: &russh::keys::ssh_key::PublicKey,
known_hosts_path: &Path,
) -> Result<bool, SshError> {
if let Some(expected) = options.host_key_fingerprint.as_deref() {
return if matches_fingerprint(server_key, expected) {
Ok(true)
} else {
Err(SshError::Config {
message: format!("SSH host-key fingerprint mismatch: expected {expected}"),
})
};
}
if options.host_key_mode == HostKeyCheckingMode::Disable {
tracing::warn!("[SFTP] Host key checking DISABLED - connection may be insecure");
return Ok(true);
}
let recorded_keys = russh::keys::known_hosts::known_host_keys_path(
&options.host,
options.port,
known_hosts_path,
)
.map_err(|error| SshError::Config {
message: format!("SSH known-hosts verification failed: {error}"),
})?;
if recorded_keys
.iter()
.any(|(_, recorded_key)| recorded_key == server_key)
{
return Ok(true);
}
if !recorded_keys.is_empty() {
return Err(SshError::Config {
message: format!("SSH host key changed for {}", options.target()),
});
}
match options.host_key_mode {
HostKeyCheckingMode::Strict => Err(SshError::Config {
message: format!(
"SSH host key for {} is not present in {}",
options.target(),
known_hosts_path.display()
),
}),
HostKeyCheckingMode::AcceptNew => {
russh::keys::known_hosts::learn_known_hosts_path(
&options.host,
options.port,
server_key,
known_hosts_path,
)
.map_err(|error| SshError::Config {
message: format!("Failed to record SSH host key: {error}"),
})?;
Ok(true)
}
HostKeyCheckingMode::Disable => unreachable!("handled before known-hosts lookup"),
}
}
fn resolve_known_hosts_path(options: &SshOptions) -> Result<PathBuf, SshError> {
if let Some(path) = options.known_hosts_path.as_ref() {
return Ok(path.clone());
}
dirs::home_dir()
.map(|home| home.join(".ssh").join("known_hosts"))
.ok_or_else(|| SshError::Config {
message: "Cannot locate the home directory for SSH known-hosts verification".into(),
})
}
struct SshClientHandler {
options: Arc<SshOptions>,
host_key_error: Arc<std::sync::Mutex<Option<SshError>>>,
}
impl SshClientHandler {
fn new(
options: Arc<SshOptions>,
host_key_error: Arc<std::sync::Mutex<Option<SshError>>>,
) -> Self {
Self {
options,
host_key_error,
}
}
}
#[async_trait::async_trait]
impl client::Handler for SshClientHandler {
type Error = SshError;
#[allow(refining_impl_trait)]
fn check_server_key(
&mut self,
_server_public_key: &russh::keys::PublicKeyOrCertificate,
) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
let options = Arc::clone(&self.options);
let host_key_error = Arc::clone(&self.host_key_error);
let server_key = _server_public_key.public_key();
async move {
debug!(
"[SFTP] Checking server key (mode={})",
options.host_key_mode
);
let result = (|| {
let path = if options.host_key_fingerprint.is_some()
|| options.host_key_mode == HostKeyCheckingMode::Disable
{
PathBuf::new()
} else {
resolve_known_hosts_path(&options)?
};
verify_server_key(&options, &server_key, &path)
})();
if let Err(error @ SshError::Config { .. }) = &result {
*host_key_error
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(error.clone());
}
result
}
}
}
pub struct SshConnection {
handle: client::Handle<SshClientHandler>,
options: Arc<SshOptions>,
}
impl std::fmt::Debug for SshConnection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SshConnection")
.field("host", &self.options.host)
.field("port", &self.options.port)
.field("host_key_mode", &self.options.host_key_mode)
.finish()
}
}
impl SshConnection {
pub async fn connect(options: SshOptions) -> Result<Self, SshError> {
let target = options.target();
debug!("[SFTP] Connecting to SSH (russh): {}", target);
let timeout = options.connect_timeout;
let host = options.host.clone();
let port = options.port;
tokio::time::timeout(timeout, async move {
let config = build_client_config(&options)?;
let stream = tokio::net::TcpStream::connect((options.host.as_str(), options.port))
.await
.map_err(|error| SshError::ConnectFailed {
host: options.host.clone(),
port: options.port,
message: error.to_string(),
})?;
Self::connect_with_config(options, stream, config).await
})
.await
.map_err(|_| SshError::ConnectTimeout {
host,
port,
timeout_secs: timeout.as_secs(),
})?
}
pub async fn connect_with_stream(
options: SshOptions,
stream: tokio::net::TcpStream,
) -> Result<Self, SshError> {
let config = build_client_config(&options)?;
Self::connect_with_config(options, stream, config).await
}
async fn connect_with_config(
options: SshOptions,
stream: tokio::net::TcpStream,
config: client::Config,
) -> Result<Self, SshError> {
let target = options.target();
debug!("[SFTP] Connecting to SSH (russh): {}", target);
let options_arc = Arc::new(options);
let config = Arc::new(config);
let timeout = options_arc.connect_timeout;
let connection = async {
let host_key_error = Arc::new(std::sync::Mutex::new(None));
let handler =
SshClientHandler::new(Arc::clone(&options_arc), Arc::clone(&host_key_error));
let mut handle = client::connect_stream(config, stream, handler)
.await
.map_err(|error| {
host_key_error
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take()
.unwrap_or_else(|| SshError::Handshake {
message: format!("SSH handshake failed: {error}"),
})
})?;
info!(
"[SFTP] SSH handshake complete (russh): {} (key_check={})",
target, options_arc.host_key_mode
);
Self::authenticate(&mut handle, &options_arc).await?;
Ok::<_, SshError>(handle)
};
let handle = tokio::time::timeout(timeout, connection)
.await
.map_err(|_| SshError::ConnectTimeout {
host: options_arc.host.clone(),
port: options_arc.port,
timeout_secs: timeout.as_secs(),
})??;
info!("[SFTP] SSH authenticated successfully: {}", target);
Ok(Self {
handle,
options: options_arc,
})
}
async fn authenticate(
handle: &mut client::Handle<SshClientHandler>,
options: &Arc<SshOptions>,
) -> Result<(), SshError> {
let username = &options.username;
if let Some(ref password) = options.password {
debug!(
"[SFTP] Attempting password authentication for user '{}'",
username
);
let result = handle
.authenticate_password(username, password)
.await
.map_err(|e| SshError::AuthFailed {
method: "password".to_string(),
message: e.to_string(),
})?;
return Self::require_successful_authentication(result, "password");
}
let key_path = options.resolve_key_path();
if let Some(key_path) = key_path {
let passphrase: Option<&str> = options.private_key_passphrase.as_deref();
debug!(
"[SFTP] Attempting public key authentication for user '{}' with key: {}",
username,
key_path.display()
);
let key =
keys::load_secret_key(&key_path, passphrase).map_err(|e| SshError::AuthFailed {
method: "publickey".to_string(),
message: format!("Failed to load key {}: {}", key_path.display(), e),
})?;
let key_with_alg = keys::PrivateKeyWithHashAlg::new(std::sync::Arc::new(key), None);
let result = handle
.authenticate_publickey(username, key_with_alg)
.await
.map_err(|e| SshError::AuthFailed {
method: "publickey".to_string(),
message: format!("Public key auth failed (key={}): {}", key_path.display(), e),
})?;
return Self::require_successful_authentication(result, "publickey");
}
Err(SshError::NoCredentials {
message: "No authentication credentials provided".to_string(),
})
}
fn require_successful_authentication(
result: client::AuthResult,
method: &str,
) -> Result<(), SshError> {
if result.success() {
return Ok(());
}
Err(SshError::AuthFailed {
method: method.to_string(),
message: "server rejected credentials".to_string(),
})
}
pub async fn open_sftp_channel(
&mut self,
) -> Result<russh::Channel<russh::client::Msg>, SshError> {
debug!("[SFTP] Opening SFTP subsystem channel");
let timeout = self.options.connect_timeout;
let target = self.options.target();
let channel =
tokio::time::timeout(timeout, async {
let channel = self.handle.channel_open_session().await.map_err(|e| {
SshError::SubsystemInit {
message: format!("Failed to open session channel: {}", e),
}
})?;
channel.request_subsystem(true, "sftp").await.map_err(|e| {
SshError::SubsystemInit {
message: format!("Failed to request SFTP subsystem: {}", e),
}
})?;
Ok::<_, SshError>(channel)
})
.await
.map_err(|_| SshError::ConnectionLost {
message: format!("Opening SFTP channel for {target} timed out after {timeout:?}"),
})??;
debug!("[SFTP] SFTP subsystem channel opened successfully");
Ok(channel)
}
pub fn options(&self) -> &Arc<SshOptions> {
&self.options
}
pub async fn disconnect(self) -> Result<(), SshError> {
let target = self.options.target();
debug!("[SFTP] Disconnecting SSH (russh): {}", target);
drop(self.handle);
info!("[SFTP] SSH disconnected: {}", target);
Ok(())
}
}
fn build_client_config(options: &SshOptions) -> Result<client::Config, SshError> {
let mut config = client::Config {
keepalive_interval: options.keepalive_interval,
..Default::default()
};
config.preferred.compression = if options.compression {
Cow::Borrowed(&[compression::ZLIB_LEGACY, compression::NONE])
} else {
Cow::Borrowed(&[compression::NONE])
};
if !options.preferred_ciphers.is_empty() {
let ciphers = options
.preferred_ciphers
.iter()
.map(|name| {
cipher::Name::try_from(name.as_str()).map_err(|()| SshError::Config {
message: format!("Unsupported SSH cipher: {name}"),
})
})
.collect::<Result<Vec<_>, _>>()?;
config.preferred.cipher = Cow::Owned(ciphers);
}
Ok(config)
}