IPTables – Logging/syslog


if you want to log all traffic, simply place these rules at the first on in each chain. all log messages will be stored in syslog

iptables -A INPUT -j LOG –log-prefix='[IPTABLES] ‘

iptables -A OUTPUT -j LOG –log-prefix='[IPTABLES] ‘

iptables -A FORWARD -j LOG –log-prefix='[IPTABLES] ‘

if you want to log a specific traffic you can do something like this

iptables -A INPUT -p tcp –dport ssh -j LOG –log-prefix='[IPTABLES] ‘

the log rule needs to be before the ACCEPT/DROP, if the log rule is after a accept/drop rule that matches the traffic, it will not be logged

for example, this will first log the traffic and then allow it

iptables -A INPUT -p TCP –dport ssh -j LOG –log-prefix='[IPTABLES] ‘

iptables -A INPUT -p tcp –dport 22 -j LOG_ACCEPT

this works fine with small IPTables, but its a bit messy with many rules, where it would be better to create a Chain that allow/blocks and log the specific rules

Create chains

iptables -N LOG_ACCEPT
iptables -N LOG_DROP

Apply rules to the chains

iptables -A LOG_ACCEPT -j LOG --log-prefix '[IPTABLES:ACCEPT] ' 
iptables -A LOG_ACCEPT -j ACCEPT

iptables -A LOG_DROP -j LOG --log-prefix '[IPTABLES:ACCEPT] ' 
iptables -A LOG_DROP -j DROP

then simply create rules as you normally would, and use -j LOG_ACCEPT and -j LOG_DROP instead of -j ACCEPT and -j DROP


iptables -A INPUT -p tcp –dport 22 -j LOG_ACCEPT


It is possible to filter out some messages with a specific prefix and forward them to a diffrent file, this can be good in this case, we could forward all iptables in a file called iptables.log

create a conf file under /etc/rsyslog.d/iptables.conf and insert this:

:msg,contains,”[IPTABLES” /var/log/iptables.log
& ~

this will copy all the lines containing [IPTABLES to /var/log/iptables.log

note: this log file can get pretty big, so best pratice would be to setup some log rotation on the file


create a logrotate conf file for iptables /etc/logrotate.d/iptables

/var/log/iptables.log {
su root root
rotate 7
/etc/init.d/rsyslog restart

this will rotate daily and keep 7 log files

Leave a Reply

Your email address will not be published.