Logging iptables to a File With rsyslog

Published by Torry Crass on

I have been fighting for some time with iptables logs going to the kern.log, debug.log and messages files. This is ridiculously spammy and makes it very difficult to find other problems that might show up in these logs. In my searches I found the following blog entry, used it as reference and modified to suit as shown below.

http://blog.shadypixel.com/log-iptables-messages-to-a-separate-file-with-rsyslog/

The first thing you need to do is modify your iptables script/entries for logging to look something like this, mileage may vary depending on what you want to do so please make sure to validate your options with this first:

-A INPUT -j LOGDROP
-A LOGDROP -p tcp -j LOG --log-prefix "iptables: "
-A LOGDROP -p udp -j LOG --log-prefix "iptables: "
-A LOGDROP -p icmp -j LOG --log-prefix "iptables: "

Note:  My entries are for dropping packets, you do not have to drop packets to log them. Just keep that in mind while creating your own entries.

The key piece is the prefix which will allow filtering on that log entry. Since we know this we can now add an iptables configuration file into the /etc/rsyslog.d directory.

vim /etc/rsyslog.d/iptables.conf

Add the following text (or modify to suit your setup):

:msg, startswith, "iptables: " -/var/log/iptables.log
& ~

Note: The first line determines what should be filtered into the specified log while the second line indicates that it should not log multiple messages of the same entry. This is something you should think about before implementing, without it your log could get spammy and large, but it could also mean you miss the importance of how many things are hitting that log.

Note: Another important thing to note is that you might need to replace the startswith directive with the contains directive because sometimes the messages have timestamping or other prefixes in front of the iptables messages. Some people may consider doing a regex statement to be more precise with this information.

Now it would also be good to add log rotation into the mix. That is accomplished by adding another config file into /etc/logrotate.d directory.

vim /etc/logrotate.d/iptables

Add the following text to this file, again modify to suit needs:

/var/log/iptables.log
	{
	        rotate 7
	        daily
	        missingok
	        notifempty
	        delaycompress
	        compress
	        postrotate
	                invoke-rc.d rsyslog reload > /dev/null
	        endscript
	}

Happy logging!


0 Comments

Leave a Reply