How to add failed logins from Logwatch as firewall rules using Iptables

Just for the record: collecting failed logins from Logwatch and feeding them to the firewall is by no means a viable strategy against brute force attacks or other intrusion attempts. There are better means to mitigate these kind of security concerns in real time.

Anyhow, sometimes you face the more cautious crackers that only make a single intrusion attempt per IP address (daily rotation) and thus are able to “fool” the system for an extended period of time. In that regard, using the Logwatch report might be a quick and dirty alternative to analyzing server logs. By using this approach, it’s important to make sure not to harvest customer IP addresses by including valid logins or known safe IP ranges.

Lets look at a snippet from a Logwatch file which we’ll be using to extract the hostile IPs from.

-- pam_unix Begin --
    Authentication Failures:       
       contact@domain.tld rhost= : 1 Time(s)
       test@domain.tld rhost= : 1 Time(s)
       test1@domain.tld rhost= : 1 Time(s)
       test2@domain.tld rhost= : 1 Time(s)
       testuser@domain.tld rhost= : 1 Time(s)
    Unknown Entries:
       check pass; user unknown: 4249 Time(s) 
-- pam_unix End -- 

-- proftpd-messages Begin --
 Failed FTP Logins: 
   Invalid Username:   
     demo: : 1 Time(s) : 1 Time(s) : 1 Time(s) : 1 Time(s) : 1 Time(s) 
   Incorrect Password: : admin - 1 Time(s) : admin - 1 Time(s) : admin - 1 Time(s) : admin - 1 Time(s) : admin - 1 Time(s) : admin - 1 Time(s) : admin - 1 Time(s) : admin - 1 Time(s) 
-- proftpd-messages End --

I’ll copy this information into a local file called logwatch.txt
The following grep expression will extract the IPs from logwatch.txt and create a new file (crackers.txt) containing a list of sorted and unique IPs:

grep -Eo '([0-9]{1,3}\.){3}[0-9]{1,3}' logwatch.txt | sort | uniq > crackers.txt

# Contents of crackers.txt

Next I’ll modify the crackers.txt by using sed to construct the firewall rules to be saved as

sed 's/.*/iptables -A INPUT -s & -j DROP/' crackers.txt >

# Contents of
iptables -A INPUT -s -j DROP
iptables -A INPUT -s -j DROP
iptables -A INPUT -s -j DROP
iptables -A INPUT -s -j DROP

Feed em to the firewall and wait for the first batch of angry customers to call and inform you that your email services are down (I already said this was a bad idea..).

Roger Comply avatar
Roger Comply
Thank you for reading!
Feel free to waste more time by subscribing to my RSS feed.