Files
bin/drop
T
2026-06-11 15:14:00 +02:00

47 lines
1.0 KiB
Bash
Executable File

#!/usr/bin/env bash
#see /usr/local/bin/block_subnet.sh
set -euo pipefail
IP="${1:-}"
if [[ -z "$IP" ]]; then
echo "Usage: $0 <IPv4-address>"
exit 2
fi
# validate basic IPv4 format
if ! [[ "$IP" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
echo "Invalid IPv4 address"
exit 2
fi
IFS='.' read -r o1 o2 o3 o4 <<< "$IP"
for oct in "$o1" "$o2" "$o3" "$o4"; do
if (( oct < 0 || oct > 255 )); then
echo "Invalid IPv4 address"
exit 2
fi
done
CIDR="${o1}.${o2}.${o3}.0/24"
echo "CIDR: $CIDR"
# add nftables rule (creates table/chain if missing)
if ! sudo nft list table ip filter >/dev/null 2>&1; then
sudo nft add table ip filter
fi
if ! sudo nft list chain ip filter input >/dev/null 2>&1; then
sudo nft 'add chain ip filter input { type filter hook input priority 0; }'
fi
# idempotent: delete existing identical rule if present, then add
sudo nft -f - <<EOF
table ip filter {
chain input {
type filter hook input priority 0;
ip saddr $CIDR drop
}
}
EOF
echo "Added nftables rule to drop traffic from $CIDR"