Created
December 15, 2024 09:41
-
-
Save 186526/abbdf396a4c79dccb9beda44520cc1b9 to your computer and use it in GitHub Desktop.
bgpq4-pve-ipset-updater
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/bash | |
| # This script is used to generate pve-ipset-fw by using bgpq4 | |
| function help() { | |
| echo "Usage: $0 <instance_id> <as_set> <interface_name>" | |
| echo "Example: $0 1000 ARIN::AS-SUNOAKI net0" | |
| exit 1 | |
| } | |
| if [ -z "$1" ]; then | |
| help | |
| fi | |
| if [ -z "$2" ]; then | |
| help | |
| fi | |
| if [ -z "$3" ]; then | |
| help | |
| fi | |
| if ! command -v bgpq4 &> /dev/null; then | |
| echo "bgpq4 could not be found" | |
| exit 1 | |
| fi | |
| instance_id=$1 | |
| as_set=$2 | |
| interface_name=$3 | |
| # Get the AS-SET's IPv4 prefix | |
| ipv4_prefixes=$(bgpq4 -4 -F '%n/%l\n' -A "$as_set") | |
| ipv6_prefixes=$(bgpq4 -6 -F '%n/%l\n' -A "$as_set") | |
| function new_ipset() { | |
| tempfile="$(mktemp)" | |
| trap 'rm -rf -- "$tempfile"' EXIT | |
| printf "[IPSET ipfilter-$interface_name] # generated in $(date -I"seconds"), by bgpq4-pve-ipset-updater\n\n" > "$tempfile" | |
| for line in $ipv4_prefixes; do | |
| echo "$line # from $as_set" >> "$tempfile" | |
| done | |
| for line in $ipv6_prefixes; do | |
| echo "$line # from $as_set" >> "$tempfile" | |
| done | |
| echo "" >> "$tempfile" | |
| cat "$tempfile" | |
| } | |
| # Read Original pve-ipset-fw file | |
| original_pve_fw_file="/etc/pve/firewall/$instance_id.fw" | |
| if [ ! -f "$original_pve_fw_file" ]; then | |
| printf "[OPTIONS]\n\nipfilter: 1\nenable: 1\npolicy_in: ACCEPT\n" > "$original_pve_fw_file" | |
| fi | |
| # Check original pve-ipset-fw file does have the ipset | |
| new_pve_fw_file="$(mktemp)" | |
| trap 'rm -rf -- "$new_pve_fw_file"' EXIT | |
| flag=0 | |
| isPrinted=0 | |
| while IFS= read -r line; do | |
| if [[ $line =~ "[IPSET ipfilter-$interface_name]" ]]; then | |
| echo "" >> "$new_pve_fw_file" | |
| new_ipset >> "$new_pve_fw_file" | |
| flag=1 | |
| isPrinted=1 | |
| fi | |
| if [[ $line =~ "[IPSET " && $flag == 1 ]]; then | |
| flag=0 | |
| fi | |
| if [[ $flag == 0 ]]; then | |
| echo "$line" >> "$new_pve_fw_file" | |
| fi | |
| done < "$original_pve_fw_file" | |
| if [[ $isPrinted == 0 ]]; then | |
| new_ipset >> "$new_pve_fw_file" | |
| fi | |
| cat "$new_pve_fw_file" > "$original_pve_fw_file" | |
| exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment