When a Linux web server experiences a sudden spike in CPU load—whether due to a legitimate traffic surge or a Distributed Denial of Service (DDoS) attack—response times can degrade or the site can go offline entirely.
Cloudflare’s “Under Attack Mode” adds an interstitial JavaScript challenge for visitors, blocking much of the malicious or automated traffic. But enabling it manually often isn’t fast enough to prevent damage.
This article covers a Python-based automation script that:
-
Continuously monitors a server’s 5-minute load average
-
Automatically enables Under Attack Mode when the load passes a configurable threshold
-
Keeps the mode active for a cooldown period to avoid rapid toggling
-
Respects manual overrides made in the Cloudflare dashboard
-
Sends optional Slack, email, or custom command alerts when the mode changes
This script builds on earlier shell-based versions, but is now fully Python for better maintainability, cleaner API handling, and richer alert formatting.
Why Python?
The original version of this script was written in Bash shell script. A switch to Python was made for the following reasons:
-
Reliable JSON parsing and API calls (no fragile
awk
/cut
parsing) -
Better alert formatting (Slack Block Kit support)
-
Cleaner configuration parsing
-
Easier extensibility for future features
How It Works
-
Configuration file (
/etc/cf-under-attack.conf
) defines Cloudflare credentials, thresholds, cooldowns, and alert preferences. -
Script runs either continuously via a systemd service or periodically via a systemd-timer.
-
Current Cloudflare mode is checked using their API.
-
Load is read from
/proc/loadavg
(5-minute average). -
Decision logic:
-
If load > threshold → enable Under Attack Mode and start cooldown.
-
If already in Under Attack Mode and cooldown not expired → stay in it.
-
If cooldown expired → revert to a low-load mode (e.g., “medium”).
-
-
Alerts (Slack/email/custom command) are sent on:
-
Entering “Under Attack Mode”
-
Exiting “Under Attack Mode”
-
Manual mode changes detected
-
-
State files in
/tmp
track the last mode and cooldown timing.
Configuration File
All settings live in /etc/cf-under-attack.conf
for security and ease of updates.
Example:
# Threshold at which to trigger "Under Attack Mode"
LOAD_THRESHOLD=7.00
# Cloudflare API token and Zone ID
CF_API_TOKEN="PUT_CF_API_TOKEN_HERE"
ZONE_ID="PUT_CF_ZONE_ID_HERE"
# Mode to set when load is low and cooldown expired
LOW_LOAD_MODE="medium"
# Cooldown duration (hours)
COOLDOWN_HOURS=3
# Cache and timestamp files
CACHE_FILE="/tmp/cf_mode_cache"
TIMESTAMP_FILE="/tmp/cf_under_attack_timestamp"
# --- Alerts (optional) ---
ALERT_MODE="slack" # none|slack|email|command
ALERT_SLACK_WEBHOOK="https://hooks.slack.com/services/XXX/YYY/ZZZ"
ALERT_SLACK_USE_BLOCKS=true
ALERT_EMAIL_TO="This email address is being protected from spambots. You need JavaScript enabled to view it. "
ALERT_EMAIL_FROM="This email address is being protected from spambots. You need JavaScript enabled to view it. "
ALERT_EMAIL_SUBJECT_PREFIX="[CF Guard]"
ALERT_COMMAND=""
ALERT_COOLDOWN_MIN=30
ALERT_TS_FILE="/tmp/cf_under_attack_alert_ts"
Secure the file:
sudo chmod 600 /etc/cf-under-attack.conf
sudo chown root:root /etc/cf-under-attack.conf
The Python Script
Download the Python script from Github: cf_under_attack.py
Or you can clone the entire repo with the following command (this will download the script and all of the example configuration files):git clone https://github.com/coyote-linux/cloudflare-monitor.git
Save as /opt/cloudflare-monitor/cf_under_attack.py
and make executable:
chmod +x /opt/cloudflare-monitor/cf_under_attack.py
This script:
-
Reads
/etc/cf-under-attack.conf
-
Talks to Cloudflare’s API via HTTPS
-
Uses Slack Block Kit formatting when enabled
-
Stores operational state in
/tmp
-
Exits quietly if no changes are needed
The full script is included in your deployment, and follows the logic described above.
Alerts
Three alert modes are supported:
-
Slack: Plain text or Block Kit cards showing host, time, mode, and load.
-
Email: Uses
sendmail
ormail
if available. -
Command: Executes any shell command, with
#MSG#
replaced by the message.
Alerts are rate-limited via ALERT_COOLDOWN_MIN
to avoid spam during unstable load conditions.
Example Slack Block message:
Cloudflare Guard Alert
----------------------
Host: web01.example.com
Time (UTC): 2025-08-14 14:03:19
Target Mode: under_attack
Load / Threshold: 12.8 / 7.0
Deployment Options
Option 1 – Persistent Systemd Service
Runs continuously and checks load on a fixed interval.
/etc/systemd/system/cf-under-attack.service
:
[Unit]
Description=Cloudflare Auto Under Attack Mode Monitor (Python)
After=network-online.target
Wants=network-online.target
[Service]
ExecStart=/usr/bin/env python3 /opt/cloudflare-monitor/cf_under_attack.py
Restart=always
RestartSec=60
User=root
NoNewPrivileges=true
ProtectSystem=full
ProtectHome=true
PrivateTmp=true
CapabilityBoundingSet=
SystemCallFilter=@system-service
[Install]
WantedBy=multi-user.target
Enable and start:
sudo systemctl daemon-reload
sudo systemctl enable --now cf-under-attack.service
Option 2 – systemd-timer (Oneshot Runs)
Runs the script once per minute, exits, and systemd starts it again.
Service: /etc/systemd/system/cf-under-attack.timer.service
[Unit]
Description=Cloudflare Under Attack Monitor (oneshot via timer, Python)
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/bin/env python3 /opt/cloudflare-monitor/cf_under_attack.py
NoNewPrivileges=true
ProtectSystem=full
ProtectHome=true
PrivateTmp=true
CapabilityBoundingSet=
SystemCallFilter=@system-service
Timer: /etc/systemd/system/cf-under-attack.timer
[Unit]
Description=Run Cloudflare Under Attack Monitor every minute
[Timer]
OnBootSec=1min
OnUnitActiveSec=60s
RandomizedDelaySec=5s
[Install]
WantedBy=timers.target
Enable timer:
sudo systemctl daemon-reload
sudo systemctl enable --now cf-under-attack.timer
Benefits Observed
-
Automatic mitigation in seconds during real-world DDoS tests
-
Zero downtime in incidents that previously caused outages
-
Immediate notifications via Slack and email
-
Configurable, secure, and portable deployment
Conclusion
This Python-based Cloudflare “Under Attack Mode” monitor offers a fast, reliable, and configurable defense against unexpected traffic surges. By combining load monitoring, API-driven security changes, and optional rich alerts, it helps keep services online under heavy load—without waiting for human intervention.
With the choice of persistent service or periodic timer, you can fit it into any operational model while keeping control through a single configuration file.