How do I allow certain ips and block all other connection in iptables?
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.
Here's an (untested!) example that blocks incoming connections only. Connections over the loopback interface, coming from 192.168.3.x, ICMP, or to the SSH port are allowed. All other connections are rejected.
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT iptables -A INPUT -p icmp -j ACCEPT iptables -A INPUT -p tcp --dport 22 -j ACCEPT iptables -A INPUT -s 192.168.3.0/24 -j ACCEPT iptables -A INPUT -i lo -j ACCEPT iptables -A INPUT -j REJECT
The below rule will allow only your IP and Block all other IPs over port 22 or ssh. Test with a new terminal before disconnecting.
iptables -I INPUT -p tcp ! -s yourIPaddress --dport 22 -j DROP
Here is full working example.
Also makes the applications work (re: my comment about keepass not starting)