SSH into remote machine via proxy

Today I configured SSH on my local machine for easy access of a remote machine via a proxy.

The setup

I have to access a server at work. This server only allows connections from a limited number of hosts. All of them have to be whitelisted in /etc/hosts.allow one by one. Since I don’t have a static IP address at home I had to use another host to connect from. My setup thus is:

  • ssh from home into my virtual server
  • From there ssh into the remote machine I actually want to conect to

My workflow looked as follows:

local$ ssh proxy.example.com
virtual_server$ ssh work.example.org
work$

The problem

This works flawelessly. I use public/private key pairs to authenticate so I don’t need to enter any passwords. However it is a hassle to use. Especially if you want to copy files using scp.

The solution

You could merge the above commands into one command to make the whole endavour easier:

local$ ssh proxy.example.com ssh work.example.org

However this is a lot to write. Using an alias doesn’t help you if you want to use other commands to use the ssh connection. Say scp.

Luckily ssh can be configured to do all the hard work for us. All you need is the ProxyCommand option in your ssh configuration. This is what you have to add to your ~/.ssh/config file:

host work
    hostname work.example.org
    ProxyCommand ssh proxy.example.com nc %h %p
    ProxyCommand ssh proxy.example.com -W %h:%p

Now you can connect to the work server with ssh work. All the hard proxy tunneling is done transparently.

The explanation

The above configuration does three things:

  1. Configur a shorthand for the host: work now resolves to the full hostname work.example.org
  2. Tell ssh not to connect to work.example.com directly but connect to proxy.example.com first.
  3. Send all data from the ssh session to work.example.org via the ssh connection to proxy.example.com.

nc is the netcat program which outputs data from the input to a ressource on the network. Thus all data from the ssh session gets routed from the proxy to the work server.

[Edit]Instead of using nc one can also use ssh’s built in -W flag to achieve the same thing. I updated the config above accordingly.[/Edit]

Looking further

Of course there is a lot of tweaking you could add to this setup. For instance you could configure the connection to the proxy server in your ~/.ssh/config. You could also add which username has to be used for any of the connections (use the User option in your config file). You could set up two and more hops to connect to the target server. etc.