Iptables – allow “reply” traffic

iptables

In iptables I drop all incoming traffic. But I want e.g. PING to work when sent to the blocked addresses.

What works is if I allow ESTABLISHED. But this also allows existing (=established) connections to continue even if the iptables rules say they should be blocked/dropped.

In man iptables:

ESTABLISHED meaning that the packet is associated with a connection which has seen packets in both directions

I don't see any better state to identify connection which just received first packet in the second direction – first reply to an outgoing request.

Is there a way to set rules for these "newly established" connections?

Maybe NEW could be somehow used on the outgoing connection to allow incoming packets on it?


UPDATE: Since i can't express the intent otherwise:

I wish to implement a whitelist, so a few specific addresses should be able to connect, others should be dropped. So i have:

iptables -A INPUT -s 1.1.1.1,2.2.2.2 -j ACCEPT
iptables -P INPUT DROP

But this also blocks reply traffic, so if this computer sends a ping to the whitelisted addresses, it will not receive a reply.
That is why i added the ESTABLISHED rule, which fixes that problem:

iptables -A INPUT -m state --state ESTABLISHED -j ACCEPT

But this introduces another problem: if a connection existed before applying these rules from a non-whitelisted addresss 9.9.9.9, it will be allowed to continue.

How can I allow reply traffic without allowing existing connection that should be blocked by the iptables rules?

Best Answer

If I understand you correctly, your problem arises when your firewall rules where to permissive and you add a rule to block traffic that was allowed before. Then the traffic that was already allowed and has an open connection in the conntrack module is allowed after the new rule is in place.

You should have a look at the conntrack-tools.

Using the conntrack program you would list the active connections and explicitely delete the unwanted connections.

Please be aware that ESTABLISHED within the conntrack module refers to the state of the connections known to the conntrack module. That means, after you have deleted the connection from there, the iptables rules will prevent the connection from being established anew because the next datagramm would set the state to NEW.