SSH Reverse socks tunnel

Can be achieved transparently with this snippet in ~/.ssh/config:

Host sockstunnel
    ProxyCommand ssh -D 3128 localhost nc -q 1 localhost 22

Host target
    RemoteForward 3128 localhost:3128
    ProxyCommand ssh -W target:22 sockstunnel

Details

We want a reverse DynamicForward. This is achieved using two ssh commands:

  • ssh -D 3128 localhost
  • ssh -R 3128:localhost:3128 target

This way target has a SOCKS tunnel to the SSH client.

What I did is to use the classical way of chaining ssh to reach a remote target through intermediate hosts so that the SOCKS tunnel creation is handled transparently while logging into the target. The first ProxyCommand + nc trick is mandatory because -W implies ClearAllForwardings.


With -D & -L you have a way to communicate either way between the two machines.

So...

  • From the local machine, use -R to create a listening port on the remote machine pointed at the local machine's sshd.
  • Use -D on the remote machine, pointed at the port you created above.

I "think" filling in the below will make it work...

ssh remotehost -R remoteport:localhost:localport "ssh -D 9050 localhost -p remoteport"

'remotehost', 'remoteport' & 'localport' in the above need changing. A socks proxy will be formed on 9050.


local$ ssh -R 1080 remote
remote$ curl --socks5 localhost https://example.com

since OpenSSH 7.6

ssh(1): add support for reverse dynamic forwarding. In this mode, ssh will act as a SOCKS4/5 proxy and forward connections to destinations requested by the remote SOCKS client. This mode is requested using extended syntax for the -R and RemoteForward options and, because it is implemented solely at the client, does not require the server be updated to be supported.

https://www.openssh.com/txt/release-7.6