Skip to content

Instantly share code, notes, and snippets.

@utarn
Created January 29, 2025 06:37
Show Gist options
  • Save utarn/3dca14df5da87c974f8e700a7369d920 to your computer and use it in GitHub Desktop.
Save utarn/3dca14df5da87c974f8e700a7369d920 to your computer and use it in GitHub Desktop.
Add fail2ban to detect error 404
#!/bin/bash
# Script to add nginx-404 fail2ban configuration
FILTER_FILE="/etc/fail2ban/filter.d/nginx-404.conf"
JAIL_FILE="/etc/fail2ban/jail.d/nginx-404.local"
JAIL_LOCAL="/etc/fail2ban/jail.local"
JAIL_NAME="nginx-404"
# 1. Add filter file: nginx-404.conf
echo "Creating filter file: $FILTER_FILE"
sudo cat > "$FILTER_FILE" <<EOF
[Definition]
failregex = ^<HOST> - - .* ".*" 404 .*
ignoreregex = .*installHook\.js\.map.*
EOF
echo "Filter file created."
# 2. Add jail file: nginx-404.local
echo "Creating jail file: $JAIL_FILE"
sudo cat > "$JAIL_FILE" <<EOF
[nginx-404]
enabled = false
port = http,https
filter = nginx-404
logpath = /var/log/nginx/*_access.log
maxretry = 3
findtime = 60000
bantime = 36000
EOF
echo "Jail file created."
# 3. Add to jail.local if not exist: enable nginx-404 jail
echo "Checking if jail '$JAIL_NAME' is enabled in $JAIL_LOCAL"
if ! sudo grep -q "^\[$JAIL_NAME\]" "$JAIL_LOCAL"; then
echo "Jail '$JAIL_NAME' not found in $JAIL_LOCAL. Adding and enabling it."
sudo sed -i '$a\'"$JAIL_NAME"']\n enabled = true' "$JAIL_LOCAL"
echo "Jail '$JAIL_NAME' enabled in $JAIL_LOCAL."
else
echo "Jail '$JAIL_NAME' already defined in $JAIL_LOCAL. Enabling it."
sudo sed -i "s/^\(\[$JAIL_NAME\]\)\nenabled = false/\1\nenabled = true/" "$JAIL_LOCAL"
echo "Jail '$JAIL_NAME' enabled in $JAIL_LOCAL."
fi
# Restart fail2ban to apply changes
echo "Restarting fail2ban service to apply changes..."
sudo systemctl restart fail2ban
if [ $? -eq 0 ]; then
echo "Fail2ban service restarted successfully."
else
echo "Failed to restart fail2ban service. Please check manually."
echo "You may need to run: sudo systemctl restart fail2ban"
fi
echo "nginx-404 fail2ban configuration added and enabled (if not already)."
echo "Remember to adjust settings in $JAIL_FILE and $JAIL_LOCAL if needed."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment