Table of Contents

Ubuntu - iptables - Log firewall messages to a separate file

Issue the following command:

sudo vi /etc/rsyslog.d/50-default.conf

and comment out the following lines near the bottom of the file by placing a hash # mark in front:

/etc/rsyslog.d/50-default.conf
daemon.*;mail.*;\
news.err;\
*.=debug;*.=info;\
*.=notice;*.=warn |/dev/xconsole

to

/etc/rsyslog.d/50-default.conf
#daemon.*;mail.*;\
# news.err;\
# *.=debug;*.=info;\
# *.=notice;*.=warn |/dev/xconsole

There is a bug in the default installation, in that on a server no /dev/xconsole exists.

Therefore this entire section if commented out.

Issue the following command:

sudo vi /etc/rsyslog.d/20-iptables.conf

and add the following lines to the file:

/etc/rsyslog.d/20-iptables.conf
# Log kernel generated iptable log messages to file
:msg,contains,"iptables: " /var/log/iptables.log
# Uncomment the following to stop logging anything that matches the last rule.
# Doing this will stop logging kernel generated iptables log messages to the file
# normally containing kern.* messages (eg, /var/log/kern.log)
& ~

This logs all firewall related messages to /var/log/iptables.log.


Prevent the logfile getting to big

Issue the following command:

sudo vi /etc/logrotate.d/iptables

and add the following lines to the file:

/etc/logrotate.d/iptables
/var/log/iptables.log
{
    rotate 3
    daily
    missingok
    notifempty
    delaycompress
    compress
    postrotate
        /usr/sbin/service rsyslog restart > /dev/null
    endscript
}

A logrotate job is created to run daily to keep the log file from getting too large.

To view the firewall log file, issue the command:

sudo cat /var/log/iptables.log | grep DPT=22 | cut -d" " -f1-4,9,13,14,21,22,23,26

Restart rsyslog

Issue the following command:

sudo service rsyslog restart