IN-Decent

Re-decentralizing internet with free software

Make SSH Connections Faster by Reusing an Existing Connection

Posted at — May 31, 2020

To avoid the overhead of connection set up and authenticating to a remote host each time, SSH provides a cool feature to reuse an already authenticated SSH connection with ControlMaster and ControlPath configuration directives.

Using this feature can greatly reduce the connection setup time and is very useful for high latency connections. Specifying auto to ControlMaster will let SSH look for an existing master socket to connect to and establish a session over an already authenticated connection and if a master socket is not existing, it will automatically create one.

Location of master socket is specified by ControlPath directive, and this socket must be uniquely identifiable for a particular remote session and must placed in a private path where only user has access to. Since, any other users with access to this socket can connect to the remote host without requiring any authentication. SSH provides several TOKENS that will be expanded at run time can be used to uniquely identify a connection.

Once all connections to the remote host is closed master socket will be exited and any new connection will again go through the overhead of setting up a new connection. To prevent this SSH provides an other option called ControlPersist which can used to specify an idle timeout and the master socket remain active in background until idle timeout is reached.

To enable connection multiplexing by default for all hosts, add the following in your ~/.ssh/config file

Host *
 ControlMaster auto
 ControlPath ~/.ssh/%r@%h:%p
 ControlPersist 30m

If you want to obfuscate master socket name, use %C which will generate a hash of token values %l%h%p%r.

Also, to check the status and control master process ssh option -O can be used as follows,

$ ssh -O check myhost #check whether the master is active
Master running (pid=8112)
$ ssh -O stop myhost #instruct master to stop accepting new requests
Stop listening request sent.
$ ssh -O exit myhost #instruct master to force exit closing all connections
Exit request sent.

NOTE:

If you specify long intervals for ControlPersist make sure to also look into ServerAliveInterval and ServerAliveCountMax which will send heartbeats to prevent connection being closed by network.

References:

  1. OpenSSH/Cookbook/Multiplexing
  2. SSH Examples, Tips & Tunnels
  3. ssh_config man page
  4. ssh man page