Skip to content

Instantly share code, notes, and snippets.

@markjlorenz
Last active March 24, 2022 06:42
Show Gist options
  • Save markjlorenz/6206454 to your computer and use it in GitHub Desktop.
Save markjlorenz/6206454 to your computer and use it in GitHub Desktop.
Reverse Proxy Tunneling with an amazon EC2. Poor-mans gotomypc, teamviewer, etc.

Reverse Port Tunneling with EC2

Reverse port tunneling is used to give a user outside of a networks firewall accesst to a computer inside the firewall where direct SSH connections aren't allowed. It works by the in-firewall computer SSH'ing to a middleman computer that then forwards incomming SSH connections on a given port to the firewalled computer.

Setup the middleman

  • Get an ubuntu EC2 instance
  • Download it's security keys (both in-firewall and out-firewall computers will need the private key)
  • Setup the security group to allow connections on port 10002
  • SSH into the middleman and add: GatewayPorts yes to /etc/ssh/sshd_config
  • sudo reload ssh
  • For good measure: sudo iptables -A INPUT -p tcp --dport 10002 -j ACCEPT

From the in-firewall computer

  • Add the ssh key for middle man to ~/.ssh/ec2_keys/ (it's a .pem file)

  • Set the permissions: chomd 400 ~/.ssh/ec2_keys/<middleman-cert>.pem

  • Add to ~/.ssh/config:

    Host <your-ec2-stuff>.compute-1.amazonaws.com
    IdentityFile ~/.ssh/ec2_keys/<middleman-cert>.pem
    User ubuntu
    
  • ssh -R 10002:localhost:22 ubuntu@<your-ec2-stuff>.compute-1.amazonaws.com (you can use -f to daemonize it)

From the out-firewall computer

  • Add the ssh key for middle man to ~/.ssh/ec2_keys/

  • Set the permissions: chomd 400 ~/.ssh/ec2_keys/<middleman-cert>.pem

  • Add to ~/.ssh/config:

    Host <your-ec2-stuff>.compute-1.amazonaws.com
    IdentityFile ~/.ssh/ec2_keys/<middleman-cert>.pem
    
  • ssh infirewall-username@<your-ec2-stuff>.compute-1.amazonaws.com -p 10002 (you can -Y to forward X11)

And you're L33t!

@johann8384
Copy link

johann8384 commented Jun 26, 2019

Just a note, to make a systemd daemon with your reverse tunnel in it:

user@loclalhost:~$ cat /etc/systemd/system/phone-home.service
[Unit]
Description=Phone Home Reverse SSH Service
ConditionPathExists=|/usr/bin
After=network.target

[Service]
User=medrc
ExecStart=/usr/bin/ssh -NTC -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes -o StrictHostKeyChecking=no -i ~username/.ssh/id_rsa -R 2244:localhost:22 username@cloudserver -p 2242

# Restart every >2 seconds to avoid StartLimitInterval failure
RestartSec=3
Restart=always

[Install]
WantedBy=multi-user.target

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment