Q: I have been trying to log some traffic from iptables and have had little success. I have found multiple tutorials online explaining how to get traffic from iptables into syslog, but none have worked out for me. I specifically want to log dropped packets to a separate file.
A: This is fairly straight forward, let’s give this a quick look using rsyslog, then we will touch on journald.
Logging IPTables to rsyslog
First, if you read my basics of iptables article you know there are three basic actions that can be taken on traffic that meet your defined rules (ACCEPT, DROP, REJECT). There is another built in action called LOG. This basically tells iptables to send this traffic to rsyslog, which is the default logging daemon in most modern Linux distros.
First, lets APPEND a rule to the INPUT chain. Just ensure it goes before any catch all DROP or REJECT statement since iptables reads rules in order from top down.
iptables -A INPUT -j LOG --log-level info --log-prefix "IPTABLES-DROP: "
Now that we have a rule in place to send traffic to rsyslog, we have to tell rsyslog where to send them. The log prefix (IPTABLES-DROP: ) makes it easy to tell rsyslog which lines we want sent to it’s own file.
In the default rsyslog configuration file (/etc/rsyslog.conf) there is a rules section that starts with the following line:
#### RULES ####
We will add our configuration right after that line. So let’s add:
:msg, startswith, "IPTABLES" -/var/log/iptables.log
& ~
The first line tells rsyslog to find any messages starting with “IPTABLES” and send them to /var/log/iptables. The second line “&~” tells rsyslog to discard those messages. If we do not add the second line, rsyslog will log those messages to both /var/log/iptables as we want, but it will also add them to /var/log/messages.
Logging IPTables to journald
I hope that helps with rsyslog, but for those using journald, it is even easier since there is no configuration file to edit. So if you are using journald and would like to log iptables messages, you can use the same rule in iptables:
iptables -A INPUT -j LOG --log-level info --log-prefix "IPTABLES-DROP: "
The messages will be logged to the journald as kernel messages, so all you have to do is query journald for kernel messages like so:
journalctl -k
Or you can follow (tail) the kernel messages like:
journalctl -k -f
Leave a Reply Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
4 Comments
Join Our Newsletter
Categories
- Bash Scripting (17)
- Basic Commands (51)
- Featured (7)
- Just for Fun (5)
- Linux Quick Tips (98)
- Linux Tutorials (65)
- Miscellaneous (15)
- Network Tools (6)
- Reviews (2)
- Security (32)
should be "startswith", not "startwith"
Updated, thank you!
Thanks for the article!
I noticed a small typo in the "journal" command
jounralctl -k -f
Best regards,
Thanks, good catch. I fixed the typo!