Skip to content

Cerberus Technical Documentation

Cerberus Technical Documentation

This document is for developers and advanced users who want to understand how Cerberus works under the hood.

Looking for the user guide? See Security Features instead.


What Is Cerberus?

Cerberus is the optional security suite built into Charon. It includes:

  • WAF (Web Application Firewall) — Inspects requests for malicious payloads
  • CrowdSec — Blocks IPs based on behavior and reputation
  • Access Lists — Static allow/deny rules (IP, CIDR, geo)
  • Rate Limiting — Limits how many requests a visitor can send in a time window

All components are disabled by default and can be enabled independently.


Architecture

Request Flow

When a visitor's request reaches one of your proxied sites, Caddy runs these checks in order. Each check runs only when its switch is on.

  1. Cerberus switch — If the security switch on the Security page is off, none of the checks below run.
  2. Block decisions — Addresses with a block decision get a 403 response. Addresses on the admin whitelist are never refused this way, so a block decision on one of them has no effect.
  3. CrowdSec — The CrowdSec bouncer checks the address against CrowdSec decisions.
  4. WAF — The selected rule set checks the request when the WAF is on for the site. A rule set in Blocking mode refuses matching requests. A rule set in Detection mode only logs them.
  5. Rate limit — A visitor who is over the limit gets a 429 response. Runs only when the request count and time window are both set.
  6. Access list — Requests that fail the site's access list are refused.
  7. Forward — The request goes on to your app.

Middleware Integration

Cerberus runs as Gin middleware on all /api/v1 routes:

r.Use(cerberusMiddleware.RequestLogger())

This means it protects the management API but does not directly inspect traffic to proxied websites (that happens in Caddy).

Access lists attached to proxy hosts do not apply on this path. The management API is checked only against the management access lists chosen on the Access Lists page, and only while access control is on. The Orthrus agent connection is exempt. See Access Control Lists.

Visitor Address

Every check above uses one visitor address. Charon takes it from the proxy's X-Forwarded-For note only when the proxy that sent it is on the trusted proxy list. Loopback is always trusted. Otherwise Charon uses the address of the connection. The same address drives the block decisions, CrowdSec, the WAF, the rate limit, the access lists, the country rules, the X-Real-IP header sent to your apps, and the security log. See Trusted Proxies.

Live streams are limited too. Each user may have 8 live views open at once (live logs, Cerberus logs, Hecate logs and stats), and Charon allows 64 across all users. A view over the limit is closed with a "too many live connections" message, and it does not reconnect by itself.


Threat Model & Protection Coverage

What Cerberus Protects

Threat Category CrowdSec ACL WAF Rate Limit
Known attackers (IP reputation) ✅ ❌ ❌ ❌
Geo-based attacks ❌ ✅ ❌ ❌
SQL Injection (SQLi) ❌ ❌ ✅ ❌
Cross-Site Scripting (XSS) ❌ ❌ ✅ ❌
Remote Code Execution (RCE) ❌ ❌ ✅ ❌
Zero-Day Web Exploits ⚠️ ❌ ✅ ❌
DDoS / Volume attacks ❌ ❌ ❌ ✅
Brute-force login attempts ✅ ❌ ❌ ✅
Credential stuffing ✅ ❌ ❌ ✅

Legend:

  • ✅ Full protection
  • ⚠️ Partial protection (time-delayed)
  • ❌ Not designed for this threat

Zero-Day Exploit Protection (WAF)

The WAF provides pattern-based detection for zero-day exploits:

How It Works:

  1. Attacker discovers new vulnerability (e.g., SQLi in your login form)
  2. Attacker crafts exploit: ' OR 1=1--
  3. WAF inspects request → matches SQL injection pattern → BLOCKED
  4. Your application never sees the malicious input

Limitations:

  • Only protects HTTP/HTTPS traffic
  • Cannot detect completely novel attack patterns (rare)
  • Does not protect against logic bugs in application code

Effectiveness:

  • ~90% of zero-day web exploits use known patterns (SQLi, XSS, RCE)
  • ~10% are truly novel and may bypass WAF until rules are updated

Request Processing Pipeline

1. [Block decisions] Refuse addresses with a block decision (admin whitelist excepted)
2. [CrowdSec]        Check the address against CrowdSec decisions, when on
3. [WAF]             Inspect the request with the selected rule set, when on
4. [Rate Limit]      Count requests per visitor, when on and its numbers are set
5. [ACL]             Check the site's access list, when on and the site has one
6. [Proxy]           Forward to upstream service

Configuration Model

Database Schema

SecurityConfig table:

type SecurityConfig struct {
    ID                   uint   `gorm:"primaryKey"`
    Name                 string `json:"name"`
    Enabled              bool   `json:"enabled"`
    AdminWhitelist       string `json:"admin_whitelist"`        // CSV of IPs/CIDRs
    CrowdsecMode         string `json:"crowdsec_mode"`          // disabled, local, external
    CrowdsecAPIURL       string `json:"crowdsec_api_url"`       // ignored: Charon always uses its own CrowdSec engine
    CrowdsecAPIKey       string `json:"crowdsec_api_key"`
    WafMode              string `json:"waf_mode"`               // disabled, monitor, block
    WafRulesSource       string `json:"waf_rules_source"`       // Rule set name, or an http(s) URL
    WafLearning          bool   `json:"waf_learning"`
    RateLimitEnable      bool   `json:"rate_limit_enable"`
    RateLimitBurst       int    `json:"rate_limit_burst"`
    RateLimitRequests    int    `json:"rate_limit_requests"`
    RateLimitWindowSec   int    `json:"rate_limit_window_sec"`
}

Switch Values

The Cerberus switch (the master security switch) takes only true or false.

  • When you save it, capital letters and spaces around the word are fine. TRUE is saved as true. Any other value is refused with 400 and nothing is saved.
  • When Charon reads it, the Security page status and the presets treat any stored value other than true or false as off. That includes a blank value, a value with extra spaces, 1 and yes.

Environment Variables (Fallbacks)

If no database config exists, Charon reads from environment:

  • CERBERUS_SECURITY_WAF_MODE — disabled | monitor | block
  • 🚨 DEPRECATED: CERBERUS_SECURITY_CROWDSEC_MODE — Use GUI toggle instead (see below)
  • 🚨 DEPRECATED: CERBERUS_SECURITY_CROWDSEC_API_URL — External mode is no longer supported, and the value is ignored. Charon always uses its own CrowdSec engine.
  • 🚨 DEPRECATED: CERBERUS_SECURITY_CROWDSEC_API_KEY — External mode is no longer supported. The name is still read as a bouncer key fallback, after the saved key file and the newer CHARON_SECURITY_CROWDSEC_API_KEY (see the CrowdSec feature guide).
  • CERBERUS_SECURITY_ACL_ENABLED — true | false
  • CERBERUS_SECURITY_RATELIMIT_ENABLED — true | false

⚠️ IMPORTANT: The CHARON_SECURITY_CROWDSEC_MODE (and legacy CERBERUS_SECURITY_CROWDSEC_MODE, CPM_SECURITY_CROWDSEC_MODE) environment variables are DEPRECATED as of version 2.0. CrowdSec is now GUI-controlled through the Security dashboard, just like WAF, ACL, and Rate Limiting.

Why the change?

  • CrowdSec now works like all other security features (GUI-based)
  • No need to restart containers to enable/disable CrowdSec
  • Better integration with Charon's security orchestration
  • The import config feature replaced the need for external mode

Migration: If you have CHARON_SECURITY_CROWDSEC_MODE=local in your docker-compose.yml, remove it and use the GUI toggle instead. See Migration Guide for step-by-step instructions.


WAF (Web Application Firewall)

Current Implementation

Status: Active. The WAF uses the Coraza engine with the selected rule set, which must contain at least one rule.

Charon writes each rule set to a file. Unless the rule set already has its own SecRuleEngine line, Charon adds a header line that sets the engine mode: SecRuleEngine On for a rule set in Blocking mode, and SecRuleEngine DetectionOnly for one in Detection mode. A rule set with no mode of its own takes the saved WAF mode. A rule set that contains its own SecRuleEngine line keeps it, and that line decides whether matching requests are blocked, whatever Blocking or Detection mode is chosen.

Rulesets

SecurityRuleSet table stores rule definitions:

type SecurityRuleSet struct {
    ID         uint   `gorm:"primaryKey"`
    Name       string `json:"name"`
    SourceURL  string `json:"source_url"`  // Optional reference URL; stored, not fetched
    Mode       string `json:"mode"`        // blocking or detection (see below)
    Content    string `json:"content"`     // Raw rule text
}

Manage via /api/v1/security/rulesets.

Choosing the Rule Set the WAF Uses

On the WAF page, pick a rule set from the list, or choose automatic selection. The saved choice is either the name of a rule set or the address (http:// or https://) of a rule file. A name that matches no rule set is refused.

How the Switch, the Saved Mode and the Rule Set Mode Combine

  • The WAF switch turns the WAF on or off. Turning it off never changes the rule sets or the saved mode.
  • Each rule set has a mode, Blocking or Detection, set on the WAF page. A rule set in Detection mode logs matching requests without stopping them. A rule set in Blocking mode stops them, unless its content has its own SecRuleEngine line (see above).
  • The saved WAF mode (monitor or block) is used only for a rule set with no mode of its own. Its monitor value means Detection; any other value means Blocking.

After Upgrading

After upgrading, check the WAF page. With the WAF switched on and a rule set selected, each rule set's own mode applies: a rule set set to blocking blocks matching requests, and one set to detection only logs them (in both cases unless the rule set contains its own SecRuleEngine line). A rule set with no mode of its own follows the saved WAF mode (detection when it is set to monitor, blocking otherwise).

Prometheus Metrics

charon_waf_requests_total — Requests to Charon's own management API (`/api/v1`). Traffic to your proxied sites is not counted.
charon_waf_blocked_total — Requests to your proxied sites that the WAF blocked, when the proxy's access log identifies the block as a WAF block. Not every block can be told apart in the log yet, so treat the count as a lower bound.
charon_crowdsec_requests_total — Requests to Charon's own management API that CrowdSec checked. Traffic to your proxied sites is not counted.
charon_crowdsec_blocked_total — Requests to your proxied sites that CrowdSec blocked, counted the same way as the WAF block count and with the same limit.
charon_url_validation_total — URL checks, by result and reason (labels `result` and `reason`).
charon_ssrf_blocks_total — Requests refused for pointing at a private or internal address, by address type (label `ip_type`).
charon_url_test_duration_seconds — How long URL connection tests take, as a histogram.

Scrape from /metrics endpoint (no auth required). The *_requests_total series count only management API requests, as above. charon_waf_monitored_total has been removed. It always read 0, so update any dashboard or alert that still uses it.

Structured Logging

WAF decisions emit JSON-like structured logs:

{
  "source": "waf",
  "decision": "block",
  "mode": "block",
  "path": "/api/v1/proxy-hosts",
  "query": "name=<script>alert(1)</script>",
  "ip": "203.0.113.50"
}

Use these for dashboard creation and alerting.


Rate Limiting

The Rate Limiting switch on the Security page turns on two limits. Both follow that one switch.

  • Proxy limit. Limits how fast each visitor can send requests to your proxied sites. Its numbers are the ones on the Rate Limiting card.
  • Management API limit. Limits requests to Charon's own management interface. It does not read the numbers on the Rate Limiting card.

Standard numbers. When the rate limit is turned on, any number that is not set is filled with the standard values: 100 requests, a 60 second window and a burst of 20. The burst applies only to the management API limit; the proxy limit uses the request count and the window. Numbers already sent in the same change are kept.

Unset numbers. If the rate limit is already on but its request count or window is not set, Charon does not invent numbers. The Security page shows the rate limit as not applied with the reason thresholds_unset until you set the numbers.

Visitor counting. The proxy limit counts visitors by the address that connects to Charon. Behind a tunnel or a shared network address, many visitors can share one count.


Access Control Lists (ACLs)

How They Work

Each AccessList defines:

  • Type: whitelist | blacklist | geo_whitelist | geo_blacklist | local_only
  • IPs: Comma-separated IPs or CIDR blocks
  • Countries: Comma-separated ISO country codes (US, GB, FR, etc.)

Evaluation logic:

  • Admin whitelist (every type): If the address is on the admin whitelist → allow, before any other check below
  • Whitelist: If IP matches list → allow; else → deny
  • Blacklist: If IP matches list → deny; else → allow
  • Geo Whitelist: If country matches → allow; else → deny
  • Geo Blacklist: If country matches → deny; else → allow
  • Local Only: If RFC1918 private IP → allow; else → deny

Multiple ACLs can be assigned to a proxy host. The first denial wins. These lists protect that proxy host's website only. Charon's own interface is protected by the management access lists chosen on the Access Lists page, which use the same list types.

Required entries:

  • An enabled allow list (Whitelist or Geo Whitelist) must contain at least one IP address, range or country. Saving an enabled allow list with no entries is refused with the error access_list_rules_required. An allow list with no entries that is not enabled is still saved.
  • A block list (Blacklist or Geo Blacklist) may be empty. An empty block list blocks nobody.

Refused requests: When a list refuses a request, the response is a 403 (or 429 for rate limits) and still carries the security headers from the host's profile. See HTTP Security Headers.

GeoIP Database

Country lists (Geo Whitelist and Geo Blacklist) need the MaxMind GeoLite2-Country database. The proxy reads it to find the country of each visitor.

  • Where it comes from: The Docker image tries to download the database when it is built and keeps it outside the data folder, in /app/geoip/, so a data volume does not hide it. If the download fails, the image is still built without it.
  • Using a newer copy: Admins can use Replace database… on the Security page's Country database (GeoIP) card, or put a GeoLite2-Country.mmdb file in the geoip folder inside your data folder (/app/data/geoip/ in the container). When both that copy and the image's copy are present, Charon uses the one with the newer build date. If the data-folder copy cannot be read, the image's copy is used.
  • Source values: The card names the map in use as one of four sources. Included with Charon is the copy in the image. Your data folder is a copy you uploaded or placed yourself. Custom path set on the server means CHARON_GEOIP_DB_PATH is in use. No database means none could be found.
  • Custom location: Set CHARON_GEOIP_DB_PATH to the full path of the .mmdb file. Charon uses that path exactly, and it wins over both copies above. The file name must end in .mmdb. A file with any other ending is treated as unavailable. If the variable is set to /app/data/geoip/GeoLite2-Country.mmdb and no file is there (an old setting copied from an earlier image), Charon ignores the variable and uses the image's copy. While the variable is in use, the card cannot replace or remove the file; Reload still works.
  • When the database is missing: Country lists are not enforced. An allow-list lets everyone in, and a block-list blocks no one. A red alert appears in the notification bell (in the app only) until a database is available. Your other lists and sites are not affected. See Country Access Lists Are Not Being Enforced.
  • After adding or replacing the file: Press Reload on the card, or restart Charon. The proxy then applies your country lists again.
  • Updates: Download a new copy from MaxMind about once a month to keep country data accurate.

CrowdSec Integration

GUI-Based Control (Current Architecture)

CrowdSec is now GUI-controlled, matching the pattern used by WAF, ACL, and Rate Limiting. The environment variable control (CHARON_SECURITY_CROWDSEC_MODE) is deprecated and will be removed in a future version.

LAPI Initialization and Health Checks

Technical Implementation:

When you toggle CrowdSec ON via the GUI, the backend performs the following:

  1. Start CrowdSec Process (/api/v1/admin/crowdsec/start)
pid, err := h.Executor.Start(ctx, h.BinPath, h.DataDir)
  1. Poll LAPI Health (automatic, server-side)
  2. Polling interval: 500ms
  3. Maximum wait: 30 seconds
  4. Health check command: cscli lapi status
  5. Expected response: Exit code 0 (success)

  6. Return Status with lapi_ready Flag

{
  "status": "started",
  "pid": 203,
  "lapi_ready": true
}

Response Fields:

  • status — "started" (process successfully initiated) or "error"
  • pid — Process ID of running CrowdSec instance
  • lapi_ready — Boolean indicating if LAPI health check passed
  • true — LAPI is fully initialized and accepting requests
  • false — CrowdSec is running, but LAPI still initializing (may take 5-10 more seconds)

Backend Implementation (internal/handlers/crowdsec_handler.go:185-230):

func (h *CrowdsecHandler) Start(c *gin.Context) {
    // Start the process
    pid, err := h.Executor.Start(ctx, h.BinPath, h.DataDir)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    // Wait for LAPI to be ready (with timeout)
    lapiReady := false
    maxWait := 30 * time.Second
    pollInterval := 500 * time.Millisecond
    deadline := time.Now().Add(maxWait)

    for time.Now().Before(deadline) {
        checkCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
        defer cancel()

        _, err := h.CmdExec.Execute(checkCtx, "cscli", []string{"lapi", "status"})
        if err == nil {
            lapiReady = true
            break
        }
        time.Sleep(pollInterval)
    }

    // Return status
    c.JSON(http.StatusOK, gin.H{
        "status":     "started",
        "pid":        pid,
        "lapi_ready": lapiReady,
    })
}

Key Technical Details:

  • Non-blocking: The Start() handler waits for LAPI but has a timeout
  • Health check: Uses cscli lapi status (exit code 0 = healthy)
  • Retry logic: Polls every 500ms instead of continuous checks (reduces CPU)
  • Timeout: 30 seconds maximum wait (prevents infinite loops)
  • Graceful degradation: Returns lapi_ready: false instead of failing if timeout exceeded

LAPI Health Endpoint:

LAPI exposes a health endpoint on http://localhost:8085/health:

curl -s http://localhost:8085/health

Response when healthy:

{"status":"up"}

This endpoint is used internally by cscli lapi status.

How to Enable CrowdSec

Step 1: Access Security Dashboard

  1. Navigate to Security in the sidebar
  2. Find the CrowdSec card
  3. Toggle the switch to ON
  4. Wait 10-15 seconds for LAPI to start
  5. Verify status shows "Active" with a running PID

Step 2: Verify LAPI is Running

docker exec charon cscli lapi status

Expected output:

✓ You can successfully interact with Local API (LAPI)

Step 3: (Optional) Enroll in CrowdSec Console

Once LAPI is running, you can enroll your instance:

  1. Go to Cerberus → CrowdSec
  2. Enable the Console enrollment feature flag (if not already enabled)
  3. Click Enroll with CrowdSec Console
  4. Paste your enrollment token from crowdsec.net
  5. Submit

Prerequisites for Console Enrollment:

  • ✅ CrowdSec must be enabled via GUI toggle
  • ✅ LAPI must be running (verify with cscli lapi status)
  • ✅ Feature flag feature.crowdsec.console_enrollment must be enabled
  • ✅ Valid enrollment token from crowdsec.net

⚠️ Important: Console enrollment requires an active LAPI connection. If LAPI is not running, the enrollment will appear successful locally but won't register on crowdsec.net.

Enrollment Retry Logic:

The console enrollment service automatically checks LAPI availability with retries:

Implementation (internal/services/console_enroll.go:218-246):

func (s *ConsoleEnrollmentService) checkLAPIAvailable(ctx context.Context) error {
    maxRetries := 3
    retryDelay := 2 * time.Second

    for i := 0; i < maxRetries; i++ {
        checkCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
        defer cancel()

        _, err := s.exec.ExecuteWithEnv(checkCtx, "cscli", []string{"lapi", "status"}, nil)
        if err == nil {
            return nil // LAPI is available
        }

        if i < maxRetries-1 {
            logger.Log().WithError(err).WithField("attempt", i+1).Debug("LAPI not ready, retrying")
            time.Sleep(retryDelay)
        }
    }

    return fmt.Errorf("CrowdSec Local API is not running after %d attempts", maxRetries)
}

Retry Parameters:

  • Max retries: 3 attempts
  • Retry delay: 2 seconds between attempts
  • Total retry window: Up to 6 seconds (3 attempts × 2 seconds)
  • Command timeout: 5 seconds per attempt

Retry Flow:

  1. Attempt 1 — Immediate LAPI check
  2. Wait 2 seconds (if failed)
  3. Attempt 2 — Retry LAPI check
  4. Wait 2 seconds (if failed)
  5. Attempt 3 — Final LAPI check
  6. Return error — If all 3 attempts fail

This handles most race conditions where LAPI is still initializing after CrowdSec start.

How CrowdSec Works in Charon

Startup Flow:

  1. Container starts → CrowdSec config initialized (but agent NOT started)
  2. User toggles CrowdSec switch in GUI → Frontend calls /api/v1/admin/crowdsec/start
  3. Backend handler starts LAPI process → PID tracked in backend
  4. User can verify status in Security dashboard
  5. User toggles OFF → Backend calls /api/v1/admin/crowdsec/stop

This matches the pattern used by other security features:

Feature Control Method Status Endpoint Lifecycle Handler
Cerberus GUI Toggle /security/status N/A (master switch)
WAF GUI Toggle /security/status Config regeneration
ACL GUI Toggle /security/status Config regeneration
Rate Limit GUI Toggle /security/status Config regeneration
CrowdSec ✅ GUI Toggle /security/status Start/Stop handlers

Import Config Feature

The import config feature (importCrowdsecConfig) allows you to:

  1. Upload a complete CrowdSec configuration (tar.gz)
  2. Import pre-configured settings, collections, and bouncers
  3. Manage CrowdSec entirely through Charon's GUI

This replaced the need for "external" mode:

  • Old way (deprecated): Set CROWDSEC_MODE=external and point to external LAPI
  • New way: Import your existing config and let Charon manage it internally

Troubleshooting

Problem: Console enrollment shows "enrolled" locally but doesn't appear on crowdsec.net

Technical Analysis: LAPI must be fully initialized before enrollment. Even with automatic retries, there's a window where LAPI might not be ready.

Solution:

  1. Verify LAPI process is running:
docker exec charon ps aux | grep crowdsec

Expected output:

crowdsec  203  0.5  2.3  /usr/local/bin/crowdsec -c /app/data/crowdsec/config/config.yaml
  1. Check LAPI status:
docker exec charon cscli lapi status

Expected output:

✓ You can successfully interact with Local API (LAPI)

If not ready:

ERROR: cannot contact local API
  1. Check LAPI health endpoint:
docker exec charon curl -s http://localhost:8085/health

Expected response:

{"status":"up"}
  1. Check LAPI can process requests:
docker exec charon cscli machines list

Expected output:

Name                     IP Address      Auth Type    Version
charon-local-machine     127.0.0.1      password     v1.x.x
  1. If LAPI is not running:
  2. Go to Security dashboard
  3. Toggle CrowdSec OFF, then ON again
  4. Wait 15 seconds (critical: LAPI needs time to initialize)
  5. Verify LAPI is running (repeat checks above)
  6. Re-submit enrollment token

  7. Monitor LAPI startup:

# Watch CrowdSec logs in real-time
docker logs -f charon | grep -i crowdsec

Look for: - ✅ "Starting CrowdSec Local API" - ✅ "CrowdSec Local API listening on 127.0.0.1:8085" - ✅ "parsers loaded: 4" - ✅ "scenarios loaded: 46" - ❌ "error" or "fatal" (indicates startup problem)

Problem: CrowdSec won't start after toggling

Solution:

  1. Check logs for errors:
docker logs charon | grep -i error | tail -20
  1. Common startup issues:

Issue: Config directory missing

# Check directory exists
docker exec charon ls -la /app/data/crowdsec/config

# If missing, restart container to regenerate
docker compose restart

Issue: Port conflict (8085 in use)

# Check port usage
docker exec charon netstat -tulpn | grep 8085

# If another process is using port 8085, stop it or change CrowdSec LAPI port

Issue: Permission errors

# Fix ownership (run on host machine)
sudo chown -R 1000:1000 ./data/crowdsec
docker compose restart
  1. Remove deprecated environment variables:

Edit docker-compose.yml and remove:

# REMOVE THESE DEPRECATED VARIABLES:
- CHARON_SECURITY_CROWDSEC_MODE=local
- CERBERUS_SECURITY_CROWDSEC_MODE=local
- CPM_SECURITY_CROWDSEC_MODE=local

Then restart:

docker compose down
docker compose up -d
  1. Verify CrowdSec binary exists:
docker exec charon which crowdsec
# Expected: /usr/local/bin/crowdsec

docker exec charon which cscli
# Expected: /usr/local/bin/cscli

Expected LAPI Startup Times:

  • Initial start: 5-10 seconds
  • First start after container restart: 10-15 seconds
  • With many scenarios/parsers: Up to 20 seconds
  • Maximum timeout: 30 seconds (Start() handler limit)

Performance Monitoring:

# Check CrowdSec resource usage
docker exec charon ps aux | grep crowdsec

# Check LAPI response time
time docker exec charon curl -s http://localhost:8085/health

# Monitor LAPI availability over time
watch -n 5 'docker exec charon cscli lapi status'

See also: CrowdSec Troubleshooting Guide


Security Decisions

The SecurityDecision table logs all security actions:

type SecurityDecision struct {
    ID        uint      `gorm:"primaryKey"`
    Source    string    `json:"source"`    // waf, crowdsec, acl, ratelimit, manual
    IPAddress string    `json:"ip_address"`
    Action    string    `json:"action"`    // allow, block, challenge
    Reason    string    `json:"reason"`
    Timestamp time.Time `json:"timestamp"`
}

Use cases:

  • Audit trail for compliance
  • UI visibility into recent blocks
  • Manual override tracking

Self-Lockout Prevention

Admin Whitelist

Purpose: Prevent admins from blocking themselves

How it works:

  • Set on the Security settings page as a list of IP addresses or ranges
  • Checked before every access list rule, for every list type (IP allow lists, IP block lists, country lists and local-network-only lists)
  • If the requesting address is on the whitelist → always allowed through, and no block list or country rule can refuse it, on a proxy host or on Charon's own interface
  • Block lists refuse only the addresses they list. A manual block decision on a whitelisted address has no effect, so remove the address from the whitelist first if you really want to block it
  • The Test IP tool on the Access Lists page gives the same answer the proxy gives

Recommendation: Add your VPN IP, Tailscale IP, or home network before enabling Cerberus.

Break-Glass Token

Purpose: Emergency disable when locked out

How it works:

  1. Generate via POST /api/v1/security/breakglass/generate
  2. Returns one-time token (plaintext, never stored hashed)
  3. Token can be used in POST /api/v1/security/disable to turn off Cerberus
  4. Token expires after first use

An emergency Disable also switches the Cerberus on/off settings off, so the proxy stops enforcing its security rules and the status shows Cerberus as off.

Storage: Tokens are hashed in database using bcrypt.

Localhost Bypass

Requests from 127.0.0.1 or ::1 may bypass security checks (configurable). Allows local management access even when locked out.


API Reference

Status

GET /api/v1/security/status

Returns:

{
  "enabled": true,
  "waf_mode": "monitor",
  "crowdsec_mode": "local",
  "acl_enabled": true,
  "ratelimit_enabled": false
}

Enable Cerberus

POST /api/v1/security/enable
Content-Type: application/json

{
  "admin_whitelist": "198.51.100.10,203.0.113.0/24"
}

Requires either:

  • admin_whitelist with at least one IP/CIDR
  • OR valid break-glass token in header

Disable Cerberus

POST /api/v1/security/disable

Requires either:

  • Request from localhost
  • OR valid break-glass token in header

Get/Update Config

GET /api/v1/security/config
POST /api/v1/security/config

See SecurityConfig schema above.

A save changes only the fields it sends. Omitted or null fields keep their stored values, and "", 0 or false are applied. Each security page saves only the settings in its own section, so saving one section leaves the others unchanged. See Upsert Global Security Config for details.

Rulesets

GET /api/v1/security/rulesets
POST /api/v1/security/rulesets
DELETE /api/v1/security/rulesets/:id

Decisions (Audit Log)

GET /api/v1/security/decisions?limit=50
POST /api/v1/security/decisions  # Manual override

Testing

Integration Test

Run the Coraza integration test:

bash scripts/coraza_integration.sh

Or via Go:

cd backend
go test -tags=integration ./integration -run TestCorazaIntegration -v

Manual Testing

  1. On the Security page, turn on the Coraza WAF switch
  2. On the WAF page, set the rule set's mode to Detection
  3. Send a request with <script> in the query string to a proxied site that has the WAF on. The request still reaches the app, because Detection only logs it
  4. On the WAF page, set the rule set's mode to Blocking
  5. Repeat step 3. The request should now be refused

Observability

Blocked requests per second:

rate(charon_waf_blocked_total[5m])

Alerting Rules

High block rate (potential attack):

alert: HighWAFBlockRate
expr: rate(charon_waf_blocked_total[5m]) > 0.3
for: 10m
annotations:
  summary: "WAF blocking more than 0.3 requests per second"

Development Roadmap

Phase Feature Status
1 WAF (Coraza engine) + Prometheus metrics ✅ Complete
2 ACL implementation ✅ Complete
3 Break-glass token ✅ Complete
4 Coraza rule set support (paste in CRS-compatible rules) ✅ Complete
5 CrowdSec local agent ✅ Complete
6 Rate limiting enforcement ✅ Complete
7 Adaptive learning/tuning 🔮 Future

FAQ

Does the WAF really block attacks?

Yes. Charon uses the Coraza engine with the rule sets you add, including OWASP Core Rule Set rules if you paste them in. Each rule set is either Detection (logs only) or Blocking (refuses matching requests), unless the rule set contains its own SecRuleEngine line, which takes precedence.

Can I use my own WAF rules?

Yes, via /api/v1/security/rulesets. Upload custom Coraza-compatible rules.

Does Cerberus protect Caddy's proxy traffic?

Yes. For each proxied site, the block decisions, CrowdSec, WAF, rate limit and access list checks run in Caddy before the request reaches your app. Charon's own management API (/api/v1) has a separate rate limit.

Why does a rule set still block when the saved WAF mode is monitor?

The saved WAF mode applies only to a rule set with no mode of its own. A rule set set to Blocking keeps blocking, unless its content sets its own SecRuleEngine DetectionOnly line. Set it to Detection on the WAF page to log only.


See Also