Iptables to allow traffic from one country only

firewalliptables

I would like to allow traffic from one country only.

I have seen and read online multiple ways, but most of them are outdated (with Xtables-addons),
and the other half show how to blacklist IPs that one dose not like.

However this is a wrong approach, to black list everything one by one.
A better approach will be to do a white list so everything beside that white list will be blocked.

I am in France; I want to allow only french clients/users to access the server.

The iptables rule I have inplace is

sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination xx.xx.xx.xx:80

just forwarding traffic.

Best Answer

I'm not suggesting this is the best option, but if you can't find another that works then you could "roll your own" using a downloadable GeoIP database and the ipset tool.

For example download the Geolite2 database Countries in CSV format. Download and unzip the files:

wget https://geolite.maxmind.com/download/geoip/database/GeoLite2-Country-CSV.zip
unzip GeoLite2-Country-CSV.zip
cd GeoLite2-Country-CSV_20190430

Find the id for France and filter all records for french networks:

grep France GeoLite2-Country-Locations-en.csv
3017382,en,EU,Europe,FR,France,1

awk -F, '$2 == 3017382 {print $1}' > french_networks.txt

Build an ipset containing french networks called france:

ipset create france hash:net
while read network ; do 
    ipset add france $network; 
done < french_networks.txt

Use the ipset to create an iptables rule which drops anything not from France. Note you might need to add extra rules ensure local networks are not dropped:

iptables -A INPUT -m set ! --match-set france src -j DROP
Related Question