Automatic SSH tunnels on demand
Sometimes you have to build an SSH tunnel to access some remote service not directly available or not secure enough (think about an internal Jabber server, for example). This occasions I normally open an SSH session with the remote host tunnelling the services I want to access. It’s a bit annoying having to open a terminal just for me to use the remote services. So, crawling the Internet I found this neat procedure to automagicaly connect to a remote service over SSH by demand.
Ingredients
- Linux machine (Debian used)
- SSH client/server (on local/remote machine)
- inetd Internet super-server daemon (on the local machine)
- nc Netcat (on the remote machine)
Procedure
- Inetd listens on an arbitrary port in local machine
- User connects to an arbitrary port in its local machine
- Inetd opens the SSH connection to remote machine
- The remote machine executes the especified command in
authorized_keys2, a Netcat that will connect to the final port (in 127.0.0.1) - The secure bidirectional connection is established
Steps
- Create a password less key to login local(root) -> remote(user)
- Install the key in remote machine
- Select the shell to use when login with that key (a netcat to the redirected port)
- Edit the Internet super daemon configuration file to tunelize the communication
- Configure the client (in local machine) to connect to 127.0.0.1 using the port especified in inetd
- Enjoy
in [local_machine] as [root]
ssh-keygen -t dsa -f ~/.ssh/tunnel_key
Don’t use a passprase (just press ENTER when asked)
in [local_machine] as [root]
scp ~/.ssh/tunnel_key.pub user@remote_machine:/tmp
in [remote_machine] as [user]
cat /tmp/tunnel_key.pub >> ~/.ssh/authorized_keys2
Edit the ~/.ssh/authorized_keys2 file, go to the last line (the line we added on last step) and just before the ssh-ds leaving the line like this:
in [remote_machine] as [user]
command="nc localhost 5222",no-X11-forwarding,no-agent-forwarding,no-port-forwarding ssh-ds...
Edit the /etc/inetd.conf file. Add a new line that will listen an arbitrary port which will tunelize to the remote server. The line may look like this:
in [local_machine] as [root]
127.0.0.1:5222 stream tcp nowait root /usr/bin/ssh -q -T -i /root/.ssh/tunnel_key user@remote_machine
This is not suitable for services like HTTP proxies an the like. This kind of services open and close connections too quickly. Keep in mind that SSH sessions take its time to connect…
