Last active
April 24, 2025 08:35
-
-
Save Lu5ck/4ef1fe8c858adacb860f2d4133a779b2 to your computer and use it in GitHub Desktop.
OpenWRT PBR AWS by Regions
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 | |
AWS_URL="https://ip-ranges.amazonaws.com/ip-ranges.json" | |
AWS_JSON_FILE="/var/tmp/pbr_aws_ip_ranges.gz" | |
AWS_REGIONS="ap-southeast-3 ap-southeast-5 ap-southeast-1 GLOBAL" | |
TARGET_TABLE="inet fw4" | |
TARGET_INTERFACE="wan" | |
AWS_IPv4="/var/tmp/pbr_aws_ipv4.txt" | |
AWS_IPv6="/var/tmp/pbr_aws_ipv6.txt" | |
cleanup() | |
{ | |
rm -f "$AWS_JSON_FILE" | |
rm -f "$AWS_IPv4" | |
rm -f "$AWS_IPv6" | |
} | |
trap cleanup 1 2 3 6 | |
mkdir -p "${AWS_JSON_FILE%/*}" | |
cleanup | |
uclient-fetch --no-check-certificate -qO- "$AWS_URL" | gzip > "$AWS_JSON_FILE" | |
[ -s "$AWS_JSON_FILE" ] || return 1 | |
if [ "$(uci get pbr.config.ipv6_enabled)" = "1" ]; then | |
for AWS_REGION in $AWS_REGIONS; do | |
AWS_IPs=$(zcat $AWS_JSON_FILE | jsonfilter -e "@.ipv6_prefixes[@.region='$AWS_REGION'].ipv6_prefix") | |
AWS_IPs=$(echo "$AWS_IPs" | xargs) | |
echo $AWS_IPs >> $AWS_IPv6 | |
done | |
AWS_IP_LIST=$(tr ' ' '\n' < "$AWS_IPv6" | awk 'BEGIN { sep = "" } NF { printf "%s%s", sep, $0; sep=", " }') | |
AWS_NFTSET="pbr_${TARGET_INTERFACE}_6_dst_ip_user" | |
nft "add element $TARGET_TABLE $AWS_NFTSET { ${AWS_IP_LIST//$'\n'/, } }" || return 1 | |
unset AWS_IP_LIST | |
unset AWS_NFTSET | |
rm -f "$AWS_IPv6" | |
fi | |
for AWS_REGION in $AWS_REGIONS; do | |
AWS_IPs=$(zcat $AWS_JSON_FILE | jsonfilter -e "@.prefixes[@.region='$AWS_REGION'].ip_prefix") | |
AWS_IPs=$(echo "$AWS_IPs" | xargs) | |
echo $AWS_IPs >> $AWS_IPv4 | |
done | |
AWS_IP_LIST=$(tr ' ' '\n' < "$AWS_IPv4" | awk 'BEGIN { sep = "" } NF { printf "%s%s", sep, $0; sep=", " }') | |
AWS_NFTSET="pbr_${TARGET_INTERFACE}_4_dst_ip_user" | |
nft "add element $TARGET_TABLE $AWS_NFTSET { ${AWS_IP_LIST//$'\n'/, } }" || return 1 | |
unset AWS_IP_LIST | |
unset AWS_NFTSET | |
rm -f "$AWS_IPv4" | |
rm -f "$AWS_JSON_FILE" | |
return 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment