SSH Tunnel with Keys – Step-by-Step Guide

sshssh-tunnel

Port 9999 on a remote server needs to be accessed through an SSH tunnel at local port 9990 to avoid firewalls.

I am using this command to SSH tunnel:

ssh -N -i share.pem -L 9990:`ecshare`:9999 ubuntu@`ecshare`

where ecmy contains the ec2 instance's ip.
As a baseline, I can ssh and get a remote shell with this command:

ssh -i share.pem ubuntu@`ecshare`

But, when I try this on the local prompt:

curl -i -X GET http://localhost:9990

I get this on the shell where the tunnel was started:

channel 2: open failed: connect failed: Connection refused

When I try this command on the remote shell:

curl -i -X GET http://localhost:9999

… I get a response from the server.

Why is connection being refused?

Best Answer

Despite the authentication method used, SSH tunneling works the same way. The problem here is not about using public key authentication but understanding the basics of How to Use SSH Tunneling.

Your -L 9990:example.com:9999 connects to the public network interface on the remote side while you connect to localhost:9999 in your curl test. The firewall you mentioned you need to avoid is probably on the remote side, preventing you to use http://example.com:9999/ in the first place.

You should use -L 9990:localhost:9999 instead to make it use local loopback.

Difference between <code>example.com</code> and <code>localhost</code> on the remote side.

This diagram visualizes your situation. The -L [ bind_address:]port:host:hostport...

...works by allocating a socket to listen to port on the local side, optionally bound to the specified bind_address. Whenever a connection is made to this port, the connection is forwarded over the secure channel, and a connection is made to host port hostport from the remote machine.