0

I have a VERY old kernel version which for dumb "boss who thinks he knows everything" reasons i can not update. I need to either fire my boss or make a bash script that can add an iptable rule everytime it reads a different ip with dmesg. How can i make this. For the moment i have this which works good but it keeps duplicating the IP for obvious reasons on how iptable works there. I need to find a way to, before appending the IP, i want to make sure the ip is NOT in the iptable list already:

for BADIP in $(dmesg | grep 'Treason uncloaked!' | cut -d' ' -f6 | cut -d':' -f1 | sort --unique)
do
iptables -A INPUT -s $BADIP -j DROP
done
Luis Alvarado
  • 179
  • 1
  • 11
  • Perhaps I am miss-reading, but this appears to be non-fatal error. Have you seen this? http://kerneltrap.org/node/7182. How is your script running? Can you just do a uniq on the dmesg output? If you are blocking things properly you should never see a second packet. – Zoredache Mar 03 '11 at 00:14
  • *Why*? I just checked `dmesg` and the only IP with the window shrinking message belongs to one of our biggest clients according to our application log. If I blocked that, I would have to have a *really* good explanation. – DerfK Mar 03 '11 at 00:28
  • Remember that the script will read AGAIN dmesg which has the Treason uncloacked part there still so it will add it again to the iptables. I need to make sure that BEFORE it adds it again it checks if it exists in the iptables – Luis Alvarado Mar 03 '11 at 00:34
  • you can use dmesg -c which will delete contents of ring buffer after it's printed to STDOUT, so next time you wont parse the same lines, but yes checking for IPs in existing firewall rules is way to go. – Hrvoje Špoljar Mar 03 '11 at 02:32

1 Answers1

1

Why not just use Fail2Ban? It should be easy enough to setup a filter for it.

However, something like the following would also work.

for BADIP in $(dmesg | grep 'Treason uncloaked!' | cut -d' ' -f6 | cut -d':' -f1 | sort --unique)
do
    iptables -L INPUT | grep $BADIP
    if [ $? -ne 0 ]
    then
        iptables -A INPUT -s $BADIP -j DROP
    fi
done

Untested, but the basics are that $? is the exit code of the last command. If grep finds the ip, it will exit with 0. If grep fails to find the ip, it will be non-zero and the if condition will be triggered.

Niall Donegan
  • 3,869
  • 20
  • 17