Skip to content

Instantly share code, notes, and snippets.

@oli-ver
Forked from dachinat/ufw_allow_countries.sh
Last active January 9, 2021 13:37
Show Gist options
  • Save oli-ver/2abc6d4176da2b53bcd17792a48393a9 to your computer and use it in GitHub Desktop.
Save oli-ver/2abc6d4176da2b53bcd17792a48393a9 to your computer and use it in GitHub Desktop.
Allow certain countries only ssh, http and https using UFW (Tested on Debian 10 Buster)
#!/bin/bash
#title :ufw_allow_countries.sh
#upstr. author :JSC Novabyte (novabyte.co)
#fork author :oli-ver
#date :01/09/2021
#version :0.0.1
#notes :Use root privileges
#usage :$sh ufw_allow_countries.sh
#license :https://opensource.org/licenses/MIT
# Formatting
ERROR=`tput setaf 1`
SUCCESS=`tput setaf 2`
PRIMARY=`tput setaf 4`
RESET=`tput sgr0`
# Stop if ufw not accessible
if ! command -v ufw > /dev/null 2>&1; then
echo "${ERROR}Error: ${RESET}ufw is not available"
exit 1
fi
# Stop if wget not accessible
if ! command -v wget > /dev/null 2>&1; then
echo "${ERROR}Error: ${RESET}wget is not available"
exit 1
fi
# UFW executable path
UFW=$(command -v ufw)
# Wget executable path
WGET=$(command -v wget)
# Egrep executable path
EGREP=$(command -v egrep)
# Whitespace separated list of country ISO codes
ALLOW_COUNTRIES="ge"
# Comma separated list of services to allow for the list of countries
ALLOWED_SERVICES="22,80,443"
# Place to store .zone files
ZONE_ROOT="/root/zones/"
# Remote country database url
REMOTE="http://www.ipdeny.com/ipblocks/data/countries"
# Wipe-out all the rules
$UFW --force reset
# Allow outgoing traffic
$UFW default allow outgoing
# Block all incoming connections
$UFW default deny incoming
# Create zone directory
[ ! -d $ZONE_ROOT ] && /bin/mkdir -p $ZONE_ROOT
# Loop through allowed countries
for COUNTRY in $ALLOW_COUNTRIES
do
# Set zone file
ZONE_FILE=$ZONE_ROOT/$COUNTRY.zone
# Download zone file
echo "${PRIMARY}GET: ${RESET}$COUNTRY.zone zone"
$WGET -O $ZONE_FILE $REMOTE/$COUNTRY.zone >> /dev/null 2>&1
# Loop through allowed ips
GOOD_IPS=$(egrep -v "^#|^$" $ZONE_FILE)
for ip_block in $GOOD_IPS
do
# Allow IP address block
echo "${SUCCESS}ALLOW: ${RESET}$ip_block IP block"
$UFW allow proto tcp from $ip_block to any port $ALLOWED_SERVICES
done
done
# Enable UFW with new rules
$UFW --force enable
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment