How to Control Access from a Specific Country on an Ubuntu 16.04 Cloud Server Using iptables?

10-01-2024 05:56:09

Step One: Install xtables-addons

Xtables-addons can be installed in the following ways.

Install using apt-get

sudo apt-get install xtables-addons-common

Install using module-assistant

sudo apt-get install module-assistant xtables-addons-source
sudo module-assistant --verbose --text-mode auto-install xtables-addons

Install from source code

sudo apt-get install git bc libncurses5-dev libtext-csv-xs-perl autoconf automake libtool xutils-dev iptables-dev
git clone git://git.code.sf.net/p/xtables-addons/xtables-addons
cd xtables-addons
./autogen.sh
./configure
make
sudo make install

Step Two: Create a Country Database

sudo apt-get install libtext-csv-xs-perl unzip
sudo mkdir /usr/share/xt_geoip
sudo /usr/lib/xtables-addons/xt_geoip_dl
sudo /usr/lib/xtables-addons/xt_geoip_build -D /usr/share/xt_geoip *.csv
sudo rm GeoIPCountryCSV.zip GeoIPCountryWhois.csv GeoIPv6.csv

Restart the system

reboot

Check module dependencies (only needs to be done once):

sudo depmod 

Step Three: Create iptables Rules

Block incoming requests from Russia and South Korea:

sudo iptables -A INPUT -m geoip --src-cc RU,KR -j DROP
sudo iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT

Allow incoming requests to port 22 from Peru on the ens3 interface:

sudo iptables -A INPUT -i ens3 -p tcp -m tcp --dport 22 -m geoip --src-cc PE -j ACCEPT

Only allow incoming requests to port 443 from China:

sudo iptables -A INPUT -p tcp -m tcp --dport 443 -m geoip --src-cc CN -j ACCEPT

Step Four: Schedule Database Updates

Create a script for scheduled updates:

vi /etc/cron.monthly/geoip-updater

The script content is as follows:

#!/usr/bin/env bash
# this script is intended to run with sudo privileges

echo 'Removing old database---------------------------------------------------'
rm -rf /usr/share/xt_geoip/*
mkdir -p /usr/share/xt_geoip

echo 'Downloading country databases-------------------------------------------'
mkdir /tmp/geoip-updater
cd /tmp/geoip-updater
/usr/lib/xtables-addons/xt_geoip_dl

echo 'Building geoip database-------------------------------------------------'
/usr/lib/xtables-addons/xt_geoip_build -D /usr/share/xt_geoip *.csv

echo 'Removing temporary files------------------------------------------------'
cd /tmp
rm -rf /tmp/geoip-updater

Set the script to be executable:

sudo chmod +x /etc/cron.monthly/geoip-updater