SSH through multiple hosts using ProxyCommand?

I have an entry in ~/.ssh/config on my computer at home that look like this:

host foo bar
    ProxyCommand ssh -x -a -q gateway.example.com nc %h 22

where gateway.example.com is a server at work that is connected to both the public Internet and an internal network. The gateway box resolves foo and bar using entries in /etc/hosts.

My problem is that I need to reach a box that is on the other side of foo. Let's call it "baz". The "baz" host is on another private network that foo is connected to, but not the one that "gateway" is connected to.

I've tried using this:

host baz
    ProxyCommand ssh -x -a -q gateway/example.com ssh foo nc %h 22

But that doesn't work, and I'm a little out of my depth. How do I do this?

I don't think it should matter, but I'm doing this in Ubuntu 10.


Easy.

Assume the following network setup:

example network setup

You should be able to use a ~/.ssh/config file that looks something like this:

host foo bar
    ProxyCommand ssh -x -a -q gateway.example.com nc %h 22

host baz
    ProxyCommand ssh -x -a -q foo nc %h 22

The idea here is that your SSH does know how to get to "foo", so an SSH there will succeed. And from there, you can "nc" to baz. And if there are other hosts on the internal private network alongside "baz", you can just add them to the "host baz" line.

In newer versions of OpenSSH than 5.4 (which all should be at this point), you can use the -W command instead of an exec to an external nc command, and of course you can pack options together:

host foo bar
    ProxyCommand ssh -xaqW%h:22 gateway.example.com

host baz
    ProxyCommand ssh -xaqW%h:22 foo

In both of these casees, this treats the host "foo" as the gateway to "baz", just as "gateway" is the gateway to "foo".

Clear?


Regarding ghoti's answer: instead of using netcat ("ssh ... nc %h 22"), starting with OpenSSH 5.4, you can do this directly with: "ssh -W %h:22 ...". This way, you don't have to worry about whether netcat is installed in the right place.


Using private keys stored on your local computer, enter this command with the private keypaths, shell usernames, and hostnames/IP addresses changed to your local->gateway->destination ssh needs.

Note that ProxyCommand is preferred over Agent Forwarding to mitigate the risk of compromising private key authentication (using the gateway and local ssh agent connection to compromise further hosts as if the hijacker had the private key) when a gateway/jumperbox is root-hijacked.

Single Command To Proxy SSH to a Server (keep both private keys on local computer):

sudo ssh -i dest_private_key.pem -o "ProxyCommand ssh -W %h:%p -i gate_private_key.pem gate_user@gate_IP" dest_user@dest_IP