use std::path::{Path, PathBuf};
use std::time::Duration;
use isothrum_runner::ProcessSpec;
use crate::Context;
use crate::exec::Unanswered;
pub mod known_hosts;
const KEYGEN_LIMIT: Duration = Duration::from_secs(60);
const CONNECT_TIMEOUT_S: u32 = 10;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum SshError {
#[error("unexpected SSH {0}")]
Invalid(&'static str),
#[error("{0}")]
Unanswered(String),
#[error("the SSH host key of {host} isn't one confirmed for it")]
HostKeyRefused {
host: String,
},
#[error("{0}")]
Failed(String),
#[error("{0}")]
Io(String),
}
impl From<Unanswered> for SshError {
fn from(e: Unanswered) -> SshError {
SshError::Unanswered(e.to_string())
}
}
impl From<std::io::Error> for SshError {
fn from(e: std::io::Error) -> SshError {
SshError::Io(e.to_string())
}
}
pub async fn ensure_key(ctx: &Context, path: &Path, comment: &str) -> Result<String, SshError> {
if !path.is_file() {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let file = path.to_string_lossy();
let spec = ProcessSpec::new("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", comment, "-f", &file]);
let made = ctx.probe_within(KEYGEN_LIMIT, &spec).await?;
made.output().map_err(|f| SshError::Failed(f.to_string()))?;
}
Ok(std::fs::read_to_string(public_half(path))?.trim().to_owned())
}
#[must_use]
pub fn public_half(path: &Path) -> PathBuf {
let mut name = path.as_os_str().to_owned();
name.push(".pub");
PathBuf::from(name)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Target {
pub host: String,
pub port: u16,
pub user: String,
pub identity: PathBuf,
pub known_hosts: PathBuf,
pub password: Option<Password>,
}
#[derive(Clone, PartialEq, Eq)]
pub struct Password {
pub secret: String,
pub askpass_dir: PathBuf,
}
impl std::fmt::Debug for Password {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Password").field("askpass_dir", &self.askpass_dir).finish_non_exhaustive()
}
}
const PASSWORD_VAR: &str = "ISOTHRUM_SSH_PASSWORD";
fn askpass_script(windows: bool) -> (&'static str, &'static str) {
if windows {
(
"askpass.cmd",
"@echo off\r\nsetlocal EnableDelayedExpansion\r\necho(!ISOTHRUM_SSH_PASSWORD!\r\n",
)
} else {
("askpass.sh", "#!/bin/sh\nprintf '%s\\n' \"$ISOTHRUM_SSH_PASSWORD\"\n")
}
}
fn write_askpass(dir: &Path) -> std::io::Result<PathBuf> {
let (name, script) = askpass_script(cfg!(windows));
std::fs::create_dir_all(dir)?;
let path = dir.join(name);
std::fs::write(&path, script)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700))?;
}
Ok(path)
}
pub(crate) fn safe_token(s: &str) -> bool {
!s.is_empty() && s.len() <= 253 && !s.starts_with('-') && s.chars().all(|c| c.is_ascii_alphanumeric() || ".-_:".contains(c))
}
#[must_use]
pub fn sh_quote(s: &str) -> String {
format!("'{}'", s.replace('\'', r"'\''"))
}
#[must_use]
pub fn config_path(path: &str) -> String {
let mut out = String::with_capacity(path.len());
for c in path.chars() {
match c {
'\\' | '"' | '\'' | ' ' => {
out.push('\\');
out.push(c);
}
'%' => out.push_str("%%"),
_ => out.push(c),
}
}
out
}
#[must_use]
pub fn batch_options(known_hosts: &Path) -> Vec<String> {
vec![
"BatchMode=yes".to_owned(),
format!("ConnectTimeout={CONNECT_TIMEOUT_S}"),
"ServerAliveInterval=15".to_owned(),
"ServerAliveCountMax=3".to_owned(),
"StrictHostKeyChecking=yes".to_owned(),
format!("UserKnownHostsFile={}", config_path(&known_hosts.to_string_lossy())),
"LogLevel=ERROR".to_owned(),
]
}
impl Target {
#[must_use]
pub fn new(host: impl Into<String>, user: impl Into<String>, identity: PathBuf, known_hosts: PathBuf) -> Target {
Target {
host: host.into(),
port: 22,
user: user.into(),
identity,
known_hosts,
password: None,
}
}
#[must_use]
pub fn with_password(self, secret: impl Into<String>, askpass_dir: PathBuf) -> Target {
Target {
password: Some(Password {
secret: secret.into(),
askpass_dir,
}),
..self
}
}
#[must_use]
pub fn on_port(self, port: u16) -> Target {
Target { port, ..self }
}
pub fn exec_args(&self, command: &str) -> Result<Vec<String>, SshError> {
if !safe_token(&self.host) {
return Err(SshError::Invalid("host"));
}
if !safe_token(&self.user) {
return Err(SshError::Invalid("user"));
}
let mut args = vec!["-p".to_owned(), self.port.to_string()];
let options = if self.password.is_some() {
let mut options = vec![
"PreferredAuthentications=password,keyboard-interactive".to_owned(),
"NumberOfPasswordPrompts=1".to_owned(),
];
options.extend(batch_options(&self.known_hosts).into_iter().filter(|o| o != "BatchMode=yes"));
options
} else {
args.splice(0..0, ["-i".to_owned(), self.identity.to_string_lossy().into_owned()]);
batch_options(&self.known_hosts)
};
for option in options {
args.extend(["-o".to_owned(), option]);
}
args.extend(["--".to_owned(), format!("{}@{}", self.user, self.host), command.to_owned()]);
Ok(args)
}
pub async fn exec(&self, ctx: &Context, command: &str, limit: Duration) -> Result<String, SshError> {
let mut spec = ProcessSpec::new("ssh", self.exec_args(command)?);
if let Some(password) = &self.password {
let askpass = write_askpass(&password.askpass_dir)?;
spec.env.extend([
("SSH_ASKPASS".to_owned(), askpass.to_string_lossy().into_owned()),
("SSH_ASKPASS_REQUIRE".to_owned(), "force".to_owned()),
("DISPLAY".to_owned(), ":0".to_owned()),
(PASSWORD_VAR.to_owned(), password.secret.clone()),
]);
}
let captured = ctx.probe_within(limit, &spec).await?;
if !captured.success() && captured.stderr_tail.iter().any(|l| l.contains("Host key verification failed")) {
return Err(SshError::HostKeyRefused { host: self.host.clone() });
}
captured.output().map_err(|f| SshError::Failed(f.to_string()))
}
}
#[cfg(test)]
mod tests;