TomatoUSB: Limit/whitelist incoming access to a single country

This is a short how to on limiting incoming access to your router running TomatoUSB to a range of IP addresses only (can be whole country etc.). The first catch is that the list of IP addresses can be rather long and you may not be able store that directly on the router (as the available free storage can be as low as few kB). The recommended way is to format a spare USB flash drive or SD card to EXT3 filesystem and mount it on a boot to something like /opt.

If you want to limit the access on a country level, you can get such list of addresses in CIDR format from site such as Store that list in /opt. Next you need to put the actual filtering rules into a Firewall section of Administration -> Scripts page. Because my router (Asus RT-N16) has MIPS processor, the syntax for iptables parameters is different from these you would normally use.

for MODULE in ip_set ip_set_nethash ip_set_iphash ipt_set; do insmod $MODULE; done
ipset -N de nethash
while read IP; do ipset -A de $IP; done < /opt/de.cidr
iptables -I wanin 1 -m set ! --set de src -j DROP

After a reboot, this rule will make sure only IP addresses listed in the CIDR file will be allowed to connect to your router. This rule for the wanin interface is put before other directives and works properly with port forwarding as well.