A website I manage has recently been targeted with a DDoS (Distributed Denial Of Service Attack).
The PHP code on the site was already logging access (as is normal) but I wanted a simple way to respond to excessive access from any particular IP other than using a coded denial of response in the website’s code because while this does reduce the traffic sent out to the abusive IP address, it does still use considerable server resources for each request.
Ideally when an IP is identified as being abusive, it should be blocked at the firewall level.
The firewall on the server in question is ConfigServer’s CSF. This allows command line tools for adding IP addresses to the deny list. But these tools must be run as ‘root’.
To make use of them I had the site’s code write any abusive IP addresses to a file ‘abuse.dat’, one IP address per line.
I then set up a cron task for the root user on the server, to run the following code every minute, to scan for the existence of that file, and if found, execute the CSF command line command to add all IP addresses to the deny list.
Here’s the cron task code:
#!/bin/bash
if [ -f /home/website/abuse.dat ];
then while IFS= read -r line; do csf -d $line; done < /home/website/abuse.dat
rm -f /home/website/abuse.dat
echo "ADDED IP(s) TO CSF DENY"
fi
And here’s the cron task specification:
* * * * * root sh /etc/my_csf_cron_job.sh