Skip to content

Instantly share code, notes, and snippets.

@tobyxdd
Created August 5, 2024 00:22
Show Gist options
  • Save tobyxdd/26758a095ad3c3b9122aa6133c37bfa0 to your computer and use it in GitHub Desktop.
Save tobyxdd/26758a095ad3c3b9122aa6133c37bfa0 to your computer and use it in GitHub Desktop.
Block Chinese IP Forwarding as VPN Server
#!/bin/bash
IP_LIST_URL="https://www.ipdeny.com/ipblocks/data/countries/cn.zone"
IP_LIST_FILE="/tmp/cn.zone"
IPSET_NAME="china_ips"
BLOCK_CHAIN="CHINA_BLOCK"
download_ip_list() {
wget -q -O $IP_LIST_FILE $IP_LIST_URL
if [[ $? -ne 0 ]]; then
echo "Failed to download IP list."
exit 1
fi
}
enable_block() {
download_ip_list
if ! ipset list $IPSET_NAME > /dev/null 2>&1; then
ipset create $IPSET_NAME hash:net
else
ipset flush $IPSET_NAME
fi
while IFS= read -r ip; do
echo "add $IPSET_NAME $ip"
done < $IP_LIST_FILE | ipset restore -!
if ! iptables -L $BLOCK_CHAIN > /dev/null 2>&1; then
iptables -N $BLOCK_CHAIN
iptables -A $BLOCK_CHAIN -m set --match-set $IPSET_NAME src -j DROP
fi
if ! iptables -C FORWARD -j $BLOCK_CHAIN > /dev/null 2>&1; then
iptables -I FORWARD -j $BLOCK_CHAIN
fi
echo "Blocking Chinese IP addresses enabled."
}
disable_block() {
if iptables -C FORWARD -j $BLOCK_CHAIN > /dev/null 2>&1; then
iptables -D FORWARD -j $BLOCK_CHAIN
fi
if iptables -L $BLOCK_CHAIN > /dev/null 2>&1; then
iptables -F $BLOCK_CHAIN
iptables -X $BLOCK_CHAIN
fi
if ipset list $IPSET_NAME > /dev/null 2>&1; then
ipset destroy $IPSET_NAME
fi
echo "Blocking Chinese IP addresses disabled."
}
case "$1" in
enable)
enable_block
;;
disable)
disable_block
;;
*)
echo "Usage: $0 {enable|disable}"
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment