use std::path::{Path, PathBuf};
use crate::Result;
use crate::error::{Error, TimedOut};
use crate::process::{Captured, ProcessError, ProcessRunner, ProcessSpec};
const KEY_FILE: &str = "id_ed25519";
const KEYGEN_LIMIT: std::time::Duration = std::time::Duration::from_secs(60);
const KEY_LOCK: &str = "ssh-key.lock";
const KEY_STEP: &str = "ssh-key";
pub(crate) const KNOWN_HOSTS: &str = "known_hosts";
const KEYSCAN_LIMIT: std::time::Duration = std::time::Duration::from_secs(30);
const PIN_STEP: &str = "host-key";
pub(crate) fn dir(home: &Path) -> PathBuf {
home.join("ssh")
}
pub(crate) fn key_path(home: &Path) -> PathBuf {
dir(home).join(KEY_FILE)
}
pub(crate) fn public_key(home: &Path) -> Result<Option<String>> {
let path = key_path(home).with_extension("pub");
let text = crate::store::if_there(std::fs::read_to_string(&path)).map_err(Error::io(&path, "read"))?;
Ok(text.map(|t| t.trim().to_owned()).filter(|k| !k.is_empty()))
}
pub(crate) async fn ensure_key(processes: &dyn ProcessRunner, home: &Path) -> Result<String> {
if let Some(key) = public_key(home)? {
return Ok(key);
}
let failed = |reason: String| Error::ToolFailed { step: KEY_STEP.into(), reason };
let lock = home.join(KEY_LOCK);
let wait = KEYGEN_LIMIT * 2;
let Some(_making) = crate::store::hold(&lock, wait).await.map_err(Error::io(&lock, "locked"))? else {
return Err(failed(format!(
"another operation has been making the runner's SSH key for {} s",
wait.as_secs()
)));
};
if let Some(key) = public_key(home)? {
return Ok(key);
}
let dir = dir(home);
crate::store::create_dir(&dir)?;
let path = key_path(home);
if let Some(key) = public_half_again(processes, &path).await? {
return Ok(key);
}
let spec = ProcessSpec::new(
"ssh-keygen",
["-q", "-t", "ed25519", "-N", "", "-C", "isothrum", "-f"]
.map(String::from)
.into_iter()
.chain([path.display().to_string()]),
);
let out = keygen(processes, &spec).await?;
if !out.success() {
return Err(failed(out.reason()));
}
public_key(home)?.ok_or_else(|| failed("ssh-keygen wrote no public key".into()))
}
async fn public_half_again(processes: &dyn ProcessRunner, path: &Path) -> Result<Option<String>> {
if !path.is_file() {
return Ok(None);
}
let derive = ProcessSpec::new("ssh-keygen", ["-y".to_owned(), "-f".to_owned(), path.display().to_string()]);
let out = keygen(processes, &derive).await?;
let derived = out.stdout.iter().map(|l| l.trim()).find(|l| l.starts_with("ssh-ed25519 "));
if let (true, Some(key)) = (out.success(), derived) {
let key = if key.split_whitespace().count() < 3 {
format!("{key} isothrum")
} else {
key.to_owned()
};
crate::store::write(&path.with_extension("pub"), format!("{key}\n").as_bytes())?;
tracing::warn!(path = %path.display(), "the runner's SSH key had lost its public half: derived from the private one again");
return Ok(Some(key));
}
let aside = path.with_extension("unusable");
tracing::warn!(path = %path.display(), reason = %out.reason(), "the runner's SSH key can't be read: it is set aside and a new one made");
std::fs::rename(path, &aside).map_err(Error::io(path, "set aside"))?;
crate::store::remove(&path.with_extension("pub"))?;
Ok(None)
}
async fn keygen(processes: &dyn ProcessRunner, spec: &ProcessSpec) -> Result<Captured> {
match tokio::time::timeout(KEYGEN_LIMIT, crate::process::capture(processes, spec)).await {
Err(_) => Err(Error::Timeout {
step: KEY_STEP.into(),
timed_out: TimedOut::Ceiling {
after_s: KEYGEN_LIMIT.as_secs(),
last_line: None,
},
}),
Ok(Err(ProcessError::Missing { .. })) => Err(Error::ToolMissing {
step: KEY_STEP.into(),
tool: "ssh-keygen".into(),
}),
Ok(Err(e)) => Err(Error::ToolFailed {
step: KEY_STEP.into(),
reason: e.to_string(),
}),
Ok(Ok(out)) => Ok(out),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Login {
pub(crate) user: String,
pub(crate) host: String,
}
impl Login {
pub(crate) fn new(user: &str, host: &str) -> Option<Login> {
let plain = |word: &str, extra: &str| {
!word.is_empty() && !word.starts_with('-') && word.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c) || extra.contains(c))
};
(plain(user, "") && plain(host, ":")).then(|| Login {
user: user.to_owned(),
host: host.to_owned(),
})
}
pub(crate) fn target(&self) -> String {
format!("{}@{}", self.user, self.host)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum First<'a> {
Pinned,
Given(&'a Path),
}
impl<'a> First<'a> {
pub(crate) fn given(file: Option<&'a Path>) -> First<'a> {
file.map_or(First::Pinned, First::Given)
}
}
pub(crate) fn options(key: &Path, state_dir: &Path, first: First<'_>) -> Result<Vec<String>> {
checked_options(key, state_dir, HostKey::first(first))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HostKey<'a> {
Pinned,
FirstMet,
Given(&'a Path),
}
impl<'a> HostKey<'a> {
fn first(first: First<'a>) -> HostKey<'a> {
match first {
First::Pinned => HostKey::Pinned,
First::Given(file) => HostKey::Given(file),
}
}
}
fn checked_options(key: &Path, state_dir: &Path, checking: HostKey<'_>) -> Result<Vec<String>> {
let (known, whose) = match checking {
HostKey::Given(file) => (file.to_path_buf(), "the host's known_hosts file"),
HostKey::Pinned | HostKey::FirstMet => (state_dir.join(KNOWN_HOSTS), "the run's folder"),
};
let quoted = config_path(&known.to_string_lossy(), PathStyle::HERE).ok_or_else(|| {
let why = format!("{whose} is at a path SSH's options can't name (it holds `\"`, `\\` outside Windows, `${{` or a control character)");
Error::io(&known, "named")(std::io::Error::new(std::io::ErrorKind::InvalidInput, why))
})?;
let mut args = vec!["-F".to_owned(), "none".to_owned(), "-i".to_owned(), key.display().to_string()];
for option in [
"IdentitiesOnly=yes".to_owned(),
format!("UserKnownHostsFile={quoted}"),
"GlobalKnownHostsFile=none".to_owned(),
match checking {
HostKey::Pinned | HostKey::Given(_) => "StrictHostKeyChecking=yes".to_owned(),
HostKey::FirstMet => "StrictHostKeyChecking=accept-new".to_owned(),
},
"BatchMode=yes".to_owned(),
"ConnectTimeout=10".to_owned(),
"ServerAliveInterval=15".to_owned(),
"ServerAliveCountMax=3".to_owned(),
"LogLevel=ERROR".to_owned(),
] {
args.extend(["-o".to_owned(), option]);
}
if matches!(checking, HostKey::Given(_)) {
args.extend(["-o".to_owned(), "UpdateHostKeys=no".to_owned()]);
}
Ok(args)
}
pub(crate) fn options_through(key: &Path, state_dir: &Path, hops: &[Login], first: First<'_>) -> Result<Vec<String>> {
let checking = if hops.is_empty() { HostKey::first(first) } else { HostKey::FirstMet };
let mut args = checked_options(key, state_dir, checking)?;
if let Some(proxy) = proxy_command(key, state_dir, hops, first, PathStyle::HERE)? {
args.extend(["-o".to_owned(), format!("ProxyCommand={proxy}")]);
}
Ok(args)
}
fn proxy_command(key: &Path, state_dir: &Path, hops: &[Login], first: First<'_>, style: PathStyle) -> Result<Option<String>> {
let Some((last, before)) = hops.split_last() else {
return Ok(None);
};
let checking = if before.is_empty() { HostKey::first(first) } else { HostKey::FirstMet };
let mut words = vec!["ssh".to_owned()];
words.extend(checked_options(key, state_dir, checking)?);
if let Some(inner) = proxy_command(key, state_dir, before, first, style)? {
words.extend(["-o".to_owned(), format!("ProxyCommand={inner}")]);
}
let line = words.iter().map(|w| command_word(w, style)).collect::<Vec<_>>().join(" ");
Ok(Some(format!("{} -W %h:%p {}", line.replace('%', "%%"), last.target())))
}
fn command_word(word: &str, style: PathStyle) -> String {
let plain = !word.is_empty() && word.chars().all(|c| c.is_ascii_alphanumeric() || "_-.,/:@%+=".contains(c));
match (style, plain) {
(_, true) => word.to_owned(),
(PathStyle::Unix, false) => crate::console::sh_quote(word),
(PathStyle::Windows, false) => windows_quote(word),
}
}
fn windows_quote(word: &str) -> String {
let mut out = String::from("\"");
let mut backslashes = 0;
for c in word.chars() {
if c == '"' {
out.extend(std::iter::repeat_n('\\', backslashes + 1));
}
backslashes = if c == '\\' { backslashes + 1 } else { 0 };
out.push(c);
}
out.extend(std::iter::repeat_n('\\', backslashes));
out.push('"');
out
}
fn config_path(path: &str, style: PathStyle) -> Option<String> {
let path = match style {
PathStyle::Windows => path.replace('\\', "/"),
PathStyle::Unix => path.to_owned(),
};
if path.contains(['"', '\\']) || path.contains("${") || path.chars().any(char::is_control) {
return None;
}
Some(format!("\"{}\"", path.replace('%', "%%")))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PathStyle {
Unix,
Windows,
}
impl PathStyle {
const HERE: PathStyle = if cfg!(windows) { PathStyle::Windows } else { PathStyle::Unix };
}
fn pins(known_hosts: &str, host: &str) -> bool {
known_hosts
.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.filter_map(|l| l.split_whitespace().next())
.any(|hosts| hosts.split(',').any(|h| h == host))
}
async fn pin(processes: &dyn ProcessRunner, state_dir: &Path, host: &str) -> Result<()> {
let path = state_dir.join(KNOWN_HOSTS);
let known = crate::store::if_there(std::fs::read_to_string(&path))
.map_err(Error::io(&path, "read"))?
.unwrap_or_default();
if pins(&known, host) {
return Ok(());
}
let failed = |reason: String| Error::ToolFailed { step: PIN_STEP.into(), reason };
let spec = ProcessSpec::new("ssh-keyscan", ["-T".to_owned(), "10".to_owned(), host.to_owned()]);
let out = match tokio::time::timeout(KEYSCAN_LIMIT, crate::process::capture(processes, &spec)).await {
Err(_) => {
return Err(Error::Timeout {
step: PIN_STEP.into(),
timed_out: TimedOut::Ceiling {
after_s: KEYSCAN_LIMIT.as_secs(),
last_line: None,
},
});
}
Ok(Err(ProcessError::Missing { .. })) => {
return Err(Error::ToolMissing {
step: PIN_STEP.into(),
tool: "ssh-keyscan".into(),
});
}
Ok(Err(e)) => return Err(failed(e.to_string())),
Ok(Ok(out)) => out,
};
let keys: Vec<&str> = out
.stdout
.iter()
.map(|l| l.trim())
.filter(|l| !l.starts_with('#') && l.split_whitespace().count() >= 3 && pins(l, host))
.collect();
if keys.is_empty() {
return Err(failed(format!("`ssh-keyscan` read no SSH host key of {host}: {}", out.reason())));
}
let mut text = known;
if !text.is_empty() && !text.ends_with('\n') {
text.push('\n');
}
for key in keys {
text.push_str(key);
text.push('\n');
}
crate::store::create_dir(state_dir)?;
crate::store::write(&path, text.as_bytes())?;
tracing::info!(host, "pinned the SSH host keys of a machine of the run, first met");
Ok(())
}
pub(crate) async fn ready(processes: &dyn ProcessRunner, state_dir: &Path, host: &str, first: First<'_>) -> Result<()> {
match first {
First::Pinned => pin(processes, state_dir, host).await,
First::Given(file) if file.is_file() => Ok(()),
First::Given(file) => Err(Error::ToolFailed {
step: PIN_STEP.into(),
reason: format!("the known_hosts file given for {host}, {}, isn't there", file.display()),
}),
}
}
pub(crate) fn forget(state_dir: &Path) -> Result<()> {
crate::store::remove(&state_dir.join(KNOWN_HOSTS))
}
#[cfg(test)]
mod tests;