Monday, July 04, 2011

Transparent SSH through proxy and gateway

Suppose you are behind a restrictive network, and you need to connect via SSH to a remote machine outside the network. You have the ability to access the Internet through a proxy server. To accomplish the task of connecting to the remote machine, you can use a feature of SSH called ProxyCommand.

In the following examples, it is assumed that the proxy server is a SOCKS proxy server. The "connect" utility is used to tunnel through a SOCKS proxy server. Please substitute the utility appropriately based on the requirements of your network infrastructure. For a list of common network tunneling tools, see my post on this topic.

Example 1: hop through a proxy

You want to connect via SSH to a remote machine on the Internet. In your .ssh/config file, add the following entry and substitute the variables with the corresponding values for your environment.

ProxyCommand connect -S <proxy_server>:<socks_proxy_port> <remote_machine> 22 2> /dev/null

Once you have configured the ProxyCommand, run the following command to connect to the remote machine.

% ssh <remote_machine>

Example 2: hop through a proxy and a gateway

Now let's suppose the scenario is the same as above, but the remote machine is located behind a gateway. To accomplish this, we first have to tunnel to the Internet through the proxy. Next, we tunnel to the remote machine through the gateway. The following ProxyCommand accomplishes the two steps.

ProxyCommand ssh -l root -o "ProxyCommand connect -S <proxy_server>:<socks_proxy_port> <gateway> 22" <gateway> <gateway_netcat> <remote_machine> 22 2> /dev/null

This ProxyCommand accomplishes multiple steps. It, itself calls ssh, but this call has a ProxyCommand, specified with the -o option, as a prerequisite. The nested ProxyCommand says we first tunnel to the Internet through the proxy. Next, we ssh into the gateway and run netcat to connect to the remote machine and port.

Once you have configured the ProxyCommand, run the following command to connect to the remote machine.

% ssh <remote_machine>

Troubleshooting

If you run into any problems, check the following.
  • Make sure you can successfully connect through your proxy using the basic tunneling utilities.
  • Make sure your username is correct at each hop. In the above examples, it is assumed that the usernames are the same on each client/machine/gateway.
  • Make sure the SSH port is correct on each machine/gateway.
  • In the example of hopping through the gateway, make sure netcat is installed on the gateway.

No comments: