Using a drop all policy for IPTABLES

echo "Set default policy to 'DROP'"

Trying to define specific rules for OUTPUT connections that include all subdomains of a domain. The reason being that in a multi step protocol, the server recieves a callback URL of a potentially unknown subdomain.

These niave rules don't work...

$IPT -A OUTPUT -p tcp -d "*.example.com" -m state --state NEW,ESTABLISHED -j ACCEPT
$IPT -A OUTPUT -p tcp -d "example.com" -m state --state NEW,ESTABLISHED -j ACCEPT

Reading around I see that wild cards do not work, and that IPTABLES is not a DNS resolver... !! waaaah! shouldn't the latter rule work for all ports and all subdomains?

So far my only solution is allowing all OUTPUT traffic like this

$IPT -I OUTPUT -o eth0 -d -j ACCEPT
$IPT -I INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT

I'm thinking maybe using this 'conntrack' rule would be more appropriate?


I'd prefer to be more restrictive, how can I create a specific rule/ruleset for a domain and its subdomains?


Nope, iptables is the wrong tool for this task.
At the level that iptables works the hostname is not applicable. When you add a rule for "example.com" it is resolved to an IP address and stored that way. If the DNS for example.com changes, the rule is no longer working as intended.

If you are trying to limit outbound connections to DNS names, you will need to use something involved in resolving DNS. For example, to blacklist a domain name, say "coinhive.com" as an example, I have this in my /etc/hosts file: coinhive.com. This prevents anything from contacting that domain no matter what IP address is points to on the internet.

In order to white list by domain name, you could run a DNS resolver locally and only provide the entries you want and not forward unknown hostnames.

I'm sure there are a few more ways to accomplish this, but iptables is not one of them.

| improve this answer | |
  • and is there no way to statefully recognise a follow up reponse to a call back ? – Kickaha Oct 10 '18 at 15:58
  • 1
    A connection to example.com at and www.example.com at are completely unrelated connections as far as the IP layer is concerned. – mjb2kmn Oct 10 '18 at 16:02
  • Your blacklist example can be easily gotten around. host coinhive.com followed by wget http://[ip address] completely by-passes /etc/hosts. – doneal24 Oct 10 '18 at 16:12
  • @DougO'Neal, you're right, I oversold it as preventing "anything" from contacting it; that case was really just to prevent my browser loading script tags from there. – mjb2kmn Oct 10 '18 at 16:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.