CountryBlock/start.sh
2025-06-23 15:54:15 +01:00

75 lines
3.2 KiB
Bash

#!/bin/bash
set -euo pipefail
echo -e "
░█████╗░███╗░░██╗██████╗░██████╗░░█████╗░░██████╗
██╔══██╗████╗░██║██╔══██╗██╔══██╗██╔══██╗██╔════╝
███████║██╔██╗██║██║░░██║██║░░██║██║░░██║╚█████╗░
██╔══██║██║╚████║██║░░██║██║░░██║██║░░██║░╚═══██╗
██║░░██║██║░╚███║██████╔╝██████╔╝╚█████╔╝██████╔╝
╚═╝░░╚═╝╚═╝░░╚══╝╚═════╝░╚═════╝░░╚════╝░╚═════╝░"
COUNTRIES="af es"
ZONE_DIR="zone"
mkdir -p "$ZONE_DIR"
function add_iptables_rule() {
local chain=$1
local set_name=$2
if iptables -t raw -C "$chain" -m set --match-set "$set_name" src -j DROP 2>/dev/null; then
echo "Regra iptables para ipset '$set_name' já existe na cadeia $chain."
else
echo "Inserindo regra iptables para ipset '$set_name' na cadeia $chain..."
iptables -t raw -I "$chain" -m set --match-set "$set_name" src -j DROP
fi
}
for country in $COUNTRIES; do
url="https://www.ipdeny.com/ipblocks/data/countries/${country}.zone"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Tentando baixar lista de IPs para o país: $country"
tmp_file="${ZONE_DIR}/${country}.zone.tmp"
target_file="${ZONE_DIR}/${country}.zone"
if curl -sSf -o "$tmp_file" "$url"; then
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Download concluído para $country."
if [ -f "$target_file" ] && cmp -s "$tmp_file" "$target_file"; then
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Arquivo para $country não mudou. Mantendo versão atual."
rm "$tmp_file"
else
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Arquivo para $country mudou ou não existia. Atualizando..."
mv "$tmp_file" "$target_file"
fi
else
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Falha no download para $country. Mantendo versão antiga (se existir)."
[ -f "$tmp_file" ] && rm "$tmp_file"
continue
fi
if ipset list "$country" &>/dev/null; then
echo "[$(date '+%Y-%m-%d %H:%M:%S')] IpSet '$country' já existe. Limpando entradas antigas..."
ipset flush "$country"
else
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Criando IpSet '$country'."
ipset create "$country" hash:net
fi
while read -r subnet; do
if ! ipset add "$country" "$subnet" -exist; then
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Aviso: falha ao adicionar $subnet ao ipset $country"
fi
done < "$target_file"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Configuração do IpSet concluída para o país $country."
add_iptables_rule PREROUTING "$country"
add_iptables_rule OUTPUT "$country"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Regras iptables configuradas para o país $country."
done
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Script concluído."