Linux – iptables: allow certain ips and block all other connection

firewalliptableslinux

How do I allow certain ips and block all other connection in iptables?

Best Answer

I wrote a blog post on basic Iptables rules for the desktop user a long time ago and you should probably read it, and its linked article on Stateful firewall design. But pre kernel 2.6.39 (which includes ipset and you may want to use that for whitelisting IP's if you have more than 10 to whitelist (where 10 is arbitrary)).

First handle state's that we know we want to accept or drop, and interfaces.

iptables -P FORWARD DROP # we aren't a router
iptables -A INPUT -m state --state INVALID -j DROP
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -s 192.168.1.1 -j ACCEPT
iptables -P INPUT DROP # Drop everything we don't accept

If you just want to do an allow by IP only, without state

iptables -A INPUT -s 192.168.1.1 -j ACCEPT
iptables -A OUTPUT -d 192.168.1.1 -j ACCEPT
iptables -P INPUT DROP
iptables -P OUTPUT DROP

you are likely to run into problems doing this though, and I suggest using state to make your life easier. For example, not allowing -i lo and -o lo will certainly cause problems for certain applications.

Related Question