Linux – PTables block outgoing traffic using wildcard subdomain reference

iptableslinux

I would like to block all outgoing traffic to any domain or subdomain using IPTables. It would appear that the -d option allows one to reference a domain. I found the following through a Google search that suggests it can be referenced this way: Allow HTTP traffic only to specific domain(s)

Similarly, we can use the above method to filter other ports and protocols as well, such as standard web traffic operating on tcp port 80.

iptables -I FORWARD 1 -p tcp -d dd-wrt.com --dport 80 -j ACCEPT
iptables -I FORWARD 2 -p tcp --dport 80 -j DROP

Which would accept all http traffic to dd-wrt.com, while blocking outgoing http traffic to anywhere else. If you wish to allow multiple sites, insert additional rules before the DROP (making sure to order and number them correctly).

However what I would like to do is reference *.domain.com (e.g. block all outgoing traffic to *.youtube.com or similar).

Does anyone know if this is possible and if so, what is the syntax for the -d option in IPTables to support a wildcard subdomain?

Best Answer

DNS resolution in IPtables is a little funny. At run time the firewall acts on IP address only, not on domain names. Let's take the process step by step for clarity.

  1. You add a rule with: iptables -I FORWARD 1 -p tcp -d dd-wrt.com --dport 80 -j ACCEPT
  2. IPtables passes dd-wrt.com to the resolver subsystem.
  3. Resolver subsystem returns: 83.141.4.210
  4. IPtables modifies and creates rule as: -p tcp -d 83.141.4.210 --dport 80 -j ACCEPT

If the domain name returned multiple addresses, such as www.google.com, then inserts a copy of that rule for each IP address returned. Unless, of course, you use the --replace option in which case multiple returned addresses will cause it to fail.

This lookup only happens when the rule is added. So if dd-wrt.com is moved to a new host then your rule will no longer work correctly. You will have to delete and re-add or restart the firewall to have the new address take effect.

As a result you can simply the implications to mean that you cannot use it to block based on domain name at all. You are only ever blocking on IP address, you may be simply using a domain name to occasionally retrieve the address. Similarly, wild cards won't work either. The hostname *.dd-wrt.com does not have an A record, therefore it cannot be converted into an IP address.

It is generally in your best interest to block or deny based solely on IP address. That way there is no confusion for you, or your staff, on what is supposed to be blocked (or allowed) versus what actually is.