Last active
April 19, 2025 13:40
-
-
Save Lu5ck/a9ab9ca974980acbaccf8b68bfe4fb00 to your computer and use it in GitHub Desktop.
OpenWRT pbr for aws by regions
This file contains 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 | |
TARGET_URL='https://ip-ranges.amazonaws.com/ip-ranges.json' | |
TARGET_DL_FILE='/var/pbr_tmp_aws_ip_ranges.gz' | |
TARGET_TABLE='inet fw4' | |
TARGET_INTERFACE='wan' | |
TARGET_REGIONS='ap-southeast-3 ap-southeast-5 ap-southeast-1 GLOBAL' | |
trap 'rm -f "$TARGET_DL_FILE"' EXIT | |
_ret=1 | |
mkdir -p "${TARGET_DL_FILE%/*}" | |
[ -s "$TARGET_DL_FILE" ] || \ | |
uclient-fetch --no-check-certificate -qO- "$TARGET_URL" | \ | |
gzip > "$TARGET_DL_FILE" | |
[ -s "$TARGET_DL_FILE" ] || return 1 | |
json_data="$(zcat "$TARGET_DL_FILE")" | |
[ "$(uci get pbr.config.ipv6_enabled)" = "1" ] && vers="4 6" || vers="4" | |
for ver in $vers; do | |
case "$ver" in | |
4) | |
prefix_path='@.prefixes' | |
region_key='region' | |
ip_key='ip_prefix' | |
;; | |
6) | |
prefix_path='@.ipv6_prefixes' | |
region_key='region' | |
ip_key='ipv6_prefix' | |
;; | |
esac | |
params="" | |
for region in $TARGET_REGIONS; do | |
region_params="$(printf '%s' "$json_data" | jsonfilter -e "$prefix_path[@.$region_key='$region'].$ip_key")" | |
[ -n "$region_params" ] && params="${params}${region_params}"$'\n' | |
done | |
# Trim trailing newline if needed | |
params="$(printf "%s" "$params")" | |
[ -n "$params" ] && _ret=0 || continue | |
nftset="pbr_${TARGET_INTERFACE}_${ver}_dst_ip_user" | |
nft "add element $TARGET_TABLE $nftset { ${params//$'\n'/, } }" || _ret=1 | |
done | |
unset json_data | |
return $_ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Removed the tmp file once script exit.
Put json into variable so we don't have to keep decompressing it every time.