Nested (Nested (Nested SSH) SSH)) SSH

There are occasions where I need to reach a server via SSH that is only reachable through multiple bastions. Sometimes this is because of security reasons and other times it is because the machines are on different networks with no direct route. One can of course SSH to the first bastion, then from there to the next, and so forth, but that is annoying to have to type each time. We can do this from the command line as well as in the SSH config.

An example from the command line (for scripting, not typing) using strung together commands:

ssh -t user@host1 ssh -t user@host2 ssh -t user@host3 … ssh user@destination

The ‘-t’ flag tells SSH to use a pseudo terminal on the remote machine. This is required if you intend on running a command, such as SSH itself, that expects to be executed in a terminal instead of as a detached/background process. The final SSH command doesn’t need the ‘-t’ flag if you are aiming for a remote shell such as bash.

An example from the command line (again, for scripting) using jumphost flag:

ssh -J user@host1,user@host2,user@host3,… user@destination

Okay so that’s pretty cool, but what if we want to make it a permanent setting in our SSH config? Well, we can do that too by adding these lines to our ~/.ssh/config:

# host1
host host1
HostName host1.fqdn
User user

# host2
host host2
HostName host2.fqdn
User user
ProxyJump host1

# host3
host host3
HostName host3.fqdn
User user
ProxyJump host2

# destination
host destination
HostName destination.fqdn
User user
ProxyJump host3

Now we can use ‘ssh destination’ and SSH will handle the rest for us.

That covers the basics and should give you a glimpse of how chill SSH is with being nested, strung together, and so on.