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?
- For rules in the
OUTPUT
chain you should specify the source port match (--sport
), not the destination port (--dport
). - Anyway
DROP
policy in theOUTPUT
chain isn't a common practice. - Read the iptables tutorial and example rule sets.
- To avoid of lost of the connection, better use
iptables-save
andiptables-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.