Automated forwarding to reverse tunnel

I have a Raspberry Pi (remote) which is behind a NAT. In order to access it from my home computer (local), I connect it to my ASW server (server) via reverse tunnel as described in various posts.

Remote connects to server:

ssh -f -N -T -R22222:localhost:22 -i ssh-ec2/ec-key.pem [email protected]

I can then connect to my ASW server via SSH and once I'm logged in I can connect to my Raspberry via:

ssh -p 22222 pi@localhost

That all works fine.

My problem now is, that I want to do remote session with intellij from my local directly to my remote Raspberry. For that I need to connect to my server via SSH and then manually enter again the connected to my remote.

How can I set up a tunnel so I can connect to my server, but directly to port 22222? I have tried the following from my local machine, but the connection times out:

ssh -l 9999:localhost:22222 [email protected] -i c:/privatekey.pem

Any suggestions what I'm doing wrong? Sorry I'm totally new to Linux, so apologies if that's a stupid question.


Solution 1:

When you connect from your ASW server, you connect to localhost. Note what man 1 ssh says:

-R [bind_address:]port:host:hostport

[…]

By default, the listening socket on the server will be bound to the loopback interface only. This may be overridden by specifying a bind_address. An empty bind_address, or the address *, indicates that the remote socket should listen on all interfaces. Specifying a remote bind_address will only succeed if the server's GatewayPorts option is enabled (see sshd_config(5)).

Then man 5 sshd_config says:

GatewayPorts

Specifies whether remote hosts are allowed to connect to ports forwarded for the client. By default, sshd(8) binds remote port forwardings to the loopback address. This prevents other remote hosts from connecting to forwarded ports. GatewayPorts can be used to specify that sshd should allow remote port forwardings to bind to non-loopback addresses, thus allowing other hosts to connect. The argument may be no to force remote port forwardings to be available to the local host only, yes to force remote port forwardings to bind to the wildcard address, or clientspecified to allow the client to select the address to which the forwarding is bound. The default is no.

To make it work you should do something like this:

  • include GatewayPorts clientspecified in sshd_config on the server (and restart/reload the daemon, see Is there any backup for ssh configuration, to roll back on error?, Does restarting sshd always keep existing sessions alive? and Restart SSH on a machine where SSH is the only mode of access);
  • connect with ssh … -R :22222:localhost:22 … from the Raspberry (note the first :, it separates empty bind_address from port).