pub mod ssh;
#[cfg(target_os = "windows")]
pub mod russh;
pub use ssh::spawn_ssh;
use crate::target::RemoteTarget;
use crate::Result;
#[cfg(target_os = "windows")]
use crate::Error;
use anyhow::bail;
use zeroize::Zeroize;
use std::path::Path;
use tokio::io::{AsyncRead, AsyncWrite};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct JumpHost {
pub user: String,
pub host: String,
pub port: u16,
}
impl JumpHost {
pub fn parse(s: &str) -> anyhow::Result<Self> {
let (user, host_port) = s
.split_once('@')
.ok_or_else(|| anyhow::anyhow!("--jump-host must be user@host, got '{s}'"))?;
if user.is_empty() {
bail!("--jump-host must be user@host, got '{s}'");
}
let (host, port) = if let Some(rest) = host_port.strip_prefix('[') {
let (host, tail) = rest
.split_once(']')
.ok_or_else(|| anyhow::anyhow!("--jump-host must be user@host, got '{s}'"))?;
let port = match tail.strip_prefix(':') {
Some(port) => parse_port(port, s)?,
None if tail.is_empty() => 22,
None => bail!("--jump-host must be user@host, got '{s}'"),
};
(host, port)
} else {
let (host, port) = match host_port.rsplit_once(':') {
Some((host, port))
if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) =>
{
(host, Some(parse_port(port, s)?))
}
_ => (host_port, None),
};
if host.contains(':') {
bail!("--jump-host host may not contain ':' outside brackets, got '{s}'");
}
(host, port.unwrap_or(22))
};
if host.is_empty() {
bail!("--jump-host must be user@host, got '{s}'");
}
Ok(Self {
user: user.to_string(),
host: host.to_string(),
port,
})
}
}
fn parse_port(s: &str, original: &str) -> anyhow::Result<u16> {
if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
bail!("--jump-host must be user@host[:port], got '{original}'");
}
let port = s
.parse::<u16>()
.map_err(|_| anyhow::anyhow!("invalid port in --jump-host '{original}'"))?;
if port == 0 {
bail!("--jump-host port must be > 0, got '{original}'");
}
Ok(port)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Transport {
Ssh,
#[cfg(target_os = "windows")]
Russh,
}
impl Transport {
#[must_use]
pub fn default_transport() -> Self {
if let Ok(value) = std::env::var("CP2_TRANSPORT") {
match value.as_str() {
"ssh" => return Self::Ssh,
#[cfg(target_os = "windows")]
"russh" => return Self::Russh,
_ => {
eprintln!(
"warning: unknown CP2_TRANSPORT '{value}' (expected 'ssh' or 'russh'); \
using the platform default"
);
}
}
}
#[cfg(not(target_os = "windows"))]
{
Self::Ssh
}
#[cfg(target_os = "windows")]
{
Self::Russh
}
}
#[must_use]
pub fn name(self) -> &'static str {
match self {
Self::Ssh => "ssh",
#[cfg(target_os = "windows")]
Self::Russh => "russh",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Sudo {
#[default]
None,
NonInteractive,
Password,
}
pub struct VersionProbe {
pub version: Option<(String, Option<String>)>,
pub sudo_password_required: bool,
pub mode: Sudo,
}
pub struct RemoteClient {
transport: Transport,
password: Option<String>,
jump_password: Option<String>,
control_path: Option<String>,
remote_sudo: bool,
sudo_password: Option<String>,
sudo_mode: Sudo,
#[cfg(target_os = "windows")]
russh: Option<russh::RusshConnection>,
#[cfg(target_os = "windows")]
russh_err: Option<String>,
}
impl Drop for RemoteClient {
fn drop(&mut self) {
if self.control_path.is_some() {
remove_control_sockets();
}
for secret in [
&mut self.password,
&mut self.jump_password,
&mut self.sudo_password,
]
.into_iter()
.flatten()
{
secret.zeroize();
}
}
}
fn remove_control_sockets() {
let pid = std::process::id();
let suffix = format!("-{pid}");
if let Ok(entries) = std::fs::read_dir(std::env::temp_dir()) {
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
if name.starts_with("cp2-ssh-") && name.ends_with(&suffix) {
let _ = std::fs::remove_file(entry.path());
}
}
}
}
impl RemoteClient {
#[must_use]
pub fn new(
transport: Transport,
password: Option<String>,
jump_password: Option<String>,
remote_sudo: bool,
sudo_password: Option<String>,
) -> Self {
let control_path = password.as_ref().map(|_| {
format!(
"{}/cp2-ssh-%C-{}",
std::env::temp_dir().to_string_lossy().replace('\\', "/"),
std::process::id()
)
});
let sudo_password = if remote_sudo {
sudo_password.or_else(|| password.clone())
} else {
None
};
Self {
transport,
password,
jump_password,
sudo_password,
remote_sudo,
sudo_mode: Sudo::None,
control_path,
#[cfg(target_os = "windows")]
russh: None,
#[cfg(target_os = "windows")]
russh_err: None,
}
}
fn ssh_auth(&self) -> ssh::SshAuth<'_> {
ssh::SshAuth {
password: self.password.as_deref(),
jump_password: self.jump_password.as_deref(),
control_path: self.control_path.as_deref(),
}
}
fn consume_ssh_password(&mut self) {
for secret in [&mut self.password, &mut self.jump_password] {
if let Some(mut secret) = secret.take() {
secret.zeroize();
}
}
}
#[cfg(target_os = "windows")]
fn forced_to_russh(&self) -> bool {
if self.password.is_some() || self.jump_password.is_some() {
tracing::warn!(
"the ssh transport cannot consume passwords on Windows; using the russh transport"
);
true
} else {
self.russh.is_some()
}
}
pub async fn probe(
&mut self,
peer: &RemoteTarget,
jump: Option<&JumpHost>,
) -> Result<Option<(String, String)>> {
#[cfg(not(target_os = "windows"))]
let _ = jump;
match self.transport {
Transport::Ssh => {
#[cfg(target_os = "windows")]
{
if self.forced_to_russh() {
return self.russh_probe(peer, jump).await;
}
}
let auth = self.ssh_auth();
let result = ssh::check_remote_platform(peer, &auth).await;
self.consume_ssh_password();
match result {
Ok(value) => Ok(value),
Err(e) => {
#[cfg(target_os = "windows")]
{
tracing::warn!("system ssh failed ({e}); retrying with the russh transport");
self.russh_probe(peer, jump).await
}
#[cfg(not(target_os = "windows"))]
{
Err(e)
}
}
}
}
#[cfg(target_os = "windows")]
Transport::Russh => self.russh_probe(peer, jump).await,
}
}
pub async fn check_version(
&mut self,
peer: &RemoteTarget,
remote_path: &str,
remote_os: &str,
jump: Option<&JumpHost>,
) -> Result<Option<(String, Option<String>)>> {
#[cfg(not(target_os = "windows"))]
let _ = jump;
match self.transport {
Transport::Ssh => {
#[cfg(target_os = "windows")]
{
if self.forced_to_russh() {
return self.russh_check_version(peer, remote_path, remote_os, jump).await;
}
}
let auth = self.ssh_auth();
let sudo = if self.remote_sudo {
Sudo::NonInteractive
} else {
Sudo::None
};
let result = ssh::check_remote_version(
peer,
remote_path,
remote_os,
&auth,
sudo,
self.sudo_password.as_deref(),
)
.await;
self.consume_ssh_password();
match result {
Ok(probe) => self.apply_version_probe(probe),
Err(e) => {
#[cfg(target_os = "windows")]
{
tracing::warn!("system ssh failed ({e}); retrying with the russh transport");
self.russh_check_version(peer, remote_path, remote_os, jump).await
}
#[cfg(not(target_os = "windows"))]
{
Err(e)
}
}
}
}
#[cfg(target_os = "windows")]
Transport::Russh => self.russh_check_version(peer, remote_path, remote_os, jump).await,
}
}
fn apply_version_probe(
&mut self,
probe: VersionProbe,
) -> Result<Option<(String, Option<String>)>> {
self.sudo_mode = probe.mode;
if probe.sudo_password_required {
return Err(crate::Error::Other(
"sudo on the remote needs a password: pass --sudo-password (or --password, reused for sudo — they are the same login password in practice), or configure a NOPASSWD sudoers rule covering the remote path (e.g. `user ALL=(root) NOPASSWD: <remote-path> *`)"
.to_string(),
));
}
Ok(probe.version)
}
pub async fn probe_and_version(
&mut self,
peer: &RemoteTarget,
remote_path: &str,
jump: Option<&JumpHost>,
) -> Result<(Option<(String, String)>, Option<(String, Option<String>)>)> {
#[cfg(not(target_os = "windows"))]
let _ = jump;
match self.transport {
Transport::Ssh => {
#[cfg(target_os = "windows")]
{
if self.forced_to_russh() {
let platform = self.russh_probe(peer, jump).await?;
let version = self
.russh_check_version(peer, remote_path, "unix", jump)
.await?;
return Ok((platform, version));
}
}
let auth = self.ssh_auth();
let sudo = if self.remote_sudo {
Sudo::NonInteractive
} else {
Sudo::None
};
let result = ssh::check_remote_platform_and_version(
peer,
remote_path,
&auth,
sudo,
self.sudo_password.as_deref(),
)
.await;
self.consume_ssh_password();
match result {
Ok((Some(platform), probe)) => {
let version = self.apply_version_probe(probe)?;
Ok((Some(platform), version))
}
Ok((None, _)) => {
let platform = self.probe(peer, jump).await?;
let version = self.check_version(peer, remote_path, "unix", jump).await?;
Ok((platform, version))
}
Err(e) => Err(e),
}
}
#[cfg(target_os = "windows")]
Transport::Russh => {
let platform = self.russh_probe(peer, jump).await?;
let version = self.russh_check_version(peer, remote_path, "unix", jump).await?;
Ok((platform, version))
}
}
}
pub async fn deploy(
&mut self,
peer: &RemoteTarget,
remote_path: &str,
local_binary: &Path,
remote_os: &str,
jump: Option<&JumpHost>,
) -> Result<()> {
#[cfg(not(target_os = "windows"))]
let _ = jump;
match self.transport {
Transport::Ssh => {
#[cfg(target_os = "windows")]
{
if self.forced_to_russh() {
return self
.russh_deploy(peer, remote_path, local_binary, remote_os, jump)
.await;
}
}
let auth = self.ssh_auth();
let result =
ssh::push_remote_binary(peer, remote_path, local_binary, remote_os, &auth).await;
self.consume_ssh_password();
match result {
Ok(()) => Ok(()),
Err(e) => {
#[cfg(target_os = "windows")]
{
tracing::warn!("system ssh failed ({e}); retrying with the russh transport");
self.russh_deploy(peer, remote_path, local_binary, remote_os, jump).await
}
#[cfg(not(target_os = "windows"))]
{
Err(e)
}
}
}
}
#[cfg(target_os = "windows")]
Transport::Russh => {
self.russh_deploy(peer, remote_path, local_binary, remote_os, jump)
.await
}
}
}
pub async fn open_session(
&mut self,
peer: &RemoteTarget,
remote_path: &str,
remote_os: &str,
server_args: &str,
jump: Option<&JumpHost>,
) -> Result<Session> {
#[cfg(not(target_os = "windows"))]
let _ = jump;
if self.remote_sudo {
if remote_os == "windows" {
tracing::warn!("--remote-sudo is ignored on a Windows remote");
self.sudo_mode = Sudo::None;
} else if self.sudo_mode == Sudo::None {
self.sudo_mode = Sudo::NonInteractive;
}
}
match self.transport {
Transport::Ssh => {
#[cfg(target_os = "windows")]
{
if self.forced_to_russh() {
return self
.russh_session(peer, remote_path, remote_os, server_args, jump)
.await;
}
}
let auth = self.ssh_auth();
let result = ssh_session(
peer,
remote_path,
remote_os,
server_args,
&auth,
self.sudo_mode,
self.sudo_password.as_deref(),
)
.await;
self.consume_ssh_password();
match result {
Ok(session) => Ok(session),
Err(e) => {
#[cfg(target_os = "windows")]
{
tracing::warn!("system ssh failed ({e}); retrying with the russh transport");
self.russh_session(
peer,
remote_path,
remote_os,
server_args,
jump,
)
.await
}
#[cfg(not(target_os = "windows"))]
{
Err(e)
}
}
}
}
#[cfg(target_os = "windows")]
Transport::Russh => {
self.russh_session(peer, remote_path, remote_os, server_args, jump)
.await
}
}
}
pub async fn open_preamble_session(
&mut self,
peer: &RemoteTarget,
remote_path: &str,
server_args: &str,
jump: Option<&JumpHost>,
) -> Result<Option<PreambleSession>> {
#[cfg(not(target_os = "windows"))]
let _ = jump;
if self.remote_sudo || self.password.is_some() || self.jump_password.is_some() {
return Ok(None);
}
match self.transport {
Transport::Ssh => {
let auth = self.ssh_auth();
let spawned = ssh::spawn_ssh_preamble(peer, remote_path, server_args, &auth);
self.consume_ssh_password();
let ssh = match spawned {
Ok(ssh) => ssh,
Err(e) => return Err(e),
};
let ssh::SshChild {
mut child,
stdin,
stdout,
} = ssh;
match ssh::read_preamble_platform(stdout).await {
Ok(Some((os, arch, reader))) => Ok(Some(PreambleSession {
os,
arch,
session: Session {
send: Box::new(stdin),
recv: Box::new(reader),
handle: SessionHandle::Ssh(child),
},
})),
Ok(None) => {
let _ = child.kill().await;
Ok(None)
}
Err(e) => Err(e.into()),
}
}
#[cfg(target_os = "windows")]
Transport::Russh => {
let connection = self.ensure_russh(peer, jump).await?;
match russh::open_preamble_on(&connection.handle, remote_path, server_args).await {
Ok(Some((os, arch, send, recv, session))) => Ok(Some(PreambleSession {
os,
arch,
session: Session {
send,
recv,
handle: SessionHandle::Russh(session),
},
})),
Ok(None) => Ok(None),
Err(e) => Err(Error::Other(format!("russh transport: {e}"))),
}
}
}
}
pub async fn deploy_and_open_session(
&mut self,
peer: &RemoteTarget,
remote_path: &str,
server_args: &str,
local_binary: &Path,
jump: Option<&JumpHost>,
) -> Result<Session> {
#[cfg(not(target_os = "windows"))]
let _ = jump;
match self.transport {
Transport::Ssh => {
let auth = self.ssh_auth();
let spawned = ssh::push_remote_binary_and_serve(
peer,
remote_path,
server_args,
local_binary,
&auth,
)
.await;
self.consume_ssh_password();
let (child, stdin, stdout) = match spawned {
Ok(parts) => parts,
Err(e) => return Err(e),
};
Ok(Session {
send: Box::new(stdin),
recv: Box::new(stdout),
handle: SessionHandle::Ssh(child),
})
}
#[cfg(target_os = "windows")]
Transport::Russh => {
let connection = self.ensure_russh(peer, jump).await?;
match russh::deploy_and_serve_on(&connection.handle, remote_path, server_args, local_binary)
.await
{
Ok((send, recv, session)) => Ok(Session {
send,
recv,
handle: SessionHandle::Russh(session),
}),
Err(e) => Err(Error::Other(format!("russh transport: {e}"))),
}
}
}
}
#[cfg(target_os = "windows")]
async fn ensure_russh(
&mut self,
peer: &RemoteTarget,
jump: Option<&JumpHost>,
) -> Result<&russh::RusshConnection> {
if let Some(message) = &self.russh_err {
return Err(Error::Other(message.clone()));
}
if self.russh.is_none() {
match russh::connect(peer, jump, self.password.take(), self.jump_password.take()).await {
Ok(connection) => self.russh = Some(connection),
Err(e) => {
let message = format!("russh transport: {e}");
self.russh_err = Some(message.clone());
return Err(Error::Other(message));
}
}
}
Ok(self.russh.as_ref().expect("connection set above"))
}
#[cfg(target_os = "windows")]
async fn russh_probe(
&mut self,
peer: &RemoteTarget,
jump: Option<&JumpHost>,
) -> Result<Option<(String, String)>> {
let connection = self.ensure_russh(peer, jump).await?;
russh::probe_on(&connection.handle).await.map_err(map_russh)
}
#[cfg(target_os = "windows")]
async fn russh_check_version(
&mut self,
peer: &RemoteTarget,
remote_path: &str,
remote_os: &str,
jump: Option<&JumpHost>,
) -> Result<Option<(String, Option<String>)>> {
let sudo = if self.remote_sudo {
Sudo::NonInteractive
} else {
Sudo::None
};
let sudo_password = self.sudo_password.clone();
let connection = self.ensure_russh(peer, jump).await?;
let probe = russh::check_version_on(
&connection.handle,
remote_path,
remote_os,
sudo,
sudo_password.as_deref(),
)
.await
.map_err(map_russh)?;
self.apply_version_probe(VersionProbe {
version: probe,
sudo_password_required: false,
mode: sudo,
})
}
#[cfg(target_os = "windows")]
async fn russh_deploy(
&mut self,
peer: &RemoteTarget,
remote_path: &str,
local_binary: &Path,
remote_os: &str,
jump: Option<&JumpHost>,
) -> Result<()> {
let connection = self.ensure_russh(peer, jump).await?;
russh::deploy_on(&connection.handle, remote_path, local_binary, remote_os)
.await
.map_err(map_russh)
}
#[cfg(target_os = "windows")]
async fn russh_session(
&mut self,
peer: &RemoteTarget,
remote_path: &str,
remote_os: &str,
server_args: &str,
jump: Option<&JumpHost>,
) -> Result<Session> {
let sudo_mode = self.sudo_mode;
let sudo_password = self.sudo_password.clone();
let connection = self.ensure_russh(peer, jump).await?;
let (send, recv, session) = russh::open_session_on(
&connection.handle,
remote_path,
remote_os,
server_args,
sudo_mode,
sudo_password.as_deref(),
)
.await
.map_err(map_russh)?;
Ok(Session {
send,
recv,
handle: SessionHandle::Russh(session),
})
}
}
async fn ssh_session(
peer: &RemoteTarget,
remote_path: &str,
remote_os: &str,
server_args: &str,
auth: &ssh::SshAuth<'_>,
sudo: Sudo,
sudo_password: Option<&str>,
) -> Result<Session> {
let ssh = ssh::spawn_ssh(
peer,
remote_path,
remote_os,
server_args,
auth,
sudo,
sudo_password,
)
.await?;
let (send, recv, child) = ssh.into_parts();
Ok(Session {
send,
recv,
handle: SessionHandle::Ssh(child),
})
}
#[cfg(target_os = "windows")]
#[expect(clippy::needless_pass_by_value, reason = "map_err passes the error by value")]
fn map_russh(e: anyhow::Error) -> Error {
Error::Other(format!("russh transport: {e}"))
}
pub struct Session {
send: Box<dyn AsyncWrite + Unpin + Send>,
recv: Box<dyn AsyncRead + Unpin + Send>,
handle: SessionHandle,
}
impl Session {
#[must_use]
pub fn into_parts(
self,
) -> (
Box<dyn AsyncWrite + Unpin + Send>,
Box<dyn AsyncRead + Unpin + Send>,
SessionHandle,
) {
(self.send, self.recv, self.handle)
}
}
pub struct PreambleSession {
pub os: String,
pub arch: String,
pub session: Session,
}
#[allow(clippy::large_enum_variant)]
pub enum SessionHandle {
Ssh(tokio::process::Child),
#[cfg(target_os = "windows")]
Russh(russh::RusshSession),
}
impl SessionHandle {
pub(crate) async fn child_exited_nonzero(&mut self) -> bool {
match self {
Self::Ssh(child) => {
matches!(
tokio::time::timeout(std::time::Duration::from_secs(2), child.wait()).await,
Ok(Ok(status)) if !status.success()
)
}
#[cfg(target_os = "windows")]
Self::Russh(_) => false,
}
}
pub async fn finish<T>(&mut self, result: anyhow::Result<T>) -> anyhow::Result<T> {
match self {
Self::Ssh(child) => {
let result = result?;
let status = tokio::time::timeout(
std::time::Duration::from_secs(30),
child.wait(),
)
.await
.map_err(|_| anyhow::anyhow!("timed out waiting for the ssh process to exit"))?
.map_err(|e| anyhow::anyhow!("failed to wait for the ssh process: {e}"))?;
if !status.success() {
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
if let Some(signal) = status.signal() {
bail!("ssh exited with signal: {signal}");
}
}
bail!("ssh exited with status: {}", status.code().unwrap_or(-1));
}
Ok(result)
}
#[cfg(target_os = "windows")]
Self::Russh(session) => session.finish(result).await,
}
}
pub async fn finish_after_local_cancel<T>(
&mut self,
result: anyhow::Result<T>,
) -> anyhow::Result<T> {
match self {
Self::Ssh(child) => {
let result = result?;
let _ = tokio::time::timeout(std::time::Duration::from_secs(30), child.wait()).await;
Ok(result)
}
#[cfg(target_os = "windows")]
Self::Russh(session) => session.finish(result).await,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn jump_host_parse_forms() {
let jh = JumpHost::parse("alice@bastion.example.com").unwrap();
assert_eq!(jh.user, "alice");
assert_eq!(jh.host, "bastion.example.com");
assert_eq!(jh.port, 22);
let jh = JumpHost::parse("alice@bastion.example.com:2222").unwrap();
assert_eq!(jh.user, "alice");
assert_eq!(jh.host, "bastion.example.com");
assert_eq!(jh.port, 2222);
assert!(JumpHost::parse("bastion.example.com").is_err());
assert!(JumpHost::parse("@bastion.example.com").is_err());
assert!(JumpHost::parse("alice@").is_err());
}
#[test]
fn jump_host_parse_ipv6() {
let jh = JumpHost::parse("alice@[::1]:2222").unwrap();
assert_eq!(jh.user, "alice");
assert_eq!(jh.host, "::1");
assert_eq!(jh.port, 2222);
let jh = JumpHost::parse("alice@[::1]").unwrap();
assert_eq!(jh.host, "::1");
assert_eq!(jh.port, 22);
assert!(JumpHost::parse("alice@::1").is_err());
}
#[test]
fn jump_host_parse_rejects_bad_ports() {
assert!(JumpHost::parse("alice@host:0").is_err());
assert!(JumpHost::parse("alice@host:").is_err());
assert!(JumpHost::parse("alice@host:abc").is_err());
assert!(JumpHost::parse("alice@host:99999").is_err());
assert!(JumpHost::parse("alice@[::1]:").is_err());
assert!(JumpHost::parse("alice@[::1]:0").is_err());
}
}