SSH tunneling

From Gentoo Wiki
Jump to:navigation Jump to:search

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:


The -f option instructs the ssh instance to go into the background, and -N instructs it to not launch a shell. Followed by:

user $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:


Similarly for sending files to the server:



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.

X11 forwarding

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:

user $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:
FILE /etc/ssh/sshd_configOn the gateway
AllowTcpForwarding yes
  • X11 forwarding must be enabled in the remote server SSH daemon configuration:
FILE /etc/ssh/sshd_configOn the server
X11Forwarding yes

See also

  • SSH — the ubiquitous tool for logging into and working on remote machines securely.
  • SSH jump host — employed as an alternative to SSH tunneling to access internal machines through a gateway.

External resources