SSH connection refused on an unusual port

amazon-web-servicessshtunnel

Using AWS EC2

Reverse SSH tunnel initiated from a remote machine to AWS:

/usr/bin/autossh -M 0 -N -R 19999:localhost:22 ec2-user@ec2.aws.com -v -i cloud.pem

Added port 19999 in AWS security groups.

Checked if I can connect with telnet to AWS:

telnet: Unable to connect to remote host: Connection refused

However, if I take away port 19999 in security groups I get a different response:

telnet: Unable to connect to remote host: Connection timed out

So I assume that problem is on the AWS host, and not with firewall on another machine.

Then I check if the sshd tunnel has started on the AWS end, in response to my connection.
netstat suggests that the service is listening:

tcp        0      0 127.0.0.1:19999   

But still I get Connection refused messages. What else I can analyze? I couldn't find any sshd logs on the AWS machine. /var/log/secure doesn't log these failed connection attempts.

Best Answer

From what I understand you wish to do a reverse tunnel to EC2 instance and then allow outside clients to make connection to that specified port 19999.

First of all when you run your command like provided as you can see with netstat the port is listening on loopback interface, so for this to work towards outsiders you need to prepend the bind address like so:

/usr/bin/autossh -M 0 -N -R 0.0.0.0:19999:localhost:22 ec2-user@ec2.aws.com -v -i cloud.pem

This will still give you error, so the next thing what you are actually looking for is GatewayPorts directive enabled in sshd server running on EC2.

You should edit /etc/ssh/sshd_config and ensure you have:

GatewayPorts clientspecified

definde inside the config. Restart your sshd server and use the above provided command. A more detailed explanation of this can be found at: Bypassing corporate firewall with reverse ssh port forwarding