Skip to content

Instantly share code, notes, and snippets.

@korzhyk
Last active November 3, 2022 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save korzhyk/5038e1b63bbc45bef04be95b20969302 to your computer and use it in GitHub Desktop.
Save korzhyk/5038e1b63bbc45bef04be95b20969302 to your computer and use it in GitHub Desktop.
OpenWRT using WireGuard VPN tunnel for banned networks.
#!/bin/sh
REPO_URL=https://zaborona.help/ips.txt
log() {
logger -t ipset "$1"
}
apply_table() {
local ipset
local target
config_get target $1 target
if [ "$target" = "MARK" ]; then
config_get ipset $1 ipset
[ "$ipset" = "$INTERFACE" ] && {
ip route add table $ipset default dev $INTERFACE
log "add table $ipset to $INTERFACE interface"
}
fi
}
assign_ipset_table() {
local match
local name
config_get name $1 name
if [ "$name" = "$INTERFACE" ]; then
config_get match $1 match
ipset create $name hash:net
wget -qO- ${REPO_URL} | grep -v '^#' | while read -r cidr; do
[ -z "$cidr" ] && continue
ipset add $name $cidr && log "assign $cidr to $name:$match table"
done
fi
}
[ "$ACTION" = ifdown ] && {
log "flush table $INTERFACE due to interface '$INTERFACE' is down"
ipset flush $INTERFACE
}
[ "$ACTION" = ifup ] && {
. /lib/functions.sh
config_load firewall
config_foreach apply_table rule
config_foreach assign_ipset_table ipset
}

Prepairing

opkg update && opkg install ipset

Setting up route tables

echo "100 wg0" >> /etc/iproute2/rt_tables
wget -O /etc/hotplug.d/iface/50-tun-routes https://gist.githubusercontent.com/korzhyk/5038e1b63bbc45bef04be95b20969302/raw/50-tun-routes

Setting up forward

uci batch <<EOF
	add network rule
	set network.@rule[-1].priority='100'
	set network.@rule[-1].lookup='wg0'
	set network.@rule[-1].mark='0x1'
EOF
uci commit network
service network restart

Setting up firewall

uci batch <<EOF
	add firewall zone
	set firewall.@zone[-1].name='tun'
	set firewall.@zone[-1].masq='1'
	set firewall.@zone[-1].output='ACCEPT'
	set firewall.@zone[-1].forward='REJECT'
	set firewall.@zone[-1].input='REJECT'
	set firewall.@zone[-1].mtu_fix='1'
	set firewall.@zone[-1].network='wg0'
	add firewall forwarding
	set firewall.@forwarding[-1].src='lan'
	set firewall.@forwarding[-1].dest='tun'
	add firewall ipset
	set firewall.@ipset[-1].name='wg0'
	set firewall.@ipset[-1].storage='hash'
	set firewall.@ipset[-1].match='dst_net'
	set firewall.@ipset[-1].loadfile='/tmp/lists/wg0.list'
	add firewall rule
	set firewall.@rule[-1].name='wg0'
	set firewall.@rule[-1].src='lan'
	set firewall.@rule[-1].dest='*'
	set firewall.@rule[-1].proto='all'
	set firewall.@rule[-1].ipset='wg0'
	set firewall.@rule[-1].set_mark='0x1'
	set firewall.@rule[-1].target='MARK'
EOF
uci commit firewall
service firewall restart
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment