IPTABLES - Logging and dropping traffic in a single rule

Many people who are familiar with IPCHAINS (the predecessor to IPTABLES) are familiar with the ability to simply tack on a '-l' to also log rules which match that rule. In IPTABLES this is not done the same way and no such option exists.

To accomplish the same task in IPTABLES you could simply put a identical rule with a LOG action before every drop rule, but that will fill your script with copies of the same rule and force updates in multiple locations. This is therefore not an ideal solution.

The cleanest method of accomplishing this is to create a new chain which does both the LOG and DROP for you. The following IPTABLES rules will create a LOGDROP chain.

# Create the LOGDROP chain
    iptables -N LOGDROP > /dev/null 2> /dev/null
    iptables -F LOGDROP
    iptables -A LOGDROP -j LOG --log-prefix "LOGDROP "
    iptables -A LOGDROP -j DROP

The first rule in this set creates the new chain. The output is sent to /dev/null because if you attempt to run this twice on the same system, you will get an error saying the chain already exists. It's up to you if you want to see that message or not.

The second rule flushes the contents of the chain, again, so that if you run it twice on the same system you don't have duplicate rules in the chain.

The third rule LOGS the traffic with the added "LOGDROP" prefix and the fourth rule DROPs the traffic

What this now means is that you can easily log and drop traffic or even log and accept traffic (with minor modifications to the above), by creating a rule such as this:

# Log and drop all connections to the HTTP port
    iptables -A INPUT -p tcp --dport 80 -j LOGDROP

As you can see, you now simply use the LOGDROP target in order to log and drop any traffic you want. You must ensure that you define the LOGDROP target BEFORE you attempt to use it in a rule.

If anyone has any comments or corrections for this, please let me know using the comment system below.


Author: DPAK
Created: Apr 28 2006 (last modified May 1 2006)
Categories: IPTABLES
TechByte #136

Warning: By visiting this site and/or by using any information contained herein, you agree to the Techbytes.ca terms of use.



Add a comment about this TechByte

If you wish to add a comment regarding this TechByte, please use the form below. Please note that by submitting comments using this form you are allowing all of the information submitted to be visible on this website. Any comments submitted using this form will only be shown on the website if they are approved by the administrators of this site. IF APPROVED, COMMENTS MAY TAKE SEVERAL DAYS TO BE POSTED.

Posted By: (Optional)

Comments:


Other TechBytes: