Help writing server script to ban IP's from a list

Posted by Chev_603 on Ask Ubuntu See other posts from Ask Ubuntu or by Chev_603
Published on 2014-06-02T18:39:03Z Indexed on 2014/06/02 21:45 UTC
Read the original article Hit count: 221

Filed under:
|
|
|

I have a VPS that I use as an openvpn and web server. For some reason, my apache log files are filled with thousands of these hack attempts:

"POST /xmlrpc.php HTTP/1.0" 404 395

These attack attempts fill up 90% of my logs. I think it's a WordPress vulnerability they're looking for. Obviously they are not successful (I don't even have Wordpress on my server), but it's annoying and probably resource consuming as well. I am trying to write a bash script that will do the following:

  1. Search the apache logs and grab the offending IP's (even if they try it once),
  2. Sort them into a list with each unique IP on a seperate line,
  3. And then block them using the IP table rules.

I am a bash newb, and so far my script does everything except Step 3. I can manually block the IP's, but that's tedious and besides, this is Linux and it's perfectly capable of doing it for me. I also want the script to be customizable so that I (or anyone else who wants to use it) can change the variables to suit whatever situation I/they may deal with in the future. Here is the script so far:

#!/bin/bash
##IP LIST GENERATOR
##Author Chev Young
##Script to search Apache logs and list IP's based on custom filters
##
##Define our variables:
DIRECT=~/Script ##Location of script&where to put results/temp files
LOGFILE=/var/log/apache2/access.log ## Logfile to search for offenders
TEMPLIST=xml_temp ## Temporary file name
IP_LIST=ipstoban ## Name of results file
FILTER1=xmlrpc ## What are we looking for? (Requests we want to ban)
cd $DIRECT
if [ ! -f $TEMPLIST ];then touch $TEMPLIST ##Create temp file
fi
cat $LOGFILE | grep $FILTER1 >> $DIRECT/$TEMPLIST ## Only interested in the IP's, so:
sed -e 's/\([0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+\).*$/\1/' -e t -e d $DIRECT/$TEMPLIST | sort | uniq > $DIRECT/$IP_LIST
rm $TEMPLIST ## Clean temp file
echo "Done. Results located at $DIRECT/$IP_LIST"

So I need help with the next part of the script, which should ban the IP's (incoming and perhaps outgoing too) from the resulting $IP_LIST file. I don't care if it utilizes UFW or IPTables directly, as long as it bans the IP's. I'd probably run it as a cron task. What I'm having trouble with is understanding how to use line of the result file as a seperate variable to do something like:

ufw deny $IP1 $IP2 $IP3, ect

Any ideas? Thanks.

© Ask Ubuntu or respective owner

Related posts about bash

Related posts about apache2