Last active
April 26, 2025 16:59
-
-
Save Lu5ck/2e1755e0fb2847b35bf492ea95fa6484 to your computer and use it in GitHub Desktop.
OpenWRT PBR by GeoIP
This file contains hidden or 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
#!/bin/sh | |
# shellcheck disable=SC2015,SC3003,SC3060 | |
# See https://www.iwik.org/ipcountry/ for list | |
GEO_PREFIX="SG" | |
GEO_URL="https://www.iwik.org/ipcountry" | |
TARGET_TABLE="inet fw4" | |
TARGET_INTERFACE="wan" | |
GEO_IPv4="/var/tmp/pbr_geo_ipv4.txt" | |
GEO_IPv6="/var/tmp/pbr_geo_ipv6.txt" | |
cleanup() | |
{ | |
rm -f "$GEO_IPv4" | |
rm -f "$GEO_IPv6" | |
} | |
trap cleanup 1 2 3 6 | |
mkdir -p "${GEO_IPv4%/*}" | |
cleanup | |
if [ "$(uci get pbr.config.ipv6_enabled)" = "1" ]; then | |
uclient-fetch --no-check-certificate -qO- "${GEO_URL}/${GEO_PREFIX}.ipv6" | gzip > "$GEO_IPv6" | |
if [ -s "$GEO_IPv6" ]; then | |
GEO_IPv6_LIST=$(zcat "$GEO_IPv6" | awk 'NF && $1 !~ /^#/ { printf "%s%s", sep, $0; sep=", " }') | |
GEO_NFTSET="pbr_${TARGET_INTERFACE}_6_dst_ip_user" | |
nft "add element $TARGET_TABLE $AZURE_NFTSET { ${GEO_IPv6_LIST//$'\n'/, } }" || return 1 | |
unset GEO_IPv6_LIST | |
fi | |
fi | |
uclient-fetch --no-check-certificate -qO- "${GEO_URL}/${GEO_PREFIX}.cidr" | gzip > "$GEO_IPv4" | |
if [ -s "$GEO_IPv4" ]; then | |
GEO_IPv4_LIST=$(zcat "$GEO_IPv4" | awk 'NF && $1 !~ /^#/ { printf "%s%s", sep, $0; sep=", " }') | |
GEO_NFTSET="pbr_${TARGET_INTERFACE}_4_dst_ip_user" | |
nft "add element $TARGET_TABLE $GEO_NFTSET { ${GEO_IPv4_LIST//$'\n'/, } }" || return 1 | |
unset GEO_IPv4_LIST | |
fi | |
unset GEO_NFTSET | |
cleanup | |
return 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment