webserver-config/install/20-nginx-cloudflare-fail2ban.sh

43 lines
1.2 KiB
Bash
Raw Normal View History

#!/bin/bash
# Check if script is run as root
if [ "$EUID" -ne 0 ]; then
echo "Please run as root or with sudo"
exit 1
fi
2024-10-23 23:58:30 +00:00
# Create maps directory if it doesn't exist
echo "Creating maps directory..."
mkdir -p /etc/nginx/maps
2024-10-23 23:27:59 +00:00
# Create banned IPs file
echo "Creating banned IPs file..."
2024-10-23 23:58:30 +00:00
touch /etc/nginx/maps/banned_ips.conf
chown www-data:www-data /etc/nginx/maps/banned_ips.conf
2024-10-23 23:27:59 +00:00
# Create NGINX configuration for fail2ban check
echo "Creating NGINX configuration..."
tee /etc/nginx/conf.d/10-fail2ban-check.conf << 'CONFFILE'
map $http_cf_connecting_ip $is_banned {
default 0;
2024-10-23 23:58:30 +00:00
volatile;
include /etc/nginx/maps/banned_ips.conf;
}
2024-10-23 23:27:59 +00:00
CONFFILE
# Create fail2ban action
2024-10-23 23:58:30 +00:00
cat > /etc/fail2ban/action.d/nginx-banned-ips.conf << 'ACTIONFILE'
2024-10-23 23:27:59 +00:00
[Definition]
actionstart =
actionstop =
actioncheck =
2024-10-23 23:58:30 +00:00
actionban = grep -q '^<ip> 1;$' /etc/nginx/maps/banned_ips.conf || echo '<ip> 1;' >> /etc/nginx/maps/banned_ips.conf && nginx -s reload
actionunban = sed -i '/^<ip> 1;$/d' /etc/nginx/maps/banned_ips.conf && nginx -s reload
2024-10-23 23:27:59 +00:00
ACTIONFILE
2024-10-25 00:53:58 +00:00
# Reload nginx
service nginx reload
echo "Installation complete!"
2024-10-23 23:27:59 +00:00
echo "Now add 'nginx-banned-ips' to the action line in your existing fail2ban jail configurations"