Last active
March 15, 2024 13:56
-
-
Save dachinat/6dd0995acc52097afefe7ce31c35b807 to your computer and use it in GitHub Desktop.
Allow certain countries only using UFW (Tested on CentOS 7, Ubuntu 16.04, Ubuntu 18.04)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
#title :ufw_allow_countries.sh | |
#author :JSC Novabyte (novabyte.co) | |
#date :20/10/2018 | |
#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" | |
# 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 | |
# Allow SSH connections | |
$UFW allow ssh | |
# Or allow SSH connection from your ip(s) only | |
# $UFW allow from x.x.x.x to any port 22 proto tcp | |
# Or allow SSH connections from your entire subnet | |
# $UFW allow from x.x.x.x/y to any port 22 proto tcp | |
# 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 from $ip_block | |
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
Hello @dachinat, Thanks for providing this script. I changed it a little bit to only allow certain ports. If I am not mistaken this script would allow to access all ports for the selected country, right?