iptables rules to allow HTTP traffic to one domain only

I need to configure my machine as to allow HTTP traffic to/from serverfault.com only. All other websites, services ports are not accessible. I came up with these iptables rules:

#drop everything
iptables -P INPUT DROP
iptables -P OUTPUT DROP

#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

#allow loopback
iptables -I INPUT 1 -i lo -j ACCEPT

It doesn't work quite well:

  • After I drop everything, and move on to rule 3:

    iptables -A OUTPUT -p tcp -d serverfault.com --dport 80 -j ACCEPT

I get this error:

iptables v1.4.4: host/network `serverfault.com' not found
Try `iptables -h' or 'iptables --help' for more information.

Do you think it is related to DNS? Should I allow it as well? Or should I just put IP addresses in the rules? Do you think what I'm trying to do could be achieved with simpler rules? How?

I would appreciate any help or hints on this. Thanks a lot!


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:

  1. The default DROP policy get applied
  2. IPTables receives a hostname as a destination
  3. IPTables attempts a DNS lookup on 'serverfault.com'
  4. 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

Add

iptables -A OUPUT -p udp --dport 53 -j ACCEPT

to allow DNS lookups.