ssh2-config 0.9.0

an ssh configuration parser for ssh2-rs
Documentation
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
#![crate_name = "ssh2_config"]
#![crate_type = "lib"]

//! # ssh2-config
//!
//! ssh2-config a library which provides a parser for the SSH configuration file,
//! to be used in pair with the [ssh2](https://github.com/alexcrichton/ssh2-rs) crate, or
//! in general with any other OpenSSH compatible SSH client implementation.
//!
//! This library provides a method to parse the configuration file and returns the
//! configuration parsed into a structure.
//! The [`SshConfig`] structure provides all the attributes which **can** be used to configure the **ssh2 Session**
//! and to resolve the host, port and username.
//!
//! Once the configuration has been parsed you can use the [`SshConfig::query`]
//! method to query configuration for a certain host, based on the configured patterns.
//! Even if many attributes are not exposed, since not supported, there is anyway a validation of the configuration,
//! so invalid configuration will result in a parsing error.
//!
//! The reference used for the configuration file and how parameters are resolved is the OpenSSH one,
//! is described at <http://man.openbsd.org/OpenBSD-current/man5/ssh_config.5>.
//!
//! ## Get started
//!
//! First of you need to add **ssh2-config** to your project dependencies:
//!
//! ```toml
//! ssh2-config = "0.9"
//! ```
//!
//! ## Feature flags
//!
//! | name              | description                                               | default |
//! | ----------------- | --------------------------------------------------------- | ------- |
//! | `default`         | Enable the default feature set, which is currently empty. | ✔       |
//! | `nolog`           | Disable logging at compile time.                          |         |
//! | `reload-ssh-algo` | Regenerate default algorithms from OpenSSH source.        |         |
//!
//! ## Example
//!
//! Here is a basic example:
//!
//! ```rust
//!
//! use ssh2::Session;
//! use ssh2_config::{HostParams, ParseRule, SshConfig};
//! use std::fs::File;
//! use std::io::BufReader;
//! use std::path::Path;
//!
//! let mut reader = BufReader::new(
//!     File::open(Path::new("./assets/ssh.config"))
//!         .expect("Could not open configuration file")
//! );
//!
//! let config = SshConfig::default().parse(&mut reader, ParseRule::STRICT).expect("Failed to parse configuration");
//!
//! // Query parameters for your host
//! // If there's no rule for your host, default params are returned
//! let params = config.query("192.168.1.2");
//!
//! // ...
//!
//! // serialize configuration to string
//! let s = config.to_string();
//!
//! ```
//!
//! ---
//!
//! ## How host parameters are resolved
//!
//! This topic has been debated a lot over the years, so finally since 0.5 this has been fixed to follow the official ssh configuration file rules, as described in the MAN <https://man.openbsd.org/OpenBSD-current/man5/ssh_config.5#DESCRIPTION>.
//!
//! > Unless noted otherwise, for each parameter, the first obtained value will be used. The configuration files contain sections separated by Host specifications, and that section is only applied for hosts that match one of the patterns given in the specification. The matched host name is usually the one given on the command line (see the CanonicalizeHostname option for exceptions).
//! >
//! > Since the first obtained value for each parameter is used, more host-specific declarations should be given near the beginning of the file, and general defaults at the end.
//!
//! This means that:
//!
//! 1. The first obtained value parsing the configuration top-down will be used
//! 2. Host specific rules ARE not overriding default ones if they are not the first obtained value
//! 3. If you want to achieve default values to be less specific than host specific ones, you should put the default values at the end of the configuration file using `Host *`.
//! 4. Algorithms, so `KexAlgorithms`, `Ciphers`, `MACs` and `HostKeyAlgorithms` use a different resolvers which supports appending, excluding and heading insertions, as described in the man page at ciphers: <https://man.openbsd.org/OpenBSD-current/man5/ssh_config.5#Ciphers>.
//!
//! ### Resolvers examples
//!
//! ```ssh
//! Compression yes
//!
//! Host 192.168.1.1
//!     Compression no
//! ```
//!
//! If we get rules for `192.168.1.1`, compression will be `yes`, because it's the first obtained value.
//!
//! ```ssh
//! Host 192.168.1.1
//!     Compression no
//!
//! Host *
//!     Compression yes
//! ```
//!
//! If we get rules for `192.168.1.1`, compression will be `no`, because it's the first obtained value.
//!
//! If we get rules for `172.168.1.1`, compression will be `yes`, because it's the first obtained value MATCHING the host rule.
//!
//! ```ssh
//!
//! Host 192.168.1.1
//!     Ciphers +c
//! ```
//!
//! If we get rules for `192.168.1.1`, ciphers will be `c` appended to default algorithms, which can be specified in the [`SshConfig`] constructor.
//!
//! ## Configuring default algorithms
//!
//! When you invoke [`SshConfig::default`], the default algorithms are set from openssh source code,
//! which can be seen in the [`default_openssh_algorithms`] function documentation.
//!
//! If you want you can use a custom constructor [`SshConfig::default_algorithms`] to set your own default algorithms.

#![doc(html_playground_url = "https://play.rust-lang.org")]

#[macro_use]
extern crate log;

use std::fmt;
use std::fs::File;
use std::io::{self, BufRead, BufReader};
use std::path::PathBuf;
use std::time::Duration;
// -- modules
mod default_algorithms;
mod host;
mod params;
mod parser;
mod serializer;

// -- export
pub use self::default_algorithms::{
    DefaultAlgorithms, default_algorithms as default_openssh_algorithms,
};
use self::host::clauses_intersect;
pub use self::host::{Host, HostClause};
#[doc(inline)]
pub use self::params::{
    Algorithms, HostParams, RemoteForward, RemoteForwardDestination, RemoteForwardListen,
};
pub use self::parser::{ParseRule, SshParserError, SshParserResult};

/// Describes the ssh configuration.
/// Configuration is described in this document: <http://man.openbsd.org/OpenBSD-current/man5/ssh_config.5>
#[derive(Debug, Clone, Eq, Default)]
pub struct SshConfig {
    /// Default algorithms for ssh.
    default_algorithms: DefaultAlgorithms,
    /// Home directory used to expand `~` and to resolve relative `Include` paths against `<home>/.ssh`.
    /// `None` means the home directory is taken from [`dirs::home_dir`].
    home_dir: Option<PathBuf>,
    /// Rulesets for hosts.
    /// Default config will be stored with key `*`
    hosts: Vec<Host>,
    /// Inherited scopes for each host rule.
    host_scopes: Vec<HostScope>,
}

pub(crate) type HostScope = Vec<Vec<HostClause>>;

/// Compares parsed configurations, ignoring the home directory used to parse them.
impl PartialEq for SshConfig {
    fn eq(&self, other: &Self) -> bool {
        let Self {
            default_algorithms,
            home_dir: _,
            hosts,
            host_scopes,
        } = self;
        let Self {
            default_algorithms: other_default_algorithms,
            home_dir: _,
            hosts: other_hosts,
            host_scopes: other_host_scopes,
        } = other;
        default_algorithms == other_default_algorithms
            && hosts == other_hosts
            && host_scopes == other_host_scopes
    }
}

impl fmt::Display for SshConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        serializer::SshConfigSerializer::from(self).serialize(f)
    }
}

impl SshConfig {
    /// Constructs a new [`SshConfig`] from a list of [`Host`]s.
    ///
    /// You can later also set the [`DefaultAlgorithms`] using [`SshConfig::default_algorithms`].
    ///
    /// ```rust
    /// use ssh2_config::{DefaultAlgorithms, Host, SshConfig};
    ///
    /// let config = SshConfig::from_hosts(vec![/* put your hosts here */]).default_algorithms(DefaultAlgorithms::default());
    /// ```
    pub fn from_hosts(hosts: Vec<Host>) -> Self {
        Self {
            default_algorithms: DefaultAlgorithms::default(),
            home_dir: None,
            host_scopes: vec![Vec::new(); hosts.len()],
            hosts,
        }
    }

    /// Appends a host rule and its inherited scope.
    pub(crate) fn append_host(&mut self, host: Host, scope: HostScope) -> usize {
        self.hosts.push(host);
        self.host_scopes.push(scope);
        self.hosts.len() - 1
    }

    /// Returns whether a host rule and all its inherited scopes match a query.
    pub(crate) fn host_matches(&self, index: usize, pattern: &str) -> bool {
        let Some(host) = self.hosts.get(index) else {
            return false;
        };
        if !host.intersects(pattern) {
            return false;
        }

        self.host_scopes.get(index).is_none_or(|scope| {
            scope
                .iter()
                .all(|clauses| clauses_intersect(clauses, pattern))
        })
    }

    /// Query params for a certain host. Returns [`HostParams`] for the host.
    pub fn query<S: AsRef<str>>(&self, pattern: S) -> HostParams {
        let mut params = HostParams::new(&self.default_algorithms);
        // iter keys, overwrite if None top-down
        for (index, host) in self.hosts.iter().enumerate() {
            if self.host_matches(index, pattern.as_ref()) {
                debug!(
                    "Merging params for host: {:?} into params {params:?}",
                    host.pattern
                );
                params.overwrite_if_none(&host.params);
                trace!("Params after merge: {params:?}");
            }
        }
        // return calculated params
        params
    }

    /// Get an iterator over the [`Host`]s which intersect with the given host pattern
    pub fn intersecting_hosts(&self, pattern: &str) -> impl Iterator<Item = &'_ Host> {
        self.hosts
            .iter()
            .enumerate()
            .filter(move |(index, _)| self.host_matches(*index, pattern))
            .map(|(_, host)| host)
    }

    /// Set default algorithms for ssh.
    ///
    /// If you want to use the default algorithms from the system, you can use the `Default::default()` method.
    pub fn default_algorithms(mut self, algos: DefaultAlgorithms) -> Self {
        self.default_algorithms = algos;

        self
    }

    /// Sets the home directory used to resolve `~` and relative `Include` paths.
    ///
    /// A leading `~` or `~/` is expanded against this directory, and relative `Include`
    /// paths are resolved against `<home>/.ssh`. Other `~`-prefixed paths, such as `~user/...`,
    /// are kept as-is in both `Include` and path options such as `IdentityFile`; an `Include`
    /// pattern that matches no file is skipped. When it is not set, the home directory is taken
    /// from [`dirs::home_dir`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use std::io::BufReader;
    /// use std::path::PathBuf;
    ///
    /// use ssh2_config::{ParseRule, SshConfig};
    ///
    /// let mut reader = BufReader::new("IdentityFile ~/.ssh/id_ed25519\n".as_bytes());
    /// let config = SshConfig::default()
    ///     .home_dir("/home/alice")
    ///     .parse(&mut reader, ParseRule::STRICT)
    ///     .expect("Failed to parse configuration");
    ///
    /// assert_eq!(
    ///     config.query("any").identity_file,
    ///     Some(vec![PathBuf::from("/home/alice/.ssh/id_ed25519")])
    /// );
    /// ```
    pub fn home_dir(mut self, home_dir: impl Into<PathBuf>) -> Self {
        self.home_dir = Some(home_dir.into());

        self
    }

    /// Parse [`SshConfig`] from stream which implements [`BufRead`] and return parsed configuration or parser error
    ///
    /// `~` is expanded against the home set with [`SshConfig::home_dir`], or against
    /// [`dirs::home_dir`] when none is set, and relative `Include` paths are resolved against
    /// `<home>/.ssh`.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// let mut reader = BufReader::new(
    ///    File::open(Path::new("./assets/ssh.config"))
    ///       .expect("Could not open configuration file")
    /// );
    ///
    /// let config = SshConfig::default().parse(&mut reader, ParseRule::STRICT).expect("Failed to parse configuration");
    /// ```
    pub fn parse(mut self, reader: &mut impl BufRead, rules: ParseRule) -> SshParserResult<Self> {
        let home = self.home_dir.clone().or_else(dirs::home_dir);
        parser::SshConfigParser::parse(
            &mut self,
            reader,
            rules,
            None,
            &mut parser::IncludeContext::new(home),
        )
        .map(|_| self)
    }

    /// Parse `~/.ssh/config`` file and return parsed configuration [`SshConfig`] or parser error
    ///
    /// The file and every `~` or relative `Include` path in it are resolved against
    /// [`dirs::home_dir`]. To parse the configuration of another home, open `<home>/.ssh/config`
    /// and parse it with [`SshConfig::home_dir`] set, as shown below.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use std::fs::File;
    /// use std::io::BufReader;
    /// use std::path::Path;
    ///
    /// use ssh2_config::{ParseRule, SshConfig};
    ///
    /// let home = Path::new("/home/alice");
    /// let mut reader = BufReader::new(
    ///     File::open(home.join(".ssh").join("config")).expect("Could not open configuration file"),
    /// );
    /// let config = SshConfig::default()
    ///     .home_dir(home)
    ///     .parse(&mut reader, ParseRule::STRICT)
    ///     .expect("Failed to parse configuration");
    /// ```
    pub fn parse_default_file(rules: ParseRule) -> SshParserResult<Self> {
        let ssh_folder = dirs::home_dir()
            .ok_or_else(|| {
                SshParserError::Io(io::Error::new(
                    io::ErrorKind::NotFound,
                    "Home folder not found",
                ))
            })?
            .join(".ssh");

        let mut reader =
            BufReader::new(File::open(ssh_folder.join("config")).map_err(SshParserError::Io)?);

        Self::default().parse(&mut reader, rules)
    }

    /// Get list of [`Host`]s in the configuration
    pub fn get_hosts(&self) -> &Vec<Host> {
        &self.hosts
    }
}

#[cfg(test)]
fn test_log() {
    use std::sync::Once;

    static INIT: Once = Once::new();

    INIT.call_once(|| {
        let _ = env_logger::builder()
            .filter_level(log::LevelFilter::Trace)
            .is_test(true)
            .try_init();
    });
}

#[cfg(test)]
mod tests {

    use pretty_assertions::assert_eq;

    use super::*;

    #[test]
    fn should_init_ssh_config() {
        test_log();

        let config = SshConfig::default();
        assert_eq!(config.hosts.len(), 0);
        assert_eq!(
            config.query("192.168.1.2"),
            HostParams::new(&DefaultAlgorithms::default())
        );
    }

    #[test]
    fn should_parse_default_config() -> Result<(), parser::SshParserError> {
        test_log();

        let _config = SshConfig::parse_default_file(ParseRule::ALLOW_UNKNOWN_FIELDS)?;
        Ok(())
    }

    #[test]
    fn should_parse_config() -> Result<(), parser::SshParserError> {
        test_log();

        use std::fs::File;
        use std::io::BufReader;
        use std::path::Path;

        let mut reader = BufReader::new(
            File::open(Path::new("./assets/ssh.config"))
                .expect("Could not open configuration file"),
        );

        SshConfig::default().parse(&mut reader, ParseRule::STRICT)?;

        Ok(())
    }

    #[test]
    fn should_ignore_home_dir_when_comparing() -> Result<(), parser::SshParserError> {
        test_log();

        let input = "Host a\n  User x\n";
        let with_home = SshConfig::default()
            .home_dir("/home/alice")
            .parse(&mut input.as_bytes(), ParseRule::STRICT)?;
        let without_home = SshConfig::default().parse(&mut input.as_bytes(), ParseRule::STRICT)?;
        assert_eq!(with_home, without_home);

        Ok(())
    }

    #[test]
    fn should_query_ssh_config() {
        test_log();

        let mut config = SshConfig::default();
        // add config
        let mut params1 = HostParams::new(&DefaultAlgorithms::default());
        params1.bind_address = Some("0.0.0.0".to_string());
        config.hosts.push(Host::new(
            vec![HostClause::new(String::from("192.168.*.*"), false)],
            params1.clone(),
        ));
        let mut params2 = HostParams::new(&DefaultAlgorithms::default());
        params2.bind_interface = Some(String::from("tun0"));
        config.hosts.push(Host::new(
            vec![HostClause::new(String::from("192.168.10.*"), false)],
            params2.clone(),
        ));

        let mut params3 = HostParams::new(&DefaultAlgorithms::default());
        params3.host_name = Some("172.26.104.4".to_string());
        config.hosts.push(Host::new(
            vec![
                HostClause::new(String::from("172.26.*.*"), false),
                HostClause::new(String::from("172.26.104.4"), true),
            ],
            params3.clone(),
        ));
        // Query
        assert_eq!(config.query("192.168.1.32"), params1);
        // merged case
        params1.overwrite_if_none(&params2);
        assert_eq!(config.query("192.168.10.1"), params1);
        // Negated case
        assert_eq!(config.query("172.26.254.1"), params3);
        assert_eq!(
            config.query("172.26.104.4"),
            HostParams::new(&DefaultAlgorithms::default())
        );
    }

    #[test]
    fn roundtrip() {
        test_log();

        // Root host
        let mut default_host_params = HostParams::new(&DefaultAlgorithms::default());
        default_host_params.add_keys_to_agent = Some(true);
        let root_host_config = Host::new(
            vec![HostClause::new(String::from("*"), false)],
            default_host_params,
        );

        // A host using proxy jumps
        let mut host_params = HostParams::new(&DefaultAlgorithms::default());
        host_params.host_name = Some(String::from("192.168.10.1"));
        host_params.proxy_jump = Some(vec![String::from("jump.example.com")]);
        let host_config = Host::new(
            vec![HostClause::new(String::from("server"), false)],
            host_params,
        );

        // Create the overall config and serialise it
        let config = SshConfig::from_hosts(vec![root_host_config, host_config]);
        let config_string = config.to_string();

        // Parse the serialised string
        let mut reader = std::io::BufReader::new(config_string.as_bytes());
        let config_parsed = SshConfig::default()
            .parse(&mut reader, ParseRule::STRICT)
            .expect("Could not parse config.");

        assert_eq!(config, config_parsed);
    }

    #[test]
    fn should_get_intersecting_hosts() {
        test_log();

        let mut config = SshConfig::default();
        let mut params1 = HostParams::new(&DefaultAlgorithms::default());
        params1.bind_address = Some("0.0.0.0".to_string());
        config.hosts.push(Host::new(
            vec![HostClause::new(String::from("192.168.*.*"), false)],
            params1,
        ));
        let mut params2 = HostParams::new(&DefaultAlgorithms::default());
        params2.bind_interface = Some(String::from("tun0"));
        config.hosts.push(Host::new(
            vec![HostClause::new(String::from("192.168.10.*"), false)],
            params2,
        ));
        let mut params3 = HostParams::new(&DefaultAlgorithms::default());
        params3.host_name = Some("172.26.104.4".to_string());
        config.hosts.push(Host::new(
            vec![HostClause::new(String::from("172.26.*.*"), false)],
            params3,
        ));

        // Test intersecting_hosts returns correct hosts
        let matching: Vec<_> = config.intersecting_hosts("192.168.10.1").collect();
        assert_eq!(matching.len(), 2);

        let matching: Vec<_> = config.intersecting_hosts("192.168.1.1").collect();
        assert_eq!(matching.len(), 1);

        let matching: Vec<_> = config.intersecting_hosts("172.26.0.1").collect();
        assert_eq!(matching.len(), 1);

        // No matches
        let matching: Vec<_> = config.intersecting_hosts("10.0.0.1").collect();
        assert_eq!(matching.len(), 0);
    }

    #[test]
    fn should_set_default_algorithms() {
        test_log();

        let custom_algos = DefaultAlgorithms {
            ca_signature_algorithms: vec!["custom-algo".to_string()],
            ciphers: vec!["custom-cipher".to_string()],
            host_key_algorithms: vec!["custom-hostkey".to_string()],
            kex_algorithms: vec!["custom-kex".to_string()],
            mac: vec!["custom-mac".to_string()],
            pubkey_accepted_algorithms: vec!["custom-pubkey".to_string()],
        };

        let config = SshConfig::default().default_algorithms(custom_algos.clone());

        assert_eq!(config.default_algorithms, custom_algos);
    }

    #[test]
    fn should_create_config_from_hosts() {
        test_log();

        let mut params = HostParams::new(&DefaultAlgorithms::default());
        params.host_name = Some("example.com".to_string());
        let host = Host::new(
            vec![HostClause::new(String::from("example"), false)],
            params,
        );

        let config = SshConfig::from_hosts(vec![host.clone()]);
        assert_eq!(config.get_hosts().len(), 1);
        assert_eq!(config.get_hosts()[0], host);
    }

    #[test]
    fn should_query_empty_config() {
        test_log();

        let config = SshConfig::default();
        let params = config.query("any-host");

        // Should return default params
        assert!(params.host_name.is_none());
        assert!(params.port.is_none());
    }

    #[test]
    fn should_display_empty_config() {
        test_log();

        let config = SshConfig::default();
        let output = config.to_string();
        assert!(output.is_empty());
    }
}