This HOWTO covers IPtables configuration for specifying services to a certain host or range of hosts.
IPtables: open port for specific IP
By Erik Rodriguez
iptables block all IPs, open for specific IP, iptables --dport, iptables drop, iptables specify IP range
Command and Syntax
There seems to be a lot of confusion with this, so I'm going to make this quick any easy. IPtables is a stateful firewall tht is both powerful and efficent. That being said, let's look at how to restrict a port or service to a specific IP or range of IPs. Entering the following at root will allow SSH connections from the first two locations and drop them from everywhere else:
iptables -I INPUT -p tcp -m tcp -s 220.127.116.11 --dport 22 -j ACCEPT
iptables -I INPUT -p tcp -m tcp -s 18.104.22.168/29 --dport 22 -j ACCEPT
iptables -I INPUT -p tcp -m tcp -s 0.0.0.0/0 --dport 22 -j DROP
Remember, if you want this configuration to survive reboots, you will need to use the command iptables-save. Red hat-based systems will store the configuration in the files /etc/sysconfig/iptables.
If you would like to edit this file directly, use the following:
-A INPUT -p tcp -m tcp -s 22.214.171.124 --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp -s 126.96.36.199/29 --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp -s 0.0.0.0/0 --dport 22 -j DROP
Remember, IPtables like most hardware firewalls, uses stateful packet inspection. It will read the rules in order from top to bottom. This is why we put all the allowed networks first and then put in a blanket deny all (0.0.0.0/0). You can enter hosts into IPtables using any of the following formats:
IP address: ex. 188.8.131.52
DNS name: ex. skullbox.net
CIDR: ex. 184.108.40.206/29
NOTE: this form DOES NOT e-mail this article, it sends feedback to the author.