id: cloudflare-waf-custom-rule-block-rate-sentinel
namespace: company.security
description: |
Continuous security sentinel for Cloudflare WAF custom firewall rules.
Queries Cloudflare GraphQL Analytics API for adaptive firewall events and time-series
metrics, inspects mitigated actions (block, challenge, managed_challenge, js_challenge),
detects acute rate spikes (> 500% over rolling 1-hour baseline), isolates top client ASNs,
targeted URI paths, and rule IDs, records telemetry in Kestra KV, and alerts Slack.
inputs:
- id: zone_id
type: STRING
displayName: "Cloudflare Zone ID"
defaults: "023e105f4ecef8ad9ca31a8372d0c353"
description: "Hexadecimal 32-character identifier of the Cloudflare zone under
WAF surveillance."
- id: spike_threshold_pct
type: FLOAT
displayName: "Block Rate Spike Threshold (%)"
defaults: 500.0
description: "Percentage surge in mitigated WAF events relative to the rolling
1-hour baseline required to trigger an alert."
- id: lookback_minutes
type: INT
displayName: "Analytics Lookback Window (Minutes)"
defaults: 75
description: "Time window in minutes queried from Cloudflare GraphQL Analytics
API, capturing the current evaluation period and rolling 1-hour baseline."
- id: min_block_count_for_spike
type: INT
displayName: "Minimum Block Count Threshold"
defaults: 50
description: "Minimum absolute number of mitigated requests required in current
interval before flagging a rate spike to eliminate low-volume false
alarms."
- id: alert_on_spike
type: BOOL
displayName: "Alert On Spike"
defaults: true
description: "Determines whether high-priority Slack notifications are
dispatched when block rate anomalies or severe spikes are detected."
triggers:
- id: periodic_waf_audit
type: io.kestra.plugin.core.trigger.Schedule
cron: "*/5 * * * *"
disabled: true
description: "Periodic schedule evaluating Cloudflare WAF block rate trends
every 5 minutes. Shipped disabled for initial configuration and manual
validation."
- id: on_waf_security_webhook
type: io.kestra.plugin.core.trigger.Webhook
key: "{{ secret('CLOUDFLARE_WAF_WEBHOOK_KEY') }}"
description: "Inbound webhook trigger for Cloudflare Notification Service or
external SIEM systems to initiate an immediate WAF forensic inspection."
tasks:
- id: get_previous_waf_telemetry
type: io.kestra.plugin.core.kv.Get
description: "Retrieves previous WAF telemetry and block rate baseline from
Kestra KV store for the specified zone."
key: "cloudflare_waf_telemetry_{{ inputs.zone_id }}"
errorOnMissing: false
- id: query_cloudflare_waf_analytics
type: io.kestra.plugin.core.http.Request
description: "Queries Cloudflare GraphQL Analytics API for
firewallEventsAdaptiveByTimeGroups and adaptive firewall events."
uri: "https://api.cloudflare.com/client/v4/graphql"
method: POST
contentType: application/json
headers:
Authorization: "Bearer {{ secret('CLOUDFLARE_API_TOKEN') }}"
options:
allowFailed: true
timeout:
connectTimeout: PT10S
readIdleTimeout: PT30S
allowFailure: true
body: |
{
"query": "query GetWafAnalytics($zoneTag: String!, $start: String!, $end: String!, $actions: [String!]) { viewer { zones(filter: { zoneTag: $zoneTag }) { firewallEventsAdaptiveByTimeGroups(limit: 100, filter: { datetime_geq: $start, datetime_leq: $end, action_in: $actions }, orderBy: [datetimeFiveMinutes_DESC]) { count dimensions { datetimeFiveMinutes action } } firewallEventsAdaptive(limit: 100, filter: { datetime_geq: $start, datetime_leq: $end, action_in: $actions }, orderBy: [datetime_DESC]) { action ruleId clientAsn clientASNDescription clientCountryName clientRequestPath clientIP datetime source } } } }",
"variables": {
"zoneTag": "{{ inputs.zone_id }}",
"start": "{{ now() | dateAdd(-inputs.lookback_minutes, 'MINUTES') | date(\"yyyy-MM-dd'T'HH:mm:ss'Z'\", timeZone='UTC') }}",
"end": "{{ now() | date(\"yyyy-MM-dd'T'HH:mm:ss'Z'\", timeZone='UTC') }}",
"actions": ["block", "challenge", "managed_challenge", "js_challenge"]
}
}
- id: evaluate_waf_block_rate_and_anomalies
type: io.kestra.plugin.scripts.python.Script
description: "Evaluates Cloudflare WAF block rate trends against historical
1-hour rolling baseline, detects sudden rate spikes (> 500%), and isolates
top offending rule IDs, client IP ASNs, and attacked URI paths."
taskRunner:
type: io.kestra.plugin.scripts.runner.docker.Docker
containerImage: python:3.12-slim
beforeCommands:
- pip install kestra
inputFiles:
waf_response.json: "{{ outputs.query_cloudflare_waf_analytics.body | toJson }}"
previous_telemetry.json: "{{ outputs.get_previous_waf_telemetry.value ?? '{}' }}"
env:
ZONE_ID: "{{ inputs.zone_id }}"
SPIKE_THRESHOLD_PCT: "{{ inputs.spike_threshold_pct }}"
MIN_BLOCK_COUNT_FOR_SPIKE: "{{ inputs.min_block_count_for_spike }}"
HTTP_STATUS_CODE: "{{ outputs.query_cloudflare_waf_analytics.code ?? 0 }}"
script: |
import json
import os
import sys
from collections import Counter, defaultdict
from datetime import datetime, timezone
from kestra import Kestra
zone_id = os.environ.get("ZONE_ID", "")
spike_threshold_pct = float(os.environ.get("SPIKE_THRESHOLD_PCT", 500.0))
min_block_count = int(os.environ.get("MIN_BLOCK_COUNT_FOR_SPIKE", 50))
http_status_code = int(os.environ.get("HTTP_STATUS_CODE", 0))
# 1. Load WAF Response and Historical KV Telemetry
waf_data = {}
try:
if os.path.exists("waf_response.json"):
with open("waf_response.json", "r", encoding="utf-8") as f:
raw_content = f.read().strip()
if raw_content and raw_content != "null":
parsed = json.loads(raw_content)
waf_data = json.loads(parsed) if isinstance(parsed, str) else parsed
except Exception as e:
print(f"Notice: Failed to load waf_response.json: {e}", file=sys.stderr)
prev_telemetry = {}
try:
if os.path.exists("previous_telemetry.json"):
with open("previous_telemetry.json", "r", encoding="utf-8") as f:
raw_prev = f.read().strip()
if raw_prev and raw_prev != "null":
parsed_prev = json.loads(raw_prev)
prev_telemetry = json.loads(parsed_prev) if isinstance(parsed_prev, str) else parsed_prev
except Exception as e:
print(f"Notice: Failed to load previous_telemetry.json: {e}", file=sys.stderr)
# 2. Extract Data Nodes
zones = waf_data.get("data", {}).get("viewer", {}).get("zones", []) if isinstance(waf_data, dict) else []
zone_payload = zones[0] if zones else {}
time_groups = zone_payload.get("firewallEventsAdaptiveByTimeGroups", []) or []
raw_events = zone_payload.get("firewallEventsAdaptive", []) or []
total_mitigated = 0
current_interval_blocks = 0
baseline_avg_blocks = 0.0
baseline_total_blocks = 0
spike_pct = 0.0
spike_detected = False
action_counts = {
"block": 0,
"challenge": 0,
"managed_challenge": 0,
"js_challenge": 0
}
rule_counts = Counter()
rule_action_map = defaultdict(Counter)
asn_counts = Counter()
asn_desc_map = {}
path_counts = Counter()
ip_counts = Counter()
ip_country_map = {}
# 3. Process Time Groups
buckets = defaultdict(lambda: {"total": 0, "actions": Counter()})
for tg in time_groups:
dt = tg.get("dimensions", {}).get("datetimeFiveMinutes")
action = tg.get("dimensions", {}).get("action", "unknown").lower()
cnt = tg.get("count", 0)
if dt:
buckets[dt]["total"] += cnt
buckets[dt]["actions"][action] += cnt
if action in action_counts:
action_counts[action] += cnt
total_mitigated += cnt
sorted_intervals = sorted(buckets.keys(), reverse=True)
if sorted_intervals:
current_interval_key = sorted_intervals[0]
current_interval_blocks = buckets[current_interval_key]["total"]
baseline_intervals = sorted_intervals[1:13]
if baseline_intervals:
baseline_total_blocks = sum(buckets[k]["total"] for k in baseline_intervals)
baseline_avg_blocks = round(baseline_total_blocks / len(baseline_intervals), 2)
else:
prev_baseline = prev_telemetry.get("baseline_interval_avg", 0.0) if isinstance(prev_telemetry, dict) else 0.0
if prev_baseline > 0:
baseline_avg_blocks = float(prev_baseline)
else:
baseline_avg_blocks = round(float(current_interval_blocks), 2)
if baseline_avg_blocks > 0:
spike_pct = round(((current_interval_blocks - baseline_avg_blocks) / baseline_avg_blocks) * 100.0, 2)
elif current_interval_blocks >= min_block_count:
spike_pct = 999.0
else:
spike_pct = 0.0
else:
current_interval_blocks = len(raw_events)
total_mitigated = current_interval_blocks
for ev in raw_events:
act = ev.get("action", "unknown").lower()
if act in action_counts:
action_counts[act] += 1
prev_baseline = prev_telemetry.get("baseline_interval_avg", 0.0) if isinstance(prev_telemetry, dict) else 0.0
if prev_baseline > 0:
baseline_avg_blocks = float(prev_baseline)
spike_pct = round(((current_interval_blocks - baseline_avg_blocks) / baseline_avg_blocks) * 100.0, 2)
elif current_interval_blocks >= min_block_count:
spike_pct = 999.0
# 4. Process Raw Events for Dimensions
for ev in raw_events:
rule_id = ev.get("ruleId") or "custom_waf_rule"
action = ev.get("action", "unknown").lower()
rule_counts[rule_id] += 1
rule_action_map[rule_id][action] += 1
asn = str(ev.get("clientAsn") or "Unknown")
asn_desc = ev.get("clientASNDescription") or "Unknown Network"
asn_counts[asn] += 1
asn_desc_map[asn] = asn_desc
path = ev.get("clientRequestPath") or "/"
path_counts[path] += 1
ip = ev.get("clientIP") or "0.0.0.0"
country = ev.get("clientCountryName") or "Unknown"
ip_counts[ip] += 1
ip_country_map[ip] = country
top_rules = [{"rule_id": r, "count": c} for r, c in rule_counts.most_common(5)]
top_asns = [{"asn": a, "description": asn_desc_map.get(a, "Unknown"), "count": c} for a, c in asn_counts.most_common(5)]
top_paths = [{"path": p, "count": c} for p, c in path_counts.most_common(5)]
top_ips = [{"ip": ip, "country": ip_country_map.get(ip, "Unknown"), "count": c} for ip, c in ip_counts.most_common(5)]
# Format strings for Slack notification
top_rules_str = ", ".join([f"`{r['rule_id']}` ({r['count']})" for r in top_rules]) if top_rules else "No rule data"
top_asns_str = ", ".join([f"AS{a['asn']} ({a['description']}: {a['count']})" for a in top_asns]) if top_asns else "No ASN data"
top_paths_str = ", ".join([f"`{p['path']}` ({p['count']})" for p in top_paths]) if top_paths else "No URI path data"
# 5. Status and Anomaly Classification
status = "NOMINAL_HEALTHY"
slack_color = "#2EB67D"
root_cause_summary = "Nominal operations: Cloudflare WAF block rate is within standard baseline limits."
if http_status_code != 200 and http_status_code != 0:
status = "API_QUERY_WARNING"
slack_color = "#ECB22E"
root_cause_summary = f"Cloudflare GraphQL API returned HTTP status {http_status_code}. Telemetry evaluation operating on cached or empty metrics."
elif spike_pct >= spike_threshold_pct and current_interval_blocks >= min_block_count:
spike_detected = True
status = "ANOMALOUS_BLOCK_RATE_SPIKE"
slack_color = "#E01E5A"
top_rule_ratio = (top_rules[0]["count"] / current_interval_blocks) if (top_rules and current_interval_blocks > 0) else 0.0
top_asn_ratio = (top_asns[0]["count"] / current_interval_blocks) if (top_asns and current_interval_blocks > 0) else 0.0
top_rule_id = top_rules[0]["rule_id"] if top_rules else "unknown"
top_path_str = top_paths[0]["path"] if top_paths else "/"
if top_rule_ratio > 0.65 and top_asn_ratio < 0.40:
root_cause_summary = (
f"POTENTIAL WAF MISCONFIGURATION: Rule '{top_rule_id}' accounts for {round(top_rule_ratio*100, 1)}% of all mitigations across high ASN diversity. "
f"Likely blocking legitimate customer traffic on path '{top_path_str}'."
)
elif top_asn_ratio > 0.50:
top_asn_id = top_asns[0]["asn"]
top_asn_name = top_asns[0]["description"]
root_cause_summary = (
f"ACTIVE BOTNET OR CREDENTIAL STUFFING ATTACK: {round(top_asn_ratio*100, 1)}% of requests originate from ASN {top_asn_id} ({top_asn_name}) "
f"targeting '{top_path_str}'. WAF mitigation rules successfully intercepting the flood."
)
else:
root_cause_summary = (
f"DISTRIBUTED ATTACK FLOOD: Mitigated {current_interval_blocks} requests (+{spike_pct}% above baseline) across multiple ASNs and rule filters."
)
elif current_interval_blocks > 0:
status = "NOMINAL_WITH_MITIGATIONS"
root_cause_summary = f"WAF operational: Intercepted {current_interval_blocks} requests within normal baseline variance (Spike: {spike_pct}%)."
telemetry_payload = {
"zone_id": zone_id,
"status": status,
"spike_detected": spike_detected,
"spike_percentage": spike_pct,
"current_interval_blocks": current_interval_blocks,
"baseline_interval_avg": baseline_avg_blocks,
"baseline_1h_total": baseline_total_blocks,
"total_mitigated": total_mitigated,
"action_breakdown": action_counts,
"top_rule_ids": top_rules,
"top_asns": top_asns,
"top_paths": top_paths,
"top_client_ips": top_ips,
"root_cause_summary": root_cause_summary,
"timestamp": datetime.now(timezone.utc).isoformat()
}
print(f"Cloudflare WAF Sentinel Audit Complete. Status: {status}")
print(f"Zone: {zone_id} | Current Blocks: {current_interval_blocks} | Baseline Avg: {baseline_avg_blocks} | Spike: {spike_pct}%")
print(f"Root Cause: {root_cause_summary}")
Kestra.outputs({
"status": status,
"spike_detected": spike_detected,
"spike_percentage": spike_pct,
"current_interval_blocks": current_interval_blocks,
"baseline_interval_avg": baseline_avg_blocks,
"action_blocks": action_counts["block"],
"action_challenges": action_counts["challenge"],
"action_managed_challenges": action_counts["managed_challenge"],
"action_js_challenges": action_counts["js_challenge"],
"top_rules_str": top_rules_str,
"top_asns_str": top_asns_str,
"top_paths_str": top_paths_str,
"slack_color": slack_color,
"root_cause_summary": root_cause_summary,
"telemetry_payload": telemetry_payload
})
- id: record_waf_telemetry_in_kv
type: io.kestra.plugin.core.kv.Set
description: "Records the latest WAF security telemetry, anomaly metrics, and
baseline rates in Kestra KV store for the specified zone."
key: "cloudflare_waf_telemetry_{{ inputs.zone_id }}"
value: "{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.telemetry_payload
| toJson }}"
kvType: JSON
- id: check_waf_spike_anomaly
type: io.kestra.plugin.core.flow.If
description: "Evaluates whether WAF block rate surge breached anomaly thresholds
and triggers incident notification."
condition: "{{ inputs.alert_on_spike and
outputs.evaluate_waf_block_rate_and_anomalies.vars.spike_detected }}"
then:
- id: notify_slack_waf_spike
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: "Dispatches rich Slack security incident alert with WAF rule impact
analysis and client IP ASN breakdown."
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"attachments": [
{
"color": "{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.slack_color }}",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "🚨 Cloudflare WAF Security Alert: Anomaly Spike Detected",
"emoji": true
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Execution ID:* `{{ execution.id }}`\n*Status:* *{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.status }}*\n*Assessment:* {{ outputs.evaluate_waf_block_rate_and_anomalies.vars.root_cause_summary }}"
}
},
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": "*Zone ID:*\n`{{ inputs.zone_id }}`"
},
{
"type": "mrkdwn",
"text": "*Block Rate Surge:*\n`+{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.spike_percentage }}%` (Threshold: `>{{ inputs.spike_threshold_pct }}%`)"
},
{
"type": "mrkdwn",
"text": "*Current Interval Blocks:*\n`{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.current_interval_blocks }}` requests"
},
{
"type": "mrkdwn",
"text": "*Rolling 1h Baseline Avg:*\n`{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.baseline_interval_avg }}` requests / 5m"
},
{
"type": "mrkdwn",
"text": "*Mitigated Action Counts:*\nBlock: `{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.action_blocks }}` | Challenge: `{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.action_challenges }}` | Managed: `{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.action_managed_challenges }}` | JS: `{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.action_js_challenges }}`"
},
{
"type": "mrkdwn",
"text": "*Targeted URI Paths:*\n{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.top_paths_str }}"
},
{
"type": "mrkdwn",
"text": "*Offending Rule IDs:*\n{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.top_rules_str }}"
},
{
"type": "mrkdwn",
"text": "*Top Source ASNs:*\n{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.top_asns_str }}"
}
]
},
{
"type": "context",
"elements": [
{
"type": "mrkdwn",
"text": "Cloudflare WAF Block Rate Sentinel | Namespace: `{{ flow.namespace }}` | Triage: Review custom rule criteria if false positives affect legitimate users, or apply rate limiting if attack persists."
}
]
}
]
}
]
}
else:
- id: log_nominal_waf_state
type: io.kestra.plugin.core.log.Log
description: "Logs nominal WAF state when block rates remain within normal
baseline parameters."
message: "Cloudflare WAF Sentinel NOMINAL: Zone '{{ inputs.zone_id }}' block
rate is normal. Current blocks: {{
outputs.evaluate_waf_block_rate_and_anomalies.vars.current_interval_b\
locks }} (Baseline 5m avg: {{
outputs.evaluate_waf_block_rate_and_anomalies.vars.baseline_interval_\
avg }}, Spike: {{
outputs.evaluate_waf_block_rate_and_anomalies.vars.spike_percentage
}}%)."
- id: export_waf_sentinel_manifest
type: io.kestra.plugin.core.debug.Return
description: "Emits structured WAF sentinel summary for downstream SIEM
integration or automated incident response subflows."
format:
zone_id: "{{ inputs.zone_id }}"
status: "{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.status }}"
spike_detected: "{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.spike_detected }}"
spike_percentage: "{{
outputs.evaluate_waf_block_rate_and_anomalies.vars.spike_percentage }}"
current_interval_blocks: "{{
outputs.evaluate_waf_block_rate_and_anomalies.vars.current_interval_blo\
cks }}"
baseline_interval_avg: "{{
outputs.evaluate_waf_block_rate_and_anomalies.vars.baseline_interval_avg
}}"
action_blocks: "{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.action_blocks }}"
action_challenges: "{{
outputs.evaluate_waf_block_rate_and_anomalies.vars.action_challenges }}"
action_managed_challenges: "{{
outputs.evaluate_waf_block_rate_and_anomalies.vars.action_managed_chall\
enges }}"
action_js_challenges: "{{
outputs.evaluate_waf_block_rate_and_anomalies.vars.action_js_challenges
}}"
root_cause_summary: "{{
outputs.evaluate_waf_block_rate_and_anomalies.vars.root_cause_summary
}}"
outputs:
- id: status
type: STRING
description: "Overall security posture and anomaly classification for the zone
WAF rules."
value: "{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.status }}"
- id: spike_detected
type: BOOL
description: "Boolean flag indicating whether block rate surge breached the
configured spike threshold."
value: "{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.spike_detected }}"
- id: spike_percentage
type: FLOAT
description: "Calculated percentage change in block rate compared to rolling
1-hour baseline."
value: "{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.spike_percentage }}"
- id: current_interval_blocks
type: INT
description: "Total mitigated events during the current evaluation interval."
value: "{{
outputs.evaluate_waf_block_rate_and_anomalies.vars.current_interval_blocks
}}"
- id: baseline_interval_avg
type: FLOAT
description: "Rolling 1-hour baseline average mitigated events per 5-minute bucket."
value: "{{
outputs.evaluate_waf_block_rate_and_anomalies.vars.baseline_interval_avg
}}"
- id: root_cause_summary
type: STRING
description: "Diagnostic assessment of root cause differentiating rule
misconfiguration from distributed attacks."
value: "{{ outputs.evaluate_waf_block_rate_and_anomalies.vars.root_cause_summary
}}"
errors:
- id: alert_pipeline_failure
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: "Dispatches emergency alert if the Cloudflare WAF sentinel
execution fails unexpectedly."
url: "{{ secret('SLACK_WEBHOOK_URL') }}"
payload: |
{
"text": "CRITICAL: Cloudflare WAF Custom Rule Block Rate Sentinel pipeline failed for zone `{{ inputs.zone_id }}` in namespace `{{ flow.namespace }}` during execution `{{ execution.id }}`! Check Kestra execution logs."
}