IPTABLES - Logging and dropping traffic in a single rule
Posted: 15 Jul 2010, 20:00pm - Thursday

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. Article From: http://www.techbytes.ca/techbyte136.html