block ips based on strings found in /var/log/nginx/access.log as easy as sfw
Find a file
2025-03-31 15:33:21 +02:00
blocklist.sh added functioning alias with variables in README.md 2025-02-17 23:18:35 +01:00
README.md updated README.md with some color 2025-03-31 15:33:21 +02:00
string2nginxips.sh first commit 2025-02-17 19:46:31 +01:00
uniqueips.sh first commit 2025-02-17 19:46:31 +01:00

Take care when using the stringfirewall.

If you block ips based on a too general or short string, you might lock yourself out. For that case its always good to have a tor service running, as it will punch a hole from the inside. So having a hidden service is recommended for usage of the string firewall.

Based on wazuh, one can see a lot of attacks. I consider the crawling of bots of big tech as an attack too.

So when you have identified certain accesses based on security intelligence, you can block further ips containing a certain string with these scripts.

For blocking, a lot of different approaches can be used. I opted in for using iplist and iptables.

apt install ipset

ipset create blocklist hash:ip hashsize 4096

iptables -I INPUT -m set --match-set blocklist src -j DROP
iptables -I FORWARD -m set --match-set blocklist src -j DROP

now you can add

ipset add blocklist 192.168.1.100

To make the iptables rules persistent:

apt install iptables-persistent

and create a small systemd service file: /etc/systemd/system/save-ipset-rules.service:

[Unit]  
Description=ipset persistent rule service  
Before=netfilter-persistent.service  
ConditionFileNotEmpty=/etc/iptables/ipset

[Service]  
Type=oneshot  
RemainAfterExit=yes  
ExecStart=/sbin/ipset -exist -file /etc/iptables/ipset restore  
ExecStop=/sbin/ipset -file /etc/iptables/ipset save

[Install]  
WantedBy=multi-user.target

You may need to create the /etc/iptables/ipset file

/sbin/ipset -file /etc/iptables/ipset save

Enable the service with

systemctl enable save-ipset-rules.service

Add the following to your .bashrc file in your homedir to make an alias out of it:

sfw()
{
	echo $1 | sudo bash ~/projekt-a/string-firewall/string2nginxips.sh | sudo bash ~/projekt-a/string-firewall/uniqueips.sh | sudo bash ~/projekt-a/string-firewall/blocklist.sh
}

issue

. .bashrc

in your home directory or open a new terminal to do

sfw amazon

to block all ips that accessed your server containing the string amazon

To List all ips that you have blocked until now, issue

cat /etc/iptables/ipset

as you can also understand from reading blocklist.sh