ssh2-config-rs 0.7.1

a pure Rust SSH configuration parser library
Documentation

ssh2-config-rs

Note: This is a fork of veeso/ssh2-config, rebranded and updated to use pure Rust dependencies (no OpenSSL). We are grateful to Christian Visintin for the original work and contributions.

license-mit repo-stars downloads latest-version conventional-commits

Build coveralls docs



About ssh2-config-rs

ssh2-config-rs is a pure Rust library which provides a parser for the SSH configuration file, designed to work with pure Rust SSH implementations like russh.

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 SSH sessions and to resolve the host, port and username.

Once the configuration has been parsed you can use the query(&str) 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.

Exposed attributes

  • AddKeysToAgent: you can use this attribute add keys to the SSH agent
  • BindAddress: you can use this attribute to bind the socket to a certain address
  • BindInterface: you can use this attribute to bind the socket to a certain network interface
  • CASignatureAlgorithms: you can use this attribute to handle CA certificates
  • CertificateFile: you can use this attribute to parse the certificate file in case is necessary
  • Ciphers: you can use this attribute to configure preferred cipher algorithms (works with russh's Preferred configuration)
  • Compression: you can use this attribute to configure compression settings
  • ConnectionAttempts: you can use this attribute to cycle over connect in order to retry
  • ConnectTimeout: you can use this attribute to set the connection timeout for the socket
  • ForwardAgent: you can use this attribute to forward your agent to the remote server
  • HostName: you can use this attribute to get the real name of the host to connect to
  • IdentityFile: you can use this attribute to set the keys to try when connecting to remote host.
  • KexAlgorithms: you can use this attribute to configure Key exchange methods (works with russh's Preferred configuration)
  • MACs: you can use this attribute to configure the MAC algorithms (works with russh's Preferred configuration)
  • Port: you can use this attribute to resolve the port to connect to
  • ProxyJump: you can use this attribute to specify hosts to jump via
  • PubkeyAuthentication: you can use this attribute to set whether to use the pubkey authentication
  • RemoteForward: you can use this method to implement port forwarding
  • ServerAliveInterval: you can use this method to implement keep alive message interval
  • TcpKeepAlive: you can use this method to tell whether to send keep alive message
  • UseKeychain: (macos only) used to tell whether to use keychain to decrypt ssh keys
  • User: you can use this method to resolve the user to use to log in as

Missing features


Get started

First of all, add ssh2-config-rs to your dependencies

[dependencies]
ssh2-config-rs = "^0.7"

then parse the configuration

use ssh2_config_rs::{ParseRule, SshConfig};
use std::fs::File;
use std::io::BufReader;

fn main() {
    let mut reader = BufReader::new(File::open(config_path).expect("Could not open configuration file"));
    let config = SshConfig::default().parse(&mut reader, ParseRule::STRICT).expect("Failed to parse configuration");

    // Query attributes for a certain host
    let params = config.query("192.168.1.2");
}

then you can use the parsed parameters to configure a russh session:

use russh::client::Config;
use russh::Preferred;
use ssh2_config_rs::HostParams;
use std::sync::Arc;

fn configure_session(config: &mut Config, params: &HostParams) {
    if let Some(compress) = params.compression {
        // Configure compression via Preferred algorithms
    }
    if params.tcp_keep_alive.unwrap_or(false) && params.server_alive_interval.is_some() {
        let interval = params.server_alive_interval.unwrap();
        config.keepalive_interval = Some(interval);
    }
    
    // Configure algorithms via Preferred
    let mut preferred = Preferred::default();
    
    // KEX algorithms
    let kex_algorithms: Vec<russh::kex::Name> = params
        .kex_algorithms
        .algorithms()
        .iter()
        .filter_map(|s| russh::kex::Name::try_from(s.as_str()).ok())
        .collect();
    if !kex_algorithms.is_empty() {
        preferred.kex = std::borrow::Cow::Owned(kex_algorithms);
    }
    
    // Host key algorithms
    let host_key_algorithms: Vec<russh::keys::Algorithm> = params
        .host_key_algorithms
        .algorithms()
        .iter()
        .filter_map(|s| russh::keys::Algorithm::new(s.as_str()).ok())
        .collect();
    if !host_key_algorithms.is_empty() {
        preferred.key = std::borrow::Cow::Owned(host_key_algorithms);
    }
    
    // Ciphers
    let ciphers: Vec<russh::cipher::Name> = params
        .ciphers
        .algorithms()
        .iter()
        .filter_map(|s| russh::cipher::Name::try_from(s.as_str()).ok())
        .collect();
    if !ciphers.is_empty() {
        preferred.cipher = std::borrow::Cow::Owned(ciphers);
    }
    
    // MACs
    let macs: Vec<russh::mac::Name> = params
        .mac
        .algorithms()
        .iter()
        .filter_map(|s| russh::mac::Name::try_from(s.as_str()).ok())
        .collect();
    if !macs.is_empty() {
        preferred.mac = std::borrow::Cow::Owned(macs);
    }
    
    config.preferred = preferred;
}

Reading unsupported fields

As outlined above, ssh2-config-rs does not support all parameters available in the man page of the SSH configuration file.

If you require these fields you may still access them through the unsupported_fields field on the HostParams structure like this:

use ssh2_config_rs::{ParseRule, SshConfig};
use std::fs::File;
use std::io::BufReader;

fn main() {
    let mut reader = BufReader::new(File::open(config_path).expect("Could not open configuration file"));
    let config = SshConfig::default().parse(&mut reader, ParseRule::ALLOW_UNSUPPORTED_FIELDS).expect("Failed to parse configuration");

    // Query attributes for a certain host
    let params = config.query("192.168.1.2");
    let forwards = params.unsupported_fields.get("dynamicforward");
}

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. They are in case appended to default algorithms, which are either fetched from the openssh source code or set with a constructor. See configuring default algorithms for more information.

Resolvers examples

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.

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.

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

To reload algos, build ssh2-config-rs with RELOAD_SSH_ALGO env variable set.

When you invoke SshConfig::default, the default algorithms are set from OpenSSH source code, which can be found here: https://docs.rs/ssh2-config-rs/latest/ssh2_config_rs/fn.default_openssh_algorithms.html.

If you want you can use a custom constructor SshConfig::default().default_algorithms(prefs) to set your own default algorithms.


Examples

You can view a working example of an implementation of ssh2-config-rs with russh in the examples folder at client.rs.

You can run the example with

cargo run --example client -- <remote-host> [config-file-path]

Support the original developer ☕

This project is a fork of veeso/ssh2-config. If you appreciate the original work, please consider supporting Christian Visintin, the original author:

ko-fi PayPal


Contributing and issues 🤝🏻

Contributions, bug reports, new features and questions are welcome! 😉 If you have any question or concern, or you want to suggest a new feature, or you want just want to improve ssh2-config-rs, feel free to open an issue or a PR.

Please follow our contributing guidelines


Changelog ⏳

View ssh2-config-rs's changelog HERE


License 📃

ssh2-config-rs is licensed under the MIT license.

You can read the entire license HERE