62 releases

0.21.2 Mar 2, 2019
0.21.0 Feb 24, 2019
0.20.7 Nov 25, 2018
0.20.0 Jul 19, 2018
0.6.0 Jul 28, 2016

#4 in #ssh

Download history 851/week @ 2018-12-20 104/week @ 2018-12-27 155/week @ 2019-01-03 82/week @ 2019-01-10 80/week @ 2019-01-17 88/week @ 2019-01-24 120/week @ 2019-01-31 90/week @ 2019-02-07 71/week @ 2019-02-14 76/week @ 2019-02-21 216/week @ 2019-02-28 148/week @ 2019-03-07 71/week @ 2019-03-14 595/week @ 2019-03-21 94/week @ 2019-03-28

619 downloads per month
Used in 7 crates (5 directly)

Apache-2.0

443KB
10K SLoC


lib.rs:

Server and client SSH asynchronous library, based on tokio/futures.

The normal way to use this library, both for clients and for servers, is by creating handlers, i.e. types that implement client::Handler for clients and server::Handler for servers.

Writing servers

In the specific case of servers, a server must implement server::Server, a trait for creating new server::Handler. The main type to look at in the server module is Session (and Config, of course).

Here is an example server, which forwards input from each client to all other clients:

extern crate thrussh;
extern crate thrussh_keys;
extern crate futures;
extern crate tokio;
use std::sync::{Mutex, Arc};
use thrussh::*;
use thrussh::server::{Auth, Session};
use thrussh_keys::*;
use std::collections::HashMap;
use futures::Future;

#[derive(Clone)]
struct Server {
    client_pubkey: Arc<thrussh_keys::key::PublicKey>,
    clients: Arc<Mutex<HashMap<(usize, ChannelId), thrussh::server::Handle>>>,
    id: usize,
}

impl server::Server for Server {
    type Handler = Self;
    fn new(&mut self) -> Self {
        let s = self.clone();
        self.id += 1;
        s
    }
}

impl server::Handler for Server {
    type Error = std::io::Error;
    type FutureAuth = futures::Finished<(Self, server::Auth), Self::Error>;
    type FutureUnit = futures::Finished<(Self, server::Session), Self::Error>;
    type FutureBool = futures::Finished<(Self, server::Session, bool), Self::Error>;

    fn finished_auth(self, auth: Auth) -> Self::FutureAuth {
        futures::finished((self, auth))
    }
    fn finished_bool(self, session: Session, b: bool) -> Self::FutureBool {
        futures::finished((self, session, b))
    }
    fn finished(self, session: Session) -> Self::FutureUnit {
        futures::finished((self, session))
    }
    fn channel_open_session(self, channel: ChannelId, session: Session) -> Self::FutureUnit {
        {
            let mut clients = self.clients.lock().unwrap();
            clients.insert((self.id, channel), session.handle());
        }
        futures::finished((self, session))
    }
    fn auth_publickey(self, _: &str, _: &key::PublicKey) -> Self::FutureAuth {
        futures::finished((self, server::Auth::Accept))
    }
    fn data(self, channel: ChannelId, data: &[u8], mut session: server::Session) -> Self::FutureUnit {
        {
            let mut clients = self.clients.lock().unwrap();
            for ((id, channel), ref mut s) in clients.iter_mut() {
                if *id != self.id {
                    s.data(*channel, None, CryptoVec::from_slice(data));
                }
            }
        }
        session.data(channel, None, data);
        futures::finished((self, session))
    }
}

fn main() {
    //! Starting the server thread.
    let client_key = thrussh_keys::key::KeyPair::generate_ed25519().unwrap();
    let client_pubkey = Arc::new(client_key.clone_public_key());
    let mut config = thrussh::server::Config::default();
    config.connection_timeout = Some(std::time::Duration::from_secs(600));
    config.auth_rejection_time = std::time::Duration::from_secs(3);
    config.keys.push(thrussh_keys::key::KeyPair::generate_ed25519().unwrap());
    let config = Arc::new(config);
    let sh = Server{
        client_pubkey,
        clients: Arc::new(Mutex::new(HashMap::new())),
        id: 0
    };
    tokio::run(thrussh::server::run(config, "0.0.0.0:2222", sh));
}

Note the call to session.handle(), which allows to keep a handle to a client outside the event loop. This feature is internally implemented using futures::sync::mpsc channels.

Note that this is just a toy server. In particular:

  • It doesn't handle errors when s.data returns an error, i.e. when the client has disappeared

  • Each new connection increments the id field. Even though we would need a lot of connections per second for a very long time to saturate it, there are probably better ways to handle this to avoid collisions.

Implementing clients

Maybe surprisingly, the data types used by Thrussh to implement clients are relatively more complicated than for servers. This is mostly related to the fact that clients are generally used both in a synchronous way (in the case of SSH, we can think of sending a shell command), and asynchronously (because the server may send unsollicited messages sometimes), and hence need to handle multiple interfaces.

The important types in the client module are Session and Connection. A Connection is typically used to send commands to the server and wait for responses, and contains a Session. The Session is passed to the Handler when the client receives data.

extern crate thrussh;
extern crate thrussh_keys;
extern crate futures;
extern crate tokio;
extern crate env_logger;
use std::sync::Arc;
use thrussh::*;
use thrussh::server::{Auth, Session};
use thrussh_keys::*;
use futures::Future;
use std::io::Read;


struct Client {
 key: Arc<thrussh_keys::key::KeyPair>
}

impl client::Handler for Client {
   type Error = ();
   type FutureBool = futures::Finished<(Self, bool), Self::Error>;
   type FutureUnit = futures::Finished<Self, Self::Error>;
   type FutureSign = futures::Finished<(Self, thrussh::CryptoVec), Self::Error>;
   type SessionUnit = futures::Finished<(Self, client::Session), Self::Error>;
   fn check_server_key(self, server_public_key: &key::PublicKey) -> Self::FutureBool {
       println!("check_server_key: {:?}", server_public_key);
       futures::finished((self, true))
   }
   fn channel_open_confirmation(self, channel: ChannelId, session: client::Session) -> Self::SessionUnit {
       println!("channel_open_confirmation: {:?}", channel);
       futures::finished((self, session))
   }
   fn data(self, channel: ChannelId, ext: Option<u32>, data: &[u8], session: client::Session) -> Self::SessionUnit {
       println!("data on channel {:?} {:?}: {:?}", ext, channel, std::str::from_utf8(data));
       futures::finished((self, session))
   }
}

impl Client {

 fn run(self, config: Arc<client::Config>, _: &str) {
    let key = self.key.clone();
    tokio::run(

      client::connect_future(
        "127.0.0.1:2222", config, None, self,
        |connection| {
          connection.authenticate_key("pe", key)
            .and_then(|session| {
              session.channel_open_session().and_then(|(session, channelid)| {
                session.data(channelid, None, "Hello, world!").and_then(|(mut session, _)| {
                  session.disconnect(Disconnect::ByApplication, "Ciao", "");
                  session
                })
              })
        })
      }).unwrap().map_err(|_| ())
    )
 }
}

fn main() {
   env_logger::init();
   // Starting the server thread.
   let client_key = thrussh_keys::key::KeyPair::generate_ed25519().unwrap();
   let client_pubkey = Arc::new(client_key.clone_public_key());
   let mut config = thrussh::client::Config::default();
   config.connection_timeout = Some(std::time::Duration::from_secs(600));
   let config = Arc::new(config);
   let sh = Client { key: Arc::new(client_key) };
   sh.run(config, "127.0.0.1:2222");
}

Using non-socket IO / writing tunnels

The easy way to implement SSH tunnels, like ProxyCommand for OpenSSH, is to use the thrussh-config crate, and use the Stream::tcp_connect or Stream::proxy_command methods of that crate. That crate is a very lightweight layer above Thrussh, only implementing for external commands the traits used for sockets.

The SSH protocol

If we exclude the key exchange and authentication phases, handled by Thrussh behind the scenes, the rest of the SSH protocol is relatively simple: clients and servers open channels, which are just integers used to handle multiple requests in parallel in a single connection. Once a client has obtained a ChannelId by calling one the many channel_open_… methods of client::Connection, the client may send exec requests and data to the server.

A simple client just asking the server to run one command will usually start by calling client::Connection::channel_open_session, then client::Connection::exec, then possibly client::Connection::data a number of times to send data to the command's standard input, and finally Connection::channel_eof and Connection::channel_close.

Design principles

The main goal of this library is conciseness, and reduced size and readability of the library's code. Moreover, this library is split between Thrussh, which implements the main logic of SSH clients and servers, and Thrussh-keys, which implements calls to cryptographic primitives.

One non-goal is to implement all possible cryptographic algorithms published since the initial release of SSH. Technical debt is easily acquired, and we would need a very strong reason to go against this principle. If you are designing a system from scratch, we urge you to consider recent cryptographic primitives such as Ed25519 for public key cryptography, and Chacha20-Poly1305 for symmetric cryptography and MAC.

Internal details of the event loop

It might seem a little odd that the read/write methods for server or client sessions often return neither Result nor Future. This is because the data sent to the remote side is buffered, because it needs to be encrypted first, and encryption works on buffers, and for many algorithms, not in place.

Hence, the event loop keeps waiting for incoming packets, reacts to them by calling the provided Handler, which fills some buffers. If the buffers are non-empty, the event loop then sends them to the socket, flushes the socket, empties the buffers and starts again. In the special case of the server, unsollicited messages sent through a server::Handle are processed when there is no incoming packet to read.

Dependencies

~5MB
~91K SLoC