Skip to content

Instantly share code, notes, and snippets.

@meznak
Last active May 18, 2017
Embed
What would you like to do?
Block entire countries' IP blocks automagically using ipsets.
#!/bin/bash
#####
# Block entire countries' IP blocks automagically using ipsets.
#
# CC BY NC SA 2017 Nate Plamondon
# Inspired by https://www.nyx.chiodo.ch/?p=91 which see for firewall setup.
#####
# number of times to retry each download
MAXTRIES=3
# 2-letter codes of countries to block (space delimited)
# See www.ipdeny.com for valid codes
countries="ae cn eg hk my ng pk ro ru sa tw ua"
####################
if [ $EUID -ne 0 ]; then
echo "$0 must be run as root."
exit 1
fi
# Create sets if they don't exist
ipset list geoblock &>/dev/null
if [ $? -ne 0 ]; then
ipset create geoblock hash:net family inet
fi
ipset list geoblock6 &>/dev/null
if [ $? -ne 0 ]; then
ipset create geoblock6 hash:net family inet6
fi
for country in $countries; do
tries=$MAXTRIES
status=-1
# download IPv4 blocks
while [ $tries -ge 0 -a $status -ne 0 ]; do
echo "$tries attempts remaining..."
wget http://www.ipdeny.com/ipblocks/data/aggregated/${country}-aggregated.zone -O /root/geoblock/${country}-4.zone
status=$?
tries=$(($tries - 1))
echo; echo
sleep 2
done
# download IPv6 blocks
tries=$MAXTRIES
status=-1
while [ $tries -ge 0 -a $status -ne 0 ]; do
echo "$tries attempts remaining..."
wget http://www.ipdeny.com/ipv6/ipaddresses/aggregated/${country}-aggregated.zone -O /root/geoblock/${country}-6.zone
status=$?
tries=$(($tries - 1))
echo; echo
sleep 2
done
done
# add IPv4 blocks to ipset
for file in /root/geoblock/*-4.zone; do
for line in `cat $file`; do
ipset -! add geoblock $line
done
done
ipset save geoblock
# add IPv6 blocks to ipset
for file in /root/geoblock/*-6.zone; do
for line in `cat $file`; do
ipset -! add geoblock6 $line
done
done
ipset save geoblock6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment