Create keys

# Generate key
ssh-keygen -t rsa -N "" -b 2048 -C "a description of the new key" -f ~/.ssh/my_key
# Create PEM
openssl rsa -in ~/.ssh/my_key -pubout > ~/.ssh/my_key_pem.pub
# Get fingerprint
openssl rsa -pubin -outform DER -in ~/.ssh/my_key_pem.pub | openssl md5 -c

Change SSH server port

Edit the sshd_config file and adjust the Port as desired. You'll need to restart sshd after the edit.

sudo vim /etc/ssh/sshd_config
sudo systemctl restart ssh

Create an SSH tunnel

# Format
ssh -L <local port>:<local host>:<remote port> <remote host>

# Example
ssh -L 80:localhost:9999 host.example.com

Create a reverse tunnel

If you want to SSH to your home computer that's behind a NAT and also have an internet facing server, you can proxy through your public server with a reverse tunnel from your home computer. Make sure to install autossh on your home computer before starting this. autossh will restart the ssh tunnel if it fails.

I'll use these as examples:

  • Home internal IP:
  • Public server: example.com

Step 1: Server setup

On your public server (the example.com one), make sure you have the line GatewayPorts clientspecified in your /etc/ssh/sshd_config. If you don't, add it and restart/reload sshd.

Step 2: Home computer setup

From your home computer (the one) issue the following command:

autossh -M 10239 -fN -o "PubkeyAuthentication=yes" -o "StrictHostKeyChecking=false" \
-o "PasswordAuthentication=no" -o "ServerAliveInterval 60" \
-o "ServerAliveCountMax 3" -R \*:12345:localhost:22 your_server_username@example.com
  • -M 10239 is used for by autossh for test data to monitor the connection
  • \* binds the port to all interfaces (not just the loopback
  • 12345 is the port you'll used when connecting to your home computer. Change this to whatever you like.

Step 3: From a 3rd remote computer

Now from a remote computer, say your laptop or mobile phone, ssh to your home computer through your server.

ssh your_home_computer_username@example.com -p 12345

Step 4 (optional): Configure autossh to startup at boot

You'll have to remove the -f option above as it doesn't work with SystemD.

Create the startup script

cat > autossh.service << EOF
Description=AutoSSH Daemon


ExecStart=/usr/bin/autossh -M 10239 -N -o "PubkeyAuthentication=yes" -o "StrictHostKeyChecking=false" \
-o "PasswordAuthentication=no" -o "ServerAliveInterval 60" \
-o "ServerAliveCountMax 3" -R \*:12345:localhost:22 your_server_username@example.com



Now, enable and start it

sudo mv autossh.service /lib/systemd/system/autossh.service
sudo systemctl enable autossh
sudo systemctl start autossh
sudo systemctl status autossh