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 --
 dovecot:
    Authentication Failures:       
       contact@domain.tld rhost=104.233.76.148 : 1 Time(s)
       test@domain.tld rhost=41.196.245.58 : 1 Time(s)
       test1@domain.tld rhost=123.19.246.251 : 1 Time(s)
       test2@domain.tld rhost=59.96.249.178 : 1 Time(s)
       testuser@domain.tld rhost=185.3.34.80 : 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.32.116.47 : 1 Time(s)
       105.158.231.65 : 1 Time(s)
       171.96.183.244 : 1 Time(s)
       171.97.24.141 : 1 Time(s)
       176.65.2.182 : 1 Time(s) 
   Incorrect Password:
    1.10.199.43 : admin - 1 Time(s)
    1.10.217.16 : admin - 1 Time(s)
    1.23.25.54 : admin - 1 Time(s)
    101.0.63.44 : admin - 1 Time(s)
    103.54.99.13 : admin - 1 Time(s)
    105.157.224.255 : admin - 1 Time(s)
    122.52.229.130 : admin - 1 Time(s)
    14.167.17.63 : 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
1.10.199.43
1.10.217.16
1.23.25.54
1.32.116.47
...

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

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

# Contents of firewall.sh
iptables -A INPUT -s 1.10.199.43 -j DROP
iptables -A INPUT -s 1.10.217.16 -j DROP
iptables -A INPUT -s 1.23.25.54 -j DROP
iptables -A INPUT -s 1.32.116.47 -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.