Route traffic by country - shenhaoyu/AnyGW GitHub Wiki
Route traffic by country
First of all, the following method is not yet automatized, it will allow you to rout chinese traffic throught VPN using OpenWrt router and ipset. I find this method is much more elegant.
1. Download APNIC IP ranges
root@OpenWrt:# wget http://ftp.apnic.net/stats/apnic/delegated-apnic-latest
2. Select Chinese IPs
root@OpenWrt:# cat delegated-apnic-latest | awk -F '|' '/CN/&&/ipv4/ {print $4 "/" 32-log($5)/log(2)}' | cat > chinaip
3. Create a new IPs list
root@OpenWrt:# ipset create chinaip hash:net --hashsize 20000
4. Put all Chinese IPs in the list
root@OpenWrt:# cat chinaip | awk '{system("ipset add chinaip " $1)}'
5. Mark the traffic in the ipset list
root@OpenWrt:# iptables -I PREROUTING -t mangle -m set --match-set chinaip dst -j MARK --set-mark 1
6. Route marked traffic with table 100 into VPN interface
root@OpenWrt:# ip rule add prio 100 fwmark 1 lookup 100
root@OpenWrt:# ip route add table 100 default dev l2tp-anygwcn2
If you want to rebuild the ipset list, firstly delete the mark rule
root@OpenWrt:# iptables -D PREROUTING -t mangle -m set --match-set chinaip dst -j MARK --set-mark 1
Then destroy the ipset list,
root@OpenWrt:# ipset destroy chinaip
and goto the begining util Step 3.
Automate a littel bit the command
root@OpenWrt:~# cat ./build-china-ipset.sh
#!/bin/sh
# Build China IP List
rm /root/delegated-apnic-latest
rm /root/chinaip
wget http://ftp.apnic.net/stats/apnic/delegated-apnic-latest -O /root/delegated-apnic-latest
cat /root/delegated-apnic-latest | awk -F '|' '/CN/&&/ipv4/ {print $4 "/" 32-log($5)/log(2)}' | cat > /root/chinaip
# Delete Iptables rule and IPSet chinaip
iptables -D PREROUTING -t mangle -m set --match-set chinaip dst -j MARK --set-mark 1
ipset destroy chinaip
# Create IPSet chinaip
ipset create chinaip hash:net --hashsize 20000
cat /root/chinaip | awk '{system("ipset add chinaip " $1)}'
# Add Iptables rule and chinaip mark
iptables -I PREROUTING -t mangle -m set --match-set chinaip dst -j MARK --set-mark 1
ip rule add prio 100 fwmark 1 lookup 100
# Route marked chinaip traffic to l2tp vpn
ip route add table 100 default dev l2tp-anygwcn2
root@OpenWrt:~# cat /etc/hotplug.d/iface/98-build-ipset-chinaip
#!/bin/sh
[ "${ACTION}" = "ifup" -a "${DEVICE}" = "eth0" ] && {
logger -t hotplug "Build China IP Set & Rule Device: ${DEVICE} Action: ${ACTION} Interface: ${INTERFACE}"
/root/build-china-ipset.sh
}
[ "${ACTION}" = "ifup" -a "${DEVICE}" = "l2tp-anygwcn2" ] && {
logger -t hotplug "Add China IP Set Route Device: ${DEVICE} Action: ${ACTION} Interface: ${INTERFACE}"
ip route add table 100 default dev l2tp-anygwcn2
}