Iptables – Creating an IP “whitelist” for iptables

iptables

I'm using a cellular modem/router that has iptables. There is also a clunky webUI that allows simple adjustments, such as turning on WAN ICMP/HTTPS/SSH. I clearly don't want those ports wide up and publicly facing. But I would like to have remote management access to this device from a predetermined whitelist of addresses. There are possibly up to 10 addresses, and some are IP ranges/subnets. I have tested this with a single address with a rule like

-A HTTPS_WAN_INPUT -i ppp0 -s x.x.x.x -p tcp -m tcp --dport 443 -j ACCEPT

But the prospect of writing rules like that 10 times and for each port/protocol seems clunky, so I'm writing to see if there is a better way to do this? Can I create a $WHITELIST variable that contains all the addresses and use that in the -s? Or can I apply the whitelist to something further up the chain, such as one of the policies?

I'm just trying to figure out if there is a more elegant way of allowing remote access to a set of IPs without writing 10 different lines for each rule.

Best Answer

You really have only 2 options (or a combination)... but one is slightly more risky than the other. Keep in mind that the src field also accepts subnets.. i.e. 192.168.1.0/24.

First, If your iptables/kernel is built with the iprange module, you can use it to specify a range of IPs instead of just 1-2... but you cannot provide a "list" of ips. Example:

-A HTTPS_WAN_INPUT -i ppp0 -m iprange --src-range x.x.x.x-y.y.y.y -p tcp -m tcp --dport 443 -j ACCEPT

Second, you can setup a new target specific target including "whitelisted" IPs just to keep things clean. Example:

iptables -N RemoteManagement
iptables -P RemoteManagement DROP
iptables -A -A HTTPS_WAN_INPUT -i ppp0 -p tcp -m tcp --dport 443 -j RemoteManagement

... and for each IP you want to permit...

iptables -I RemoteManagement -s x.x.x.x -j ACCEPT

This allows you to keep your rules a bit cleaner, and be able to simply delete IPs/add IPs as needed. Of course, if you have the iprange module available, you can also specify ranges in the RemoteManagement chain. You could also reuse this same chain in other scenarios where it applies.