Bash script to block brute force attacks with .htaccess

in #programming5 years ago

Your site is under attack. May be not right now, but several times a day. Password guessing, security vulnerabilities - that kind of stuff. In the error log it looks like this:

[Thu Jul 13 05:28:49 2017] [error] [client] ModSecurity: Access denied with code 401 (phase 2). Operator GT matched 0 at USER:bf_block. [file "/etc/apache2/mod_security/custom/wpbrute.conf"] [line "20"] [id "9999001"] [msg "ip address blocked for 5 minutes, more than 15 login attempts in 3 minutes."] [hostname ""] [uri "/wp-login.php"] [unique_id "WWdngc26uBEAAGIsOAEAAABG"]

The server, Apache in my case, handles these attacks routinely, but morons come back over and over again. Apart from performance implications there's a small chance of successful attack, so I made a simple script to block hackers via .htaccess.

This script runs by a cron job and has three parameters: ../logs/error_log ../domains/.htaccess 200

It searches error_log for ip-addresses that appear there more than 200 times and adds those to .htaccess with "deny from" prefix. Here's the script source code, don't forget to add "Execute" attribute when you create it on your server:

if [ $# -ne 3 ]; then
echo "Incorrect number of arguments. Should be 3: apache error log path, .htaccess file path, number of entries."


#If .htaccess file does not exist, create it and add 2 first lines
if [ ! -f "$filename" ]; then
echo order allow,deny >> "$filename"
echo allow from all >> "$filename"

#Check if .htaccess file has new line at the end. If not - add it.
c=tail -c 1 "$filename"
if [ "$c" != "" ]; then
echo >> "$filename"

arr=($(grep -o 'client [0-9.]*' "$error_log"| sort -r | uniq -c | sort -nr | awk -v pNum=$num_entries '$1>pNum {print $3}'))
for i in "${arr[@]}"
if ! grep -q -P "$i$" "$filename"; then
if [ ! -z "$msg" ]; then
msg+="deny from ${i}"

if [ ! -z "$msg" ]; then
echo -e "$msg" >> "$filename"
echo "$msg"
echo "no matching records found"


Congratulations @shuler! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

Award for the number of upvotes

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

Thanks for first upvote :>

Thanks for the info. I recommend block brute force attacks with ConfigServer Security & Firewall (csf).

I'm on shared hosting, it would not work for me.

Coin Marketplace

STEEM 0.23
TRX 0.07
JST 0.030
BTC 21415.88
ETH 1229.10
USDT 1.00
SBD 3.30