Ssh – iptables is preventing ssh to aws ec2 instance

amazon ec2awsiptablesssh

I have a home laptop running Windows 7 and have just set up an Amazon aws ec2 instance running Ubuntu. The Ubuntu instance has the public IP address 34.195.109.193. I use PuTTY to ssh to the ec2 instance. I have found that setting up the iptables rules, on the Ubuntu instance as follows, prevents me from using ssh to access the Ubuntu ec2 instance.

sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A INPUT -d 34.195.109.193 -p tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -j DROP

I have set my security group up to allow ssh input and output on port 22. I cannot understand why the
sudo iptables -A INPUT -d 34.195.109.193 -p tcp –dport 22 -j ACCEPT

line does not allow me to ssh using PuTTY.

Best Answer

You need to change this line

sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

To

sudo iptables -A INPUT -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT

Because your rule matches only established (syn-ack) and related connections, not new ones (syn)

So complete rule should look like:

sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 22 -d 34.195.109.193 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A INPUT -j DROP

sudo iptables -A OUTPUT -p tcp -m state --state ESTABLISHED,RELATED -j ACCEPT
sudo iptables -A OUTPUT -p tcp -j DROP

The last output rule, will allow established connections to your host.

Related Question