Skip to main content

isothrum_machine/place/
ssh.rs

1//! SSH to a server's own system (a Proxmox VE node, say): with a key the caller keeps at a path
2//! it chooses ([`ensure_key`]), the server's host keys trusted on first use ([`known_hosts`]) and
3//! checked strictly from then on. Every `ssh`, `ssh-keygen` and `ssh-keyscan` runs through the
4//! context's [`ProcessRunner`](isothrum_runner::ProcessRunner).
5//!
6//! Which keys a user is shown and how they confirm them is the caller's: [`known_hosts::offered`]
7//! reads what a server offers, [`known_hosts::confirm`] writes the ones confirmed.
8
9use std::path::{Path, PathBuf};
10use std::time::Duration;
11
12use isothrum_runner::ProcessSpec;
13
14use crate::Context;
15use crate::exec::Unanswered;
16
17pub mod known_hosts;
18
19/// How long making a key may take.
20const KEYGEN_LIMIT: Duration = Duration::from_secs(60);
21
22/// How long an unattended `ssh` may wait for its connection.
23const CONNECT_TIMEOUT_S: u32 = 10;
24
25/// Why an SSH step failed.
26#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
27#[non_exhaustive]
28pub enum SshError {
29    /// A host, user or path that isn't put on a command line (`-o…`, `a;b`, a space).
30    #[error("unexpected SSH {0}")]
31    Invalid(&'static str),
32    /// The tool couldn't be started (OpenSSH not installed), or ran out of time: why.
33    #[error("{0}")]
34    Unanswered(String),
35    /// The server's host key isn't one confirmed for it (none yet, or another): nothing was sent.
36    #[error("the SSH host key of {host} isn't one confirmed for it")]
37    HostKeyRefused {
38        /// The host asked.
39        host: String,
40    },
41    /// The tool ran and failed: the runner's wording of it.
42    #[error("{0}")]
43    Failed(String),
44    /// A file couldn't be read or written: why.
45    #[error("{0}")]
46    Io(String),
47}
48
49impl From<Unanswered> for SshError {
50    fn from(e: Unanswered) -> SshError {
51        SshError::Unanswered(e.to_string())
52    }
53}
54
55impl From<std::io::Error> for SshError {
56    fn from(e: std::io::Error) -> SshError {
57        SshError::Io(e.to_string())
58    }
59}
60
61/// The key at `path`, made when there is none (`ssh-keygen -t ed25519`, no passphrase, `comment`
62/// as its comment), and its public half, one line. A key already there is kept as it is: servers
63/// that trust it keep working.
64///
65/// # Errors
66///
67/// `ssh-keygen` couldn't be run or failed, or the public half can't be read.
68pub async fn ensure_key(ctx: &Context, path: &Path, comment: &str) -> Result<String, SshError> {
69    if !path.is_file() {
70        if let Some(dir) = path.parent() {
71            std::fs::create_dir_all(dir)?;
72        }
73        let file = path.to_string_lossy();
74        let spec = ProcessSpec::new("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", comment, "-f", &file]);
75        let made = ctx.probe_within(KEYGEN_LIMIT, &spec).await?;
76        made.output().map_err(|f| SshError::Failed(f.to_string()))?;
77    }
78    Ok(std::fs::read_to_string(public_half(path))?.trim().to_owned())
79}
80
81/// Where the public half of the key at `path` is (`<path>.pub`).
82#[must_use]
83pub fn public_half(path: &Path) -> PathBuf {
84    let mut name = path.as_os_str().to_owned();
85    name.push(".pub");
86    PathBuf::from(name)
87}
88
89/// Where to SSH, and as whom.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct Target {
92    /// The address to connect to.
93    pub host: String,
94    /// Its SSH port.
95    pub port: u16,
96    /// The user to sign in as.
97    pub user: String,
98    /// The private key to sign in with.
99    pub identity: PathBuf,
100    /// The host keys confirmed for it ([`known_hosts`]): the only ones accepted.
101    pub known_hosts: PathBuf,
102    /// A password to sign in with instead of the key, answered once to ssh's prompt
103    /// ([`Target::with_password`]); none to sign in with the key.
104    pub password: Option<Password>,
105}
106
107/// A password ssh is answered with, through its askpass hook: a script written into `askpass_dir`
108/// (the caller's own folder, never a shared temporary one) that prints the password ssh is given
109/// in its environment. Never shown by `Debug`.
110#[derive(Clone, PartialEq, Eq)]
111pub struct Password {
112    /// The password.
113    pub secret: String,
114    /// The folder the askpass script is written to.
115    pub askpass_dir: PathBuf,
116}
117
118impl std::fmt::Debug for Password {
119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        f.debug_struct("Password").field("askpass_dir", &self.askpass_dir).finish_non_exhaustive()
121    }
122}
123
124/// The variable the askpass script reads the password from.
125const PASSWORD_VAR: &str = "ISOTHRUM_SSH_PASSWORD";
126
127/// The askpass script's file name and contents for this computer's ssh: a `sh` script, or on
128/// Windows (whose OpenSSH can't run one) a `.cmd` printing the password after the line is parsed
129/// (delayed expansion), so `&`, `|` or `%` in it are printed, not run.
130fn askpass_script(windows: bool) -> (&'static str, &'static str) {
131    if windows {
132        (
133            "askpass.cmd",
134            "@echo off\r\nsetlocal EnableDelayedExpansion\r\necho(!ISOTHRUM_SSH_PASSWORD!\r\n",
135        )
136    } else {
137        ("askpass.sh", "#!/bin/sh\nprintf '%s\\n' \"$ISOTHRUM_SSH_PASSWORD\"\n")
138    }
139}
140
141/// Writes the askpass script into `dir`, runnable by its owner only (on unix), and returns its path.
142fn write_askpass(dir: &Path) -> std::io::Result<PathBuf> {
143    let (name, script) = askpass_script(cfg!(windows));
144    std::fs::create_dir_all(dir)?;
145    let path = dir.join(name);
146    std::fs::write(&path, script)?;
147    #[cfg(unix)]
148    {
149        use std::os::unix::fs::PermissionsExt as _;
150        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700))?;
151    }
152    Ok(path)
153}
154
155/// A user or host put on a command line: plain characters only, never an option.
156pub(crate) fn safe_token(s: &str) -> bool {
157    !s.is_empty() && s.len() <= 253 && !s.starts_with('-') && s.chars().all(|c| c.is_ascii_alphanumeric() || ".-_:".contains(c))
158}
159
160/// `s` single-quoted for a POSIX shell (the remote command's).
161#[must_use]
162pub fn sh_quote(s: &str) -> String {
163    format!("'{}'", s.replace('\'', r"'\''"))
164}
165
166/// A path as the value of an ssh `-o Key=value` option. OpenSSH splits option values into words
167/// (on whitespace, honouring quotes and backslash escapes) and expands `%` tokens in file paths:
168/// unescaped, a path with a space (`~/Library/Application Support/…`) became two files. Escaped
169/// here so ssh reads the path back verbatim (a tab can't be escaped this way).
170#[must_use]
171pub fn config_path(path: &str) -> String {
172    let mut out = String::with_capacity(path.len());
173    for c in path.chars() {
174        match c {
175            '\\' | '"' | '\'' | ' ' => {
176                out.push('\\');
177                out.push(c);
178            }
179            '%' => out.push_str("%%"),
180            _ => out.push(c),
181        }
182    }
183    out
184}
185
186/// The `-o` values of an SSH that runs unattended: only the host keys in `known_hosts` are
187/// accepted (a host with none or another is refused, never pinned silently), no prompt, a short
188/// connect timeout, and keepalives, so a server that stops answering mid-command ends it in under
189/// a minute.
190#[must_use]
191pub fn batch_options(known_hosts: &Path) -> Vec<String> {
192    vec![
193        "BatchMode=yes".to_owned(),
194        format!("ConnectTimeout={CONNECT_TIMEOUT_S}"),
195        "ServerAliveInterval=15".to_owned(),
196        "ServerAliveCountMax=3".to_owned(),
197        "StrictHostKeyChecking=yes".to_owned(),
198        format!("UserKnownHostsFile={}", config_path(&known_hosts.to_string_lossy())),
199        "LogLevel=ERROR".to_owned(),
200    ]
201}
202
203impl Target {
204    /// `user@host` on port 22, signed in with `identity`, its host keys checked against
205    /// `known_hosts`.
206    #[must_use]
207    pub fn new(host: impl Into<String>, user: impl Into<String>, identity: PathBuf, known_hosts: PathBuf) -> Target {
208        Target {
209            host: host.into(),
210            port: 22,
211            user: user.into(),
212            identity,
213            known_hosts,
214            password: None,
215        }
216    }
217
218    /// The same, signing in with `secret` rather than the key, ssh's prompt answered by a script
219    /// written into `askpass_dir`.
220    #[must_use]
221    pub fn with_password(self, secret: impl Into<String>, askpass_dir: PathBuf) -> Target {
222        Target {
223            password: Some(Password {
224                secret: secret.into(),
225                askpass_dir,
226            }),
227            ..self
228        }
229    }
230
231    /// The same on `port`.
232    #[must_use]
233    pub fn on_port(self, port: u16) -> Target {
234        Target { port, ..self }
235    }
236
237    /// The `ssh` arguments that run `command` on it (no local shell in between).
238    ///
239    /// # Errors
240    ///
241    /// [`SshError::Invalid`] for a host or user that isn't a plain word.
242    pub fn exec_args(&self, command: &str) -> Result<Vec<String>, SshError> {
243        if !safe_token(&self.host) {
244            return Err(SshError::Invalid("host"));
245        }
246        if !safe_token(&self.user) {
247            return Err(SshError::Invalid("user"));
248        }
249        let mut args = vec!["-p".to_owned(), self.port.to_string()];
250        let options = if self.password.is_some() {
251            // A password is asked through askpass, which batch mode turns off: only the password
252            // is tried, once.
253            let mut options = vec![
254                "PreferredAuthentications=password,keyboard-interactive".to_owned(),
255                "NumberOfPasswordPrompts=1".to_owned(),
256            ];
257            options.extend(batch_options(&self.known_hosts).into_iter().filter(|o| o != "BatchMode=yes"));
258            options
259        } else {
260            args.splice(0..0, ["-i".to_owned(), self.identity.to_string_lossy().into_owned()]);
261            batch_options(&self.known_hosts)
262        };
263        for option in options {
264            args.extend(["-o".to_owned(), option]);
265        }
266        args.extend(["--".to_owned(), format!("{}@{}", self.user, self.host), command.to_owned()]);
267        Ok(args)
268    }
269
270    /// Runs `command` on it, within `limit`, and returns its standard output.
271    ///
272    /// # Errors
273    ///
274    /// [`SshError::HostKeyRefused`] when ssh refused the server's host key; else why it didn't
275    /// answer or failed.
276    pub async fn exec(&self, ctx: &Context, command: &str, limit: Duration) -> Result<String, SshError> {
277        let mut spec = ProcessSpec::new("ssh", self.exec_args(command)?);
278        if let Some(password) = &self.password {
279            let askpass = write_askpass(&password.askpass_dir)?;
280            spec.env.extend([
281                ("SSH_ASKPASS".to_owned(), askpass.to_string_lossy().into_owned()),
282                ("SSH_ASKPASS_REQUIRE".to_owned(), "force".to_owned()),
283                ("DISPLAY".to_owned(), ":0".to_owned()),
284                (PASSWORD_VAR.to_owned(), password.secret.clone()),
285            ]);
286        }
287        let captured = ctx.probe_within(limit, &spec).await?;
288        if !captured.success() && captured.stderr_tail.iter().any(|l| l.contains("Host key verification failed")) {
289            return Err(SshError::HostKeyRefused { host: self.host.clone() });
290        }
291        captured.output().map_err(|f| SshError::Failed(f.to_string()))
292    }
293}
294
295#[cfg(test)]
296mod tests;