-
-
Save oli-ver/2abc6d4176da2b53bcd17792a48393a9 to your computer and use it in GitHub Desktop.
Block certain countries and allow ports ssh, http and https using UFW (Tested on Debian 12 Bookworm)
This file contains hidden or 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_block_countries.sh | |
| #author :JSC Novabyte (novabyte.co),oli-ver | |
| #date :12/06/2025 | |
| #version :0.0.2 | |
| #notes :Use root privileges | |
| #usage :$sh ufw_block_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) | |
| # Whitespace separated list of country ISO codes | |
| BLOCK_COUNTRIES="ru" | |
| # Comma separated list of services to allow in general | |
| 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 by default | |
| $UFW default deny incoming | |
| # Allow certain tcp ports | |
| $UFW allow $ALLOWED_SERVICES/tcp | |
| # Create zone directory | |
| [ ! -d $ZONE_ROOT ] && /bin/mkdir -p $ZONE_ROOT | |
| # Loop through allowed countries | |
| for COUNTRY in $BLOCK_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 | |
| BAD_IPS=$(grep -E -v "^#|^$" "$ZONE_FILE") | |
| for ip_block in $BAD_IPS | |
| do | |
| # Block IP address block | |
| echo "${SUCCESS}BLOCK: ${RESET}$ip_block IP block" | |
| $UFW deny proto tcp 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