use crate::target::RemoteTarget;
use std::path::Path;
use crate::transport::ssh::{
deploy_command, deploy_payload, parse_remote_version, parse_uname, remote_command,
};
use crate::transport::{JumpHost, Sudo};
use anyhow::{anyhow, bail, Context as _};
use base64::Engine as _;
use russh::client::{self, Config, Handle, KeyboardInteractiveAuthResponse};
use russh::keys::agent::client::{AgentClient, AgentStream};
use russh::keys::ssh_key::{self, certificate::CertType, public::KeyData, Fingerprint, HashAlg, PublicKey};
use russh::keys::{self, PrivateKeyWithHashAlg, PublicKeyBase64};
use russh::ChannelMsg;
use ssh_key::known_hosts::{Entry, HostPatterns, Marker};
use zeroize::Zeroize;
use std::io::{IsTerminal, Write};
use std::net::ToSocketAddrs;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, ReadBuf};
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
fn ssh_config() -> Arc<Config> {
Arc::new(Config {
keepalive_interval: Some(std::time::Duration::from_secs(30)),
keepalive_max: 3,
nodelay: true,
..Config::default()
})
}
pub(crate) struct ClientHandler {
host: String,
port: u16,
}
impl client::Handler for ClientHandler {
type Error = anyhow::Error;
async fn check_server_key(
&mut self,
server_public_key: &ssh_key::PublicKey,
) -> Result<bool, Self::Error> {
std::future::ready(host_key_ok(&self.host, self.port, server_public_key)).await
}
async fn auth_banner(
&mut self,
banner: &str,
_session: &mut client::Session,
) -> Result<(), Self::Error> {
if !banner.trim().is_empty() {
let mut stderr = std::io::stderr();
let _ = stderr.write_all(banner.as_bytes());
let _ = stderr.flush();
}
std::future::ready(Ok(())).await
}
}
fn host_key_ok(host: &str, port: u16, key: &PublicKey) -> anyhow::Result<bool> {
match key.key_data() {
KeyData::Certificate(cert) => verify_host_certificate(host, cert),
_ => match check_plain_host_key(host, port, key)? {
KnownHostCheck::Accepted => Ok(true),
KnownHostCheck::Changed { line } => bail!(
"REMOTE HOST IDENTIFICATION HAS CHANGED for host '{host}' \
(known_hosts line {line}). Possible man-in-the-middle attack."
),
KnownHostCheck::Revoked { line } => bail!(
"host key for '{host}' was revoked in known_hosts (line {line}); refusing to connect"
),
KnownHostCheck::Unknown => trust_on_first_use(host, port, key),
},
}
}
enum KnownHostCheck {
Accepted,
Changed { line: usize },
Revoked { line: usize },
Unknown,
}
fn check_plain_host_key(host: &str, port: u16, key: &PublicKey) -> anyhow::Result<KnownHostCheck> {
let (content, candidates) =
tokio::task::block_in_place(|| -> anyhow::Result<(Option<String>, Vec<String>)> {
Ok((read_known_hosts()?, host_candidates(host, port)))
})?;
let Some(content) = content else {
return Ok(KnownHostCheck::Unknown);
};
Ok(match_known_hosts(&content, &candidates, key))
}
fn match_known_hosts(content: &str, candidates: &[String], key: &PublicKey) -> KnownHostCheck {
let mut first_entry: Option<usize> = None;
let mut revoked_line: Option<usize> = None;
let mut accepted = false;
for (line_no, raw) in content.lines().enumerate() {
let line = raw.split_once('#').map_or(raw, |(head, _)| head).trim();
if line.is_empty() {
continue;
}
let entry = match line.parse::<Entry>() {
Ok(entry) => entry,
Err(e) => {
tracing::warn!("skipping malformed known_hosts line {}: {e}", line_no + 1);
continue;
}
};
if matches!(entry.marker(), Some(Marker::CertAuthority)) {
continue;
}
if !entry_matches_host(&entry, candidates) {
continue;
}
first_entry.get_or_insert(line_no + 1);
if entry.public_key() == key {
accepted = true;
}
if matches!(entry.marker(), Some(Marker::Revoked)) && entry.public_key() == key {
revoked_line = Some(line_no + 1);
}
}
if let Some(line) = revoked_line {
return KnownHostCheck::Revoked { line };
}
if accepted {
return KnownHostCheck::Accepted;
}
match first_entry {
Some(line) => KnownHostCheck::Changed { line },
None => KnownHostCheck::Unknown,
}
}
fn entry_matches_host(entry: &Entry, candidates: &[String]) -> bool {
match entry.host_patterns() {
HostPatterns::Patterns(patterns) => candidates.iter().any(|candidate| {
patterns_match_host(candidate, patterns.iter().map(String::as_str))
}),
HostPatterns::HashedName { salt, hash } => candidates
.iter()
.any(|candidate| hmac_sha1_verify(salt, hash, candidate.as_bytes())),
}
}
fn patterns_match_host<'a>(host: &str, patterns: impl IntoIterator<Item = &'a str>) -> bool {
let mut negated = false;
let mut positive = false;
for pattern in patterns {
if let Some(rest) = pattern.strip_prefix('!') {
if glob_match(host, rest) {
negated = true;
}
} else if pattern.starts_with("|1|") {
tracing::warn!(
"skipping hashed pattern '{pattern}': hashed patterns cannot be matched by name"
);
} else if glob_match(host, pattern) {
positive = true;
}
}
positive && !negated
}
fn host_candidates(host: &str, port: u16) -> Vec<String> {
let mut names = vec![host.to_string()];
if let Ok(addrs) = (host, 0u16).to_socket_addrs() {
for addr in addrs {
let ip = addr.ip().to_string();
if !names.contains(&ip) {
names.push(ip);
}
}
}
if port == 22 {
names
.into_iter()
.map(|name| {
if name.contains(':') {
format!("[{name}]")
} else {
name
}
})
.collect()
} else {
names
.into_iter()
.map(|name| format!("[{name}]:{port}"))
.collect()
}
}
fn hmac_sha1_verify(salt: &[u8], expected: &[u8; 20], data: &[u8]) -> bool {
const BLOCK: usize = 64;
let mut key = salt.to_vec();
if key.len() > BLOCK {
key = sha1(&key).to_vec();
}
key.resize(BLOCK, 0);
let mut ipad = [0x36u8; BLOCK];
let mut opad = [0x5cu8; BLOCK];
for (byte, key_byte) in ipad.iter_mut().zip(key.iter()) {
*byte ^= key_byte;
}
for (byte, key_byte) in opad.iter_mut().zip(key.iter()) {
*byte ^= key_byte;
}
let mut inner = ipad.to_vec();
inner.extend_from_slice(data);
let inner_digest = sha1(&inner);
let mut outer = opad.to_vec();
outer.extend_from_slice(&inner_digest);
sha1(&outer) == *expected
}
fn sha1(data: &[u8]) -> [u8; 20] {
let mut state = [
0x6745_2301u32,
0xEFCD_AB89,
0x98BA_DCFE,
0x1032_5476,
0xC3D2_E1F0,
];
let (blocks, rem_bytes) = data.as_chunks::<64>();
for block in blocks {
sha1_compress(&mut state, block);
}
let rem = rem_bytes.len();
let bit_len = u64::try_from(data.len())
.unwrap_or(u64::MAX)
.wrapping_mul(8);
let mut final_block = [0u8; 64];
final_block[..rem].copy_from_slice(rem_bytes);
final_block[rem] = 0x80;
if rem < 56 {
final_block[56..].copy_from_slice(&bit_len.to_be_bytes());
sha1_compress(&mut state, &final_block);
} else {
sha1_compress(&mut state, &final_block);
let mut tail = [0u8; 64];
tail[56..].copy_from_slice(&bit_len.to_be_bytes());
sha1_compress(&mut state, &tail);
}
let mut digest = [0u8; 20];
let (digest_words, _) = digest.as_chunks_mut::<4>();
for (word, slot) in state.iter().zip(digest_words) {
slot.copy_from_slice(&word.to_be_bytes());
}
digest
}
fn sha1_compress(state: &mut [u32; 5], block: &[u8; 64]) {
let mut words = [0u32; 80];
let (word_bytes, _) = block.as_chunks::<4>();
for (word, bytes) in words[..16].iter_mut().zip(word_bytes) {
*word = u32::from_be_bytes(*bytes);
}
for idx in 16..80 {
words[idx] = (words[idx - 3] ^ words[idx - 8] ^ words[idx - 14] ^ words[idx - 16])
.rotate_left(1);
}
let (mut h0, mut h1, mut h2, mut h3, mut h4) =
(state[0], state[1], state[2], state[3], state[4]);
for (round, &word) in words.iter().enumerate() {
let (f, k) = match round {
0..=19 => ((h1 & h2) | (!h1 & h3), 0x5A82_7999u32),
20..=39 => (h1 ^ h2 ^ h3, 0x6ED9_EBA1),
40..=59 => ((h1 & h2) | (h1 & h3) | (h2 & h3), 0x8F1B_BCDC),
_ => (h1 ^ h2 ^ h3, 0xCA62_C1D6),
};
let temp = h0
.rotate_left(5)
.wrapping_add(f)
.wrapping_add(h4)
.wrapping_add(k)
.wrapping_add(word);
h4 = h3;
h3 = h2;
h2 = h1.rotate_left(30);
h1 = h0;
h0 = temp;
}
state[0] = state[0].wrapping_add(h0);
state[1] = state[1].wrapping_add(h1);
state[2] = state[2].wrapping_add(h2);
state[3] = state[3].wrapping_add(h3);
state[4] = state[4].wrapping_add(h4);
}
fn verify_host_certificate(host: &str, cert: &ssh_key::Certificate) -> anyhow::Result<bool> {
let cas = cert_authorities_for(host)?;
if cas.is_empty() {
bail!(
"no @cert-authority entry in known_hosts matches host '{host}'; \
cannot verify its host certificate"
);
}
if cert.cert_type() != CertType::Host {
bail!(
"host '{host}' presented a certificate of type {:?}, not a host certificate",
cert.cert_type()
);
}
cert.validate(cas.iter())
.map_err(|e| anyhow!("host certificate for '{host}' failed validation: {e}"))?;
if !cert.critical_options().is_empty() {
bail!(
"host certificate for '{host}' carries unsupported critical options: {:?}",
cert.critical_options()
);
}
if !cert.valid_principals().is_empty()
&& !cert
.valid_principals()
.iter()
.any(|principal| principal == host)
{
bail!(
"host certificate for '{host}' does not list '{host}' among its principals"
);
}
Ok(true)
}
fn cert_authorities_for(host: &str) -> anyhow::Result<Vec<Fingerprint>> {
let Some(content) = tokio::task::block_in_place(read_known_hosts)? else {
return Ok(Vec::new());
};
let mut cas = Vec::new();
for line in content.lines() {
let line = line.trim();
if !line.starts_with("@cert-authority") {
continue;
}
let mut fields = line.split_whitespace();
fields.next(); let (Some(patterns), Some(_key_type), Some(b64)) =
(fields.next(), fields.next(), fields.next())
else {
continue;
};
if !host_matches_pattern(host, patterns) {
continue;
}
match keys::parse_public_key_base64(b64) {
Ok(ca) => cas.push(Fingerprint::new(HashAlg::Sha256, ca.key_data())),
Err(e) => tracing::warn!(
"skipping malformed @cert-authority line matching '{host}': {e}"
),
}
}
Ok(cas)
}
fn host_matches_pattern(host: &str, pattern: &str) -> bool {
patterns_match_host(host, pattern.split(','))
}
fn glob_match(host: &str, pattern: &str) -> bool {
fn rec(host: &[char], pattern: &[char]) -> bool {
match (host.first(), pattern.first()) {
(None, None) => true,
(_, Some('*')) => rec(host, &pattern[1..]) || (!host.is_empty() && rec(&host[1..], pattern)),
(Some(_), Some('?')) => rec(&host[1..], &pattern[1..]),
(Some(a), Some(b)) if a == b => rec(&host[1..], &pattern[1..]),
_ => false,
}
}
let host: Vec<char> = host.chars().collect();
let pattern: Vec<char> = pattern.chars().collect();
rec(&host, &pattern)
}
fn trust_on_first_use(host: &str, port: u16, key: &PublicKey) -> anyhow::Result<bool> {
if !std::io::stdin().is_terminal() {
bail!(
"host key for '{host}' is not in known_hosts and no terminal is \
available to confirm it (run with an interactive terminal, or add \
it with `ssh-keyscan`/ssh)"
);
}
eprintln!("The authenticity of host '{host}' can't be established.");
eprintln!(
"{} key fingerprint is SHA256:{}.",
key.algorithm(),
fingerprint_b64(&Fingerprint::new(HashAlg::Sha256, key.key_data()))
);
eprint!("Are you sure you want to continue connecting (yes/no)? ");
std::io::stderr().flush()?;
let answer = tokio::task::block_in_place(|| {
let mut line = String::new();
let _ = std::io::stdin().read_line(&mut line);
line.trim().to_ascii_lowercase()
});
if answer == "yes" {
tokio::task::block_in_place(|| learn_known_hosts(host, port, key))?;
Ok(true)
} else {
bail!("host key verification failed for '{host}'");
}
}
fn fingerprint_b64(fingerprint: &Fingerprint) -> String {
let bytes: &[u8] = match fingerprint {
Fingerprint::Sha256(bytes) => bytes,
Fingerprint::Sha512(bytes) => bytes,
_ => &[], };
base64::engine::general_purpose::STANDARD_NO_PAD.encode(bytes)
}
pub(crate) struct RusshConnection {
pub(crate) handle: Handle<ClientHandler>,
#[expect(dead_code, reason = "drop-order anchor for the jump connection")]
jump_handle: Option<Handle<ClientHandler>>,
}
struct SecretVault(Option<String>);
impl SecretVault {
fn new(secret: Option<String>) -> Self {
Self(secret)
}
fn get(&self) -> Option<&str> {
self.0.as_deref()
}
fn set(&mut self, secret: String) {
self.0 = Some(secret);
}
fn is_none(&self) -> bool {
self.0.is_none()
}
fn clone_from(&mut self, other: &Self) {
if let Some(secret) = &other.0 {
self.0 = Some(secret.clone());
}
}
}
impl Drop for SecretVault {
fn drop(&mut self) {
if let Some(secret) = &mut self.0 {
secret.zeroize();
}
}
}
struct SecretStrings(Vec<String>);
impl Drop for SecretStrings {
fn drop(&mut self) {
for secret in &mut self.0 {
secret.zeroize();
}
}
}
pub(crate) async fn connect(
peer: &RemoteTarget,
jump: Option<&JumpHost>,
password: Option<String>,
jump_password: Option<String>,
) -> anyhow::Result<RusshConnection> {
let mut target_vault = SecretVault::new(password);
let mut jump_vault = SecretVault::new(jump_password);
if jump_vault.is_none() {
jump_vault.clone_from(&target_vault);
}
let (handle, jump_handle) = if let Some(jump_host) = jump {
let jump_handler = ClientHandler {
host: jump_host.host.clone(),
port: jump_host.port,
};
let jump_handle = connect_one(
&jump_host.host,
jump_host.port,
&jump_host.user,
jump_handler,
&mut jump_vault,
)
.await?;
if target_vault.is_none() {
target_vault.clone_from(&jump_vault);
}
let channel = jump_handle
.channel_open_direct_tcpip(peer.host.clone(), u32::from(peer.port), "127.0.0.1", 0)
.await
.context("failed to open a direct-tcpip channel to the target through the jump host")?;
let stream = channel.into_stream();
let handle = client::connect_stream(ssh_config(), stream, ClientHandler {
host: peer.host.clone(),
port: peer.port,
})
.await
.context("failed to connect to the target through the jump host")?;
(handle, Some(jump_handle))
} else {
let handle = client::connect(ssh_config(), (peer.host.as_str(), peer.port), ClientHandler {
host: peer.host.clone(),
port: peer.port,
})
.await
.context("failed to connect")?;
(handle, None)
};
let mut handle = handle;
let auth = authenticate(
&mut handle,
&peer.user,
&format!("{}@{}", peer.user, peer.host),
&mut target_vault,
)
.await;
auth?;
Ok(RusshConnection {
handle,
jump_handle,
})
}
async fn connect_one(
host: &str,
port: u16,
user: &str,
handler: ClientHandler,
vault: &mut SecretVault,
) -> anyhow::Result<Handle<ClientHandler>> {
let mut handle = client::connect(ssh_config(), (host, port), handler)
.await
.context("failed to connect")?;
authenticate(&mut handle, user, &format!("{user}@{host}"), vault).await?;
Ok(handle)
}
async fn authenticate(
handle: &mut Handle<ClientHandler>,
user: &str,
display: &str,
vault: &mut SecretVault,
) -> anyhow::Result<()> {
let rsa_hash = handle.best_supported_rsa_hash().await?.flatten();
for path in candidate_keys() {
if !path.is_file() {
continue;
}
let key = match keys::load_secret_key(&path, None) {
Ok(key) => key,
Err(keys::Error::KeyIsEncrypted) => {
let passphrase = match prompt_secret(&format!(
"Enter passphrase for {}: ",
path.display()
)) {
Ok(passphrase) => passphrase,
Err(e) => {
tracing::debug!(
"skipping key {}: cannot read a passphrase: {e}",
path.display()
);
continue;
}
};
let passphrase = SecretVault::new(Some(passphrase));
keys::load_secret_key(&path, passphrase.get())
.map_err(|e| anyhow!("failed to decrypt {}: {e}", path.display()))?
}
Err(e) => {
tracing::debug!("skipping key {}: {e}", path.display());
continue;
}
};
let result = handle
.authenticate_publickey(
user,
PrivateKeyWithHashAlg::new(Arc::new(key.clone()), rsa_hash),
)
.await?;
if result.success() {
return Ok(());
}
let cert_path = cert_path_for(&path);
if cert_path.is_file() && let Ok(cert) = keys::load_openssh_certificate(&cert_path) {
let result = handle
.authenticate_openssh_cert(user, Arc::new(key), cert)
.await?;
if result.success() {
return Ok(());
}
}
}
if let Some(mut agent) = connect_agent().await
&& let Ok(identities) = agent.request_identities().await
{
for identity in identities {
let Some(key) = identity_public_key(&identity) else {
continue;
};
match handle
.authenticate_publickey_with(user, key, rsa_hash, &mut agent)
.await
{
Ok(result) if result.success() => return Ok(()),
Ok(_) => {}
Err(e) => tracing::debug!("agent key rejected: {e}"),
}
}
}
if let Err(e) = keyboard_interactive_auth(handle, user, vault).await {
tracing::debug!("keyboard-interactive authentication failed: {e}");
if password_auth(handle, user, display, vault).await? {
return Ok(());
}
} else {
return Ok(());
}
bail!("authentication failed for {display} (tried keys, agent, keyboard-interactive, password)")
}
fn identity_public_key(identity: &russh::keys::agent::AgentIdentity) -> Option<PublicKey> {
match identity {
russh::keys::agent::AgentIdentity::PublicKey { key, .. } => Some(key.clone()),
russh::keys::agent::AgentIdentity::Certificate { .. } => None,
}
}
async fn connect_agent(
) -> Option<AgentClient<Box<dyn AgentStream + Send + Unpin>>> {
#[cfg(not(windows))]
{
keys::agent::client::AgentClient::connect_env()
.await
.ok()
.map(AgentClient::dynamic)
}
#[cfg(windows)]
{
let named_pipe = keys::agent::client::AgentClient::connect_named_pipe(r"\\.\pipe\openssh-ssh-agent")
.await;
match named_pipe {
Ok(client) => Some(AgentClient::dynamic(client)),
Err(_) => keys::agent::client::AgentClient::connect_pageant()
.await
.ok()
.map(AgentClient::dynamic),
}
}
}
async fn keyboard_interactive_auth(
handle: &mut Handle<ClientHandler>,
user: &str,
vault: &mut SecretVault,
) -> anyhow::Result<()> {
let mut response = handle.authenticate_keyboard_interactive_start(user, None).await?;
loop {
match response {
KeyboardInteractiveAuthResponse::Success => return Ok(()),
KeyboardInteractiveAuthResponse::Failure { .. } => {
bail!("keyboard-interactive authentication failed")
}
KeyboardInteractiveAuthResponse::InfoRequest {
name,
instructions,
prompts,
} => {
if !name.is_empty() {
eprintln!("{name}");
}
if !instructions.is_empty() {
eprintln!("{instructions}");
}
let mut answers = SecretStrings(Vec::with_capacity(prompts.len()));
for prompt in prompts {
let answer = if prompt.echo {
read_line_visible(&prompt.prompt)
} else if let Some(cached) = vault.get() {
cached.to_string()
} else {
let entered = prompt_secret(&prompt.prompt)?;
vault.set(entered.clone());
entered
};
answers.0.push(answer);
}
response = handle
.authenticate_keyboard_interactive_respond(std::mem::take(&mut answers.0))
.await?;
}
}
}
}
async fn password_auth(
handle: &mut Handle<ClientHandler>,
user: &str,
display: &str,
vault: &mut SecretVault,
) -> anyhow::Result<bool> {
let mut password = if let Some(cached) = vault.get() {
cached.to_string()
} else {
let entered = prompt_secret(&format!("{display}'s password: "))?;
vault.set(entered.clone());
entered
};
let result = handle.authenticate_password(user, &password).await;
password.zeroize();
Ok(result?.success())
}
fn candidate_keys() -> Vec<PathBuf> {
let dir = ssh_dir();
["id_ed25519", "id_ecdsa", "id_rsa"]
.iter()
.map(|name| dir.join(name))
.collect()
}
fn cert_path_for(key: &Path) -> PathBuf {
let mut name = key.as_os_str().to_os_string();
name.push("-cert.pub");
PathBuf::from(name)
}
fn home_dir() -> PathBuf {
std::env::var_os("USERPROFILE")
.or_else(|| std::env::var_os("HOME"))
.map(PathBuf::from)
.unwrap_or_default()
}
fn ssh_dir() -> PathBuf {
home_dir().join(".ssh")
}
fn known_hosts_path() -> PathBuf {
ssh_dir().join("known_hosts")
}
fn read_known_hosts() -> anyhow::Result<Option<String>> {
let path = known_hosts_path();
match std::fs::read_to_string(&path) {
Ok(content) => Ok(Some(content)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(anyhow!("failed to read {}: {e}", path.display())),
}
}
fn learn_known_hosts(host: &str, port: u16, key: &PublicKey) -> anyhow::Result<()> {
let path = known_hosts_path();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.map_err(|e| anyhow!("failed to create {}: {e}", parent.display()))?;
}
let host_entry = if host.contains(':') {
if port == 22 {
format!("[{host}]")
} else {
format!("[{host}]:{port}")
}
} else if port == 22 {
host.to_string()
} else {
format!("[{host}]:{port}")
};
let mut file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.map_err(|e| anyhow!("failed to open {} for append: {e}", path.display()))?;
writeln!(
file,
"{host_entry} {} {}",
key.algorithm(),
key.public_key_base64()
)
.map_err(|e| anyhow!("failed to record host key in {}: {e}", path.display()))?;
Ok(())
}
fn prompt_secret(prompt: &str) -> anyhow::Result<String> {
tokio::task::block_in_place(|| rpassword::prompt_password(prompt))
.map_err(|e| anyhow!("failed to read secret: {e}"))
}
fn read_line_visible(prompt: &str) -> String {
tokio::task::block_in_place(|| {
let mut line = String::new();
eprint!("{prompt}");
let _ = std::io::stderr().flush();
let _ = std::io::stdin().read_line(&mut line);
line.trim_end().to_string()
})
}
const REMOTE_COMMAND_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
async fn exec_capture(
handle: &Handle<ClientHandler>,
command: &str,
stdin_payload: Option<&[u8]>,
) -> anyhow::Result<(u32, String, String)> {
let mut channel = handle.channel_open_session().await?;
channel.exec(true, command).await?;
if let Some(payload) = stdin_payload {
channel.data(payload).await?;
}
channel.eof().await?;
let (code, stdout, stderr) = tokio::time::timeout(
REMOTE_COMMAND_TIMEOUT,
async {
let mut stdout = Vec::new();
let mut stderr = Vec::new();
let mut code = None;
loop {
let Some(msg) = channel.wait().await else {
break;
};
match msg {
ChannelMsg::Data { data } => stdout.extend_from_slice(&data),
ChannelMsg::ExtendedData { data, ext: 1 } => {
stderr.extend_from_slice(&data);
}
ChannelMsg::ExitStatus { exit_status } => code = Some(exit_status),
_ => {}
}
}
(code.unwrap_or(255), stdout, stderr)
},
)
.await
.map_err(|_| anyhow!("remote command timed out after 10s: {command}"))?;
Ok((
code,
String::from_utf8_lossy(&stdout).into_owned(),
String::from_utf8_lossy(&stderr).into_owned(),
))
}
fn sh_quote(path: &str) -> String {
if path
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '~' | '/' | '.' | '-' | '_' | '@' | '%' | ':' | '+'))
{
return path.to_string();
}
let mut quoted = String::with_capacity(path.len() + 2);
quoted.push('\'');
for c in path.chars() {
if c == '\'' {
quoted.push_str("'\\''");
} else {
quoted.push(c);
}
}
quoted.push('\'');
quoted
}
pub(crate) async fn probe_on(handle: &Handle<ClientHandler>) -> anyhow::Result<Option<(String, String)>> {
let (code, stdout, _stderr) = exec_capture(handle, "uname -s -m", None).await?;
if code == 0 && let Some(platform) = parse_uname(&stdout) {
return Ok(Some(platform));
}
let (_, stdout, _stderr) = exec_capture(handle, "cmd /c echo %PROCESSOR_ARCHITECTURE%", None).await?;
let arch = stdout.split_whitespace().next().unwrap_or("");
let arch = match arch {
"AMD64" => "x86_64",
"ARM64" => "aarch64",
_ => return Ok(None),
};
Ok(Some(("windows".to_string(), arch.to_string())))
}
pub(crate) async fn check_version_on(
handle: &Handle<ClientHandler>,
remote_path: &str,
remote_os: &str,
sudo: Sudo,
sudo_password: Option<&str>,
) -> anyhow::Result<Option<(String, Option<String>)>> {
let mut command = if remote_os == "windows" {
remote_command(remote_os, &format!("{remote_path} --version"))
} else {
let path = sh_quote(remote_path);
format!("test -x {path} && {path} --version")
};
let stdin_payload = match sudo {
Sudo::NonInteractive => {
command = format!("sudo -n {command}");
None
}
Sudo::Password => {
command = format!("sudo -S {command}");
Some(format!("{}\n", sudo_password.unwrap_or_default()).into_bytes())
}
Sudo::None => None,
};
let (code, stdout, _stderr) = exec_capture(handle, &command, stdin_payload.as_deref()).await?;
if code != 0 {
return Ok(None);
}
Ok(parse_remote_version(&stdout))
}
pub(crate) async fn deploy_on(
handle: &Handle<ClientHandler>,
remote_path: &str,
local_binary: &Path,
remote_os: &str,
) -> anyhow::Result<()> {
let payload = deploy_payload(remote_os, local_binary)?;
let command = deploy_command(remote_os, remote_path);
let (code, _stdout, _stderr) = exec_capture(handle, &command, Some(&payload)).await?;
if code != 0 {
bail!("failed to deploy cp2 to the server: remote command exited with {code}");
}
Ok(())
}
pub(crate) async fn open_session_on(
handle: &Handle<ClientHandler>,
remote_path: &str,
remote_os: &str,
server_args: &str,
sudo: Sudo,
sudo_password: Option<&str>,
) -> anyhow::Result<(
Box<dyn AsyncWrite + Unpin + Send>,
Box<dyn AsyncRead + Unpin + Send>,
RusshSession,
)> {
let base = if remote_os == "windows" {
format!("{remote_path} --server")
} else {
format!("{} --server", sh_quote(remote_path))
};
let base = if server_args.is_empty() {
base
} else {
format!("{base} {server_args}")
};
let remote_cmd = match sudo {
Sudo::None => base,
Sudo::NonInteractive => format!("sudo -n {base}"),
Sudo::Password => format!("sudo -S {base}"),
};
let remote_cmd = remote_command(remote_os, &remote_cmd);
let channel = handle.channel_open_session().await?;
channel.exec(true, remote_cmd).await?;
let (read_half, write_half) = channel.split();
let mut send: Box<dyn AsyncWrite + Unpin + Send> = Box::new(write_half.make_writer());
if sudo == Sudo::Password {
use tokio::io::AsyncWriteExt;
let send_mut = send.as_mut();
send_mut
.write_all(format!("{}
", sudo_password.unwrap_or_default()).as_bytes())
.await?;
}
let (bytes_tx, bytes_rx) = mpsc::channel::<bytes::Bytes>(64);
let recv_task = tokio::spawn(async move {
let mut read_half = read_half;
let mut reader = read_half.make_reader();
let mut buf = vec![0u8; 64 * 1024];
loop {
match reader.read(&mut buf).await {
Ok(0) | Err(_) => break,
Ok(n) => {
if bytes_tx
.send(bytes::Bytes::copy_from_slice(&buf[..n]))
.await
.is_err()
{
break;
}
}
}
}
});
let (eof_tx, eof_rx) = tokio::sync::oneshot::channel();
tokio::spawn(async move {
let _ = eof_rx.await;
let _ = write_half.eof().await;
});
let recv: Box<dyn AsyncRead + Unpin + Send> = Box::new(RxBytes::new(bytes_rx));
Ok((send, recv, RusshSession {
recv_task,
eof_trigger: Some(eof_tx),
}))
}
pub(crate) async fn open_preamble_on(
handle: &Handle<ClientHandler>,
remote_path: &str,
server_args: &str,
) -> anyhow::Result<Option<(
String,
String,
Box<dyn AsyncWrite + Unpin + Send>,
Box<dyn AsyncRead + Unpin + Send>,
RusshSession,
)>> {
let remote_cmd = crate::transport::ssh::preamble_command(remote_path, server_args);
let channel = handle.channel_open_session().await?;
channel.exec(true, remote_cmd).await?;
let (mut read_half, write_half) = channel.split();
let send: Box<dyn AsyncWrite + Unpin + Send> = Box::new(write_half.make_writer());
let (bytes_tx, bytes_rx) = mpsc::channel::<bytes::Bytes>(64);
let recv_task = tokio::spawn(async move {
let mut reader = read_half.make_reader();
let mut buf = vec![0u8; 64 * 1024];
loop {
match reader.read(&mut buf).await {
Ok(0) | Err(_) => break,
Ok(n) => {
if bytes_tx
.send(bytes::Bytes::copy_from_slice(&buf[..n]))
.await
.is_err()
{
break;
}
}
}
}
});
let (eof_tx, eof_rx) = tokio::sync::oneshot::channel();
tokio::spawn(async move {
let _ = eof_rx.await;
let _ = write_half.eof().await;
});
let rx = RxBytes::new(bytes_rx);
match crate::transport::ssh::read_preamble_platform(rx).await {
Ok(Some((os, arch, reader))) => Ok(Some((
os,
arch,
send,
Box::new(reader),
RusshSession {
recv_task,
eof_trigger: Some(eof_tx),
},
))),
Ok(None) | Err(_) => Ok(None),
}
}
pub(crate) async fn deploy_and_serve_on(
handle: &Handle<ClientHandler>,
remote_path: &str,
server_args: &str,
local_binary: &Path,
) -> anyhow::Result<(
Box<dyn AsyncWrite + Unpin + Send>,
Box<dyn AsyncRead + Unpin + Send>,
RusshSession,
)> {
use tokio::io::AsyncWriteExt;
let payload = std::fs::read(local_binary)?;
let remote_cmd =
crate::transport::ssh::deploy_serve_command(remote_path, server_args, payload.len() as u64);
let channel = handle.channel_open_session().await?;
channel.exec(true, remote_cmd).await?;
let (mut read_half, write_half) = channel.split();
let mut send: Box<dyn AsyncWrite + Unpin + Send> = Box::new(write_half.make_writer());
send.write_all(&payload).await?;
let (bytes_tx, bytes_rx) = mpsc::channel::<bytes::Bytes>(64);
let recv_task = tokio::spawn(async move {
let mut reader = read_half.make_reader();
let mut buf = vec![0u8; 64 * 1024];
loop {
match reader.read(&mut buf).await {
Ok(0) | Err(_) => break,
Ok(n) => {
if bytes_tx
.send(bytes::Bytes::copy_from_slice(&buf[..n]))
.await
.is_err()
{
break;
}
}
}
}
});
let (eof_tx, eof_rx) = tokio::sync::oneshot::channel();
tokio::spawn(async move {
let _ = eof_rx.await;
let _ = write_half.eof().await;
});
let recv: Box<dyn AsyncRead + Unpin + Send> = Box::new(RxBytes::new(bytes_rx));
Ok((
send,
recv,
RusshSession {
recv_task,
eof_trigger: Some(eof_tx),
},
))
}
#[expect(clippy::module_name_repetitions)]
pub struct RusshSession {
recv_task: JoinHandle<()>,
eof_trigger: Option<tokio::sync::oneshot::Sender<()>>,
}
impl Drop for RusshSession {
fn drop(&mut self) {
self.recv_task.abort();
if let Some(trigger) = self.eof_trigger.take() {
let _ = trigger.send(());
}
}
}
impl RusshSession {
pub async fn finish<T>(&mut self, result: anyhow::Result<T>) -> anyhow::Result<T> {
if let Some(trigger) = self.eof_trigger.take() {
let _ = trigger.send(());
}
let _ = tokio::time::timeout(std::time::Duration::from_secs(10), &mut self.recv_task).await;
result
}
}
struct RxBytes {
rx: mpsc::Receiver<bytes::Bytes>,
current: bytes::Bytes,
}
impl RxBytes {
fn new(rx: mpsc::Receiver<bytes::Bytes>) -> Self {
Self {
rx,
current: bytes::Bytes::new(),
}
}
}
impl AsyncRead for RxBytes {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<std::io::Result<()>> {
if self.current.is_empty() {
match self.rx.poll_recv(cx) {
Poll::Ready(Some(chunk)) => self.current = chunk,
Poll::Ready(None) => return Poll::Ready(Ok(())), Poll::Pending => return Poll::Pending,
}
}
let n = self.current.len().min(buf.remaining());
buf.put_slice(&self.current[..n]);
self.current = self.current.slice(n..);
Poll::Ready(Ok(()))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn unhex(s: &str) -> [u8; 20] {
assert_eq!(s.len(), 40);
let mut out = [0u8; 20];
for (i, byte) in out.iter_mut().enumerate() {
*byte = u8::from_str_radix(&s[i * 2..i * 2 + 2], 16).unwrap();
}
out
}
#[test]
fn sha1_known_vectors() {
assert_eq!(
sha1(b""),
unhex("da39a3ee5e6b4b0d3255bfef95601890afd80709")
);
assert_eq!(
sha1(b"abc"),
unhex("a9993e364706816aba3e25717850c26c9cd0d89d")
);
assert_eq!(
sha1(&[b'a'; 60]),
unhex("13d956033d9af449bfe2c4ef78c17c20469c4bf1")
);
}
#[test]
fn hmac_sha1_rfc2202_case1() {
let key = [0x0bu8; 20];
assert!(hmac_sha1_verify(
&key,
&unhex("b617318655057264e28bc0b6fb378c8ef146be00"),
b"Hi There"
));
assert!(!hmac_sha1_verify(
&key,
&unhex("b617318655057264e28bc0b6fb378c8ef146be00"),
b"Hi Therf"
));
}
}