use md5::Md5;
use russh::client;
use russh::keys;
use russh::keys::ssh_key::HashAlg;
use sha1::Digest as Sha1Digest;
use sha1::Sha1;
use std::sync::Arc;
use tracing::{debug, info};
mod options;
#[cfg(test)]
mod tests;
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,
}
}
struct SshClientHandler {
options: Arc<SshOptions>,
}
impl SshClientHandler {
fn new(options: Arc<SshOptions>) -> Self {
Self { options }
}
}
#[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::ssh_key::PublicKey,
) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send {
let mode = self.options.host_key_mode.clone();
let expected = self.options.host_key_fingerprint.clone();
let server_key = _server_public_key.clone();
async move {
debug!("[SFTP] Checking server key (mode={})", mode);
if let Some(expected) = expected {
if !matches_fingerprint(&server_key, &expected) {
return Err(SshError::Handshake {
message: format!("SSH host-key fingerprint mismatch: expected {expected}"),
});
}
return Ok(true);
}
match mode {
HostKeyCheckingMode::Strict => {
debug!("[SFTP] Strict host key checking - accepting key");
Ok(true)
}
HostKeyCheckingMode::AcceptNew => {
info!("[SFTP] Accept-new mode - accepting server key");
Ok(true)
}
HostKeyCheckingMode::Disable => {
tracing::warn!(
"[SFTP] Host key checking DISABLED - connection may be insecure"
);
Ok(true)
}
}
}
}
}
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("target", &self.options.target())
.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 stream = tokio::time::timeout(
options.connect_timeout,
tokio::net::TcpStream::connect((options.host.as_str(), options.port)),
)
.await
.map_err(|_| SshError::ConnectTimeout {
host: options.host.clone(),
port: options.port,
timeout_secs: options.connect_timeout.as_secs(),
})?
.map_err(|error| SshError::Handshake {
message: format!("SSH TCP connection failed: {error}"),
})?;
Self::connect_with_stream(options, stream).await
}
pub async fn connect_with_stream(
options: SshOptions,
stream: tokio::net::TcpStream,
) -> Result<Self, SshError> {
let target = options.target();
debug!("[SFTP] Connecting to SSH (russh): {}", target);
let options_arc = Arc::new(options);
let config = client::Config::default();
let config = Arc::new(config);
let handler = SshClientHandler::new(Arc::clone(&options_arc));
let mut handle = tokio::time::timeout(
options_arc.connect_timeout,
client::connect_stream(config, stream, handler),
)
.await
.map_err(|_| SshError::ConnectTimeout {
host: options_arc.host.clone(),
port: options_arc.port,
timeout_secs: options_arc.connect_timeout.as_secs(),
})?
.map_err(|e| SshError::Handshake {
message: format!("SSH handshake failed: {}", e),
})?;
info!(
"[SFTP] SSH handshake complete (russh): {} (key_check={})",
target, options_arc.host_key_mode
);
Self::authenticate(&mut handle, &options_arc).await?;
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 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),
})?;
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(())
}
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum SshError {
#[error("TCP connect timed out connecting to {host}:{port} after {timeout_secs}s")]
ConnectTimeout {
host: String,
port: u16,
timeout_secs: u64,
},
#[error("TCP connection failed to {host}:{port}: {message}")]
ConnectFailed {
host: String,
port: u16,
message: String,
},
#[error("SSH handshake failed: {message}")]
Handshake { message: String },
#[error("Authentication failed ({method}): {message}")]
AuthFailed { method: String, message: String },
#[error("No authentication credentials available: {message}")]
NoCredentials { message: String },
#[error("SSH session initialization failed: {message}")]
SessionInit { message: String },
#[error("SFTP subsystem initialization failed: {message}")]
SubsystemInit { message: String },
#[error("Configuration error: {message}")]
Config { message: String },
#[error("Protocol error: {message}")]
Protocol { message: String },
#[error("Connection lost: {message}")]
ConnectionLost { message: String },
}
impl SshError {
pub fn is_retryable(&self) -> bool {
matches!(
self,
Self::ConnectTimeout { .. } | Self::ConnectFailed { .. } | Self::ConnectionLost { .. }
)
}
pub fn is_auth_failure(&self) -> bool {
matches!(self, Self::AuthFailed { .. })
}
pub fn user_message(&self) -> String {
match self {
Self::ConnectTimeout { host, port, .. } => {
format!("Connection to {}:{} timed out", host, port)
}
Self::ConnectFailed {
host,
port,
message,
} => {
format!("Cannot connect to {}:{}: {}", host, port, message)
}
Self::AuthFailed { method, .. } => {
format!("Authentication failed ({})", method)
}
Self::NoCredentials { .. } => "No valid credentials provided".to_string(),
Self::Handshake { message } => {
format!("SSH handshake failed: {}", message)
}
other => other.to_string(),
}
}
}
impl From<russh::Error> for SshError {
fn from(err: russh::Error) -> Self {
SshError::Protocol {
message: err.to_string(),
}
}
}