Monday, April 18, 2016

Blocking all countries except one using iptables

I created a small site I was planning on only sharing with friends and family.

To minimize the odds of being targeted by any attacks, I decided to only allow visitors that originated from Canada.

First, let's become root
> sudo bash

We install a few things:

> apt-get install xtables-addons-common
> apt-get install iptables-persistent
> mkdir /usr/share/xt_geoip
> apt-get install libtext-csv-xs-perl unzip
> /usr/lib/xtables-addons/xt_geoip_dl
> /usr/lib/xtables-addons/xt_geoip_build -D /usr/share/xt_geoip *.csv
Then we write a few rules (assuming your home network is using subnet 192.168.1.x):

> iptables -A INPUT -p tcp -s 192.168.1.0/24 -j ACCEPT
> iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
> iptables -A INPUT -m geoip --src-cc CA -j ACCEPT
> iptables -A INPUT -p tcp -s 127.0.0.1/32 -j ACCEPT
> iptables -P INPUT DROP
Now we persist the iptables

> iptables-save > /etc/iptables/rules.v4

We should be good to reboot! 

> sudo iptables -S
-P INPUT DROP
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -s 192.168.1.0/24 -p tcp -j ACCEPT
-A INPUT -m geoip --source-country CA  -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

Reference: http://superuser.com/questions/996526/ubuntu-iptables-allow-only-allow-1-country