Securing your server: IPTables

Setting up good firewall rules is essential for server administration. The following iptables configuration is a good starting point for IPv4. It only allows specific traffic through (ping, http/https, irc, ssh) and rejects everything else. The config is a little flexible once traffic has been established, as it will allow that traffic through.

While changing iptables rules, ensure that you have an active connection to the server as you do not want to get locked out of your own server. These snippets of configuration are mostly for my own reference, just in case I forget something.

*filter

# Allow all loopback (lo0) traffic and reject traffic
# to localhost that does not originate from lo0.
-A INPUT -i lo -j ACCEPT
-A INPUT ! -i lo -s 127.0.0.0/8 -j REJECT

# Allow ping.
-A INPUT -p icmp -m state --state NEW --icmp-type 8 -j ACCEPT

# Allow SSH connections.
-A INPUT -p tcp --dport 22 -m state --state NEW -j ACCEPT

# Allow HTTP and HTTPS connections from anywhere
# (the normal ports for web servers).
-A INPUT -p tcp --dport 80 -m state --state NEW -j ACCEPT
-A INPUT -p tcp --dport 443 -m state --state NEW -j ACCEPT

# Allow inbound traffic from established connections.
# This includes ICMP error returns.
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow IRC connections.
-A INPUT -p tcp --dport 6697 -m state --state NEW -j ACCEPT

# Allow a range of connections.
-A INPUT -p tcp --match multiport --dports 25950:26000 -m state --state NEW -j ACCEPT

# Log what was incoming but denied (optional but useful).
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables_INPUT_denied: " --log-level 7

# Reject all other inbound.
-A INPUT -j REJECT

# Log any traffic that was sent to you
# for forwarding (optional but useful).
-A FORWARD -m limit --limit 5/min -j LOG --log-prefix "iptables_FORWARD_denied: " --log-level 7

# Reject all traffic forwarding.
-A FORWARD -j REJECT

COMMIT

External Resources