Just quick writeup if someone finds this thread and wants to do a similar thing.
Recap of what I wanted to do:
Block as much traffic as possible already at the router based on country whitelist. Main reason is that I have a number of virtual and physical servers on my local net which I need in my work and I wanted to avoid having to add the same block rules individually on all of them.
To do the following you need to have enabled both JFFS and SSH to be able to login to your router and use JFFS filesystem to store some temporary files. It is then a good idea to create a subdirectory under /jffs where you do all the work described below.
STEP 1 - Get country ip-address range
Aggregated country IP lists can be downloaded from
http://www.ipdeny.com/
For example to block a country download the complete ipset with:
wget -P . http://www.ipdeny.com/ipblocks/data/aggregated/[COUNTRY-CODE]-aggregated.zone
Where you replace [COUNTRY-CODE] with the appropriate two letter country code.
STEP 2 - Create whitelist using ipset
Create a whitelist (I used the name "
whitelist") using ipset. If the whitelist exists you should first delete it
ipset -X whitelist
You can then create a new whitelist with the following (the hashsize does not strictly need to be set but the larger hash the quicker it will be for the lookup at the expense of some memory)
ipset -N whitelist nethash --hashsize 16384
STEP 3 - Add the country range to the whitelist
Then it is time to populate the whitelist. You could use the following construct for each country list you have downloaded
for i in $(cat [COUNTRY-CODE]-aggregated.zone ); do ipset -A whitelist $i; done
Do not forget to add the local addresses as well, i.e.
ipset -A whitelist 192.168.0.0/16
ipset -A whitelist 127.0.0.0/24
STEP 4 - Add a drop rule in the FORWARD chain
Finally add a drop rule in the FORWARD chain in the filter table to block everything NOT coming from a source in the whitelist. Exactly on what row you want to add the rule depends on your existing rules in the FORWARD chain. But you should add the rule as high up as possible as long as it is after the rule to allow existing and related connections, in my case this will be the third rule.
iptables -I FORWARD 3 -p ALL -m set ! --set whitelist src -j DROP
This should of course be automated in a shell script and a few times a year you should probably also refresh the whitelist from the latest country IP address ranges.