Using swatchdog for monitoring new firewall logs

Always interested in trying out a new tool, so I decided to use this when I wanted to monitor a new rule I put in my firewall, to see what it was doing.

The rule was an ipset rule to match against a bunch of addresses and blacklist them. I dumped out a copy of the ruleset using iptables-save > rules.txt

The rule in question was

-A INPUT -p tcp -m set --match-set blacklist-script src -j DROP

So I added a line above it to log any matches with the tag "BlacklistDrop:", which would allow me to identify the matches in my syslog

-A INPUT -p tcp -m set --match-set blacklist-script src -j LOG --log-prefix "BlacklistDrop: "
-A INPUT -p tcp -m set --match-set blacklist-script src -j DROP

After editing the file you can make it active by using iptables-restore rules-edited.txt . So far so good. I didn't want to make the changes permanent so I left it like that. If iptables is restarted, it will forget the new rule.

Next, time to tell swatchdog what to do. In ~/.swatchdogrc I set up the following.

watchfor /BlacklistDrop:/
	exec /root/scripts/blacklistlogger.sh "$_"

So it will watch syslog (the default setting), and when it finds a line in there matching our tag, it will pass it to the blacklistlogger.sh script as a commandline argument. "$_" means pass the whole line. In this case, a whole line will look like this:

Sep 2 16:39:39 server kernel: [543547.097604] BlacklistDrop: IN=eth0 OUT= MAC=00:50:56:42:fc:3a:28:99:3a:4d:23:91:08:00 SRC=45.134.26.57 DST=62.171.162.39 LEN=40 TOS=0x00 PREC=0x00 TTL=247 ID=41722 PROTO=TCP SPT=50248 DPT=27741 WINDOW=1024 RES=0x00 SYN URGP=0

Now we just need the script, which you'll need to make executable. Its just a one liner with some sed magic in, to trim the line into the relevant parts.

#!/bin/bash
# In use by swatchdog
# ps -auxf | grep swatchdog

echo "$1" | sed -r 's/.*SRC=([0-9.]+).*DPT=([0-9]+).*/ /' >> /root/scripts/blacklist.log

Lets digest that sed command I only wanted to log the source IP address and what port its attacking. So in the example line above, that would be SRC=45.134.26.57 and DPT=27741
sed matches the expression between the first two // marks on the line. Its looking for
any character followed by an exact match of "SRC=" +
(one or more digits and periods ) +
any character followed by an exact match of "DPT=" +
(one or more digits)
sed will replace that with the expression between the second and third // marks. In this case its \1 \2, which refer to the bracketed terms in the original match … our two number terms.

So its fed a long log line, and it spits out the two numbers we're interested in, logging them to blacklist.log. All that remains to do is to start swatchdog with the –daemon switch so it carries on logging after we log out, and we can come back in the morning to see what we've got.

There don't seem to be a lot of examples of swatchdog usage around. I'd be interested to see more if anyone feels like sharing.

Leave a Comment