Skip to content

Instantly share code, notes, and snippets.

@nudles
Forked from markjlorenz/how-to.markdown
Last active January 19, 2021 03:59
Show Gist options
  • Save nudles/27bf71212d67e0978086c63dce6c1a2f to your computer and use it in GitHub Desktop.
Save nudles/27bf71212d67e0978086c63dce6c1a2f 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 -f -N -R 10002:localhost:22 ubuntu@<your-ec2-stuff>.compute-1.amazonaws.com

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!

@nudles
Copy link
Author

nudles commented Dec 31, 2020

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