How to log connections hitting certain rules in iptables on Linux?
Posted on In QAHow to log connections hitting certain rules in iptables on Linux? Like the one that are dropped because of too frequently creating SSH connections.
You can create a new chain named LOGNDROP that log the connections and drop them, then pass the connection to be redirected to the LOGNDROP chain.
$tables -N LOGNDROP
# Connections to LOGNDROP chain will be logged and dropped
$tables -A LOGNDROP -j LOG --log-level 6
$tables -A LOGNDROP -j DROP
As an example, the rules for How to use iptables to limit rates new SSH incoming connections from each IP on Linux can be changed to:
for tables in iptables ip6tables ; do
# start with a clean table
$tables -F
# allow localhost connections
$tables -A INPUT -p tcp -s localhost -j ACCEPT
# Allow established inbound connections
$tables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
# Create LOGNDROP chain
$tables -N LOGNDROP
# Connections to LOGNDROP chain will be logged and dropped
$tables -A LOGNDROP -j LOG --log-level 6
$tables -A LOGNDROP -j DROP
# Maximum 6 new connections every 60 seconds
$tables -A INPUT -p tcp --dport 22 -m recent --update --seconds 60 --hitcount 6 --name SSH --rsource -j LOGNDROP
# Record new connections
$tables -A INPUT -p tcp --dport 22 -m recent --set --name SSH --rsource -j ACCEPT
# Reject other connections; use only needed
$tables -A INPUT -j REJECT
$tables -A FORWARD -j REJECT
done