Friday, March 11, 2016

Reverse SSH Forward with special user

We will create a user on our machine that the remote machine can connect as and initiate a reverse port forward. For this example, we'll allow the remote machine to connect with the user name "ssh-limited" and forward port 62222 back to themselves. Just make sure that the remote machine can reach your box via ssh first ;)

Create user with no shell, and set passwd (src):

sudo useradd -m \
     -s $(which nologin || echo "/bin/false") \
     -c "special user for ssh forwards only" \
     ssh-limited

sudo passwd ssh-limited
# enter password to be used to login as ssh-limited

Restrict ssh usage (src):


sudo bash -c "cat <<EOF >>/etc/ssh/sshd_config

# Special ssh user for port forwards only ~ $(whoami), $(date)
Match User ssh-limited
   AllowTcpForwarding yes
   X11Forwarding no
   PermitTunnel no
   GatewayPorts no
   AllowAgentForwarding no
   PermitOpen localhost:62222
EOF"
You'll also need to restart ssh to take the new config:
sudo service ssh restart

Testing the setup

First, check to see that you can connect locally as "ssh-limited":
ssh ssh-limited@localhost
# should return false and send a message if 'nologin' was specified for shell
Do the same from your public IP (don't forget to add the '-p PORT' if you're not listening on 22!):
ssh ssh-limited@YOUR_PUBLIC_IP
# should return same as above
Finally test the whole thing (again '-p' for non standard public ssh port):

# this shouldn't work (unless you've set up ssh to listen on port 62222
ssh localhost -p 62222

# in one terminal initiate the forward
ssh -N -R 62222:localhost:22 ssh-limited@YOUR_PUBLIC_IP

# in the another terminal attempt to login through the tunnel:
ssh localhost -p 62222
# Now it should have worked!
At this point you (or a third party) can enter the following command at the remote machine and enter the password when prompted. Just replace YOUR_PUBLIC_IP with your actual IP or domain name:
ssh -N -R 62222:localhost:22 ssh-limited@YOUR_PUBLIC_IP
# client enters password for ssh-limited
# Now you can connect to the remote machine
# with `ssh client-user@localhost -p62222'
Further reading:

No comments :