Blocking whole countries
From FBSD_tips
Contents |
[edit] Rationale
The sad fact today is that many countries tolerate and even promote very antisocial and even criminal activities on the internet. And while the free flow of information is essential to overcoming these regimes, many of us just do not possess the resources to withstand the downside of such altruism. Here I will delineate the steps necessary to find the netblocks allocated to a specific country and block it.
[edit] Sources of netblock assignments
Remote Technology Management offers a database culled from ARIN, APNIC, LACNIC, RIPENCC and AFRINIC and updated daily. There are many applications they offer built from this database. You should click on their advertising links, they deserve it.
On that page choose the country you wish to block, for example China and click on "choose countries" (they allow multiple selections but I like to keep the counties in separate files). Copy and paste the text into a file like :
/usr/local/etc/network/bad_country_china.txt
[edit] Tables in IPFW
[edit] Include IPFW in your kernel
GENERIC ships without IPFW built in by default. You must either rebuild your kernel OR load the kernel object. To load the kernel object on boot put this into /boot/loader.conf :
ipfw_load="YES"
Remember that the default IPFW is deny all. If the machine is not local and you do not have remote console you might consider doing something like this.
IPFW supports tables these are useful in many situations, e.g. you don't want to re-read you entire ruleset to block something OR if you have a lot of rules and don't want your ruleset to be really long.
[edit] Loading a table in IPFW
Adding an entry to a table in IPFW that will match any IP in 10.9.8.0/24 :
ipfw table 1 add 10.9.8.0/24
[edit] Matching against a table
This will deny anything matching table 1 :
deny ip from table(1)
Depending on your shell, you might need to escape the parenthesis.
[edit] Implementation
I define a shell function to load the table in firewall.subr Here is the download for the shell include file :
curl --output firewall.subr http://bsdtips.utcorp.net/mediawiki/index.php?title=Firewall.subr&action=raw
[edit] Function call
Here is the function of interest :
load_table () \
{
FILE=$1
TBL=$2
cat ${FILE} | \
while read N
do
ipfw table ${TBL} add $N || echo "Issue with $N"
done
}
[edit] Example
Here we read all the files matching bad_country_*.txt and load them into a table, then block them.
cat /usr/local/etc/network/bad_country_*.txt | \
while read N
do
ipfw load_table ${N} 2
done
ipfw add deny all from table(2) to any via $OUT_IF
