#!/bin/bash # Configuration API_KEY="keyredacted" SITE_ID="secretredacted" ENABLE_WAF_URL="https://waf.sucuri.net/api?v2" DISABLE_WAF_URL="https://waf.sucuri.net/api?v2" ENABLE_WAF_DATA="a=update_setting&http_flood_protection=js_filter" DISABLE_WAF_DATA="a=update_setting&http_flood_protection=disable" PROCESS_NAME="apache2" # Change to "nginx" if using Nginx CPU_THRESHOLD_HIGH=80 CPU_THRESHOLD_LOW=50 MEM_THRESHOLD_HIGH=80 MEM_THRESHOLD_LOW=50 STATE_FILE="/tmp/waf_state" # Initialize state file if it doesn't exist if [ ! -f "$STATE_FILE" ]; then echo "disabled" > "$STATE_FILE" fi # Function to get current CPU and memory usage get_usage() { ps aux | grep "$PROCESS_NAME" | grep -v grep | awk ' BEGIN { cpu = 0; mem = 0; } { cpu += $3; mem += $4; } END { print cpu, mem; }' } # Function to enable WAF enable_waf() { curl -s "$ENABLE_WAF_URL" --data "k=$API_KEY&s=$SITE_ID&$ENABLE_WAF_DATA" > /dev/null echo "enabled" > "$STATE_FILE" echo "WAF enabled due to high resource usage." } # Function to disable WAF disable_waf() { curl -s "$DISABLE_WAF_URL" --data "k=$API_KEY&s=$SITE_ID&$DISABLE_WAF_DATA" > /dev/null echo "disabled" > "$STATE_FILE" echo "WAF disabled due to normal resource usage." } # Main monitoring loop while true; do usage=$(get_usage) cpu_usage=$(echo "$usage" | awk '{print $1}') mem_usage=$(echo "$usage" | awk '{print $2}') state=$(cat "$STATE_FILE") if (( $(echo "$cpu_usage > $CPU_THRESHOLD_HIGH" | bc -l) )) || (( $(echo "$mem_usage > $MEM_THRESHOLD_HIGH" | bc -l) )); then if [ "$state" = "disabled" ]; then enable_waf fi elif (( $(echo "$cpu_usage < $CPU_THRESHOLD_LOW" | bc -l) )) && (( $(echo "$mem_usage < $MEM_THRESHOLD_LOW" | bc -l) )); then if [ "$state" = "enabled" ]; then disable_waf fi fi # Sleep for a minute before checking again sleep 60 done