I monitored the google ip that accessed my server for a few years and identified these masks: 66.249.64.0/19 66.102.0.0/20 64.233.160.0/19 34.64.0.0/10 216.58.192.0/19 74.125.0.0/16
Then I created this script in php which I include in all my websites.
include_once('function_global/cidr_match_function.php');
if(cidr_match($_SERVER['REMOTE_ADDR'], '66.249.64.0/19') === false && cidr_match($_SERVER['REMOTE_ADDR'], '66.102.0.0/20') === false && cidr_match($_SERVER['REMOTE_ADDR'], '64.233.160.0/19') === false && cidr_match($_SERVER['REMOTE_ADDR'], '34.64.0.0/10') === false && cidr_match($_SERVER['REMOTE_ADDR'], '216.58.192.0/19') === false&& cidr_match($_SERVER['REMOTE_ADDR'], '74.125.0.0/16') === false){
$fake_google_ip_list = file_get_contents('function_global/ip_add_fwd.txt');
if(strpos($fake_google_ip_list, $_SERVER['REMOTE_ADDR']) === false){
file_put_contents('function_global/ip_add_fwd.txt', $_SERVER['REMOTE_ADDR'].PHP_EOL , FILE_APPEND | LOCK_EX);
}
}
}
The result is this file containing a list of IPs that pretend to be google and access my server with scam intentions.
Then I, more or less once a day, run this console command which adds all these ip to ufw:
while read line; do sudo ufw insert 1 deny from $line to any; done < /var/www/html/function_global/ip_add_fwd.txt
and upload a new blank file to the server.
I would like to automate this last part and maybe use fail2ban instead of filling more and more of ip, which may never come back, in ufw.
And I think I need a .sh script, or something similar, but I have no idea how to write it... (I am a php programmer and I only use ubuntu as a web server limited to what is necessary for the functioning of my sites).
The script should be:
- callable with a crontab
- add the ip list to ufw, or rather to fail2ban
- empty the ip_add_fwd.txt file
- maybe send me an email with the IPs list, just to know what it has done and be able to verify if it works correctly (the crontab outputs also arrive via email, so maybe an output would be enough?)
Can anyone help me write it or at least give me some hints to get started? I have no idea where to start, I tried to put pieces of some other files together, but it didn't go very well ... :(
You can try this approach.
For Apache, to Configure a webserver "jail" in fail2ban configuration, there is a guide: fail2ban with Apache
Here you can configure temporary bans for IPs and also there is a client fail2ban-client that you could call directly from your php script (need to check permissions) to ban IPs manually.
I think this will work better than the cron approach, but if you still want to go via shell:
script with fail2ban