With IPTables rules, order matters. The rules are added, and applied, in order. Moreover, when adding rules manually they get applied immediately. Thus, in your example, any packets going through the INPUT and OUTPUT chains start getting dropped as soon as the default policy is set. This is also, incidentally, why you received the error
message you did. What is happening is this:
- The default DROP policy get applied
- IPTables receives a hostname as a destination
- IPTables attempts a DNS lookup on 'serverfault.com'
- The DNS lookup is blocked by the DROP action
While the source/destination options will accept hostnames, it is strongly discouraged. To quote the man page,
Hostnames will be resolved once
only, before the rule is submitted to
the kernel. Please note that
specifying any name to be resolved
with a remote query such as DNS is a
really bad idea.
Slillibri hit the nail on the head which his answer, you missed the DNS ACCEPT rule. In your case it won't matter, but generally I would set the default policy later on the process. The last thing you want is to be working remotely and allow SSH after turning on a default deny.
Also, depending on your distribution, you should be able to save your firewall rules such that they will be automatically applied at start time.
Knowing all that, and rearranging your script, here is what I would recommend.
# Allow loopback
iptables -I INPUT 1 -i lo -j ACCEPT
# Allow DNS
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
# Now, allow connection to website serverfault.com on port 80
iptables -A OUTPUT -p tcp -d serverfault.com --dport 80 -j ACCEPT
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# Drop everything
iptables -P INPUT DROP
iptables -P OUTPUT DROP
Have you tried loading your new rules with the iptables-restore
command? This is in theory an atomic operation, which may take care of most of your issues. This does require that you write your rules in the format used by iptables-save
.
Best Answer
Hard to say since you're not displaying for which chains these rules apply.
Easily said: For a firewall you've got to start with the FORWARD chain and follow all rules that match in sequence until you hit an ACCEPT, DROP or REJECT
If you reach the end of all rules this way, the FORWARD's default policy applies.