1use 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
19const KEYGEN_LIMIT: Duration = Duration::from_secs(60);
21
22const CONNECT_TIMEOUT_S: u32 = 10;
24
25#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
27#[non_exhaustive]
28pub enum SshError {
29 #[error("unexpected SSH {0}")]
31 Invalid(&'static str),
32 #[error("{0}")]
34 Unanswered(String),
35 #[error("the SSH host key of {host} isn't one confirmed for it")]
37 HostKeyRefused {
38 host: String,
40 },
41 #[error("{0}")]
43 Failed(String),
44 #[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
61pub 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#[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#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct Target {
92 pub host: String,
94 pub port: u16,
96 pub user: String,
98 pub identity: PathBuf,
100 pub known_hosts: PathBuf,
102 pub password: Option<Password>,
105}
106
107#[derive(Clone, PartialEq, Eq)]
111pub struct Password {
112 pub secret: String,
114 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
124const PASSWORD_VAR: &str = "ISOTHRUM_SSH_PASSWORD";
126
127fn 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
141fn 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
155pub(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#[must_use]
162pub fn sh_quote(s: &str) -> String {
163 format!("'{}'", s.replace('\'', r"'\''"))
164}
165
166#[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#[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 #[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 #[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 #[must_use]
233 pub fn on_port(self, port: u16) -> Target {
234 Target { port, ..self }
235 }
236
237 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 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 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;