Block countries using iptables + ipset + ipdeny.com
This used to be a Gist but was moved here instead
Please do not add Gist comments, but create an issue here
ipset-country -i
ipset-country -u
Running this script will insert an iptables 'REJECT' or 'DROP' rule for ipset. Make sure you do not lock yourself out in case of issues on a remote system.
In case of issues check the log file (/var/log/ipset-country.log)
All options are set and explained in the script itself: ipset-country
Optionally you can use a seperate config file located in the same directory as the script, "/etc" or "/usr/local/etc". Specify a custom location using ipset-country -c /path/to/conf
The config file will overwrite any options set in script. To create a new conf file run:
sed -n '/# CONFIGURATION:/,/# END OF CONFIG/p' ipset-country > ipset-country.conf
Distro:
If needed change OS using DISTRO
setting. Default is "auto" which should be OK.
Options are:
confdir="/etc/iptables"
(example)rulesfile="${confdir}/myrules"
(example)Countries:
Specify countries to block as "ISOCODE,Name"
(same as ipdeny.com), multiple entries should be seperated by semicolon ;
Example:
COUNTRY="CN,China; US,United States; RU,Russia"
Firewalls and options:
Iptables and ipset are used by default to create the chains, rules and ipsets. If firewalld frontend is enabled it will be used instead.
MODE
to "reject" or "drop"MODE
to "accept"Iptables:
Set target to use when ip matches country: "accept", "drop" or "reject". Default is MODE="reject"
FirewallD:
Set this option to "1" to enable firewalld: FIREWALLD=0
Set FIREWALLD_MODE=0
to use the default Blacklist mode (uses 'drop' zone). Change to "1" for Whitelist ('public' zone). See MODE above for more information
pkill firewal-cmd; nft flush ruleset
Block list providers:
Set URLs for ipv4 and/or ipv6 block files, you probably do not have to change these.
To use ipverse.net instead of ipdeny.com and for more details see script
IPBLOCK_URL_V4="http://www.ipdeny.com/ipblocks/data/aggregated"
IPBLOCK_URL_V6="http://www.ipdeny.com/ipv6/ipaddresses/blocks"
Logs:
In case you want to change file location set: LOG="/var/log/ipset-country.log"
Useful ipset commands:
ipset list
ipset test setname <ip>
ipset flush
ipset destroy
Also available: github.com/tokiclover/dotfiles/blob/master/bin/ips.bash