Saturday, July 25, 2020

How to blacklist IPs using iptables….

I finally made the jump to Linux for my firewall. I used wrt for the longest time and that was sufficient… But then I decided I needed more control. I was having problems getting IPSec through the firewall. I know it’s possible, and can even host it, however it’s just not the easiest. So I figured I wanted to just separate the functions. Which I did.

I HAD NO IDEA how much the Internet has changed. I’m getting probed about every minute for ssh and a whole variety of things. Back in the 90’s I had hosts on the Internet, and go maybe accessed a couple times a day. Now it seems the whole of freaking china, India, Russia and several other small countries are blasting the Internet ALL THE TIME.

So I wrote a blacklist script to grab the ip’s of the offenders and toss it into a file. Then I just drop any traffic coming in from those IPs…

root@r1:~# cat blacklist.sh
BLACKLIST=/tmp/blacklist
GREP="/usr/bin/grep -Ev"
IPT="/usr/sbin/iptables -A"

/root/blacklistip.sh

IPS=$($GREP "^#" $BLACKLIST)

for IP in $IPS
 do
  $IPT INPUT -s $IP -j DROP
  $IPT OUTPUT -d $IP -j DROP
done

My blacklist file calls a parser program. I probably should have made it a function, but I’m planning to reuse some sections of these, so I’ve kept em separate…. Do what ever is right for yourself :)

root@r1:~# cat blacklistip.sh
#!/bin/sh
CAT="/usr/bin/cat"
GREP="/usr/bin/grep -i"
AWK="/usr/bin/awk"
UNIQ="/usr/bin/uniq"
SORT="/usr/bin/sort"

ATTACK="sshd"
TMPFILE=/tmp/$ATTACK.attack
BLACK="/tmp/blacklist"
FILE="/var/log/iptables.log"
#
#  Copy off previous

$CAT $BLACK.new > $BLACK.old

$CAT $FILE | $GREP $ATTACK | $AWK '{ print $11 }' > $TMPFILE.1
$CAT $TMPFILE.1 | $AWK -F "=" '{ print $2 }' >> $TMPFILE.2
$SORT $TMPFILE.2 > $TMPFILE.3

$UNIQ $TMPFILE.3 > $BLACK.new
#
#  Only blacklist ones not done before....
#
$AWK 'NR=FNR{a[$0];next}!($0 in a)' $BLACK.old $BLACK.new > $BLACK
root@r1:/tmp# tail blacklist.old
79.17.217.113
80.211.246.93
84.2.226.70
89.154.4.249
89.248.168.51
91.121.211.59
92.222.156.151
93.148.0.91
94.103.80.118
97.90.110.160
[/code

[code]
root@r1:/tmp# tail blacklist.new
79.17.217.113
80.211.246.93
84.2.226.70
89.154.4.249
89.248.168.51
91.121.211.59
92.222.156.151
93.148.0.91
94.103.80.118
97.90.110.160
root@r1:/tmp#