Skip to content

Instantly share code, notes, and snippets.

@solariz
Last active May 6, 2022 08:43
Show Gist options
  • Save solariz/fab395fd448f6ab628b2c3a533b93206 to your computer and use it in GitHub Desktop.
Save solariz/fab395fd448f6ab628b2c3a533b93206 to your computer and use it in GitHub Desktop.
iptables droplist;
#!/bin/sh
# based on this version http://www.timokorthals.de/?p=334
# adapted by Stéphane T.
# update Marco Goetze see: https://solariz.de/en/preventive-blocking-of-bad-ips-using-iptables.htm
_ipt=/sbin/iptables # Location of iptables (might be correct)
_input=badips.db # Name of database (will be downloaded with this name)
_pub_if=eth0 # Device which is connected to the internet (ex. $ifconfig for that)
_droplist=droplist # Name of chain in iptables (Only change this if you have already a chain with this name)
_level=2 # Blog level: not so bad/false report (0) over confirmed bad (3) to quite aggressive (5) (see www.badips.com for that)
_service=http # Logged service (see www.badips.com for that)
# https://www.badips.com/get/categories
_whitelist="10.20.30.40;1.1.1.1" #enter IPs for whitelist filter, use a separator e.g. "1.0.0.1;1.1.1.1;8.8.8.8"
_log=false # Should we LOG the blocked packages (true) or silently discard (false) ?
_age=2w # Maximum Age of the entry to block it, options like: (1w,2w,3w,...)
stringContain() {
local _lc=${2,,}
[ -z "$1" ] || { [ -z "${_lc##*${1,,}*}" ] && [ -n "$2" ] ;};
}
echo "Fetching badips.com"
# Get the bad IPs
wget -qO- https://www.badips.com/get/list/${_service}/$_level?age=$_age > "$_input.tmp" || { echo "$0: Unable to download ip list."; exit 1; }
echo "Fetching emergingthreats.net"
# Get C&C emergingthread list
wget -qO- https://rules.emergingthreats.net/fwrules/emerging-Block-IPs.txt >> "$_input.tmp" || { echo "$0: Unable to download ip list."; exit 1; }
### Setup our black list ###
# First flush it
$_ipt --flush $_droplist
# Create a new chain
# Decomment the next line on the first run
$_ipt -N $_droplist
# Sorting and dedup
sort "$_input.tmp" | uniq -u | egrep -o '(([0-9]|[0-9]{2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[0-9]{2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])(/[0-9]{2})?' > $_input
# Filter out comments and blank lines
# store each ip in $ip
for ip in `cat $_input`
do
# check whitelist
if [ -z "${_whitelist##*$ip*}" ] ;then
echo "- Ignoring '$ip' whitelisted."
else
#echo "+ '$ip'"
# Append everything to $_droplist
if [ "$_log" = true ] ; then
$_ipt -A $_droplist -i ${_pub_if} -s $ip -j LOG --log-prefix "Drop Bad IP List"
else
$_ipt -A $_droplist -i ${_pub_if} -s $ip -j DROP
fi
fi
done
# Finally, insert or append our black list
$_ipt -I INPUT -j $_droplist
$_ipt -I OUTPUT -j $_droplist
$_ipt -I FORWARD -j $_droplist
# Delete your temp files
echo "Cleaning up..."
rm $_input
rm "$_input.tmp"
echo -n "Added Blacklist Entrys: "
$_ipt -S | grep "j DROP" | grep -c "$_droplist"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment