Skip to content

Instantly share code, notes, and snippets.

@Lu5ck
Created April 25, 2025 16:10
Show Gist options
  • Save Lu5ck/6372f4f7a0311bd8c314764752e4ecce to your computer and use it in GitHub Desktop.
Save Lu5ck/6372f4f7a0311bd8c314764752e4ecce to your computer and use it in GitHub Desktop.
OpenWRT PBR by AS number
#!/bin/sh
# shellcheck disable=SC2015,SC3003,SC3060
# ASN example
# Replace "ASN_" with a unique word to minimize conflicts with other asn based scripts
ASN_URL="https://stat.ripe.net/data/announced-prefixes/data.json?resource=AS138341"
ASN_JSON_FILE="/var/tmp/pbr_asn_ip_ranges.gz"
TARGET_TABLE="inet fw4"
TARGET_INTERFACE="wan"
ASN_IPv4="/var/tmp/pbr_asn_ipv4.txt"
ASN_IPv6="/var/tmp/pbr_asn_ipv6.txt"
cleanup()
{
rm -f "$ASN_JSON_FILE"
rm -f "$ASN_IPv4"
rm -f "$ASN_IPv6"
}
trap cleanup 1 2 3 6
mkdir -p "${ASN_JSON_FILE%/*}"
cleanup
uclient-fetch --no-check-certificate -qO- "$ASN_URL" | gzip > "$ASN_JSON_FILE"
[ -s "$ASN_JSON_FILE" ] || return 1
ASN_IPs=$(zcat $ASN_JSON_FILE | jsonfilter -e "@.data.prefixes[*].prefix")
ASN_IPs=$(echo "$ASN_IPs" | xargs)
for ASN_IP in $ASN_IPs; do
case "$ASN_IP" in
*:*) echo $ASN_IP >> $ASN_IPv6 ;;
*) echo $ASN_IP >> $ASN_IPv4 ;;
esac
done
unset ASN_IP
unset ASN_IPs
if [ "$(uci get pbr.config.ipv6_enabled)" = "1" ] && [ -s "$ASN_IPv6" ]; then
ASN_IPv6_LIST=$(awk 'NF { printf "%s%s", sep, $0; sep=", " }' "$ASN_IPv6")
ASN_NFTSET="pbr_${TARGET_INTERFACE}_6_dst_ip_user"
nft "add element $TARGET_TABLE $AZURE_NFTSET { ${ASN_IPv6_LIST//$'\n'/, } }" || return 1
unset ASN_IPv6_LIST
fi
if [ -s "$ASN_IPv4" ]; then
ASN_IPv4_LIST=$(awk 'NF { printf "%s%s", sep, $0; sep=", " }' "$ASN_IPv4")
ASN_NFTSET="pbr_${TARGET_INTERFACE}_4_dst_ip_user"
nft "add element $TARGET_TABLE $ASN_NFTSET { ${ASN_IPv4_LIST//$'\n'/, } }" || return 1
unset ASN_IPv4_LIST
fi
unset ASN_NFTSET
cleanup
return 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment