Ssh into NATted VM via AutoSSH

Overview

Suppose you have a virtual machine running on a natted network connection. It can get out just fine to the Internet.
Now, with the network address translation (NAT), you can’t send traffic in to that network. So you can’t just ssh username@vm.example.com and get in. You are going to need something a little fancier to accomplish that. This document explains how to do that.

Sample environment

For this document, these example values will be used. The vm is centos.vm.example.com and the system on the main network is desktop.example.com. The desktop will have port 5000 be forwarded to the vm’s port 22, which is the standard ssh port.

Set up autossh

You need ssh connectivity between the vm and the physical host. Make sure you have an automatic log in from the vm to the physical host. A good way to do that is by having an ssh key. If you need to generate one on the vm and copy it to the physical machine, use these commands.
# on vm
ssh-keygen # follow the prompts

The next step is to copy it to the physical machine.
# still on vm
ssh-copy-id username@desktop.example.com

Check that you can log in automatically with
ssh username@desktop.example.com
Once that is done, install autossh and make a systemd service file and enable and start it.
yum -y install autossh
tf=/usr/lib/systemd/system/autossh-ssh.service
touch "${tf}"; chmod 0644 "${tf}"
cat <<EOF > "${tf}"
[Unit]
Description=AutoSSH tunnel service for ssh
After=network.target
[Service]
Environment="AUTOSSH_GATETIME=0"
ExecStart=/usr/bin/autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -N -R 5000:localhost:22 username@desktop.example.com -p 22
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable autossh-ssh.service
systemctl start autossh-ssh.service

Using the reverse tunnel

To connect to centos.vm.example.com, you just need to do this:
ssh centosusername@localhost -p 5000

Bonus: nickname the connection and copy ssh key

What I did was set up my ~/.ssh/config file with the following snippet, so I can just use the nickname “centosvm.”

# in ~/.ssh/config, mode 0600
Host centosvm centosvm.vm.example.com
 User centosuser
 Hostname localhost
 Port 5000

I then copied my ssh id to that, so I could connect without a password.
ssh-copy-id centosvm

References

  1. https://www.everythingcli.org/ssh-tunnelling-for-fun-and-profit-autossh/
  2. http://www.harding.motd.ca/autossh/index.html
  3. http://surniaulula.com/2012/12/10/autossh-startup-script-for-multiple-tunnels/

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.