Reverse SSH shell to WSL2
WLS2 is configured by default in a NAT network.That means we can't generally reach it from the outside.
To connect to it externally, let us configure WSL 2 for reverse shell
Prerequisite
- Another SSH server that acts as gateway. This server should be accessible from the outside. For this exercise we will be using 192.168.2.30 as the gateway IP.
Step 1: Enable SSH on WSL2
$: sudo ssh-keygen -A
$: sudo service ssh start
Step 2: Verify connection from WSL2 to the gateway SSH server
$: ssh -R 2222:localhost:22 u1@192.168.2.30
$: ssh u2@localhost -p 2222
u2@localhost: Permission denied (publickey).
To fix this, change /etc/ssh/sshd_config on WSL2, ensure that:
- PasswordAuthentication is set to yes
- ChallengeResponseAuthentication is set to no
$: sudo service ssh restart
$: ssh -R 2222:localhost:22 u1@192.168.2.30
$: ssh u2@localhost -p 2222
Step 3: Use public/private key to connect
Providing the password everytime we establish a connection gets really tiring, so let us use public/private key for the connection.Let us start from WSL2 to the gateway, generate private/public key pair on WSL2:
$: ssh-keygen -t rsa -b 2048
$: cat ~/.ssh/id_rsa.pub | ssh u1@192.168.2.30 "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
$: ssh -R 2222:localhost:22 u1@192.168.2.30
$: ssh-keygen -t rsa -b 2048
$: cat ~/.ssh/id_rsa.pub | ssh u2@localhost -p 2222 "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
Step 4: Create the tunnel when WSL2 is started
It is probably best for the tunnel that was created to require no interaction, so we run it like:$: ssh -R 2222:localhost:22 u1@192.168.2.30 -N
$: ssh -R 2222:localhost:22 u1@192.168.2.30 -N &
$: sudo visudo
u2 ALL=(ALL) NOPASSWD: ALL
Then add the following to ~/.bashrc, do this towards the end of the file:
sudo service ssh status if [ $? -ne 0 ]; then echo "Starting" sudo service ssh start echo "tunnel" nohup ssh -R 2222:localhost:22 u1@192.168.2.30 -N >/dev/null 2>&1 & fi
Step 5: Connect to WSL2 via the gateway
Now for the fun stuff, to connect to WSL2 from getaway, we need to create another tunnel!!! This time ssh client will listen on port 2222 locally, any connection to that port will be tunneled to the gateway (192.168.2.30) on port 2222. Remember that port 2222 on the gateway was reverse tunnelled to port 22 on WSL2:c:\> ssh -L 2222:localhost:2222 u1@192.168.2.30
c:\> ssh u2@localhost -p 2222
Comments