Files
shellscripts/ufw/china-block.sh
2026-05-29 15:23:42 +07:00

48 lines
1.3 KiB
Bash
Executable File

#!/bin/bash
set -e
IPSET_NAME="china"
CIDR_FILE="/tmp/cn.cidr"
UFW_RULE="/etc/ufw/applications.d/block-china"
SOURCES=(
"https://www.ipdeny.com/ipblocks/data/countries/cn.zone"
"https://raw.githubusercontent.com/mayaxcn/china-ip-list/master/chnroute.txt"
)
echo "[*] Downloading CN IP ranges..."
for url in "${SOURCES[@]}"; do
echo " Trying $url ..."
wget -q "$url" -O "$CIDR_FILE"
if [[ $(wc -l < "$CIDR_FILE") -gt 10 ]]; then
echo " [+] Success: $(wc -l < "$CIDR_FILE") entries"
break
fi
done
if [[ $(wc -l < "$CIDR_FILE") -lt 10 ]]; then
echo "[!] All sources failed. Aborting."
exit 1
fi
echo "[*] Creating ipset..."
ipset create "$IPSET_NAME" hash:net 2>/dev/null || ipset flush "$IPSET_NAME"
echo "[*] Populating ipset..."
while IFS= read -r cidr; do
[[ -z "$cidr" ]] && continue
ipset add "$IPSET_NAME" "$cidr"
done < "$CIDR_FILE"
echo "[*] Saving ipset..."
ipset save > /etc/ipset.conf
echo "[*] Adding iptables rules directly..."
iptables -A INPUT -m set --match-set "$IPSET_NAME" src -j DROP
iptables -A OUTPUT -m set --match-set "$IPSET_NAME" dst -j DROP
echo "[*] Saving iptables rules..."
iptables-save > /etc/iptables/iptables.rules
systemctl enable --now iptables
echo "[+] Done! Chinese IPs are now blocked."