Can't access instance after setting up iptables rules

I'm trying to setup some rules to block all ports except 21 and 22 on TCP (SSH and FTP). But when I try to run this script I get locked out of my instance and can't access it. This is the script:

# Flush the FW Rules 
iptables -F
iptables -X

# Block all traffic
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP

# Allow SSH
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 22 -j ACCEPT

# Allow FTP
iptables -A INPUT -p tcp --dport 21 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 21 -j ACCEPT

# Allow ICMP (ping)
iptables -A INPUT -p icmp -j ACCEPT
iptables -A OUTPUT -p icmp -j ACCEPT

In script it sets up both incoming and outgoing requests for SSH and FTP but why can't I access it?


  1. For rules in the OUTPUT chain you should specify the source port match (--sport), not the destination port (--dport).
  2. Anyway DROP policy in the OUTPUT chain isn't a common practice.
  3. Read the iptables tutorial and example rule sets.
  4. To avoid of lost of the connection, better use iptables-save and iptables-apply tools.

You should set up state tracking, and lose the -A OUTPUT ... -j ACCEPT lines.

IPTABLES -I INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
IPTABLES -I FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
IPTABLES -I OUTPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

It's good to see you are using explicit egress filtering, but it's more work to implement.