Skip to content

Instantly share code, notes, and snippets.

@splitbrain
Last active November 12, 2025 11:46
Show Gist options
  • Select an option

  • Save splitbrain/68f331bb153a9714731ffb8f968660d5 to your computer and use it in GitHub Desktop.

Select an option

Save splitbrain/68f331bb153a9714731ffb8f968660d5 to your computer and use it in GitHub Desktop.
Block an ASN with UFW
#!/usr/bin/env bash
#
# Block all ranges from a given ASN via UFW.
# Usage:
# sudo ./block_asn.sh AS1234 ["optional comment"]
#
# Requires: ufw, curl
#
set -euo pipefail
ASN="${1:-}"
if [[ -z "$ASN" ]]; then
echo "Usage: $0 <ASN> [optional comment]"
exit 1
fi
# Always include ASN in comment
USER_COMMENT="${2:-}"
if [[ -n "$USER_COMMENT" ]]; then
COMMENT="AS${ASN} - ${USER_COMMENT}"
else
COMMENT="AS${ASN}"
fi
BASE_URL="https://raw.githubusercontent.com/ipverse/asn-ip/master/as/${ASN}"
for FAMILY in ipv4-aggregated.txt ipv6-aggregated.txt; do
URL="${BASE_URL}/${FAMILY}"
echo "Fetching $URL"
TMPFILE=$(mktemp)
if ! curl -fsSL "$URL" -o "$TMPFILE"; then
echo "Failed to fetch $URL"
rm -f "$TMPFILE"
continue
fi
# Read ranges skipping blanks & comments
while IFS= read -r line; do
[[ -z "$line" ]] && continue
[[ "$line" =~ ^# ]] && continue
echo "Blocking range: $line"
ufw prepend deny from "$line" comment "$COMMENT"
done < "$TMPFILE"
rm -f "$TMPFILE"
done
echo "Done. Block rules inserted for ${ASN}."
#!/usr/bin/env bash
#
# List all ASNs that appear in UFW rule comments, sorted numerically.
# Usage:
# sudo ./list_asn.sh
#
set -euo pipefail
# Extract all "AS####" patterns from ufw output, normalize, and sort numerically
mapfile -t ASNS < <(
ufw status numbered |
grep -Eo 'AS[0-9]+' |
sed -E 's/^AS//' |
sort -u |
sort -n
)
if [[ ${#ASNS[@]} -eq 0 ]]; then
echo "No ASN blocks found."
exit 1
fi
echo "Blocked ASNs (sorted numerically):"
for asn in "${ASNS[@]}"; do
printf "% 10s\n" "$asn"
done
#!/usr/bin/env bash
#
# Remove all UFW rules having a comment that contains AS{ASN}.
# Usage:
# sudo ./unblock_asn.sh 1234
#
# Requires: ufw
#
set -euo pipefail
ASN="${1:-}"
if [[ -z "$ASN" ]]; then
echo "Usage: $0 <ASN>"
exit 1
fi
echo "Searching for UFW rules containing ${ASN}..."
# Capture all lines containing the ASN
mapfile -t MATCHES < <(ufw status numbered | grep -F "AS${ASN}" || true)
if [[ ${#MATCHES[@]} -eq 0 ]]; then
echo "No rules found for ${ASN}."
exit 0
fi
echo "Found ${#MATCHES[@]} matching rule(s):"
printf '%s\n' "${MATCHES[@]}"
# Extract the numeric IDs correctly —
# The rule number is inside [ ... ], possibly with spaces.
mapfile -t NUMBERS < <(
printf '%s\n' "${MATCHES[@]}" |
sed -E 's/^\[[[:space:]]*([0-9]+)\].*/\1/' |
sort -nr
)
for NUM in "${NUMBERS[@]}"; do
if [[ "$NUM" =~ ^[0-9]+$ ]]; then
echo "Deleting rule #${NUM}"
ufw --force delete "$NUM"
fi
done
echo "All rules containing AS${ASN} have been removed."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment