SSH tunneling is a method of connecting to machines on the other side of a gateway machine. The gateway machine will be 'tunneled' through in order to gain access to machines on the other side. This method presumes both these machines are running SSH making it possible to set up the tunnel.
Begin with creating a ssh tunneling session:
ssh -f <GATEWAY_USERNAME@>GATEWAY -L localhost:CPORT:SERVER:SPORT -N
-f option instructs the ssh instance to go into the background, and
-N instructs it to not launch a shell. Followed by:
ssh -p CPORT <SUSERNAME@>localhost
The variables above represent:
- The hostname/IP address of the gateway machine.
- The username on the gateway (optional if this username is the same as on the client).
- The hostname/IP address of the server you wish to log into.
- The username on the server (optional if this username is the same as on the client).
- The port number on which the server SSH daemon is listening, by default 22.
- The port number of your choosing on which the tunnel will be receiving connections on the client machine (should be greater than 1024 unless you are invoking as root).
You can scp files from the server as you would normally by specifying the tunnel port:
scp -P CPORT localhost:REMOTEPATH LOCALPATH
Similarly for sending files to the server:
scp -P CPORT LOCALPATH localhost:REMOTEPATH
In order to make this tunneling process less onerous in the future:
- Set these commands as shell aliases (in Bash, usually in ~/.bashrc).
- To avoid typing passwords, copy the client key to the gateway, and the client and gateway keys to the server.
- If you rely upon keeping an unattended connection alive which may become dropped due to timeouts, consider altering the various TCP keepalive settings in the client and server configurations. Perhaps the most robust solution is to install a connection watchdog such as net-misc/autossh which will babysit an ssh session and restart it if necessary.
To enable X11 forwarding, first the X11Forwarding and ForwardX11 options must be set to
yes for both the X client and server being connected to respectively. In your SSH client connection, add the
-Y option to the second invocation above, and optionally the
-C switch to also enable compression i.e:
ssh -YC -p CPORT <SUSERNAME@>localhost
The following is required for the forwarding of X11 connections from the remote server to local client to work:
- The SSH daemon on the gateway machine must have TCP forwarding must be enabled, otherwise X11 connections won't be forwarded:
- The xauth tool must be present on the local X server. Install net-misc/openssh with the
XUSE flag set to pull it in or install x11-apps/xauth.
- X11 forwarding must be enabled in the remote server SSH daemon configuration: