moshpit 0.20.1

moshpit client (mp) — encrypted, resilient remote terminal session client
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
// Copyright (c) 2025 moshpit developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! Per-host `[[hosts]]` blocks in the client config, like `Host` sections in
//! `~/.ssh/config`:
//!
//! ```toml
//! [[hosts]]
//! match = "box"                          # or a list; `*`/`?` globs, `!` excludes
//! hostname = "box.internal.example.com"  # connect here instead
//! user = "me"
//! transport = "tcp"
//! ```
//!
//! Every block whose `match` fits the host as typed applies, in file order,
//! and the first block to set an option wins.  Their options sit between the
//! file's top-level settings and the command line: `env > CLI > [[hosts]] >
//! top-level file`.

use std::{collections::BTreeSet, fs::read_to_string, io::ErrorKind, path::Path};

use anyhow::{Context as _, Result, bail};
use serde::Deserialize;
use toml::{Table, Value};

/// Options a `[[hosts]]` block may set besides `match`, `hostname` and `user`:
/// the client's per-connection settings.
pub(crate) const HOST_OPTIONS: &[&str] = &[
    "server_port",
    "private_key_path",
    "public_key_path",
    "max_reconnect_backoff_secs",
    "predict",
    "nat_warmup",
    "nat_warmup_count",
    "min_protocol_version",
    "diff_mode",
    "transport",
    "legacy_passthrough",
    "probe_terminal_colors",
    "preferred_algorithms",
    "send_env",
    "send_path",
    "escape_key",
];

/// What the matching `[[hosts]]` blocks say about one destination.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct HostSettings {
    /// Options to layer over the file's top-level settings.
    pub(crate) overlay: Table,
    /// Host to connect to instead of the one typed.
    pub(crate) hostname: Option<String>,
    /// User to log in as when the destination has no `user@`.
    pub(crate) user: Option<String>,
    /// The `match` patterns of each block that applied, in file order.
    pub(crate) matched: Vec<String>,
}

impl HostSettings {
    /// The option keys the blocks set, with nested tables flattened as
    /// `table.key` (e.g. `preferred_algorithms.kex`), for `mp ec`.
    pub(crate) fn keys(&self) -> BTreeSet<String> {
        let mut keys = BTreeSet::new();
        for (key, value) in &self.overlay {
            let _ = keys.insert(key.clone());
            if let Value::Table(sub) = value {
                for sub_key in sub.keys() {
                    let _ = keys.insert(format!("{key}.{sub_key}"));
                }
            }
        }
        for (key, set) in [("hostname", &self.hostname), ("user", &self.user)] {
            if set.is_some() {
                let _ = keys.insert(key.to_string());
            }
        }
        keys
    }
}

#[derive(Deserialize)]
#[serde(untagged)]
enum Patterns {
    One(String),
    Many(Vec<String>),
}

impl Patterns {
    /// Every pattern, splitting strings on whitespace and commas like ssh's
    /// `Host a b,c`.
    fn into_list(self) -> Vec<String> {
        let parts = match self {
            Patterns::One(s) => vec![s],
            Patterns::Many(v) => v,
        };
        parts
            .iter()
            .flat_map(|s| s.split(|c: char| c.is_whitespace() || c == ','))
            .filter(|p| !p.is_empty())
            .map(str::to_owned)
            .collect()
    }
}

#[derive(Deserialize)]
struct Block {
    #[serde(rename = "match")]
    patterns: Patterns,
    hostname: Option<String>,
    user: Option<String>,
    #[serde(flatten)]
    options: Table,
}

#[derive(Deserialize)]
struct HostsFile {
    #[serde(default)]
    hosts: Vec<Block>,
}

/// Read `path` and resolve its `[[hosts]]` blocks for `host`.  A missing
/// file has no blocks.
///
/// # Errors
/// Fails if the file can't be read or a block is malformed (see
/// [`host_settings`]).
pub(crate) fn host_settings_from_file(path: &Path, host: &str) -> Result<HostSettings> {
    let text = match read_to_string(path) {
        Ok(text) => text,
        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(HostSettings::default()),
        Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
    };
    host_settings(&text, host).with_context(|| format!("in {}", path.display()))
}

/// Resolve the `[[hosts]]` blocks in `toml_text` for `host` (the host as
/// typed, before any `hostname` substitution).
///
/// Every block is checked, matching or not, so a typo anywhere is reported
/// rather than silently ignored.
///
/// # Errors
/// Fails on a block with no `match` patterns or with an option a block
/// can't set.
pub(crate) fn host_settings(toml_text: &str, host: &str) -> Result<HostSettings> {
    let file: HostsFile = toml::from_str(toml_text).context("invalid [[hosts]] block")?;
    let mut settings = HostSettings::default();
    for (index, block) in file.hosts.into_iter().enumerate() {
        let number = index + 1;
        let patterns = block.patterns.into_list();
        if patterns.is_empty() {
            bail!("[[hosts]] block {number} has an empty `match`");
        }
        let spec = patterns.join(" ");
        if let Some(key) = block
            .options
            .keys()
            .find(|key| !HOST_OPTIONS.contains(&key.as_str()))
        {
            bail!(
                "[[hosts]] block {number} (match = \"{spec}\"): unknown option '{key}'; \
                 a host block can set hostname, user, {}",
                HOST_OPTIONS.join(", ")
            );
        }
        if !matches_host(&patterns, host) {
            continue;
        }
        settings.matched.push(spec);
        if settings.hostname.is_none() {
            settings.hostname = block.hostname;
        }
        if settings.user.is_none() {
            settings.user = block.user;
        }
        for (key, value) in block.options {
            let _ = settings.overlay.entry(key).or_insert(value);
        }
    }
    Ok(settings)
}

/// Whether a block's patterns select `host`: at least one plain pattern
/// matches and no `!` pattern does, as in ssh.  Case-insensitive.
fn matches_host(patterns: &[String], host: &str) -> bool {
    let host = host.to_ascii_lowercase();
    let mut matched = false;
    for pattern in patterns {
        let pattern = pattern.to_ascii_lowercase();
        if let Some(negated) = pattern.strip_prefix('!') {
            if glob_match(negated, &host) {
                return false;
            }
        } else if glob_match(&pattern, &host) {
            matched = true;
        }
    }
    matched
}

/// `*` matches any run of characters (including none), `?` exactly one.
fn glob_match(pattern: &str, text: &str) -> bool {
    let pattern: Vec<char> = pattern.chars().collect();
    let text: Vec<char> = text.chars().collect();
    let (mut p, mut t) = (0, 0);
    // Position of the last `*` and the text position it was tried at.
    let mut star: Option<(usize, usize)> = None;
    while t < text.len() {
        if p < pattern.len() && (pattern[p] == '?' || pattern[p] == text[t]) {
            p += 1;
            t += 1;
        } else if p < pattern.len() && pattern[p] == '*' {
            star = Some((p, t));
            p += 1;
        } else if let Some((star_p, star_t)) = star {
            // Let the last `*` swallow one more character.
            p = star_p + 1;
            t = star_t + 1;
            star = Some((star_p, star_t + 1));
        } else {
            return false;
        }
    }
    pattern[p..].iter().all(|&c| c == '*')
}

/// The host part of a destination as typed: `user@host:port` → `host`,
/// `[::1]:port` → `::1`.  Used to match `[[hosts]]` patterns.
pub(crate) fn destination_host(destination: &str) -> &str {
    let host_part = destination
        .split_once('@')
        .map_or(destination, |(_, host)| host);
    if let Some(rest) = host_part.strip_prefix('[') {
        return rest.split_once(']').map_or(rest, |(host, _)| host);
    }
    match host_part.split_once(':') {
        Some((host, port)) if !port.contains(':') => host,
        _ => host_part,
    }
}

/// `destination` with a matching block's `hostname` and `user` applied: the
/// host is replaced (keeping any explicit `:port`), and `user@` is added only
/// when the destination doesn't already name a user.
pub(crate) fn apply_host_aliases(
    destination: &str,
    hostname: Option<&str>,
    user: Option<&str>,
) -> String {
    let (typed_user, host_part) = destination
        .split_once('@')
        .map_or((None, destination), |(user, host)| (Some(user), host));
    let host_part = match hostname {
        Some(hostname) => {
            let port = port_suffix(host_part);
            if hostname.contains(':') && !hostname.starts_with('[') {
                format!("[{hostname}]{port}")
            } else {
                format!("{hostname}{port}")
            }
        }
        None => host_part.to_string(),
    };
    match typed_user.or(user) {
        Some(user) => format!("{user}@{host_part}"),
        None => host_part,
    }
}

/// The `:port` suffix of a `host[:port]` (or `[v6]:port`), or `""`.
fn port_suffix(host_part: &str) -> &str {
    if host_part.starts_with('[') {
        return host_part.split_once(']').map_or("", |(_, rest)| rest);
    }
    match host_part.find(':') {
        Some(i) if host_part.matches(':').count() == 1 => &host_part[i..],
        _ => "",
    }
}

#[cfg(test)]
mod tests {
    use toml::Value;

    use super::{
        HOST_OPTIONS, HostSettings, apply_host_aliases, destination_host, glob_match,
        host_settings, matches_host,
    };

    const SAMPLE: &str = r#"
server_port = 40404
transport = "udp"

[[hosts]]
match = "box"
hostname = "box.internal.example.com"
user = "me"
transport = "tcp"

[[hosts]]
match = ["*.example.com", "!secret.example.com"]
escape_key = "ctrl-a"
transport = "udp"

[[hosts]]
match = "*"
escape_key = "ctrl-]"
server_port = 40500
[hosts.preferred_algorithms]
kex = ["ml-kem-768-sha256"]
"#;

    #[test]
    fn globs() {
        assert!(glob_match("*", ""));
        assert!(glob_match("*", "anything"));
        assert!(glob_match("box", "box"));
        assert!(!glob_match("box", "box2"));
        assert!(glob_match("box?", "box2"));
        assert!(!glob_match("box?", "box"));
        assert!(glob_match("*.example.com", "a.b.example.com"));
        assert!(!glob_match("*.example.com", "example.com"));
        assert!(glob_match("10.0.*.?", "10.0.0.3"));
        assert!(glob_match("a*b*c", "aXXbYYc"));
        assert!(!glob_match("a*b*c", "aXXbYY"));
    }

    #[test]
    fn negation_and_case() {
        let patterns = vec![
            "*.Example.com".to_string(),
            "!secret.example.com".to_string(),
        ];
        assert!(matches_host(&patterns, "web.EXAMPLE.com"));
        assert!(!matches_host(&patterns, "secret.example.com"));
        // A negation alone never selects anything.
        assert!(!matches_host(&["!foo".to_string()], "bar"));
    }

    #[test]
    fn first_block_to_set_an_option_wins() -> anyhow::Result<()> {
        let s = host_settings(SAMPLE, "box")?;
        assert_eq!(s.matched, vec!["box", "*"]);
        assert_eq!(s.hostname.as_deref(), Some("box.internal.example.com"));
        assert_eq!(s.user.as_deref(), Some("me"));
        assert_eq!(s.overlay.get("transport"), Some(&Value::from("tcp")));
        assert_eq!(s.overlay.get("escape_key"), Some(&Value::from("ctrl-]")));
        assert_eq!(s.overlay.get("server_port"), Some(&Value::from(40500)));
        assert!(s.keys().contains("preferred_algorithms.kex"));
        assert!(s.keys().contains("hostname"));
        Ok(())
    }

    #[test]
    fn later_blocks_fill_in_and_excluded_hosts_skip() -> anyhow::Result<()> {
        let web = host_settings(SAMPLE, "web.example.com")?;
        assert_eq!(web.matched, vec!["*.example.com !secret.example.com", "*"]);
        assert_eq!(web.overlay.get("escape_key"), Some(&Value::from("ctrl-a")));
        assert_eq!(web.hostname, None);

        let secret = host_settings(SAMPLE, "secret.example.com")?;
        assert_eq!(secret.matched, vec!["*"]);
        assert_eq!(
            secret.overlay.get("escape_key"),
            Some(&Value::from("ctrl-]"))
        );
        Ok(())
    }

    #[test]
    fn no_blocks_or_no_match_is_empty() -> anyhow::Result<()> {
        assert_eq!(
            host_settings("server_port = 1\n", "box")?,
            HostSettings::default()
        );
        let s = host_settings("[[hosts]]\nmatch = \"a b,c\"\ntransport = \"tcp\"\n", "d")?;
        assert!(s.matched.is_empty() && s.overlay.is_empty());
        let s = host_settings("[[hosts]]\nmatch = \"a b,c\"\ntransport = \"tcp\"\n", "c")?;
        assert_eq!(s.matched, vec!["a b c"]);
        Ok(())
    }

    #[test]
    fn unknown_options_and_empty_match_are_errors() {
        // Reported even when the block doesn't match this host.
        let typo = "[[hosts]]\nmatch = \"other\"\ntransprot = \"tcp\"\n";
        let err = format!("{:#}", host_settings(typo, "box").unwrap_err());
        assert!(err.contains("unknown option 'transprot'"), "{err}");
        assert!(err.contains("match = \"other\""), "{err}");

        let tracing = "[[hosts]]\nmatch = \"box\"\n[hosts.tracing]\n";
        assert!(host_settings(tracing, "box").is_err());

        let empty = "[[hosts]]\nmatch = \" , \"\n";
        let err = format!("{:#}", host_settings(empty, "box").unwrap_err());
        assert!(err.contains("empty `match`"), "{err}");

        let no_match = "[[hosts]]\ntransport = \"tcp\"\n";
        assert!(host_settings(no_match, "box").is_err());
    }

    #[test]
    fn every_host_option_is_a_config_field() -> anyhow::Result<()> {
        // Each allowed option must deserialize into the client Config, or a
        // host block could set something that silently does nothing.
        use crate::config::Config;
        let defaults = toml::to_string(&Config::default())?;
        let defaults: toml::Table = toml::from_str(&defaults)?;
        for option in HOST_OPTIONS {
            let optional = [
                "private_key_path",
                "public_key_path",
                "min_protocol_version",
            ]
            .contains(option);
            assert!(
                defaults.contains_key(*option) || optional,
                "{option} is not a Config field"
            );
        }
        Ok(())
    }

    #[test]
    fn destination_hosts() {
        assert_eq!(destination_host("box"), "box");
        assert_eq!(destination_host("me@box"), "box");
        assert_eq!(destination_host("me@box:2222"), "box");
        assert_eq!(destination_host("[::1]:40404"), "::1");
        assert_eq!(destination_host("me@[fe80::1]"), "fe80::1");
        assert_eq!(destination_host("10.0.0.3:40405"), "10.0.0.3");
    }

    #[test]
    fn aliases() {
        let h = Some("box.internal");
        assert_eq!(apply_host_aliases("box", h, Some("me")), "me@box.internal");
        // A typed user or port wins / is kept.
        assert_eq!(
            apply_host_aliases("you@box", h, Some("me")),
            "you@box.internal"
        );
        assert_eq!(apply_host_aliases("box:2222", h, None), "box.internal:2222");
        assert_eq!(apply_host_aliases("[::1]:9", h, None), "box.internal:9");
        // An IPv6 hostname gets brackets.
        assert_eq!(
            apply_host_aliases("box", Some("fe80::1"), None),
            "[fe80::1]"
        );
        assert_eq!(
            apply_host_aliases("box:7", Some("fe80::1"), None),
            "[fe80::1]:7"
        );
        // Nothing to apply.
        assert_eq!(apply_host_aliases("me@box:1", None, None), "me@box:1");
        assert_eq!(apply_host_aliases("box", None, Some("me")), "me@box");
    }
}