Last active
May 7, 2024 21:43
-
-
Save cyrbil/96389ef47ee5a656d0df1706e1143cfc to your computer and use it in GitHub Desktop.
A small script to create iptables rules to block known malware IPs
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/bash | |
set -o errexit | |
set -o errtrace | |
set -o functrace | |
set -o pipefail | |
set -o nounset | |
[ -z ${DEBUG+x} ] || set -o xtrace | |
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)" | |
TYPE_FILTER="KnownAttacker|Malware|Spammer" | |
SET_NAME="suspicious_ips" | |
BLOCK_FILE="${ROOT_DIR}/blocklist.json" | |
IP_FILE="${ROOT_DIR}/suspiciousIPs.txt" | |
echo "Downloading latest block list" | |
wget -q --progress=bar --show-progress -O "${BLOCK_FILE}" https://malwareworld.com/textlists/ips.txt | |
echo "Filtering block list with '${TYPE_FILTER}'" | |
pv "${BLOCK_FILE}" \ | |
| jq -r 'to_entries[] | select(.key | length > 7) | .key + "\t" + (.value.type | join(","))' \ | |
| awk "/${TYPE_FILTER}/{print \$1}" \ | |
> "${IP_FILE}" | |
echo "Importing IP list" | |
TMP_DIR="$(mktemp -d)" | |
( | |
cd "${TMP_DIR}" | |
cat "${IP_FILE}" | split --suffix-length=2 --numeric-suffixes=1 --lines=65536 | |
for SPLIT in $( ls x* ); do | |
CURRENT_SET="${SET_NAME}_${SPLIT:1:2}" | |
echo "Creating ipset '${CURRENT_SET}'" | |
iptables -D INPUT -m set --match-set "${CURRENT_SET}" src -j DROP 2>/dev/null || true | |
sleep 1; # wait for iptables changes | |
ipset destroy "${CURRENT_SET}" 2>/dev/null || true | |
ipset create "${CURRENT_SET}" hash:ip | |
pv "${SPLIT}" | sed "s/^/add \"${CURRENT_SET}\" /" | ipset restore | |
echo "Add set to iptables rules" | |
iptables -A INPUT -m set --match-set "${CURRENT_SET}" src -j DROP | |
done | |
) | |
rm -rf "${TMP_DIR}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment