Iptables – How to allow with Iptables all ports only for local ips except of two specific Ports

iptables

I'm looking for a way to allow connections on all ports on my debian server only for a local IP (192.168.2.*) except of two specific Ports X and Y, that should be allowed for any IP. If the IP isn't a local one, all connections to all ports except of the Ports X and Y should be blocked.

How can I handle this situation with Iptables?

Best Answer

I am not sure if I understood you well, but here is how to do it.

To allow all ports for local IP range 192.168.2.0/24 except two ports (X, and Y), you can use a rule like:

iptables -A INPUT -s 192.168.2.0/24 -p tcp --dport X -j DROP
iptables -A INPUT -s 192.168.2.0/24 -p tcp --dport Y -j DROP
iptables -A INPUT -s 192.168.2.0/24 -p tcp -j ACCEPT

For other non-local IPs, allow connections ONLY to X and Y, you can use:

iptables -A INPUT -p tcp --dport X -j ACCEPT
iptables -A INPUT -p tcp --dport Y -j ACCEPT
iptables -A INPUT -p tcp -j DROP

You did not specify protocol (TCP or UDP) and I am assuming TCP as it is clear above. You need to insert the rules in this specific order and I am assuming no other pre-defined rules.