Logging activity using IPTables

Using iptables, you can write network activity to the log file, that is, which data is sent to and from where it comes from.

Example command (http traffic):

iptables -t filter -A FORWARD -s 192.168.1.0/24 -m tcp -p tcp --dport 80 -j LOG --log-prefix "iptables: "

I will give an example for DNS traffic:

iptables -t filter -A INPUT -m tcp -p tcp --dport 53 -j LOG --log-prefix "iptables: "
iptables -t filter -A INPUT -m udp -p udp --dport 53 -j LOG --log-prefix "iptables: "
iptables -t filter -A INPUT -s 192.168.5.0/24 -m udp -p udp --dport 53 -j LOG --log-prefix "iptables: "
iptables -t filter -A INPUT -s 192.168.5.0/24 -m tcp -p tcp --dport 53 -j LOG --log-prefix "iptables: "
iptables -t filter -A FORWARD -d 10.0.0.1 -m udp -p udp --dport 53 -j LOG --log-prefix "iptables: "

If the traffic is very large and so that the logs do not quickly take up the entire disk space, then you can limit the number of entries, for example, write SMTP traffic logs no more than 10 entries per minute:

iptables -t filter -A FORWARD -s 172.16.0.0/12 -m tcp -p tcp --dport 25 -m limit --limit 10/minute -j LOG --log-prefix "iptables: "

To remove the rule, replace -A with -D.

That the information was written not in rsyslog a file, and separately, we will create a file:

sudo nano /etc/rsyslog.d/10-iptables.conf

And add the following to it:

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

To apply the changes, restart rsyslog:

sudo /etc/init.d/rsyslog reload

Done, the network activity specified in the first rule will be written to the file /var/log/iptables.log.

It is also desirable to configure logrotate to remove old logs, to save disk space.

See also my articles:
Configuring logrotate for log rotation
Configuring IPTables

Leave a comment

Leave a Reply

Discover more from IT Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading