Last active
August 1, 2024 11:51
-
-
Save merrickluo/03ca80b9825dc46de54101c26ba57e3d to your computer and use it in GitHub Desktop.
A script to setup iptable rules
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
#!/usr/bin/env bash | |
[[ $EUID -ne 0 ]] && exec sudo $0 -- $@ | |
set -e | |
command=${2:-help} | |
port=${3:-1024} | |
CHNROUTE_FILE="`dirname "$0"`/chnroute.txt" | |
IGNORE_FILE="`dirname "$0"`/ignore.txt" | |
function proxy-up { | |
ipset -N chnroute hash:net maxelem 65536 | |
echo "generating ipset from chnroute.txt" | |
for ip in $(cat ${CHNROUTE_FILE}); do | |
ipset add chnroute ${ip} | |
done | |
# put proxy server in ignore.txt | |
for ip in $(cat ${IGNORE_FILE}); do | |
echo "ignoring ${ip}" | |
ipset add chnroute ${ip} | |
done | |
iptables -t nat -N PROXY | |
# intranet | |
iptables -t nat -A PROXY -d 0.0.0.0/8 -j RETURN | |
iptables -t nat -A PROXY -d 10.0.0.0/8 -j RETURN | |
iptables -t nat -A PROXY -d 127.0.0.0/8 -j RETURN | |
iptables -t nat -A PROXY -d 169.254.0.0/16 -j RETURN | |
iptables -t nat -A PROXY -d 172.16.0.0/12 -j RETURN | |
iptables -t nat -A PROXY -d 192.168.0.0/16 -j RETURN | |
iptables -t nat -A PROXY -d 224.0.0.0/4 -j RETURN | |
iptables -t nat -A PROXY -d 240.0.0.0/4 -j RETURN | |
# chnroute | |
iptables -t nat -A PROXY -p tcp -m set --match-set chnroute dst -j RETURN | |
iptables -t nat -A PROXY -p icmp -m set --match-set chnroute dst -j RETURN | |
# else redir to moproxy | |
iptables -t nat -A PROXY -p tcp -j REDIRECT --to-port ${port} | |
iptables -t nat -A OUTPUT -p tcp -j PROXY | |
echo "tcp traffic is now redirected to ${port}" | |
} | |
function proxy-down { | |
echo "removing redirect rules" | |
iptables -t nat -D OUTPUT -p tcp -j PROXY | |
iptables -t nat -F PROXY | |
iptables -t nat -X PROXY | |
echo "removing ipset" | |
ipset destroy chnroute | |
echo "tcp traffic is now not redirected" | |
} | |
function chnroutes-update { | |
wget 'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest' -O /tmp/delegated-apnic-latest | |
cat /tmp/delegated-apnic-latest | awk -F\| '/CN\|ipv4/ { printf("%s/%d\n", $4, 32-log($5)/log(2)) }' > chnroute.txt | |
rm /tmp/delegated-apnic-latest | |
} | |
if [[ "$command" == "up" ]]; then | |
proxy-up | |
elif [[ "$command" == "down" ]]; then | |
proxy-down | |
elif [[ "$command" == "update" ]]; then | |
chnroutes-update | |
else | |
echo "Usage: " | |
echo "proxy up port #setup iptable rules default port: 1024" | |
echo "proxy down #remove iptable rules" | |
echo "proxy update #update chnroutes" | |
fi | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment