This is the multi-page printable view of this section. .

Return to the regular view of this page.

Product Documentation

Technical documentation and user guides for CheeseSec products.

This section provides comprehensive technical documentation and operational references for CheeseSec products.

Self-hosted Web Application Firewall covering system deployment, configuration management, security policies, and daily operations.

An independent plugin product shared across CheeseSec. Read development, signing, publication, and host compatibility guidance.

1 - CheeseWAF

Self-hosted Web Application Firewall with a single-binary data plane, management console, and asynchronous threat review.

CheeseWAF is a self-hosted reverse-proxy WAF. It keeps deterministic request inspection on the data plane and runs optional model-assisted review out of band, so an external model is never required to serve normal traffic.

The shortest supported path is: run the official Linux installer, open the HTTPS setup URL it prints, complete /setup, and onboard one test site. Downloads prefer the official source, with GitHub as a backup for failed downloads; checksum or signature failures stop installation. See the Linux guide for the command and backup entry. The Apache License 2.0 is available in the source repository.

Choose a path

Start with the task you need to complete:

Install, initialize the console, verify the service, and protect one test site.

Install with the one-line installer or a verified archive, then run as a systemd service.

Run an isolated evaluation or compose-based deployment with explicit port and data mounts.

Five-minute path

  1. Prepare a supported Linux host with sudo, enough disk for the release and runtime data, and an administration path to port 9443.
  2. Run the official one-line installer. It downloads and verifies the latest stable release, installs the systemd service when available, and prints the HTTPS setup URL. Follow the verified archive path in the Linux guide when the host has no outbound access.
  3. Open the printed HTTPS URL, create the first administrator, and keep the one-time token out of tickets, screenshots, shell history, and logs.
  4. Follow Quick Start to add a test site before changing production DNS.

The installer creates a dedicated cheesewaf system user, copies the Web Console assets, installs the runtime configuration only when it does not already exist, enables HTTPS on the management listener, and places the systemd unit under /etc/systemd/system by default. It does not replace an existing configuration.

What CheeseWAF provides

  • Data plane: reverse proxying, request normalization, AST-based semantic inspection, ACLs, IP and fingerprint controls, rate limiting, and bot challenges.
  • Management plane: Web Console, REST API, CLI/TUI workflows, setup wizard, RBAC, audit records, and operational health endpoints.
  • Asynchronous review: optional ALAP review for ambiguous samples. The review queue is out of band; it must not be treated as the inline enforcement path.
  • Storage choices: the default temporary profile uses the local runtime store. Production deployments must explicitly provide the required external storage and must fail closed instead of silently falling back.
  • Adapters and plugins: adapterd integrates existing gateways; CRP packages provide signed offline resources. Review Plugins & CRP before enabling third-party packages.
  • Air-gapped operation: release archives, checksums, signed resources, and local runtime data can be managed without making the data plane depend on an external model.

Default network boundaries

Plane / serviceDefault addressPurpose
Data planehttp://127.0.0.1:8080Business traffic inspection and reverse proxying
Management planehttps://PUBLIC_IP:9443/setup → https://PUBLIC_IP:9443/SECURITY_ENTRYFirst setup uses a fixed /setup path with a one-time token; after setup, the generated security entry signs an access Cookie and redirects to login
Cluster planehttps://127.0.0.1:9444Optional mTLS node interconnect when clustering is enabled
Local controllerhttp://127.0.0.1:17943Desktop helper controller for Windows and macOS

The one-line installer binds the management listener on all interfaces, enables HTTPS, and gates first setup with a one-time token and a generated security entry. Restrict port 9443 to trusted administration networks before exposing it. The shipped configuration template and the setup wizard default to 0.0.0.0:9443 with server.admin_public: true. A configuration that omits the server keys falls back to the loader default 127.0.0.1:9443. A public listener still requires management TLS, a valid certificate, and an external access policy. Do not expose /setup or the management port to the Internet as a substitute for those controls.

Continue

Understand the request lifecycle, management boundaries, storage profiles, and enforcement order.

Configure semantic inspection, ACLs, IP controls, challenges, and rate limits.

Connect NGINX or Envoy through the authenticated adapter contract.

1.1 - Architecture & Working Principles

Understand the division of labor between the Data Plane and asynchronous ALAP review, the out-of-band analysis model, and single-binary packaging.

Traditional signature-based Web Application Firewalls rely heavily on expansive regular expression libraries. These approaches incur high rule maintenance costs and remain susceptible to bypasses via multi-layer encoding, nested syntax, and character obfuscation. Conversely, invoking Large Language Models (LLMs) synchronously within the real-time request path introduces unacceptable network latency and availability bottlenecks.

To address these challenges, CheeseWAF adopts a decoupled dual-plane architecture with asynchronous out-of-band threat review, combining deterministic, sub-millisecond blocking with deep semantic intelligence.

Dual-Plane Architecture

Data Plane

The Data Plane processes incoming HTTP/1.1, HTTPS, and HTTP/3 traffic through an ordered, high-performance pipeline:

  1. Network & Identity Filtering: Evaluates IP access control lists, GeoIP country bans, and client soft-fingerprints.
  2. Access Control & Anti-Scraping: Enforces bot challenges, sharded sliding-window counter rate limits, and waiting room scheduling.
  3. AST Semantic Analysis: Parses recursively decoded parameters into language syntax trees for attack detection.
  4. Reverse Proxying: Dispatches validated requests to the configured backend upstream servers.

The Data Plane operates strictly within the critical request path, adhering to deterministic execution and never blocking on external LLM calls.

Management Plane

The management plane provides administrative and observability capabilities through a dedicated listener endpoint:

  • /setup Initialization Wizard: Guides initial deployment and provisions administrator credentials.
  • Web Management Console: Serves a modern, responsive React-based single-page application.
  • RESTful Management API: Powers automation scripts and third-party operational integrations under the /api namespace.
  • Metrics & Observability: Exports Prometheus metrics and provides health check probes.

For security reasons, keep server.admin_public set to false unless TLS encryption is enabled and strict network-level access controls (such as IP whitelisting or private networks) are in place.

Asynchronous ALAP Threat Review

After the Data Plane completes response delivery to the client, CheeseWAF enqueues selected samples into the background ALAP (AI Large-Language-Model Auto Pilot) review pipeline:

  • High-Severity Blocked Samples: Deterministic standalone attack payloads blocked at paranoia level 5.
  • Embedded Feature Samples: Mixed-context requests allowed at paranoia levels 2–4 that contain suspicious patterns within larger text blocks.
  • Borderline Samples: Traffic marked by the semantic engine as low-confidence or near decision thresholds.

Background workers asynchronously query the configured LLM for deep contextual analysis. Security operators can review decisions in the console or enable auto-agreement to persist confirmed threats as long-term defensive rules. See ALAP and Review Queue.

Delivery Components & Single-Binary Distribution

CheeseWAF ships as a self-contained single binary (BusyBox model) delivering all core security engines, management services, and interactive utilities:

ComponentRole & Functionality
cheesewafPrimary server process; default command is serve to launch data and management listeners in one process
waf-cliSame binary (or symbolic link); default command launches the interactive TUI management panel
cheesewaf-guiLocal service controller for Windows and macOS (binds exclusively to loopback)
Web ConsoleModern React application embedded within the binary and hosted by the management listener
Storage EnginesEmbedded SQLite for management state persistence; supports external PostgreSQL for asynchronous access logs
CRP Local StagingOffline Ed25519 signature verification and content-addressed staging via crp verify and crp stage

1.2 - Deployment & Installation

Choose a CheeseWAF deployment path, prepare the host, and verify the first running service.

Use this page to choose a deployment path. For a fresh Linux server, start with the one-line installer or the verified release archive; systemd remains the path used by the quick start.

One-line installer or verified archive, a shared application root or FHS layout, and a systemd service.

Compose deployment for evaluation or environments already managed by Docker.

CLI, portable archive, or NSIS desktop installation with a local controller.

DMG desktop application or portable command-line archive.

Prepare

ItemMinimum or defaultWhy it matters
Operating systemSupported 64-bit Linux for the recommended pathThe release archive and systemd installer target Linux hosts.
CPU and memory1–2 cores and 2 GB RAM can run the lightweight profileThe setup wizard recommends a conservative profile on small hosts.
DiskSpace for the archive, Web assets, runtime data, and logsKeep runtime data outside the source/template directory.
Privilegeroot or an administrator with sudoThe installer creates the cheesewaf service account and systemd unit.
NetworkAdministration path to 9443; data-plane path to 8080Keep management and business traffic on separate access policies.
BrowserA browser that can reach the management listenerRequired for the Web setup wizard and Console.
Release integrityMatching archive and SHA256SUMS from the official source, with GitHub as the backup download sourceVerify before extracting or running the binary; stop on checksum or signature errors.

The one-line installer enables HTTPS and binds the management listener on all interfaces, then gates first setup with a one-time token and a generated security entry. Restrict 9443 to trusted administration networks before exposing it. The shipped configuration template and the setup wizard default to 0.0.0.0:9443 with server.admin_public: true; a configuration that omits the server keys falls back to the loader default 127.0.0.1:9443. A public listener still requires management TLS, a valid certificate, and a restricted source network.

On small hosts, use the lightweight profile: the setup wizard recommends low when the host has at most 2 logical cores or 2 GB RAM; a probe timeout, cancellation, or failure also falls back to low. storage.profile: production refuses to start until the production wiring is complete and does not silently fall back to SQLite.

Choose an installation mode

  • Setup / single node: the one-line installer, a verified archive with systemd, or Docker. Use this for a first deployment, evaluation, and a small self-hosted service.
  • Deploy / production: Start from the Linux or Docker guide, then add a trusted certificate, an external access policy, backups, log retention, and a tested upgrade path. See Operations.
  • Offline / air-gapped: Download the release archive, checksums, and signed resource packages on a connected machine, transfer them through your approved channel, and follow the offline section of the Linux guide.

Release files

Start with the official CheeseSec website for release downloads. The Linux installer prefers official release metadata and files, with GitHub Releases as the backup for failed downloads. Checksum or signature verification failures stop installation and must not trigger a source switch. Select the artifact that matches the target platform and architecture:

Artifact patternTarget
cheesewaf-amd64-linux-*.tar.gzLinux x86_64
cheesewaf-arm64-linux-*.tar.gzLinux ARM64
cheesewaf-loong64-linux-*.tar.gzLinux LoongArch
cheesewaf-amd64-darwin-* / cheesewaf-arm64-darwin-*macOS Intel / Apple Silicon
cheesewaf-*-windows-*Windows executable, ZIP, or setup package

Every Linux archive must include the cheesewaf binary, web/dist, configs/, the systemd unit, and install-linux.sh. Stop and download the archive again if one of these items is missing.

After installation

  1. Start the service and confirm the process owns the expected listener.
  2. Open the HTTPS setup URL printed by the installer, complete /setup, and create the first administrator.
  3. Add one test site and send test traffic through the data-plane listener.
  4. Keep the management port restricted to trusted administration networks until TLS, access control, backups, and upgrade procedures are verified.

Continue with Quick Start.

1.2.1 - Linux Deployment (systemd)

Install CheeseWAF with the one-line installer or an offline release archive, then complete first setup through the HTTPS management entry.

This guide covers Linux physical servers, cloud instances, and virtual machines. The one-line installer asks for a language, detects the CPU architecture, downloads the latest stable release from CheeseSec’s official source first, verifies its checksum, installs the systemd service when systemd is available, and prints the first-setup URLs. GitHub is the backup for failed downloads. Use the offline path when the host has no outbound access.

Summary

TEXT
One-line installer
        ↓
HTTPS setup URL printed by the installer
        ↓
Create the first administrator
        ↓
Verify service, listener, and readiness
        ↓
Onboard one test site

For a host without outbound access: download the archive and SHA256SUMS, verify the checksum, extract the complete package, and run sudo ./install-linux.sh from the package root.

Prepare

ItemRequirement
OS64-bit Linux matching the release artifact: amd64, arm64, or loong64
Resources1–2 cores and 2 GB RAM can run the lightweight setup profile; allocate more for production traffic
Privilegeroot or an administrator with sudo
DiskSpace for the archive, Web assets, runtime data, and logs
AccessA browser that can reach port 9443, possibly through a restricted network or SSH tunnel
FirewallRestrict 9443 to trusted administration networks; open the data-plane port only where business traffic needs it
Toolscurl, tar, sha256sum, systemctl, and ss

1. One-line installation (recommended)

BASH
curl --proto '=https' --proto-redir '=https' -fsSL https://cheesesec.com/install.sh | sudo bash

When already running as root, omit sudo:

BASH
curl --proto '=https' --proto-redir '=https' -fsSL https://cheesesec.com/install.sh | bash

The script reads language, install-root, and entry-name input from /dev/tty, so interactive answers are not consumed as script source. For unattended provisioning, set the documented CHEESEWAF_* environment variables and invoke the downloaded script; never put passwords or setup tokens in shell arguments or history.

Downloads and redirects must use HTTPS. The installer prefers official release metadata and files, and tries GitHub only when an official download fails. A checksum failure or a failed signature verification stops the run before extraction or installation; do not switch sources to bypass a failed check. To verify release provenance as well as the checksum, install a trusted cosign separately and set CHEESEWAF_VERIFY_SIGNATURE=1; verification requires the release workflow identity for the exact selected tag.

GitHub backup entry

If the official install.sh cannot be downloaded, use the GitHub release entry:

BASH
curl --proto '=https' --proto-redir '=https' -fsSL https://github.com/LaokeQwQ/CheeseWAF/releases/latest/download/install-linux.sh | sudo bash

This is a download fallback. It must not be used to retry an installation that stopped on a checksum or signature error.

Select a version or installation directory

To install a specific stable or beta tag, set CHEESEWAF_RELEASE (the v prefix is optional):

BASH
curl --proto '=https' --proto-redir '=https' -fsSL https://cheesesec.com/install.sh \
  | sudo env CHEESEWAF_RELEASE=v0.4.5 bash

During the interactive flow, choose an application install root after selecting the language. Entering /opt/cheesewaf, for example, places the binary, Web assets, runtime configuration, data, and logs under bin/, web/, config/, data/, and logs/ beneath that root. Press Enter to keep the split FHS layout shown below. The systemd unit remains under /etc/systemd/system unless CHEESEWAF_UNIT_DIR is overridden.

For automation, set CHEESEWAF_INSTALL_DIR before invoking the installer. Individual CHEESEWAF_PREFIX, CHEESEWAF_WEB_DIR, CHEESEWAF_CONFIG_DIR, CHEESEWAF_DATA_DIR, and CHEESEWAF_LOG_DIR values take precedence for their respective paths:

BASH
curl --proto '=https' --proto-redir '=https' -fsSL https://cheesesec.com/install.sh \
  | sudo env CHEESEWAF_INSTALL_DIR=/opt/cheesewaf bash

Install roots must be absolute dedicated directories whose path components contain only ASCII letters, digits, ., _, or -; shared system directories and paths containing shell metacharacters are rejected.

The installer will:

  1. Ask for 中文 or English and check Linux, architecture, disk space, curl, tar, sha256sum, awk, and od prerequisites.
  2. Download the selected server archive from the official source first, using GitHub only for failed downloads, and verify its single matching SHA256SUMS entry. When signature verification is enabled, verify the checksum file against the exact release tag. A failed verification stops before installation or service startup.
  3. Install the binary, Web Console, runtime configuration, and systemd unit, then create the non-login cheesewaf service account.
  4. Generate an HTTPS management listener, a one-time setup token, and a security-entry path. The entry path accepts ASCII letters and digits only; a random value is generated by default, and a custom value is accepted only when it passes the same validation.
  5. Start the service when systemd is available, check the listener and health state, and print the version, architecture, installation paths, service state, public management URL, detected private management URLs, token lifetime, and next steps. Without systemd, the files are installed but the service is reported as not started.

Save the complete setup URL printed at the end. On an interactive terminal the installer prints the public setup URL and the security-entry URL, and also prints each detected private-address setup URL. In a non-interactive run, secrets are withheld from stdout and stored in the root-only install-secrets.txt receipt under the configuration directory; set CHEESEWAF_SHOW_SECRETS=1 only when the output is protected. The setup URL envelope expires after 10 minutes. The setup token itself has no timer; it is revoked after the first successful setup or by an explicit reset. Do not paste the complete URL into tickets, screenshots, shell history, or logs.

2. First setup and public entry

Open the https:// URL printed by the installer. The setup URL always uses the fixed /setup path:

TEXT
https://PUBLIC_IP:9443/setup#setup_token=ONE_TIME_TOKEN

ONE_TIME_TOKEN is the one-time bootstrap token. The browser reads the token from the URL fragment, clears it from the address bar, and sends it in the X-CheeseWAF-Setup-Token header. The token is never placed in query parameters, cookies, or localStorage.

After setup completes, open https://PUBLIC_IP:9443/SECURITY_ENTRY. The security entry contains ASCII letters and digits only; it is generated by default or accepted as a validated custom value. The entry endpoint signs an access Cookie and redirects to the login page. Keep the setup route and the post-setup security entry as separate paths.

The management plane uses HTTPS and binds on all interfaces by default for this installation path. The installer writes the detected public host to admin.env; set CHEESEWAF_ADMIN_PUBLIC_HOST when the host has no directly assigned public address, for example behind NAT or a reverse proxy. Restrict security groups, firewalls, and any reverse proxy to trusted administration networks before exposing port 9443 to the Internet. A locally generated certificate may cause a browser warning on first access; replace it with a trusted certificate for production use.

After setup completes, the bootstrap token is invalid. If the URL is lost before an administrator is created, reset it on the host:

BASH
sudo -u cheesewaf /usr/local/bin/cheesewaf \
  --config /etc/cheesewaf/cheesewaf.yaml \
  --data-dir /var/lib/cheesewaf \
  setup token reset --show

The command prints a new URL when --show is set; without it, the URL is written to the protected setup.url file under the data directory. Adjust the paths when the service uses a custom install root. The old URL cannot be recovered.

Running the installer again against an existing configuration performs an upgrade. It keeps the existing listener, TLS settings, sites, policies, and security-entry path; choose the same install root or set the same CHEESEWAF_*_DIR overrides so the intended service is upgraded.

3. Verify

BASH
systemctl is-enabled cheesewaf
systemctl is-active cheesewaf
ss -ltnp | grep ':9443'
curl -kfsS https://127.0.0.1:9443/health/ready
sudo journalctl -u cheesewaf -n 100 --no-pager

Expected result: the service is enabled and active, the expected process owns 9443, and the readiness endpoint returns successfully. Confirm that the version and architecture match the target host. After first setup, add one protected site and configure the data-plane listener from the Console.

Standard paths

PathPurpose
/usr/local/bin/cheesewafMain binary
/usr/local/bin/waf-cliCLI symlink
/usr/share/cheesewaf/webWeb Console assets
/etc/cheesewaf/cheesewaf.yamlRuntime configuration copy
/var/lib/cheesewafLocal database, certificates, setup state, and runtime data
/var/log/cheesewafAccess and audit logs

With CHEESEWAF_INSTALL_DIR=/opt/cheesewaf, the corresponding application paths are /opt/cheesewaf/bin/cheesewaf, /opt/cheesewaf/web, /opt/cheesewaf/config/cheesewaf.yaml, /opt/cheesewaf/data, and /opt/cheesewaf/logs.

4. Offline or manual installation

On a connected machine, prefer the official CheeseSec website to obtain the architecture-specific .tar.gz, SHA256SUMS, and signature files when published. GitHub Releases is the backup download source. Keep every file from the same release, then transfer them to the target host. Verify the files in the download directory, extract the archive, and run the installer from the package root:

BASH
sha256sum --check SHA256SUMS --ignore-missing &&
tar -xzf cheesewaf-*-linux-*.tar.gz &&
cd cheesewaf-*-linux-* &&
sudo ./install-linux.sh

The packaged installer expects the matching cheesewaf, web/dist, configs/, and systemd unit in its working directory; it does not download a release by itself. Do not pipe an arbitrary script from an unverified URL into bash, and do not run the packaged installer outside its extracted package root.

The offline script still asks for the language and entry path locally, generates the setup token, and starts the service. On a host without systemd, copy the binary and web/dist into your process manager’s paths and start the service there. Keep a runtime configuration copy and a dedicated data directory; never edit the tracked configs/cheesewaf.yaml template in place.

Do not use unverified binaries, third-party mirrors, or stale installer scripts. A complete Linux archive contains cheesewaf, Web assets, configuration templates, the systemd unit, and the installer; stop and download the archive again if any item is missing.

Troubleshooting

SymptomCheckAction
cheesewaf binary not foundpwd and ls in the extracted directoryRun the packaged installer from the package root; do not extract only the binary.
web/dist/index.html missingfind web -maxdepth 2 -type fDownload the complete release archive again.
Checksum or signature verification failsCheck the selected release and matching checksum/signature filesStop installation and investigate the mismatch. Do not switch to the backup source or disable verification to continue.
Service exits immediatelysudo journalctl -u cheesewaf -b --no-pagerFix the first validation error; confirm the runtime config is a copy, not the tracked template.
Port 9443 is unreachable remotelyss -ltnp | grep ':9443'Allow 9443 from trusted administration networks in the firewall or security group, and confirm the listener and CHEESEWAF_ADMIN_PUBLIC_HOST.
Setup page loads but initialization failssudo ls -l /etc/cheesewaf/install-secrets.txtUse the setup URL from the receipt, or reset the token with sudo -u cheesewaf /usr/local/bin/cheesewaf --config /etc/cheesewaf/cheesewaf.yaml --data-dir /var/lib/cheesewaf setup token reset --show; never paste the URL into logs or tickets.
Proxy returns 502Check the configured upstream from the Console and test it from the WAF hostConfirm the origin is reachable and that the site points at the data-plane listener, not the management port.
Production storage refuses to startInspect the storage error in journalctlConfigure the required production storage; do not force a local SQLite fallback.

For Docker-specific port and data-volume behavior, use the Docker guide. For backups and upgrades, continue with Operations.

1.2.2 - Docker Compose Deployment

Deploy CheeseWAF with Docker Compose supporting read-only root filesystems and unprivileged container security.

This guide covers deploying CheeseWAF on containerized infrastructure. The repository provides a hardened Dockerfile and Compose example; the example builds the image locally. Do not treat cheesewaf:dev as a vendor-signed or registry-published image unless you have separately verified the image provenance. The runtime is configured to run as an unprivileged user (UID 10001) with a read-only root filesystem.

Compose Configuration

Reference deploy/docker/docker-compose.yml:

YAML
services:
  cheesewaf:
    image: cheesewaf:dev
    build:
      context: ../..
      dockerfile: deploy/docker/Dockerfile
    user: "10001:10001"
    restart: unless-stopped
    read_only: true
    cap_drop:
      - ALL
    security_opt:
      - no-new-privileges:true
    tmpfs:
      - /tmp:size=32m,mode=1777,noexec,nosuid,nodev
    ports:
      - "8080:8080"
      - "127.0.0.1:9443:9443"
    volumes:
      - cheesewaf-data:/var/lib/cheesewaf
      - cheesewaf-logs:/var/log/cheesewaf
    healthcheck:
      test: ["CMD", "/usr/local/bin/cheesewaf-entrypoint", "healthcheck"]
      interval: 30s
      timeout: 5s
      retries: 3

volumes:
  cheesewaf-data:
  cheesewaf-logs:

When building locally, ensure the build context points to the root of the CheeseWAF repository so both the frontend (web/) and backend Go modules build successfully. The sample 8080:8080 mapping publishes the data-plane listener on all Docker host interfaces. Put it behind an intentional firewall/reverse-proxy policy, or bind it to a controlled interface; only the admin mapping is loopback-bound by default.

Launching & Initialization

Start the container daemon and view logs:

BASH
docker compose -f deploy/docker/docker-compose.yml up -d
docker compose -f deploy/docker/docker-compose.yml logs -f cheesewaf

On initial startup, the container generates self-signed TLS certificates for the admin API. This Compose file binds the admin port to the Docker host’s loopback interface (127.0.0.1:9443), so open https://127.0.0.1:9443/setup on the Docker host. From another machine, set CHEESEWAF_SSH_TARGET to your SSH target and create a tunnel with ssh -N -L 9443:127.0.0.1:9443 "$CHEESEWAF_SSH_TARGET", then use the same local URL; if you intentionally change the port binding, apply an appropriate access-control policy. You can also run the CLI wizard inside the container:

While first-install setup is pending, the container log never prints the setup token or complete URL. It shows only the base /setup URL, the protected /var/lib/cheesewaf/setup.url path, and an opaque receipt. Read the complete URL from that mode 0600 file within its 10-minute validity period. After setup completes, the token is revoked; expired setup.url files are cleaned up.

BASH
docker compose -f deploy/docker/docker-compose.yml exec -it cheesewaf \
  cheesewaf --config /var/lib/cheesewaf/config/cheesewaf.yaml \
  --data-dir /var/lib/cheesewaf setup

Stopping containers with docker compose -f deploy/docker/docker-compose.yml down safely preserves SQLite data, certificates, and log streams inside the named volumes cheesewaf-data and cheesewaf-logs. If storage.postgresql is configured, it receives external access-log records; the Docker volume still contains the management database for the default storage.profile: temporary. The reserved production profile currently fails closed at startup.

1.2.3 - Windows Deployment

Three Windows deployment modes: Single-file CLI, Portable Zip archive, and NSIS graphical installer, plus native Windows Service integration and a loopback-only local controller.

CheeseWAF offers three distribution options for Windows, each utilizing the identical core engine and protection capabilities:

1. Single-File CLI & Native Windows Service

Designed for rapid testing, automated scripts, or native Windows Service hosting:

POWERSHELL
# Start WAF forwarder and management plane interactively
.\cheesewaf.exe serve --config .\data\config\cheesewaf.yaml --data-dir .\data

# Query running daemon status and PID lease
.\cheesewaf.exe status

# Gracefully terminate the running daemon
.\cheesewaf.exe stop

Native Windows Service Awareness

cheesewaf serve includes native Windows Service state machine integration (golang.org/x/sys/windows/svc):

  • When invoked by the Windows Service Control Manager (SCM), the process automatically identifies service mode, seamlessly handling SCM Stop and Shutdown signals with zero external service wrappers (like NSSM or WinSW).
  • The default service name is CheeseWAF.

2. Portable Zip Archive

The portable package bundles default configuration templates and compiled Web Console assets:

  1. Extract cheesewaf-amd64-windows-*.zip to your target directory (e.g., D:\CheeseWAF).
  2. Run terminal setup and start the server:
POWERSHELL
# Run the interactive setup wizard on first launch
.\cheesewaf.exe setup

# Launch the WAF daemon
.\cheesewaf.exe serve --config .\data\config\cheesewaf.yaml --data-dir .\data

When first-install setup is pending, the process log shows only the base /setup URL, the protected data\setup.url path, and an opaque receipt. Read the complete URL from the mode 0600 file within its 10-minute validity period. After setup completes, the token is revoked; expired setup.url files are cleaned up.

3. NSIS Graphical Installer (Recommended)

Ideal for workstation or production servers requiring guided installation and Windows Service registration:

  1. Run the cheesewaf-amd64-windows-*-setup.exe installer (use the arm64 variant on Windows ARM64).
  2. Follow the wizard prompts. The installer registers the CheeseWAF Windows service in manual (start= demand) mode; start or stop it explicitly from the Service Control Manager or with sc.exe.
  3. Upon uninstallation, the data\ directory containing your databases and certificates is retained by default to prevent accidental data loss.

Local Helper Controller (GUI)

cheesewaf-gui is a lightweight browser-based local controller for managing the lifecycle of the underlying service:

  • Network Security: Strictly binds only to the local loopback address 127.0.0.1:17943.
  • Key Features: Service start/stop/restart, status and PID display, direct access to the Web Console, and a shortcut to the configuration directory.
  • Process Model: The controller starts the local cheesewaf serve process when requested; it is not a second management backend.
POWERSHELL
.\cheesewaf-gui.exe --config .\data\config\cheesewaf.yaml --data-dir .\data

Once started, open http://127.0.0.1:17943/ in your browser to view the local desktop controller dashboard.

1.2.4 - macOS Deployment

Install CheeseWAF on macOS via graphical DMG package or lightweight tar.gz command-line archive.

CheeseWAF supports two primary deployment mechanisms on macOS:

1. DMG Graphical Installer

Ideal for local testing, development, and desktop workstations:

  1. Download the DMG matching your CPU architecture: cheesewaf-arm64-darwin-*.dmg for Apple Silicon (M-series), or cheesewaf-amd64-darwin-*.dmg for Intel Macs.
  2. Open the DMG image and drag CheeseWAF into your Applications folder.
  3. Launch CheeseWAF from Launchpad or Spotlight.

Gatekeeper Guidance: A release is signed and notarized only when the build has a Developer ID identity and Apple notarization credentials. The packaging script intentionally falls back to ad-hoc signing without notarization when those credentials are unavailable. Verify the exact downloaded artifact with its published signature metadata before deployment. For an ad-hoc developer build that triggers macOS security prompts, Control-click the app icon, select “Open”, and confirm the prompt.

Upon launching, the DMG application runs a lightweight browser-based local controller bound to loopback at http://127.0.0.1:17943/. It provides process start/stop/restart controls, status monitoring, and shortcuts to the Web Console and configuration directory. Default runtime data is saved under ~/Library/Application Support/CheeseWAF.

2. Command-Line Archive (tar.gz)

Ideal for headless servers, developer terminal workflows, or automated scripts:

BASH
# Extract the archive
tar -xzf cheesewaf-arm64-darwin-*.tar.gz
cd cheesewaf-*

# Run terminal setup wizard
./cheesewaf setup

# Launch the WAF daemon
./cheesewaf serve --config ./data/config/cheesewaf.yaml --data-dir ./data

If first-install Web setup is still pending, process output shows only the base /setup URL, the protected data/setup.url path, and an opaque receipt. Read the complete URL from the mode 0600 file within its 10-minute validity period. After setup completes, the token is revoked; expired setup.url files are cleaned up.

Once initialized, navigate to http://127.0.0.1:9443/ to log into the Web Console.

1.3 - Quick Start Guide

Install, initialize, verify, and protect one test site before moving to production.

This is the single-node path. It follows the same order as the product workflow: Install → Setup → Verify → Onboard.

Short version

  1. Run the official one-line Linux installer, or install the verified release archive when the host has no outbound access.
  2. Open the HTTPS setup URL printed by the installer and create the first administrator.
  3. Confirm that the service and readiness check are healthy.
  4. Add a test site and send a request through the data-plane listener.

The Web Console and deterministic data-plane protection work without an LLM. Configure ALAP only after the basic request path is healthy.

Step 1: Install

On a Linux host with sudo, run:

BASH
curl --proto '=https' --proto-redir '=https' -fsSL https://cheesesec.com/install.sh | sudo bash

The installer asks for a language and an optional application install root, downloads and verifies the latest stable release from the official source first, starts the systemd service when available, and prints the setup URLs. GitHub is used only when an official download fails; a checksum or signature verification failure stops installation. If the bootstrap script itself cannot be downloaded, use the GitHub backup entry. All downloads and redirects must use HTTPS. Enter /opt/cheesewaf to keep the binary, Web assets, configuration, data, and logs together, or press Enter for the standard FHS layout. Set CHEESEWAF_RELEASE=vX.Y.Z[-beta] when you need a specific release.

Keep the complete setup URL private. Its URL fragment contains a one-time token that the browser converts to the X-CheeseWAF-Setup-Token header; it is revoked after setup. If the server has no outbound access, download the matching release archive and checksum files on a connected machine and follow the offline section of the Linux installation guide. For Docker, use the Docker guide.

Step 2: Setup

Open the https:// URL printed by the installer. The setup route always uses the fixed /setup path:

TEXT
https://PUBLIC_IP:9443/setup#setup_token=ONE_TIME_TOKEN

Create the initial administrator and keep the management port restricted to trusted administration networks. The System Initialization page covers credential rules, setup-token handling, and the explicit requirements for public management access. If the URL is lost before an administrator exists, reset the token on the host:

BASH
sudo -u cheesewaf /usr/local/bin/cheesewaf \
  --config /etc/cheesewaf/cheesewaf.yaml \
  --data-dir /var/lib/cheesewaf \
  setup token reset --show

Step 3: Verify

Run the service and readiness checks from the Linux installation guide. The expected state is:

TEXT
systemd: enabled and active
management: https://127.0.0.1:9443 ready
data plane: 127.0.0.1:8080 available for a test site

If a check fails, use the symptom table in Linux Troubleshooting before changing configuration.

Step 4: Onboard

Configure the public domain, upstream origin, baseline policy, and a safe test request.

Optionally connect an OpenAI- or Anthropic-compatible API for asynchronous review.

Do not point production DNS at the WAF until the origin, health checks, access policy, logging, and rollback path have been tested.

CheeseWAF’s Data Plane provides deterministic AST semantic protection immediately after startup, even without an LLM connected. Before configuring the ai block, the ALAP review queue simply remains idle.

Next steps

  • Read Core Concepts to understand data-plane and management-plane boundaries.
  • Configure Security Policies for ACLs, IP controls, challenges, and rate limits.
  • Read Operations before enabling public management, external storage, backups, or upgrades.

1.3.1 - System Setup & Initialization

Initialize CheeseWAF via the browser Web wizard or the cheesewaf setup terminal command with hardware probing, profiling, and credential configuration.

Following a fresh installation, CheeseWAF requires initial administrator provisioning and hardware baseline profiling. CheeseWAF provides both a Terminal CLI Wizard and a Web GUI Wizard.

Option 1: Terminal Setup Wizard (Recommended)

Run the interactive setup command directly in your terminal:

BASH
cheesewaf setup

1. Automated Hardware Probing & Profiling

The wizard inspects host resources (logical CPU cores, visible RAM, and an 8 MiB sequential write test) and recommends a runtime profile:

  • low (Lightweight): Best for 1–2 CPU cores / 1–2 GB RAM; requests exceeding inspection budgets automatically fall back here.
  • smart (Smart, default): Recommended for standard servers (2–4 CPU cores / 4–8 GB RAM); dynamically tunes inspection depth based on request risk.
  • medium (Balanced): Fixed inspection depth 2 with a 50 ms timeout per request.
  • high (Performance): Best for 4+ CPU cores / 8+ GB RAM on core gateways; performs full deep semantic analysis.
  • custom (Custom): Allows manual tuning of inspection depth and timeout budgets.

The probe runs for at most 30 seconds. If it times out, is cancelled, or the Web probe request fails, the wizard recommends the conservative low tier. In non-interactive mode, --skip-probe also selects low unless an explicit --profile is provided.

2. Guided Credentials & Transactional Safety

  • Username: Enter a username of 3–32 ASCII characters. It must start with an ASCII letter, end with an ASCII letter or digit, and contain only ASCII letters, digits, ., _, and -. Non-ASCII characters, Unicode whitespace, control characters (Cc), and format/invisible characters (Cf) are rejected; the server preserves the exact value and does not trim or lowercase it.
  • Password: New passwords need at least 10 characters and at least 3 of 4 classes: uppercase, lowercase, non-repeating digits, and special characters. Common or simple patterns are rejected, and the password cannot equal or contain the username. The Web review step shows that a password is set; it never displays the password, a password hash, a system master key, or an administrator credential digest.
  • Optional integrations: The interactive terminal wizard can apply selected GeoIP, Prometheus /metrics, and VictoriaLogs settings when it commits the configuration. The Web wizard records integration choices in the setup draft for review; it does not apply them to the live configuration. Configure supported integrations after setup from the relevant System Settings, Storage, or Monitoring pages. The PostgreSQL option is an asynchronous access-log sink, not the management database.
  • Transactional Cleanliness: Configuration, database, certificate, and administrator state are accumulated in memory and are committed only at the final step. Aborting does not leave partial setup state. The selected CLI language is a separate user preference and may be persisted in data/cli.lang; this file is not the runtime configuration or management database.

3. Headless Scripted Automation

For CI/CD pipelines or cloud-init automation, use non-interactive command-line flags:

BASH
cheesewaf setup --yes \
  --username admin \
  --password-stdin < /etc/cheesewaf/secrets/admin_pass.txt \
  --admin-listen 0.0.0.0:9443 \
  --skip-probe

Note: In automated mode, --yes strictly requires --password-stdin to guarantee that the administrator password satisfies the credential policy. Upon completion, the wizard prints the canonical http:// or https:// panel URL according to the current administrative TLS state.

Option 2: Browser Web Wizard

1. Open the Setup URL

During initialization, open the https://PUBLIC_IP:9443/setup#setup_token=ONE_TIME_TOKEN URL printed by the installer. The setup route is always /setup; the token is one-time and short-lived.

The management plane is HTTPS and publicly reachable by default for the one-line installation path. Restrict port 9443 with cloud security groups, host firewalls, and an administrator IP allowlist before production use. Replace a locally generated certificate with a trusted certificate when the service is put on a public hostname.

The URL fragment carries a short-lived one-time token. The browser reads it, clears the address bar, and sends it only in X-CheeseWAF-Setup-Token; it is never placed in a query parameter, cookie, or localStorage. The token is revoked after setup and the protected setup.url file is removed or invalidated.

After setup, open https://PUBLIC_IP:9443/SECURITY_ENTRY. The entry contains ASCII letters and digits only, is generated by default or accepted after validation, signs an access Cookie, and redirects to the login page. Keep the setup route and the post-setup security entry as separate paths.

The setup token remains required in X-CheeseWAF-Setup-Token until setup completes, when it is revoked. If CHEESEWAF_SETUP_TOKEN was set before startup, keep that value out of logs and shell history. The browser reads setup_token from the URL fragment, clears it from the address bar, and sends it only in that header.

If you open bare /setup, paste the token from the protected file. It remains in page memory and is cleared after submission. Never put the token in a query parameter or include it in tickets, screenshots, or logs.

2. Create Root Administrator Account

Follow the on-screen steps:

  1. Enter a username that follows the canonical username rule above.
  2. Enter a password of at least 10 characters that satisfies at least 3 of the 4 password classes and does not contain the username.
  3. Review the summary. It shows the username, that the password is set, the environment check, and selected integrations; it does not display the password, a password hash, a system master key, or an administrator credential digest.

3. Configure Admin Network Boundaries

  • Keep server.admin_tls enabled and restrict ingress using cloud security groups, host firewall rules, and IP allowlists.
  • If you intentionally need loopback-only administration, override server.admin_listen to 127.0.0.1:9443 and use an SSH tunnel; this is an explicit hardening choice, not the default one-line path.

Upon completing initialization, navigating to the admin endpoint redirects to the Web Console login view. Local credentials can subsequently be managed using waf-cli or cheesewaf user.

The generated configuration may contain an update.ota.server value, but OTA is disabled by default and the current binary has no updater worker. It cannot download or install rules or binaries through OTA; keep update.ota.enabled: false.

1.3.2 - Onboard Your First Site

Configure public domain names, backend upstream origin servers, and baseline paranoia protection in CheeseWAF.

Log in to the Web console and navigate to Sites → New Site to configure your first reverse proxy service:

1. Configure Public Domains

Enter the public hostnames used by your clients (e.g., app.example.com). CheeseWAF matches incoming HTTP Host headers against the configured sites[].domains list.

2. Configure Backend Upstream Origins

Specify the origin server address and port (e.g., 10.0.0.10:8000). When multiple upstreams are defined, the system distributes traffic according to the configured load balancing policy (round_robin by default).

3. Set Baseline Paranoia Level

New sites default to paranoia level 3 (Smart Standard Mode); if the current wizard exposes this option, leave it at 3. In this mode, the system blocks high-confidence standalone payloads while allowing embedded features through to asynchronous ALAP review, ensuring business continuity while collecting threat data.

4. Save & Hot-Reload

Click Save Site. CheeseWAF dynamically reloads site definitions in memory without terminating the main daemon or interrupting active connections.

After saving, update your DNS records or local hosts file to point the domain to the CheeseWAF Data Plane listener (http://127.0.0.1:8080 by default) to verify end-to-end reverse proxy forwarding.

For health checks, automatic SSL issuance, and path rewrite configurations, see Sites & Reverse Proxy.

1.3.3 - Connect Large Language Models

Configure OpenAI- or Anthropic-compatible API endpoints for ALAP asynchronous threat reasoning and self-learning rules.

CheeseWAF’s ALAP (AI Large-Language-Model Auto Pilot) engine integrates with industry-standard LLM APIs to perform out-of-band semantic reasoning on suspicious and borderline traffic.

In the Web management console, navigate to the AI section and configure the following parameters:

SettingConfiguration KeyDescription & Examples
Enable AIai.enabledMaster toggle for ALAP functionality (boolean)
Providerai.providerAPI protocol dialect: openai or anthropic
Base URLai.api_baseAPI Base URL (e.g., https://api.openai.com/v1)
Allow Private Endpointai.allow_private_api_baseAllows connecting to private/local LLM gateways (Ollama, LocalAI; defaults to false)
API Keyai.api_keySecret access token / API key provided by your LLM vendor
Model Nameai.modelModel identifier (e.g., gpt-4o-mini, claude-3-5-sonnet-latest)
Auto-Agreementsites[].waf.semantic_policy.auto_agreeWhen enabled, threats evaluated as high or critical are automatically persisted as defensive rules

Legacy configuration migration: The old ai.base_url and ai.auto_agree keys are not read by the current release. Move ai.base_url to ai.api_base, and move the approval setting to each site’s sites[].waf.semantic_policy.auto_agree; save the configuration and reload/restart the service as required.

Best Practices & Security Guidelines

  • Enforce Asynchronous Execution: Always maintain ai.async: true in your configuration to guarantee that the Data Plane never blocks real-time traffic while waiting for model inference.
  • Connection Testing: Before enabling rules, click Test Connection in the console to validate network routing, DNS resolution, and credential authentication.
  • Gradual Rollout of Auto-Agreement: Keep sites[].waf.semantic_policy.auto_agree disabled during initial deployment. Review samples manually in the threat queue for 1–2 weeks to verify evaluation fidelity before enabling automated rule generation.

For details on assistant tool approvals, review queues, and automated self-learning, see ALAP & Review Queue.

1.4 - Core Concepts

In-depth exploration of the request processing lifecycle, paranoia level evaluation, payload isolation mechanisms, and unified access control.

This section introduces the foundational architecture and evaluation mechanics of CheeseWAF. Prior to tuning production paranoia levels or configuring advanced security policies, reviewing these concepts is strongly recommended:

Trace the end-to-end request lifecycle across network filters, access control, AST semantic inspection, and asynchronous ALAP review.

Detailed breakdown of paranoia levels 0 through 5, false-positive suppression strategies, and dynamic time-windowed auto-promotion.

Distinguish standalone attack payloads from benign context embedding, and understand targeted gadget isolation safeguards.

Understand the shared RBAC authorization model, session mechanics, and audit trail spanning the Web console, TUI, and REST API.

1.4.1 - Traffic Pipeline & Two-Phase Execution

Deep dive into the synchronous Two-Phase detection pipeline (Pre-Filters + Semantic Worker Pool) and the asynchronous ALAP offline review loop.

CheeseWAF separates traffic processing into two distinct flows: the Synchronous Detection Pipeline and the Asynchronous Out-of-Band Review Loop. Within the synchronous path, CheeseWAF employs a high-performance Two-Phase Pipeline architecture to achieve microsecond-level short-circuit drops while preserving high throughput for deep AST parsing:

flowchart TB
  Client[Client Request] --> Ingress[Ingress HTTP / HTTPS / HTTP3]
  subgraph Phase1 [Phase 1: Pre-Filters (Sequential / Short-Circuit / Priority < 290)]
    IP{IP / Geo / Fingerprint} -->|Pass| Bot{Bot Challenge / RateLimit}
    Bot -->|Pass| Rules{Custom Rules Priority 250}
  end
  Ingress --> IP
  IP -->|Blacklisted| Block[Render Block Page]
  Bot -->|Trigger Challenge| Challenge[Solve Challenge / Waiting Room]
  Challenge -->|Verified| Rules
  Rules -->|Match Block| Block

  subgraph Phase2 [Phase 2: Semantic Group (Parallel Worker Pool / Deterministic Merge / Priority >= 290)]
    Sem[AST Semantic Analyzers: SQL / XSS / RCE / LFI / NoSQL / SSTI etc.]
  end
  Rules -->|Clean| Sem

  Sem --> Shape{Payload Context}
  Shape -->|Isolated Attack Level 2~5| Block
  Shape -->|Embedded Attack Level 5| Block
  Shape -->|Embedded Attack Level 2~4| Pass[Pass & Enqueue Asynchronously]
  Shape -->|Clean| Origin[Forward to Backend Upstream]
  Pass --> Origin
  Pass -.-> Queue[ALAP Review Queue]
  Sem -.->|Level 5 Blocked Sample| Queue
  Queue --> LLM[LLM Reasoning & Attribution]
  LLM --> Review{Decision}
  Review -->|High / Critical| Rule[Generate Protective Rules]
  Review -->|Low / False Positive| Dismiss[Dismiss / Allowlist]
  Rule -.-> IP

Two-Phase Pipeline Architecture

To ensure deterministic latency guarantees under high concurrent load, the detection pipeline partitions all registered detectors by Priority into two separate execution phases:

1. Phase 1: Pre-Filters (Priority < 290)

  • Components: IP Access Control, GeoIP, Soft Client Fingerprinting, Bot Challenges, Rate Limiting, and the Custom Regex Rule Engine (Priority 250).
  • Execution Model: Strictly sequential single-threaded execution.
  • Fast Short-Circuiting: If any pre-filter returns ActionBlock, the request is immediately dropped and the pipeline terminates. The request never reaches the AST semantic parsing stage, allowing reconnaissance probes and known signatures to be discarded within microseconds.

2. Phase 2: Semantic Group (Priority >= 290)

  • Components: Deep syntax analyzers for SQL injection, Cross-Site Scripting (XSS), Remote Code Execution (RCE), Local File Inclusion (LFI), NoSQL injection, Server-Side Template Injection (SSTI), SSRF, and XXE.
  • Execution Model:
    • Shared Worker Pool: Dispatched across a shared worker pool (bounded at 8 workers) to maximize multi-core CPU efficiency without unbounded goroutine proliferation.
    • Context Forking: Each detector executes with a forked RequestContext, guaranteeing data race immunity for Metadata and Results writes.
    • Deterministic Merge: Once parallel evaluations conclude, results are merged in strict priority order, ensuring 100% deterministic decision-making and logging.

Pipeline Timeout & Budget Protection

  • 100ms Hard Timeout: A global 100ms pipeline deadline guarantees that adversarial payloads cannot cause request processing hangs.
  • Analysis Budget Depletion Policy (budget_exhausted_policy): If deep parsing cannot finish within the deadline, the fallback policy takes effect:
    • auto: Follows the global web_attack policy level.
    • open: Fails open to preserve application availability while recording metrics.
    • observe: Logs observation details without a hard drop.
    • closed: Security-first challenge or strict block.
  • Overload Guarding: Built-in guard monitors detect backpressure and return ErrDetectionOverload, protecting the primary service from cascading degradation.

Asynchronous Review Loop (ALAP)

The asynchronous path runs completely decoupled from real-time reverse proxying:

  • Sample Dispatch: Embedded samples passed under Paranoia Levels 2–4 and blocked samples under Level 5 are delivered to the review queue after response delivery.
  • LLM Intent Extraction: Background workers issue inference requests to extract threat semantics and confidence scores.
  • Closed-Loop Rule Derivation: Manual review decisions can promote a verified sample to the selected payload, URI, IP, or fingerprint rule. Site-level automated adoption is narrower: it writes a site-scoped custom payload rule only.

For detailed configuration options of individual detectors, see Protection; for setting up AI models, see ALAP Review.

1.4.2 - Paranoia Level Mechanism

Understand paranoia levels 0 through 5, differential actions for isolated vs. embedded payloads, and dynamic time-windowed promotion.

CheeseWAF allows configuring the paranoia level independently for each reverse proxy site via sites[].waf.paranoia_level. Supported values range from 0 to 5, with 3 (Standard Smart Protection) recommended as the production baseline.

The paranoia level mechanism balances high threat detection rates with false-positive suppression. When inspecting decoded parameter values, the AST semantic engine executes tiered responses based on payload morphology (Isolated vs. Embedded).

Two Independent Knobs:

  • waf.paranoia_level (0–5) drives the AST semantic engine itself—determining how strictly the engine identifies attack payload morphology (Isolated vs. Embedded features).
  • Ingress proxy enforcement actions are driven by an entirely separate setting: protection_policy.web_attack (off, low, smart, high, strict, default smart). It dictates downstream action thresholds (severity and confidence cutoffs, aggregate risk scoring, and failure policies when the 100ms detection budget is exhausted). The two controls are completely decoupled.

Paranoia Levels Comparison

LevelPolicy ProfileIsolated PayloadEmbedded PayloadAuto-Promotion
0Record OnlyLog alert & allowLog alert & allowNo
1Observation ModeLog alert & allowLog alert & allowNo
2Basic DefenseBlock immediatelyAllow, enqueue for ALAP reviewNo
3Smart Standard (Recommended)Block immediatelyAllow, enqueue for ALAP reviewNo
4Active DefenseBlock immediatelyAllow, trigger auto-promotion & reviewYes (promotes to 5)
5Strict DefenseBlock immediatelyBlock immediately, enqueue for reviewAlready maximum

Dynamic Auto-Promotion Mechanism

At Paranoia Level 4, when suspicious embedded payloads are detected within live traffic, the system proactively promotes the site to Level 5 (Strict Mode) for a configurable duration defined by promote_seconds (e.g., 300 seconds) to prevent reconnaissance-stage exploitation.

  • State Persistence: The promotion deadline timestamp is stored in local management storage and persists across service restarts; access logs can stream asynchronously to external PostgreSQL.
  • Automatic Decay: Once the promotion window elapses without subsequent suspicious triggers, the site seamlessly reverts to its baseline Level 4 configuration.

Level 5 Review Constraints

Samples blocked under Paranoia Level 5 are submitted to the ALAP review queue with a blocked status tag:

  • Non-Retroactive Release: Because the connection was physically terminated, operators cannot mutate the sample status to “Allowed”.
  • Rule Synthesis: Upon review, confirmed threats can be exported into permanent global defense rules (including signature patterns, URL path filters, IP blacklists, or client soft-fingerprints).

1.4.3 - Isolated vs. Embedded Payloads

In-depth analysis of semantic engine payload morphology evaluation, contextual boundary detection, and targeted gadget isolation coverage.

In modern web applications, user submissions vary widely in structure. In community forums, developer blogs, or technical support tickets, legitimate users frequently submit code snippets, SQL queries, or log entries. Applying strict signature matching to such content inevitably causes widespread false positives.

To resolve this challenge, CheeseWAF’s AST semantic engine evaluates the contextual proportion and structural wrapping of decoded parameter values, categorizing detections into Isolated Payloads or Embedded Payloads.

Payload Morphologies

1. Isolated Payloads

An isolated payload indicates that the parameter value consists almost entirely of an attack pattern without legitimate surrounding business text.

  • Typical Scenario: Direct inputs into search boxes or login fields such as UNION SELECT 1,2,3 or ' OR 1=1 --.
  • Wrapping Evaluation: Even when attackers prepend/append light obfuscation—such as @, trailing semicolons, or ${...} wrappers—the engine still classifies the value as isolated if the payload dominates the syntax tree.
  • Enforcement: Under Paranoia Levels 2 through 5, isolated payload detections trigger an immediate block.

2. Embedded Payloads

An embedded payload occurs when suspicious syntax constructs are enclosed within larger natural language text, documentation, or product descriptions.

  • Typical Scenario: A user posting in a technical forum discussing database tuning by quoting an example SQL query, or an article referencing a Log4j JNDI string.
  • Enforcement: Under standard paranoia levels (2–4), the engine allows the request and asynchronously enqueues the sample to ALAP, preserving user experience while maintaining vigilance. Under strict mode (Level 5), embedded hits are blocked immediately.

Gadget Coverage & Engineering Scope

To ensure complete operational clarity, the following outlines the exact engineering boundaries of the current feature isolation implementation:

  • Targeted Gadgets: Dedicated gadget isolation analyzers currently cover PHP/JSP dynamic webshells, Log4j JNDI injection, and short quoted/predicate SQL injection (constrained to fragments under 96 runes/characters).
  • Document Shape Guards: Attack vectors such as XSS, Remote Code Execution (RCE), Server-Side Template Injection (SSTI), Server-Side Request Forgery (SSRF), and XML External Entity (XXE) are evaluated by specialized Document Shape Guards, operating independently of the short-gadget analyzer.
  • Evidence Fallback: Detections classified as embedded bypass inline blocking below Level 5. Unclassified or ambiguous hits adhere strictly to deterministic blockableHit evidence rules and are never silently downgraded to embedded status.
  • Operational Guidance: Isolation mitigates false positives on known gadgets in rich-text workflows. For strictly structured API endpoints, enabling higher paranoia levels or schema validation remains recommended.

1.4.4 - Unified Management Surfaces & Authorization

Understand the shared RBAC authorization model, unified user identity, session management, and audit pipeline across the Web console, TUI, and REST API.

CheeseWAF provides three dedicated management surfaces tailored for visual operations, headless terminal maintenance, and automated CI/CD workflows:

Management SurfaceRole & Intended ScenariosAccess & Invocation
Web ConsoleVisual operations, security policy management, real-time log querying, and attack map visualizationAccess the configured HTTP/HTTPS management URL after setup. Docker Compose uses HTTPS at https://127.0.0.1:9443/ on the Docker host loopback (use an SSH tunnel for remote access).
CLI / TUIHeadless server administration, jump boxes, and rapid interactive terminal troubleshootingExecute waf-cli or cheesewaf cli to launch the interactive terminal interface
RESTful APICI/CD automation, external monitoring integration, and orchestration pipelinesInvoke /api/... endpoints using Session Cookie or Bearer API token authentication

Unified Identity & RBAC Matrix

When setup.three_end_unified: true is configured, CheeseWAF synchronizes identity and authorization across all three surfaces:

  • Universal User Credentials: Administrator and operator accounts provisioned in the Web console can be used directly for TUI login and API authentication.
  • Consistent RBAC Enforcement: API Tokens created in the console’s System Management section inherit the exact RBAC permission matrix defined in apisec.permissions.
  • Granular Roles: Built-in default roles include admin (holding full ["*"] permissions) and readonly (scoped to ["read:*", "read:cluster"]).
  • Exact identity fields: Usernames use the canonical 3–32 ASCII-character form documented in the CLI reference. Roles must exactly match configured apisec.permissions keys; leading/trailing/embedded Unicode whitespace, control characters (Cc), format/invisible characters (Cf), and permission expressions such as * or : are rejected. The server never trims or case-normalizes identity fields.

Operational Audit Trail

When apisec.audit.enabled: true is active, all configuration mutations, policy changes, and user management operations initiated via the Web Console, TUI, or REST API are written to the structured audit log specified by apisec.audit.path, ensuring enterprise-grade auditability.

Related Documentation

1.5 - Site Management & Reverse Proxy

Configure host domains, upstream load balancing algorithms (round_robin/weighted/ip_hash/least_conn), active health checks, and per-site protection policies.

In CheeseWAF, a Site is the fundamental administrative unit for reverse proxying and application security policies. A site binds inbound domain names (Host) to one or more backend origin upstreams (Upstream).

Provisioning Methods

  • Web Console: Visual configuration, upstream monitoring, and policy tuning under the Sites page.
  • RESTful API: Programmatic lifecycle automation via GET/POST /api/sites and GET/PUT/DELETE /api/sites/{id}.
  • Nginx Config Importer: Call POST /api/nginx/import to parse and import existing Nginx server blocks directly.

YAML Configuration vs. REST API Schema Note:

  • YAML Configuration (cheesewaf.yaml): Upstreams are structured objects (upstreams: [{address: "127.0.0.1:8080", weight: 1}]) and WAF settings are nested under waf.
  • REST API DTO (POST /api/sites): Uses a flat structure where upstreams is a string array (["http://127.0.0.1:8080"]) and WAF settings are flattened (waf_enabled, waf_mode, paranoia_level). Submitting nested objects directly to the REST API will return an unmarshaling error.

Site Configuration Schema

PropertyYAML Key PathType & Description
Site IDsites[].idUnique alphanumeric string identifier
Site Namesites[].nameHuman-readable site label
Bound Domainssites[].domainsString array matching the inbound HTTP Host header
Origin Upstreamssites[].upstreams[].addressBackend destination (host:port), supporting weight proportions
Dedicated Portsites[].listen_portMetadata field (for nginx import and UI display; WAF process routes traffic on primary listeners)
Load Balancingsites[].loadbalanceAlgorithm choice: round_robin, weighted, ip_hash, least_conn
Enabledsites[].enabledBoolean toggle; false halts reverse proxying for this site
WAF Enabledsites[].waf.enabledWhether request inspection is active
WAF Modesites[].waf.modeblock (drop malicious requests), monitor (record only; log accepted as alias), or off
Paranoia Levelsites[].waf.paranoia_levelInspection strictness from 0 (disabled) to 5 (maximum paranoia), default 3
Semantic Enginessites[].waf.semantic_enginesIndependent engine toggles for sql, xss, rce, lfi, xxe, ssrf, nosql, ssti
Custom Rulessites[].waf.custom_rulesSite-scoped RE2 rules (supports batch CLI and Web UI import/export)
Path Rewritingsites[].waf.rewriteInternal silent path rewrite or HTTP 3xx redirection rules
Health Checksites[].waf.health_checkActive probe path, check interval, and healthy/unhealthy thresholds
Trusted CIDRssites[].waf.access_control.trusted_cidrsFronting CDN/LB CIDR subnets for trusted client IP extraction

Load Balancing Algorithms

For sites fronting multiple backend upstreams, sites[].loadbalance provides four distribution strategies:

  1. round_robin (Default): Inbound requests rotate sequentially through all healthy upstreams. Ideal for identical backend server instances.
  2. weighted (Weighted Round-Robin): Requests are apportioned according to upstreams[].weight (e.g., a 3:1 weight distributes 3 out of every 4 requests to the primary upstream).
  3. ip_hash (Source IP Hash): Consistent hashing based on the client’s verified IP address keeps subsequent requests from the same user pinned to the same backend for session statefulness.
  4. least_conn (Least In-Flight Connections): Dynamically routes incoming traffic to the healthy upstream with the fewest active, incomplete requests, mitigating connection backlog on slow endpoints.

Upstream Health Checking

When health_check.enabled: true is set, CheeseWAF periodically issues HTTP health probes to each configured upstream path (health_check.path):

  • When probe failures reach unhealthy_threshold, the node is temporarily marked unhealthy and removed from the active routing pool.
  • Once the node recovers and consecutive successes meet healthy_threshold, traffic dispatch automatically resumes.
  • If all upstreams fail health probes, fail-open fallback may retry only a safe, empty GET or HEAD request against configured upstreams. Non-idempotent methods (such as POST/PUT) or any request carrying a body are not replayed.

Path Rewriting & Redirects

Rewriting rules define a matching regex pattern, a target replacement, and a redirect_code:

  • Silent Rewrite (redirect_code: 0): The URI path is modified transparently before reaching the backend upstream without altering the browser address bar.
  • External Redirect (redirect_code: 301 or 302): Directly responds with an HTTP redirection header to the client.

Site Custom Rules Integration

Each site manages an isolated list of custom_rules:

  • Visually configured or uploaded via the Rules page in the Web Console.
  • Automated through CI/CD pipelines, for example export CHEESEWAF_SITE_ID='site-demo'; export CHEESEWAF_RULES_FILE='rules.yaml'; cheesewaf rules import --site "$CHEESEWAF_SITE_ID" --file "$CHEESEWAF_RULES_FILE".
  • Evaluated in Phase 1 at Priority 250, short-circuiting malicious probes before syntax tree generation.

1.6 - Gateway Adapters

Go-first self-hosted gateway adapters for NGINX, Envoy, and Kubernetes, decoupling protocol translation from the core detection engine.

CheeseWAF-Adapters provides Go-first, self-hosted gateway adapters for CheeseWAF. It completely separates gateway-specific glue code from the core detection engine. By running as a lightweight daemon (adapterd) beside your reverse proxy or workload, it translates gateway-specific protocols into a standardized, versioned HTTP inspection contract and maps core security decisions back to native gateway responses.

Architecture & Design Principles

TEXT
    NGINX / Envoy / Kubernetes Gateway
                  |
                  | auth_request / ext_authz / ext_proc
                  v
    CheeseWAF-Adapters (Go, adapterd)
                  |
                  | Versioned HTTP Inspection Contract (/api/v1/adapter/inspect)
                  v
    CheeseWAF Core Daemon (Self-hosted, Go)
                  |
                  +-- Inline Synchronous Decisions (allow / block / challenge)
                  +-- Asynchronous Telemetry / Postanalytics (/api/v1/adapter/telemetry)
  • Self-Hosted & Sidecar-First: Operates without external SaaS control planes or vendor dependencies. By default, adapterd deploys as a local loopback process (127.0.0.1:9080) directly alongside the gateway.
  • Ultra-Thin Adapter Boundary: Focuses exclusively on protocol translation and response mapping. It never duplicates detectors, AST parsers, signature tables, or management state; all security decisions remain centralized in CheeseWAF core.
  • Fail-Closed by Default: When the CheeseWAF core service is unreachable or encounters timeouts, the adapter returns HTTP 503 Service Unavailable. Traffic is never silently allowed unless explicitly configured.
  • Bounded Request Body Handling: By default, request bodies are not forwarded to the core. When explicitly enabled, body inspection is capped at a strict boundary (default 64 KB). Truncated payloads are flagged with BodyTruncated=true; if the core returns allow or times out, the adapter rejects the request with HTTP 413 Request Entity Too Large.
  • Security Credentials & Network Policy: Gateway callers authenticate using the dedicated X-CheeseWAF-Adapter-Token HTTP header (never via Authorization: Bearer), restricted to validated CIDR blocks configured in CHEESEWAF_ADAPTER_TRUSTED_PROXY_CIDRS.

Versioned Inspection Contract (v1)

The adapter communicates with the CheeseWAF core via contracts/inspection/v1:

  • Inline Inspection Endpoint: Accessible by default at /api/v1/adapter/inspect, receiving normalized client metadata, TLS fingerprints, and bounded body content within a strict latency budget (default 100ms).
  • Core Security Actions:
    • allow: Permits the request and forwards it upstream.
    • block: Terminates the request and renders a configured block page or status code.
    • challenge: Triggers client verification (such as silent JS challenge or CAPTCHA).
    • log: Permits the request while recording an audit entry (normalized to monitoring mode).
  • Asynchronous Telemetry Endpoint: Hosted at /api/v1/adapter/telemetry, receiving rate-limited, best-effort events without impacting real-time forwarding throughput.

Gateway Integration Examples

1. NGINX auth_request Configuration

Use NGINX’s ngx_http_auth_request_module to authorize incoming requests with adapterd:

NGINX
# Primary business site configuration
location / {
    auth_request /cheesewaf_auth;
    auth_request_set $waf_status $upstream_status;

    # Forward to upstream application upon successful authorization
    proxy_pass http://backend_cluster;
}

# Internal authorization subrequest endpoint
location = /cheesewaf_auth {
    internal;
    proxy_pass http://127.0.0.1:9080/v1/inspect;
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
    proxy_set_header X-CheeseWAF-Adapter-Token "YOUR_SECURE_ADAPTER_TOKEN";
    proxy_set_header X-Original-URI $request_uri;
    proxy_set_header X-Original-Method $request_method;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

2. Envoy ext_authz Configuration

Configure Envoy’s external authorization HTTP filter in the filter chain:

YAML
http_filters:
  - name: envoy.filters.http.ext_authz
    typed_config:
      "@type": type.googleapis.com/envoy.extensions.filters.http.ext_authz.v3.ExtAuthz
      http_service:
        server_uri:
          uri: 127.0.0.1:9080
          cluster: cheesewaf_adapter_cluster
          timeout: 0.100s
        authorization_request:
          allowed_headers:
            patterns:
              - exact: cookie
              - exact: user-agent
              - prefix: x-
          headers_to_add:
            - key: x-cheesewaf-adapter-token
              value: "YOUR_SECURE_ADAPTER_TOKEN"
      failure_mode_allow: false
      with_request_body:
        max_request_bytes: 65536
        pack_as_bytes: true

When Envoy indicates x-envoy-auth-partial-body: true, the adapter flags the body as incomplete and rejects the request with HTTP 413 unless the core explicitly blocks it, preventing large-payload truncation bypasses.

Runtime Configuration Reference

BASH
# Launch the local adapter daemon
adapterd --listen 127.0.0.1:9080 --core-url http://127.0.0.1:8080
Variable / FlagDefault ValueDescription
CHEESEWAF_ADAPTER_LISTEN / --listen127.0.0.1:9080Local network address for the adapter daemon
CHEESEWAF_CORE_URL / --core-urlRequiredAddress of the self-hosted CheeseWAF data plane or core inspection service
CHEESEWAF_CORE_INSPECT_PATH/api/v1/adapter/inspectCore inline inspection API path
CHEESEWAF_CORE_TELEMETRY_PATH/api/v1/adapter/telemetryCore telemetry reporting endpoint
CHEESEWAF_CORE_HEALTH_PATH/healthzCore health endpoint used for /readyz probe delegation
CHEESEWAF_CORE_TOKENEmptyBearer token used by adapterd to communicate with the core
CHEESEWAF_ADAPTER_TOKENEmptyDedicated token required from gateways in X-CheeseWAF-Adapter-Token
CHEESEWAF_ADAPTER_TRUSTED_PROXY_CIDRS127.0.0.1/32,::1/128Trusted CIDR list permitted to provide forwarded client IP headers
CHEESEWAF_ADAPTER_REQUEST_TIMEOUT100msMaximum execution budget for inline decisions
CHEESEWAF_ADAPTER_FAIL_MODEclosedFail mode when core is offline: closed (HTTP 503) or open (HTTP 204)
CHEESEWAF_ADAPTER_FORWARD_BODYfalseEnables bounded request body inspection
CHEESEWAF_ADAPTER_MAX_BODY_BYTES65536Maximum body capture limit (64 KB)
CHEESEWAF_ADAPTER_FORWARD_SENSITIVE_HEADERSfalsePermits forwarding credentials (Cookie/Authorization) to the core

Roadmap

  1. Streaming Protocol: Envoy ext_proc adapter for streaming inspection of large request bodies and dynamic response header mutations.
  2. Kubernetes Integration: Dedicated Kubernetes Sidecar Controller supporting automated injection and routing via Pod Annotations.
  3. Ecosystem Gateways: Native integrations for Kong, Apache APISIX, and Traefik.

1.7 - Security Protection Policies

Complete guide to the AST semantic engine, custom regex rules, IP/GeoIP filtering, bot challenges, sharded sliding-window counter rate limits, ACLs, and block pages.

CheeseWAF provides a defense-in-depth architecture spanning from network-level controls to application semantic analysis. Baseline protection policies are defined globally in protection and protection.policy, with support for granular per-site overrides via sites[].waf.protection_policy.

Recursive parameter decoding, abstract syntax tree analysis, engine toggles, and analysis budget control.

High-performance regular expression matching on URIs, headers, and parameters with priority ordering.

IP access lists, ISO GeoIP country restrictions, threat intelligence synchronization, and client soft-fingerprinting.

Silent JavaScript challenges, PoW (Altcha), interactive slider/image CAPTCHAs, and waiting room scheduling.

High-performance sharded sliding-window counter rate limiting on the Data Plane with queue and drop actions.

Pre-built modern block templates, custom HTML branding upload, and Trace ID request tracking.

1.7.1 - AST Semantic Analysis Engine

Modern web attack detection engine based on multi-layer recursive decoding and Abstract Syntax Tree (AST) grammar analysis, achieving 97.08% TPR on external benchmark corpora.

CheeseWAF’s primary detection capability is powered by an Abstract Syntax Tree (AST) grammar analysis architecture rather than traditional brittle regular expressions. Inbound payloads undergo multi-layer recursive decoding (URL encoding, Unicode normalization, hex, and nested Base64) before being parsed into domain-specific syntax trees to evaluate true payload semantics.

Through systematic evaluation and remediation against 7 external real-world corpora using an independent Corpus Fidelity Classifier, the semantic engine achieves an independently verified 97.08% True Positive Rate (TPR).

Engine Configuration Matrix

Individual specialized semantic engines can be toggled per site via sites[].waf.semantic_engines:

Engine KeyAttack Scope & Deep Detection Capabilities
sqlSQL Injection: Major SQL dialect grammar parsing; integrated XPath injection parser; heavy time-blind injection detection (Cartesian product / generate_series); whitespace comment truncation resilience
xssCross-Site Scripting: HTML/SVG tag balance analysis; fully split protocol scheme detection (detects scattered tokens like j a v a s c r i p t: and CDATA/HTML comment interspersal); obfuscated javascript: URI concatenation regex; dynsrc/lowsrc attribute probes; JavaScript string escaping; malformed event handler inspection
rceCommand & Code Injection: Comprehensive command table alignment (including id, ls, echo, netstat, lsof); newline command chains; automatic basename extraction for absolute executable paths; ; + system function calls
lfiFile Inclusion & Path Traversal: POSIX and Windows absolute path traversal (smart Program Files exclusion to eliminate false positives); deep UTF-8 folding; SSI server-side includes (<!--#exec)
nosqlNoSQL Injection: Deep HTTP request header analysis (e.g., X-User-Filter); MongoDB shell escaping; isolation of malicious operators from legitimate query filter operators
sstiTemplate Injection: Jinja2, Twig, and common template grammar trees; quoted operand probes; direct expression detection when entire value is a template expression
ssrfServer-Side Request Forgery: URI parameter schema inspection; full request body URL detection treating the whole body as a potential fetch sink
xxeXML External Entity: DOCTYPE entity declarations, SYSTEM/PUBLIC external resource references, and parameter entity attacks
webshellWebshell & Malicious Scripts: Combines PHP execution primitive analysis with Shannon entropy measurement ($\ge$ 5.2) to accurately flag high-entropy Base64 one-liners and obfuscated droppers while eliminating false positives on repeated strings, JWT tokens, and minified code

In production, keeping core engines enabled is recommended. If a service clearly lacks a specific stack (such as a static site without SQL backends), disabling that engine saves CPU cycles.

Latency Engineering & Pre-Filter Gating

To deliver deep syntax parsing without sacrificing microsecond-level latency, CheeseWAF employs several algorithmic safeguards:

  • Cheap Substring Gating: Prior to expensive AST generation or complex regular expressions, constant-time substring pre-filters discard benign traffic in microseconds.
  • Worker Pool & Request Context Forking: In Phase 2, semantic analyzers run concurrently over bounded worker goroutines with isolated context copies, merging results deterministically by priority.
  • 100ms Hard Budget Deadline: If oversized adversarial inputs consume parsing time, the global deadline prevents request processing hangs and triggers the configured fallback policy.

Analysis Budget & Allowlists

Fine-grained controls in sites[].waf.semantic_policy allow tuning parsing behavior:

  • budget_exhausted_policy: Fallback action when syntax analysis exhausts its budget: auto (derives from web_attack level), open (availability-first pass), observe (log only), or closed (challenge/strict block).
  • path_allowlist: URI path prefixes that bypass semantic analysis entirely.
  • param_allowlist: Parameter keys excluded from deep AST inspection.

Migration note: The canonical location is sites[].waf.semantic_policy.budget_exhausted_policy. Values left in older, non-canonical configuration locations are not read; move them manually under each site’s waf.semantic_policy block. When migrating legacy values, map pass to open, and map block or challenge to closed (the current closed mode prefers a challenge when analysis cannot finish). Leave the field empty or set it to auto to derive the effective action from the site’s web_attack level.

Global limits can be configured in sites[].waf.performance, including max_body_bytes (default 8MB), max_header_bytes, and proxy_timeout.

Outbound Response Inspection (Data Leak Prevention)

sites[].waf.response inspects upstream HTTP response bodies to prevent sensitive credential exposure:

  • Detection Scope: Discovers AWS Access Keys, generic leaked credential patterns, and any additional patterns configured for the site. The built-in default set includes password/secret-key patterns; PEM private-key detection is available when explicitly included in sensitive_patterns (the shipped site template does not enable it by default).
  • Pattern Precedence: When sites[].waf.response.sensitive_patterns is non-empty, it replaces the built-in defaults rather than extending them; include every pattern you need in the site-level list.
  • Tuning Advice: For large file downloads or streaming media, restrict response inspection to JSON/HTML content types via path patterns.

For classification semantics regarding isolated attacks vs embedded long-text inputs, see Isolated vs. Embedded Payloads.

1.7.2 - Custom Regex Rules

High-performance Go RE2 regular expression rules with priority ordering, target location matching, strict validation limits, and batch import/export.

The Custom Rule Engine operates as a Phase 1 Pre-Filter in the request pipeline (engine priority 250). It executes prior to the AST Semantic Analysis Engine (priority 290+). Custom rules are designed to intercept high-frequency reconnaissance, scanner headers, and custom application path blocks. When a rule triggers with a block action, execution short-circuits immediately, eliminating unnecessary AST parsing overhead.

You can manage custom rules visually in the Rules section of the Web Console (sites[].waf.custom_rules), via the cheesewaf rules CLI utility, or using REST APIs.

Configuration Example

YAML
custom_rules:
  - id: "block-admin-probe"
    name: "Admin path probe"
    pattern: "(?i)/(wp-admin|phpmyadmin|\\.git)"
    location: "uri"
    action: "block"
    severity: "medium"
    enabled: true
    priority: 180
  - id: "challenge-bot-header"
    name: "Challenge suspicious scraper header"
    pattern: "(?i)(headlesschrome|phantomjs)"
    location: "header"
    action: "challenge"
    severity: "high"
    enabled: true
    priority: 200

Field Reference & Valid Enumerations

FieldTypeDescription & Validation Constraints
idStringGlobally unique rule ID within the site. If omitted during import, the engine generates one automatically
nameStringHuman-readable rule title for logging and UI display
patternStringRegular expression pattern (Go RE2 syntax; max 16KB per pattern, max 4096 compiled instructions)
locationStringTarget inspection location. Strictly limited to: uri, query, header, body, cookie (default uri)
actionStringAction on match. Strictly limited to: block, log, challenge (default block)
severityStringThreat level: low, medium, high, critical (default medium)
priorityIntegerRule execution priority (-1,000,000 to 1,000,000). Lower numbers execute first
enabledBooleanRule enable flag (default true)

Deterministic Enforcement & Policy Bypass

Custom rules represent explicit administrative intent rather than probabilistic detector signals. Within the data plane pipeline:

  • Direct Execution: When a request matches a custom rule, the engine unconditionally and immediately executes the designated action (block, challenge, or log).
  • Exempt from Policy Thresholds: Unlike semantic detections, custom rule actions bypass protection_policy.web_attack gates (such as minimum severity thresholds, model confidence filters, or aggregate risk score ceilings), guaranteeing deterministic enforcement as configured.

Security Constraints & Quota Limits

To prevent malformed or unbounded rules from causing performance degradation, the configuration validator enforces strict boundaries:

  • Resource Limits: A single site supports up to 256 custom rules (maxCustomRulesCount = 256). Import document size must not exceed 1MB, and total pattern length across all rules cannot exceed 256KB. The imported document must explicitly define the custom_rules root key.
  • ReDoS Immunity: Backed by Go’s regexp (RE2 guarantees linear-time execution, eliminating catastrophic backtracking ReDoS). Expressions exceeding 4096 compiled program instructions are rejected.
  • Deduplication Check: Rule IDs must be unique within each site. Duplicate location + pattern combinations are strictly rejected.
  • Content-Disposition Sanitization: When exporting rule archives (GET /api/rules/export), output filenames are strictly sanitized against an [A-Za-z0-9._-] whitelist, preventing HTTP response header injection and directory traversal attacks.

Batch Import, Export & Template Generation

CheeseWAF provides seamless CLI and Web UI workflows for importing and exporting rules in YAML and JSON:

1. CLI Management

BASH
# Generate official custom rule YAML template
cheesewaf rules example --format yaml --file template.yaml

# Validate and replace custom rules for a target site (triggers smooth daemon hot-reload)
cheesewaf rules import --site site-prod-01 --file new-rules.yaml

# Export custom rules of a site to JSON
cheesewaf rules export --site site-prod-01 --format json --file rules-backup.json

2. Web Management Console

In the Rules page of the Web Console, click the Import / Export button in the header:

  • Drag and drop or upload local .yaml or .json rule definition files.
  • Inspect syntax validation and preview differences prior to committing.
  • Download a full JSON or YAML rule backup with a single click.

Operational Best Practices

  • Focus on Definitive Signatures: Use custom rules for known static probes (admin interfaces, sensitive files, scanner fingerprints). Defer complex application injection patterns (SQL injection, XSS) to the AST semantic engine.
  • Leverage Short-Circuiting: Order high-confidence malicious signatures with lower priority numbers to drop bad traffic early, minimizing server CPU load.

1.7.3 - IP, GeoIP & Client Fingerprinting

Configure IP whitelists and blacklists, GeoIP country restrictions, threat intelligence feed synchronization, and client soft-fingerprinting.

CheeseWAF enforces network-layer access controls at the outermost boundary of the request pipeline. Manage these controls visually under IP in the Web console, or define them in the configuration file under protection.ip.

Static Access Lists & Base Configuration

YAML
protection:
  ip:
    whitelist: ["127.0.0.1", "::1"]
    blacklist: []
    access_rules: []
    reputation_overrides: {}
    tags: {}
    threat_intel: []
    geoip:
      enabled: false
      database: "./data/GeoLite2-Country.mmdb"
      blocked_countries: []
  • IP Whitelist (whitelist): Matching client IPs bypass subsequent IP restrictions, GeoIP rules, threat intel, bot challenges, and rate limiting (the semantic engine pipeline continues to inspect payloads for application security).
  • IP Blacklist (blacklist): Matching client IPs are blocked at the network entry point, returning a block page without consuming semantic engine resources.

GeoIP Country Restrictions

Block traffic from specific countries using offline MaxMind MMDB databases:

  1. Set geoip.enabled to true.
  2. Point geoip.database to a valid Country MMDB file path (e.g., ./data/GeoLite2-Country.mmdb).
  3. Specify ISO 3166-1 alpha-2 two-letter country codes in blocked_countries (e.g., ["US", "RU"]).

Threat Intelligence Integration

Import third-party threat intelligence IP feeds directly into CheeseWAF. The Web console supports automated scheduled synchronization, manual updates, and connectivity tests. Query intelligence status for specific IPs via the REST endpoint POST /api/ip/threat-intel/lookup.

Client Soft-Fingerprinting & Trusted Proxies

  • Client Soft-Fingerprints: The Data Plane computes lightweight fingerprints based on client User-Agent and Accept-Language headers (sha256 8-byte prefix). ALAP review can persist malicious fingerprints as defense rules to serve as corroborating evidence.
  • Trusted Upstream Proxies: When CheeseWAF is deployed behind a CDN, cloud load balancer, or reverse proxy, configure sites[].waf.access_control.trusted_cidrs or trusted_proxy_providers to correctly extract client IP addresses from X-Forwarded-For headers.

1.7.4 - Bot Challenges & CAPTCHA Mitigation

Configure silent JavaScript challenges, Proof of Work (Altcha), slider and image CAPTCHAs, management console defense, and waiting room scheduling.

Modern web applications constantly face malicious automated traffic, including AI web scrapers, credential stuffing attacks, and automated vulnerability scanners. CheeseWAF provides multi-layered bot mitigation and challenge capabilities. Configure policies in the Web console under Bot Challenge and CAPTCHA Lab, or declare them in protection.bot and console.login.captcha.

Traffic Challenge Configuration

YAML
protection:
  bot:
    enabled: false
    js_challenge: true
    captcha: true
    captcha_type: "slider"
    cookie_name: "cheesewaf_js_clearance"
    path_prefixes: ["/login", "/register", "/api/order"]
    exempt_path_prefixes: ["/health", "/static"]
    suspicious_user_agents: ["curl", "sqlmap", "nuclei"]
Configuration ParameterDescription
js_challengeIssues silent JavaScript challenge and sets clearance cookie upon validation
captchaOverlays interactive CAPTCHA validation on top of JS challenge
captcha_typeChallenge mechanism: pow (Proof of Work), slider (sliding puzzle), or image (character glyphs)
cookie_nameName of the authorization clearance cookie; defaults to cheesewaf_js_clearance
path_prefixesList of URI path prefixes where challenges are strictly enforced
exempt_path_prefixesWhitelist of URI prefixes exempt from challenges (e.g., /health)
suspicious_user_agentsUser-Agent substring matches that immediately escalate to full human verification

Do not check challenge signing secret values into version control. When the value is empty or a known placeholder, setup/startup generates a strong runtime secret and persists it in the protected runtime configuration or runtime secret file according to the selected deployment; it is not an in-memory-only guarantee. Keep the runtime path and permissions private.

Challenge Types & Interaction Mechanisms

  • Proof of Work (PoW / Altcha): Clients compute a cryptographic hash challenge in the browser background and submit the nonce via the X-CheeseWAF-Altcha request header. This is fully frictionless for real users while making automated concurrent scraping computationally prohibitive.
  • Sliding Puzzle (Slider): Analyzes mouse drag trajectories and validates minimum drag timing thresholds (configured via slider_captcha_*).
  • Character Image (Image): Supports configurable string lengths, image dimensions, and audio assistance limits.
  • Experimental Behavioral Tests: Includes gesture curves, scratch-off, and icon point-and-click puzzles. Verify user experience in the console CAPTCHA Lab before rolling out to production traffic.

Custom background images and iconography can be uploaded via /api/captcha/assets.

Management Console Login Defense

console.login.captcha protects the Web Management Console login endpoint (completely isolated from business data plane traffic), supporting slider puzzles with optional PoW verification.

The source template enables the management-login slider CAPTCHA by default (console.login.captcha.enabled: true). After initialization, the first browser login therefore requires completing the human-verification challenge in addition to the username and password. For local test fixtures only, set console.login.captcha.enabled: false in a runtime configuration copy and restart; do not disable this control in production merely to bypass acceptance checks.

Additionally, enable console.login.security_entry to obscure the management portal behind an obfuscated path and pre-shared authorization cookie.

Waiting Room Queue Scheduling

Enable waiting_room: true and specify waiting_room_max_active to gracefully hold excess concurrent clients in an organized queue during flash sales or traffic surges, preventing origin resource exhaustion. The waiting room is effective only when the global protection.policy.bot_cc policy is not off and its action is challenge; enabling the site waiting-room flag alone is not sufficient. See Rate Limiting.

1.7.5 - Rate Limiting & Traffic Shaping

High-performance sharded sliding-window counter rate limiting on the Data Plane with queueing and rejection handling.

CheeseWAF integrates a high-performance sharded sliding-window counter rate limiting algorithm on the Data Plane to smooth out traffic spikes and mitigate HTTP flood / CC attacks. Configuration is located under protection.ratelimit, and can be updated dynamically via PUT /api/protection/ratelimit.

Base Configuration Example

YAML
protection:
  ratelimit:
    enabled: true
    default:
      requests: 100
      window: 60s
      burst: 20
ParameterTypeDescription
enabledBooleanMaster switch for Data Plane rate limiting
requestsIntegerBaseline request quota permitted within the rolling window
windowDurationCalculation time window (e.g., 60s, 1m)
burstIntegerExtra burst capacity accommodating temporary traffic surges

This module enforces global/client-level traffic shaping on the Data Plane. For fine-grained rate limits targeting specific API endpoints (HTTP method + path), see API Security Rate Limits.

Limit Exceeded Actions

When a client’s request rate exceeds the sharded sliding-window counter capacity, the system executes one of the following actions:

  1. HTTP 429 Block Page: Responds immediately with HTTP 429 Too Many Requests and a customized error page.
  2. Waiting Room Scheduling: If Waiting Room Mechanism is active and the global protection.policy.bot_cc policy is enabled with action challenge, excess requests are smoothly queued rather than dropped.

During initial rollout, use generous limits and observe 1–2 weeks of production traffic before tightening requests and burst thresholds.

1.7.6 - Access Control Lists (ACL)

Rapid request filtering and denial based on HTTP methods, URI path prefixes, and request headers.

Access Control Lists (ACL) execute at the front of the traffic processing pipeline, offering ultra-low overhead filtering to immediately reject known diagnostic endpoints, probe paths, or enforce mandatory request headers. Configure ACLs under protection.acl, or update them dynamically via PUT /api/protection/acl.

Configuration Example

YAML
protection:
  acl:
    enabled: true
    rules:
      - id: "deny-debug"
        name: "Deny debug endpoints"
        method: ""
        path_prefix: "/debug"
        header: ""
        header_value: ""
        action: "block"
        severity: "high"
        enabled: true

Schema Attributes

FieldDescription
methodTarget HTTP method (e.g., GET, POST); leave empty to match any method
path_prefixMatching URI path prefix (e.g., /debug, /actuator)
headerHTTP header key to evaluate; leave empty if unconstrained
header_valueExpected or rejected value for the specified header
actionAction on match: block, log, or challenge
severityThreat severity recorded in security logs and audit events

ACL evaluates enabled rules in declaration order, using case-normalized method checks, literal URI-prefix comparisons, and exact case-insensitive header-value comparisons. For complex regex-based pattern matching, use Custom Regex Rules.

1.7.7 - Block Pages & HTML Sanitization

Configure responsive block page templates, upload custom HTML designs, SanitizeBlockPageHTML anti-XSS policy, and Trace ID request tracking.

When an inbound request is blocked by IP reputation, ACLs, Bot defense, or the AST semantic engine, CheeseWAF renders a structured block page response. Managed under block_page, templates can be visually previewed, edited, and deployed within the Block Pages view in the Web Console.

Basic Configuration

YAML
block_page:
  template_id: "minimal"
  custom_enabled: false
  custom_html: ""

Template Lifecycle & Sandboxed Previews

  • Built-In Modern Designs: Enumerate built-in response templates via GET /api/block-pages/templates.
  • Sandboxed Rendering: Preview custom templates safely in an isolated iframe (POST /api/block-pages/preview) prior to publishing globally.
  • Custom HTML Uploads: Call POST /api/block-pages/upload to upload custom branding, or revert to defaults via DELETE /api/block-pages/custom.

HTML Sanitization Standards (SanitizeBlockPageHTML)

To prevent custom block pages from introducing Stored XSS or phishing vectors, CheeseWAF enforces strict sanitization on all custom HTML inputs before persistence:

1. Tag Whitelist

Only safe layout and typographic tags are permitted:

  • Structure: html, head, body, title, main, section, header, footer, div, span
  • Typography: h1–h6, p, strong, em, b, i, small, pre, code, br, hr
  • Lists & Tables: ul, ol, li, table, thead, tbody, tfoot, tr, th, td
  • Assets & Style: a, img, style, meta

2. Active Script & Event Stripping

  • Zero Scripts: All <script> elements and HTML comments are completely removed.
  • Event Handler Neutralization: Attributes prefixed with on (e.g., onclick, onload, onerror) are excised.
  • Form Action Protection: formaction, action, and method attributes are stripped to prevent credential-harvesting forms.
  • Redirect Prevention: <meta> elements only permit the charset attribute; http-equiv="refresh" and arbitrary header injections are rejected.

3. CSS Style Sanitization

  • @import rules inside <style> tags or inline style attributes are stripped.
  • Risky CSS primitives such as javascript:, vbscript:, expression(, behavior:, and -moz-binding are removed.

4. URL Scheme Controls

  • The href and src attributes are strictly restricted to http, https, mailto, and tel.
  • <img> elements additionally support embedded Base64 image payloads (data:image/*;base64,...); arbitrary data URIs are discarded.

Traceability & Operational Guidelines

  • Global Trace ID Correlation: Block pages dynamically display a unique request traceId. When users report false positives, operators can correlate the exact rule evaluation chain under Monitoring & Logs.
  • Information Leakage Prevention: Custom block templates should avoid revealing backend hostnames, private IPs, or internal technology stacks to external clients.

1.8 - API Security & Governance

Automated API asset discovery, request schema structure validation, JWT/JWKS authentication, route-level rate limiting, and RBAC policies.

With the widespread adoption of single-page applications and microservices, API endpoints represent a primary attack surface. CheeseWAF’s API Security module delivers automatic endpoint discovery, strict contract schema validation, stateless JWT authentication, and route-level rate limiting.

Configure settings visually in the Web console under API Security, or define them in configuration files under the apisec block.

1. Automated API Asset Discovery

When apisec.discovery.enabled: true is active, CheeseWAF samples live request streams across window intervals up to sample_limit volumes, automatically clustering URI paths into an API asset inventory:

  • Static Path Filtering: Configure ignore_prefixes to exclude static assets (such as /static, *.css, or image paths).
  • Asset Query Endpoint: Invoke GET /api/apisec/endpoints to retrieve the current inventory of discovered endpoints and traffic statistics.
  • Contract Testing: Invoke POST /api/apisec/validate to validate a test request against registered schemas.

2. Request Schema Validation

Schema validation enforces strict structural contracts on incoming requests, preventing unauthorized parameter injection and parameter pollution:

YAML
apisec:
  validation:
    enabled: true
    schemas:
      - id: "api-search"
        method: "GET"
        path_pattern: "^/api/search$"
        required_params: ["q"]
        required_headers: []
        max_body_bytes: 0
        enabled: true

Supports validation of HTTP methods, path regular expressions, mandatory query/body parameters, mandatory HTTP headers, and maximum allowable body payload sizes (max_body_bytes).

3. JWT & JWKS Authentication

Enforce stateless JSON Web Token authentication at the proxy layer via apisec.auth:

  • Claim Verification: Validates cryptographic signatures, token issuers (iss), audiences (aud), timestamps (exp/nbf), and allowed signing algorithms.
  • Key Providers: Supports symmetric shared secrets, local PEM certificate files, inline PEM strings, local JWKS files, and remote jwks_url endpoints.
  • Automated Caching & Rotation: Remote JWKS keys are cached locally in jwks_cache_file and automatically refreshed according to jwks_refresh_interval.

4. Route-Level Precision Rate Limiting

Unlike global Data Plane sharded sliding-window counter limiting, API rate limiting applies strictly to specific HTTP method and path combinations (such as sensitive authentication or SMS dispatch endpoints):

YAML
apisec:
  rate_limits:
    - id: "login-api"
      method: "POST"
      path_pattern: "^/api/auth/login$"
      requests: 10
      window: 1m
      enabled: true

5. RBAC Permission Matrix

apisec.permissions defines role-based access control mappings for the management plane:

YAML
apisec:
  permissions:
    admin: ["*"]
    readonly: ["read:*", "read:cluster"]

For the mapping between permission identifiers (such as read:sites, write:protection, manage:api_tokens) and REST API endpoints, see RESTful API Reference.

1.9 - Edge Optimization: Headers, Caching & Compression

Edge HTTP header rewriting, static resource proxy caching, and Brotli/Gzip response payload compression.

CheeseWAF provides edge acceleration capabilities at the reverse proxy layer to optimize response latency and reduce origin bandwidth consumption. Manage these settings visually under Edge in the Web console, or define them in configuration files under the edge block.

1. HTTP Response Header Rewriting

YAML
edge:
  headers:
    enabled: true
    rules:
      - id: "set-edge-marker"
        operation: "set"
        header: "X-CheeseWAF"
        value: "edge"
        enabled: true
      - id: "remove-origin-leak"
        operation: "delete"
        header: "X-Origin-Secret"
        enabled: true
  • Set Headers (set): Appends custom tracking or security headers (e.g., X-Content-Type-Options: nosniff).
  • Strip Headers (delete): Removes sensitive internal origin response headers (such as Server, X-Powered-By, or internal debug tokens) before responses reach the public internet.

2. Static Asset Proxy Caching

YAML
edge:
  cache:
    enabled: true
    mode: "public"
    ttl: 5m
    status_codes: [200, 304]
    path_prefixes: ["/assets/", "/static/"]
    max_body_bytes: 2097152
  • Path Targeting: Specify path prefixes in path_prefixes strictly for purely static assets (e.g., CSS, JS, fonts, images).
  • Security Caution: Never configure caching rules for authenticated dynamic API endpoints or personalized HTML pages.

3. High-Efficiency Response Compression

YAML
edge:
  compression:
    enabled: true
    algorithms: ["br", "gzip"]
    level: 5
    min_bytes: 1024
  • Compression Algorithms: Supports Brotli (br) and standard Gzip (gzip) algorithms.
  • Trigger Conditions: Responses are compressed only when payload sizes exceed min_bytes (e.g., 1024 bytes) and match defined MIME types (text/*, application/json, application/javascript, image/svg+xml).

1.10 - TLS & Certificate Management

Management plane TLS encryption, business site HTTPS certificate configuration, ACME automated issuance, HTTP/3, and HSTS policies.

CheeseWAF provides comprehensive TLS/HTTPS cryptographic capabilities, covering secure transport encryption for the management plane as well as automated certificate provisioning, renewal, and HTTP/3 support for business traffic.

Manage certificates visually in the Web console under SSL, or configure settings under server.admin_tls and tls.

1. Management Plane TLS Configuration

YAML
server:
  admin_tls:
    enabled: false
    cert_file: "./data/certs/admin.crt"
    key_file: "./data/certs/admin.key"
    self_signed: true
  • Container Default Behavior: The Docker deployment image enables management TLS by default, generating a self-signed certificate upon initial container launch.
  • Production Requirements: If the management plane is exposed over public networks, replace self-signed certificates with a trusted CA-signed certificate.

2. Business Site TLS & HTTP/3 Configuration

YAML
tls:
  auto_cert: false
  cert_file: "./data/certs/site.crt"
  key_file: "./data/certs/site.key"
  min_version: "1.3"
  hsts: true
  • Data Plane Listeners: Configure server.listen_tls to enable an HTTPS ingress listener; it has no default value and remains disabled until explicitly set. Enable HTTP/3 with server.http3.enabled: true; server.listen_http3 may be set explicitly and otherwise falls back to the TLS listener (or :443 when neither address is set).
  • TLS Version Constraints: Use min_version to enforce minimum protocol versions (e.g., 1.2 or 1.3).
  • HSTS Enforcement: Setting hsts: true automatically injects the Strict-Transport-Security header into outbound responses.
  • HTTP/3 (QUIC) Support: Set server.http3.enabled: true to enable UDP-based HTTP/3 support (requires an active TLS listener).

3. ACME Automated Certificate Issuance & Renewal

CheeseWAF natively supports the ACME protocol for automated certificate management (e.g., Let’s Encrypt):

  1. Query DNS Providers: Call GET /api/acme/providers to list the DNS API challenge providers that are configured and enabled in the running instance; this is not a catalog of every provider supported by the implementation.
  2. Issue Certificates: Invoke POST /api/sites/{id}/acme/issue for a site to automatically perform DNS challenge verification and bind the issued certificate.
  3. Secure Key Storage: ACME account private keys and generated certificates are persisted securely in the runtime data directory; do not commit them to Git.

1.11 - ALAP Asynchronous Review & Self-Learning

Asynchronous LLM threat review queue, automated rule adoption with fail-closed guarantees, AI assistant tool approvals, and self-learning analytics.

ALAP (AI Large-Language-Model Auto Pilot) serves as CheeseWAF’s out-of-band analytical brain. By decoupling LLM semantic reasoning from real-time proxying, it introduces generalized intelligence without introducing latency into the forwarding data path.

Configured under the ai block, capabilities are managed across the AI Settings and Threat Review sections of the Web Console.

1. Asynchronous Queue & Concurrency Claims

After response delivery completes, boundary samples and embedded attacks are pushed to the background review queue:

  • Protocol Adapters: Background workers adapt prompts to OpenAI Chat Completions or Anthropic Messages protocols according to ai.provider.
  • Decoupled Guarantee: ai.async: true ensures real-time traffic forwarding never blocks on third-party model inference.
  • Concurrency Decision Claims: When multiple operators collaborate, the persistence layer uses atomic decision claims (review_decisions locks) to prevent race conditions and duplicate actions, while bounding queue retention.

2. Threat Triage & Operator Decisions

Security teams can audit and act upon threat findings via the console or REST API:

  • Queue Inspection: Call GET /api/review to fetch flagged samples and model confidence scores.
  • Decision Submission: Call POST /api/review/{id}/decide to mark samples as verified threats, false positives, or promote them to persistent protection rules.
  • Strict Invariance: Payloads blocked under Paranoia Level 5 represent physically terminated connections and cannot be retroactively passed. An operator may still submit a separate review decision (payload/URI/IP/fingerprint) to create the selected rule.

3. Automated Rule Adoption & Fail-Closed Guardrails

When sites[].waf.semantic_policy.auto_agree: true is enabled, the system automatically translates high-confidence malicious assessments (high or critical) into a site-scoped custom payload rule. Auto-agreement itself does not create global IP denylists or client-fingerprint bans; those remain separate, explicit operator actions.

Fail-Closed Invariance: Proposed rules that fail syntax validation, lack clear site associations, or fall below confidence thresholds fail closed. The engine never injects unverified rules into the active data plane.

4. AI Copilot Tool Approvals & Replay Protection

CheeseWAF includes a streaming AI copilot (POST /api/ai/assistant using Server-Sent Events):

  • Actor & Preview Binding: When the assistant generates actions affecting network bindings, site definitions, or rule tables, it requires explicit approval via /api/ai/tools/approvals. Approval tokens are cryptographically bound to the authenticated operator (actor), the exact parameter preview fingerprint, and execution state, preventing replay attacks and privilege escalation.
  • RBAC Scope Separation:
    • use:ai: Query and interactive chat dialogs.
    • write:ai: Modifying AI settings and triggering self-learning jobs.
    • approve:ai: Authorizing high-risk system-level tool executions.

5. Scheduled Self-Learning Analytics

CheeseWAF includes automated periodic clustering of access logs and attack samples:

YAML
ai:
  self_learning:
    enabled: false
    auto_apply: false
    dry_run: true
    interval: 24h
    at: "03:30"
    min_confidence: 0.995
    min_events: 5
    max_events: 200
    max_rules_per_run: 3
    action: "block"
  • Configuration Properties:
    • min_confidence: Minimum confidence score required to propose a rule (default 0.995).
    • min_events / max_events: Sample bounds for unsupervised clustering.
    • max_rules_per_run: Maximum rules synthesized per execution (default 3) to prevent rule bloat.
    • dry_run: Simulation mode; generates analytical reports without modifying active rules.
  • Manual Trigger: Invoke POST /api/ai/self-learning/run to execute immediate cluster analysis over recent traffic.

1.12 - Plugins & CRP Specification

CheeseSec plugin distribution model, CRP v1 offline resource package format, Ed25519 signature verification, staging lifecycle, and extension boundaries.

CheeseWAF defines CRP (CheeseWAF Resources Package) as its signed resource-package format and provides local offline verification and staging commands. Release policy and developer instructions are maintained in CheeseSec_Plugin and CheeseSec_Plugin_Docs.

For the complete developer guide, read the plugin handbook. Browse actual published entries in the plugin store.

CRP v1 Archive Layout

The CheeseWAF CRP v1 parser requires resource packages to be standard ZIP archives containing only the following three entries. Any extra files or unknown directories cause immediate admission rejection (Hard Reject):

TEXT
my-plugin-v1.0.0.crp (ZIP archive)
├── manifest.json              # Package metadata manifest
├── artifact/                  # Single payload directory
│   └── payload.bin            # Binary payload artifact
└── signatures/
    └── manifest.json          # Offline Ed25519 signature bundle

Manifest Schema Reference

The manifest.json file uses strict schema validation and rejects unknown JSON properties:

Field NameTypeDescription
api_versionStringManifest specification version (fixed to crp/v1)
kindStringResource package type (detector, model, or ruleset)
nameStringHuman-readable plugin name
plugin_idStringGlobally unique plugin identifier
versionStringSemantic version string (e.g., 1.0.0)
namespaceStringPlugin namespace (official, enterprise, or community)
publisherStringPublisher entity name
sourceStringDistribution source ID (must exist in trusted source registry)
source_rootStringIdentifier of the bound signature trust root
release_sequenceIntegerMonotonically increasing sequence number (rollback rejected)
digestsObjectMulti-algorithm digests of the archive (SHA-256, SHA-1, MD5)
artifactObjectArtifact descriptor containing name, size, and digests

Signature Verification & Offline Admission

CRP archives require multi-party threshold signatures using Ed25519:

  • Trust Roots & Source Registry: Admission verifies public key fingerprints and validity windows against policy/trust-roots.json and policy/source-registry.json. No outbound CRL or OCSP network calls are made.
  • Signature Thresholds: Defined by policy/trust-levels.json, requiring official packages to meet threshold criteria (such as 2-of-3 quorum signatures).
  • Air-Gapped Operation: In air-gapped environments, the daemon verifies complete cryptographic integrity locally as long as trust roots are installed.

Command-Line Operations

CheeseWAF provides dedicated subcommands for offline verification and local staging:

1. Verify Package (crp verify)

Validates archive format, digest consistency, and signatures without installing, executing, or accessing the network:

BASH
cheesewaf crp verify \
  --package ./plugin.crp \
  --trust-roots ./trust-roots.json \
  --sources ./sources.json \
  --now 2026-09-08T12:00:00Z

2. Stage Package (crp stage)

Persists verified packages into protected, content-addressed staging slots (restricted to owner-only read/write permissions, without activating):

BASH
cheesewaf crp stage \
  --package ./plugin.crp \
  --trust-roots ./trust-roots.json \
  --sources ./sources.json \
  --runtime-dir /var/lib/cheesewaf/crp-runtime \
  --now 2026-09-08T12:00:00Z

3. Explicit Temporary HTTPS Probe (temporary-online probe)

For constrained environments requiring remote connectivity testing, CheeseWAF provides an explicit, single-use HTTPS probe. This command requires administrator password stdin, TLS leaf certificate pinning, and records metadata-only audit logs to <data-dir>/audit/netlease.jsonl:

BASH
cheesewaf temporary-online probe \
  --administrator admin \
  --password-stdin \
  --plugin-id my-plugin \
  --plugin-version 1.0.0 \
  --host updates.cheesesec.com \
  --leaf-pin sha256:abcd... \
  --ttl 60s

Distribution Endpoints

  • Catalog Service: https://store.cheesesec.com (read-only metadata)
  • OTA Index Service: https://ota.cheesesec.com (read-only release indices)
  • Immutable Resource Store: https://res.cheesesec.com (read-only SHA-256 content-addressed artifacts)

Offline Analytics Boundary (DuckDB)

The DuckDB extension operates as an asynchronous, host-provided one-shot-job rather than a persistent service on the request path. The job reads redacted Parquet audit snapshots to produce structured analysis-record/v1 outputs, ensuring offline analytical queries run in an isolated sandbox without affecting real-time WAF throughput or forwarding latency.

1.13 - Observability, Logging & Threat Attack Map

Access log rotation, Prometheus metrics and Remote Write protobuf streaming, alerts, and 100% offline air-gapped threat attack maps.

CheeseWAF provides end-to-end observability, including structured JSON access logs, standard Prometheus metrics, multi-channel alerting, and an interactive real-time threat attack map.

Configured under logging and monitor, these capabilities are visualized across the Dashboard, Logs, Monitor, and Attack Map modules in the Web Console.

1. Structured Access Logs

YAML
logging:
  level: "info"
  format: "json"
  output:
    type: "file"
    file:
      path: "./logs/access.log"
      max_size: "100MB"
      max_backups: 10
  • Rotation & Retention: Automatically rotates files based on size (max_size) and retains a configurable number of historical backups (max_backups).
  • Trace ID Correlation: Every request receives a globally unique traceId for end-to-end tracing across all processing stages.
  • Log Support Bundles: Execute cheesewaf logs pack to immediately generate a timestamped ZIP archive containing all runtime logs.
  • External Sinks: Asynchronously stream logs to ClickHouse, PostgreSQL, VictoriaLogs, or Elasticsearch. See Storage & Scheduler Architecture.

2. Prometheus Metrics & Remote Write

YAML
monitor:
  prometheus:
    enabled: true
    path: "/metrics"
    public: false
  remote_write:
    enabled: false
    endpoint: "https://prometheus-push.internal/api/v1/write"
    interval: 1m
    timeout: 10s
  • Scrape Endpoint: When public: false, scraping /api/metrics requires an administrative Bearer token. Setting public: true exposes /metrics directly at the root path.
  • Remote Write (Protobuf Streaming): Periodically pushes metrics directly to compatible collectors using the official Prometheus Remote Write protocol format.

3. Alerts & Notification Channels

Configure alert thresholds for anomalous drop surges (high-block-rate) or storage exhaustion (disk-usage):

  • Notifiers: Deliver notifications via standard HTTP Webhooks (enterprise platforms like Slack, DingTalk, WeChat Work, and Lark connect via their incoming bot webhook URLs).
  • In-App Notifications: Event alerts are mirrored to the system notification bus and retrievable via /api/notifications.

4. Threat Attack Map (100% Offline & Compliance Ready)

Navigate to /attack-map or fullscreen /attack-map/screen to monitor inbound attack geolocations and threat distributions in real time.

The attack map is engineered for air-gapped security and compliance:

  • Certified National Boundaries: Integrates officially approved China border geometries and the South China Sea ten-dash line.
  • Licensed Gaode World Polygons: Uses licensed country and regional polygon datasets.
  • 3D Offline Earth Canvas: Eliminates all external dependencies on public OpenStreetMap (OSM) raster tile servers. The 3D globe operates completely offline, preventing external DNS leakage and guaranteeing 100% availability in air-gapped, isolated networks.

1.14 - High Availability & Cluster Federation

Node join tokens, mutual TLS (mTLS) health and heartbeat interconnects, external consensus coordination, Ansible orchestration, and CLI cluster management.

CheeseWAF provides a cluster interconnect for mTLS node identity, health and heartbeat reporting, and node status. The interconnect is not a site-policy replication channel. The current runnable configuration supports a builtin single-node coordinator. Selecting etcd does not enable a working shared-cluster backend in the current binary and fails closed. The configuration and commands below do not provide production multi-node HA.

Cluster administration is accessible via the Cluster module in the Web Console, the cheesewaf cluster CLI commands, or REST APIs at /api/cluster/*.

1. Core Architecture & Configuration

The default standalone configuration:

YAML
deployment:
  mode: "standalone"
cluster:
  enabled: false
  ha_mode: "single-node"
  interconnect:
    listen: "127.0.0.1:9444"
    mtls_required: true

The following values describe the current interconnect and admission contract; they do not turn the current binary into a production multi-node HA deployment:

  1. Set deployment.mode: cluster and cluster.enabled: true, then assign a consistent cluster_id.
  2. Assign a globally unique node_id to each physical or virtual instance.
  3. Configure interconnect.advertise_addr as the routable IP/port accessible by peer nodes.
  4. Keep mtls_required: true and configure trusted ca_file, cert_file, and key_file paths.

The built-in consensus provider is limited to a single node. Setting cluster.consensus.provider: etcd and etcd_endpoints does not enable a supported shared-cluster deployment in the current binary. For the separate command’s public parameters and current limits, see Standalone Control Runtime.

Split-Brain Protection & Majority Quorum

  • cluster.protection.freeze_writes_without_majority: When network partitioning prevents forming a majority quorum, configuration mutations are automatically frozen to prevent state divergence.
  • allow_traffic_in_protection_mode: Ensures that the data plane continues forwarding and protecting traffic during read-only protection mode.

2. Cluster CLI Command Suite

CheeseWAF includes a CLI surface for local cluster initialization, token/certificate operations, and heartbeat checks. These commands expose the current compatibility contract; they do not make the unwired shared-cluster backend production-ready:

1. Controller Setup & Token Issuance

BASH
# Initialize a local single-node cluster (defaults bind the interconnect to loopback)
cheesewaf cluster init

# Mint a temporary worker join token (default TTL: 15 minutes)
cheesewaf cluster token create --ttl 15m

# List active tokens or revoke an existing token
cheesewaf cluster token list
export CHEESEWAF_TOKEN_ID='token-id-to-revoke'
cheesewaf cluster token revoke "$CHEESEWAF_TOKEN_ID"

cluster init only writes configuration; the service initializes its cluster identity when cluster mode starts. Before adding remote peers, use routable values for both addresses (for example, rerun with --force --advertise-addr 10.0.0.1:9444 --listen 0.0.0.0:9444) and configure the explicit etcd contract described above. Ensure network routes, firewalls, and cluster discovery backends are reachable across all cluster nodes.

2. Worker Node Joining & Certificate Rotation

BASH
export CHEESEWAF_CONTROLLER='https://10.0.0.1:9443'
export CHEESEWAF_JOIN_TOKEN='one-time-join-token'
export CHEESEWAF_NODE_ID='node-worker-02'
export CHEESEWAF_ADVERTISE_ADDR='10.0.0.2:9444'
export CHEESEWAF_CONTROLLER_CA='/var/lib/cheesewaf/certs/admin-ca.crt'

# Join a worker node into the cluster using a one-time token and local CSR
cheesewaf cluster join \
  --controller "$CHEESEWAF_CONTROLLER" \
  --token "$CHEESEWAF_JOIN_TOKEN" \
  --node-id "$CHEESEWAF_NODE_ID" \
  --advertise-addr "$CHEESEWAF_ADVERTISE_ADDR" \
  --ca-file "$CHEESEWAF_CONTROLLER_CA"

export CHEESEWAF_API_TOKEN='management-token-with-write-cluster'

# Request a new node certificate (requires existing certificate paths; reload/restart the service after writing)
cheesewaf cluster cert rotate \
  --controller "$CHEESEWAF_CONTROLLER" \
  --ca-file "$CHEESEWAF_CONTROLLER_CA" \
  --api-token-env CHEESEWAF_API_TOKEN
# Inspect current node and cluster quorum health
cheesewaf cluster status

--ca-file is the CA used to verify the controller’s HTTPS management endpoint, not the cluster CA returned during enrollment. It is optional when the controller certificate chains to the system trust store; pre-provision the controller’s private CA (for example, admin-ca.crt) when needed. The join command generates the node’s local key and CSR, receives the cluster CA and signed certificate, and writes them under the configured data directory; the private key is never sent to the controller.

Certificate rotation likewise requires a configured existing node identity/certificate path and exactly one API-token source (--api-token, --api-token-file, or --api-token-env). It writes replacement files locally; follow the service’s reload/restart procedure before expecting the new certificate to be used.

3. Ansible Automated Deployment

The POST /api/cluster/deploy/ansible exporter generates a CheeseWAF daemon bootstrap package (inventory, variables, playbook, role, configuration template, and README). Before execution, provide a verified binary URL and SHA-256, complete the service paths and required configuration, and review every generated command. The export does not provide plugin installation or a ready-to-run production multi-node HA deployment.

  • Playbook Generation API: Call POST /api/cluster/deploy/ansible with a list of nodes, roles (waf / monitor), SSH ports, and region metadata. The response is JSON with a files object mapping relative filenames (for example inventory.ini, playbook.yml, and role files) to their text contents. Save those entries as a package, fill in the required verified binary variables and etcd settings, review the generated commands, and only then run the playbook.
  • Web UI Export: In the Cluster view of the Web Console, configure the target node inventory and click “Export Ansible Bundle” to download the generated bundle for review and completion; it is not a ready-to-run production package.

4. Cluster REST API Reference

OperationREST API RouteDescription
Cluster HealthGET /api/cluster/statusQuery overall topology, software versions, and quorum state
Node ListGET /api/cluster/nodesList active nodes, IPs, and heartbeat timestamps
Issue Join TokenPOST /api/cluster/join-tokensMint a temporary join token
Join NodePOST /api/cluster/joinJoin cluster carrying an authorized token
Rotate CertificatePOST /api/cluster/nodes/{id}/rotate-certificateRotate interconnect mTLS certificates
Revoke NodePOST /api/cluster/nodes/{id}/revokeRevoke node certificate and evict from cluster
Ansible BundlePOST /api/cluster/deploy/ansibleExport Ansible deployment playbooks
Rolling UpgradePOST /api/cluster/orchestrate/rolling-upgradeCreate a sequential node upgrade task
Upgrade RollbackPOST /api/cluster/orchestrate/rolling-upgrade/{id}/rollbackCreate a reverse-order rollback task from backup state
Consensus StateGET /api/cluster/consensusQuery current cluster consensus status and coordinator details

The default provider is builtin, which is intended for single-node deployments. Configuring external etcd endpoints does not make the current binary a supported production multi-node HA deployment.

1.15 - Storage & Scheduler Architecture

Embedded SQLite management storage, optional external log sinks, encrypted diagnostics, and scheduler maintenance.

CheeseWAF uses lightweight embedded persistence alongside optional external log sinks. The current management store is SQLite; the external sinks do not replace it.

Storage and task scheduling are managed via the Operations and System views in the Web Console (storage, setup.data_dir, and scheduler).

1. Storage profiles

YAML
setup:
  data_dir: "./data"
storage:
  profile: temporary
  management_postgresql:
    dsn: ""
    timeout: 10s
  sqlite:
    path: "./data/cheesewaf.db"

CheeseWAF operates under storage.profile: temporary by default. The SQLite schema stores users, admin sessions, sites, site rules, review items, notifications, promotion deadlines, TOTP replay markers, and audit records. Runtime configuration remains in the YAML file.

storage.profile: production requires an independent storage.management_postgresql.dsn, separate from storage.postgresql.dsn. If external storage is unconfigured or unreachable, the daemon enforces fail-closed safety and terminates with ErrProductionStorageUnavailable to prevent persisting production data into temporary storage.

storage.postgresql is an optional asynchronous access-log sink, not the management database.

Configuration migration

Older configurations that omit storage.profile default to temporary. When migrating to production mode, ensure the external database endpoint is verified and accessible.

Versioned Schema Migrations

CheeseWAF runs an automated transaction-safe migrator. The current supported SQLite schema is version 5:

  • v1 (Initial Schema): Base tables for sites, users, credentials, and review queue items.
  • v2 (Review Decision Claims): Introduces concurrency locks and operator metadata tracking for review triage.
  • v3 (Legacy Rules to Site Custom Rules): Smoothly converts legacy global rule tables into standardized site-scoped custom rule collections.
  • v4 (Historical Username Repair Audit): Adds the append-only user_username_repairs table used by the explicit immutable-ID repair command; existing usernames are not rewritten.
  • v5 (User Credential Epochs): Adds credential_epoch to users and admin_sessions. Security changes advance the user epoch, and session validity requires the session epoch to match the current user epoch, so old sessions cannot remain active after a credential change.

Concurrency & Data Integrity Guarantees

  • WAL Mode (Write-Ahead Logging): Configured automatically via PRAGMA journal_mode = WAL. Readers can proceed while a writer is active, while writes remain serialized by the single SQLite connection and bounded by the configured busy timeout.
  • Foreign Key Constraints: Enforced by default via PRAGMA foreign_keys = ON to protect referential integrity.
  • Forward-Compatibility Lock (ErrSQLiteSchemaTooNew): If a database file was written by a newer CheeseWAF binary, an older daemon refuses to open it, preventing accidental schema degradation or corruption.

2. Redis ephemeral coordination

Redis configuration is present for planned integrations, but the current runtime does not use Redis for Bot challenges, sessions, leases, or replay state. Enabling storage.redis alone does not change the active management store.

The current challenge implementation uses the configured non-Redis backend. Native-raft and a PostgreSQL management source of truth are planned commercial architecture, not active storage paths.

3. External Log Sinks

For enterprise-scale access logs, CheeseWAF streams events asynchronously to external backends:

Storage SinkUse Case & Integration
storage.clickhouseHigh-throughput column-oriented OLAP storage for real-time aggregation across billions of records
storage.victorialogsLightweight log aggregation featuring high compression ratios
storage.postgresqlStandard relational database integration for corporate SIEM pipelines
storage.elasticsearchDirect indexing into Elasticsearch or OpenSearch clusters for Kibana dashboards
storage.redisReserved integration; not the current Bot challenge backend

To prevent SSRF attacks, external storage endpoints for ClickHouse, VictoriaLogs, and Elasticsearch resolving to private IP ranges require setting allow_private_endpoint: true (PostgreSQL and Redis drivers do not carry this field). Test connectivity via POST /api/system/storage/test prior to cutover.

4. Automated Task Scheduler

The built-in scheduler can run log cleanup, configuration snapshot, and security-report tasks. A configuration snapshot is not a complete database export, and the task is disabled by default in the source template:

YAML
scheduler:
  enabled: true
  tasks:
    - id: "log-cleanup"
      type: "cleanup"
      every: 24h
      target: "./logs"
      keep: 14
      enabled: true
    - id: "config-backup"
      type: "backup"
      every: 24h
      target: "./data/backups"
      keep: 7
      enabled: false
    - id: "security-daily-report"
      type: "security_report"
      frequency: "daily"
      at: "08:00"
      enabled: false
  • Task Management: Query and adjust task schedules via GET/PUT /api/scheduler/tasks.
  • Execution History: Inspect execution durations and exit statuses via GET /api/scheduler/history.

5. Backup & Space Recovery

  • Backup API status: POST /api/backup/export and POST /api/backup/restore are registered routes, but the current handlers return HTTP 501 (BACKUP_EXPORT_NOT_IMPLEMENTED / BACKUP_RESTORE_NOT_IMPLEMENTED). Do not treat them as a restorable backup workflow. Use the SQLite online-backup procedure in Operations & Security Hardening, or the scheduler’s configuration snapshot task, until a verified archive/restore format is shipped.
  • Disk Space Defragmentation: Reclaim operations apply to the active storage profile; SQLite VACUUM is only used by temporary mode.

6. Encrypted diagnostic queue

Diagnostic data strictly follows bounded local queueing and application-side envelope encryption with time-bounded TTL and redaction controls, ensuring sensitive business data remains private within the internal network.

1.16 - Web Management Console

Modern React-based single-page management console navigation, module routing matrix, and security mechanisms.

CheeseWAF includes a modern single-page visual management console built with React and hosted directly by the cheesewaf process on its management listener. After completing System Setup, navigate to the configured management endpoint. Standalone deployments may use the configured HTTP/HTTPS scheme; the official Docker Compose file publishes the admin listener as HTTPS on the Docker host loopback, so use https://127.0.0.1:9443/ there (or an SSH tunnel), not a remote host URL unless you explicitly change the bind address.

The console enforces session cookie statefulness with strict double-submit CSRF defenses (dynamically adjusting Secure flags when running on unencrypted local loops and enforcing them under HTTPS), and supports enabling CAPTCHA challenges on login.

Console Routing Matrix

Frontend RouteModule Scope & CapabilitiesDocumentation Reference
/Dashboard: Real-time QPS, drop statistics, and security summariesMonitoring & Logs
/sitesSites: Domain mappings, upstream origins, 4 load balancing algorithms, and health checksSite Management
/sslSSL Certificates: Certificate upload and automated ACME renewalsTLS & Certificates
/rulesRules: Site custom regex rules, YAML/JSON batch import/export, and live RE2 validationCustom Rules
/reviewThreat Review: ALAP offline threat triage, decision claims, and rule promotionALAP Review
/logsLog Explorer: Trace ID lookups and multi-dimensional query filtersMonitoring & Logs
/ipIP Management: IP allow/denylists, GeoIP restrictions, and threat feedsIP, Geo & Fingerprints
/protectionProtection: AST semantic engine toggles and paranoia levelsSecurity Policies
/bot-challengeBot Protection: JS challenges, slider CAPTCHAs, and waiting room policiesBot & CAPTCHA
/edgeEdge: Header rewriting, static caching, and Gzip/Brotli compressionEdge Features
/aiAI Settings: Model connectivity, self-learning jobs, and automated adoptionALAP Review
/monitorMonitoring & Alerts: Prometheus metrics, Remote Write, and Webhook alertsMonitoring & Logs
/apisecAPI Security: Endpoint discovery, schema validation, and rate limitingAPI Security
/usersUser Management: Administrator accounts, role scopes, and 2FA credentialsOperations
/opsOperations & Cron: Automated task scheduler and log maintenanceStorage & Scheduling
/updatesUpdates: Version status, release channel information, and update checksOperations
/block-pagesBlock Pages: Response templates, HTML sanitization, and sandboxed previewBlock Pages
/attack-mapThreat Map: Global attack visualization with official borders and 100% offline 3D EarthMonitoring & Logs
/clusterCluster: Node health, token issuance, certificate rotation, Ansible bundle export, and orchestration task viewsCluster HA
/systemSystem: Runtime configuration, NTP synchronization, and backup managementOperations
/captcha-labCAPTCHA Lab: Interactive puzzle testing and asset debuggingBot & CAPTCHA

The console provides light, dark, and custom color accents. Visual preferences are stored locally in the browser and do not impact data plane operations.

1.17 - Standalone Control Runtime

Public command parameters, local status endpoints, and current limits of the standalone cheesewaf-control process.

cheesewaf-control is a separate command with a local status service. It does not inspect WAF traffic, host the Web Console, or replace cheesewaf serve.

This command does not provide a complete high-availability deployment, empty-cluster initialization, remote node enrollment, plugin installation, or OTA updates. The main WAF service continues to use its own configuration and supported storage profile.

Command parameters

The process accepts flags only. Positional arguments are rejected. Use cheesewaf-control --help to inspect the parameters supported by your installed version.

TEXT
cheesewaf-control \
  --profile production \
  --cluster-id cluster-a \
  --node-id node-a \
  --data-dir /var/lib/cheesewaf/control \
  --listen 127.0.0.1:9450 \
  --raft-listen 127.0.0.1:9451 \
  --mode join \
  --ca-file /etc/cheesewaf/control/ca.pem \
  --cert-file /etc/cheesewaf/control/node.pem \
  --key-file /etc/cheesewaf/control/node-key.pem \
  --postgres-dsn '<provided-by-a-protected-secret-source>' \
  --timeout 15s
FlagDefaultRule
--profileproductionOnly production is accepted.
--cluster-idemptyRequired; whitespace, control characters, and invisible format characters are rejected.
--node-idgeneratedOptional node identity, persisted under --data-dir when generated.
--data-diremptyRequired persistent directory with restricted permissions.
--listen127.0.0.1:9450Local HTTP address; must be a loopback host:port.
--raft-listen127.0.0.1:9451Consensus listener; must be a different loopback host:port.
--modejoinMust be bootstrap or join; the default does not initialize a cluster.
--ca-fileemptyRequired PEM CA bundle in a protected regular file.
--cert-fileemptyRequired node certificate PEM; its identity must match an explicitly configured node identity.
--key-fileemptyRequired private key PEM; keep it owner-readable (0600) and out of logs and source control.
--postgres-dsnemptyRequired management database connection; never included in status JSON.
--timeout15sPositive startup timeout. Expiration stops startup.

Both listeners are restricted to loopback. A remote database connection requires certificate-verified TLS. The management database connection is separate from the optional storage.postgresql.dsn access-log sink used by the main WAF service.

The paths and identities above are examples. Prepare valid credentials and the required service state before running the command; the example alone does not create a working HA deployment.

Startup status

The command validates its configuration and required dependencies before reporting readiness. A startup failure prints control-plane startup failed closed and exits. Stop and correct the reported configuration or dependency problem before trying again. A running process or a successful liveness response alone does not mean it is ready to accept writes.

Local status endpoints

The status service is for local supervisors and probes on --listen.

MethodPathResponse
GET/healthz200 with the current status document; liveness does not imply readiness.
GET/readyz200 only when ready for writes; otherwise 503.
GET/status200 with bounded status and readiness information.
POST/proposals503 before readiness; the current command returns 501 when ready because this operation is unavailable. Other methods return 405.

Status responses exclude credentials, database connection strings, and private filesystem paths. These endpoints are not a remote cluster-management API.

Startup modes

bootstrap and join select startup modes. Neither mode provides a complete cluster-administration workflow. The command cannot initialize an empty production cluster or enroll remote peers, and it has no controller-address or join-token flag. Do not use these modes as evidence that production multi-node HA is available.

Main WAF service

Continue to run cheesewaf serve for WAF traffic and the Web Console. Starting cheesewaf-control does not migrate the main service’s storage or change its supported features. See Cluster for the main service’s public configuration and current limits.

1.18 - Command-Line Interface & Interactive TUI

Unified single-binary CLI distribution for cheesewaf and waf-cli, global flags, subcommand reference, and terminal UI operations.

CheeseWAF utilizes a unified single-binary (BusyBox pattern) architecture. The execution mode is determined automatically based on the invocation command name:

Executable NameDefault Execution Behavior
cheesewafExecutes the serve command by default, launching the Data Plane reverse proxy and the same process’s Management Plane API/Web services
waf-cliLaunches the interactive Terminal User Interface (TUI, equivalent to cli; panel is a compatibility alias)

Global Command-Line Flags

TEXT
-c, --config string     Path to configuration file (default ./data/config/cheesewaf.yaml)
    --data-dir string   Path to runtime data directory (default ./data)
    --lang string       UI language preference (en or zh-CN)

The language resolution hierarchy is: CLI --lang flag > Environment variable CHEESEWAF_LANG > Saved setting in data directory > Host operating system locale.

Identity and Password Rules

CheeseWAF applies one username rule to the setup wizard, Web Console, REST API, CLI, storage layer, human JWT claims, and CAPTCHA receipts. A username must be 3–32 ASCII characters, start with an ASCII letter, end with an ASCII letter or digit, and contain only ASCII letters, digits, ., _, and -. Non-ASCII characters, Unicode whitespace, control characters (Cc), and format/invisible characters (Cf) are rejected. The server preserves the exact input and never trims or lowercases usernames, so admin and admin are different strings and the latter is invalid.

The role field is also exact. It must match a configured key in apisec.permissions (normally admin or readonly); empty or unknown values, */: permission expressions, and leading, trailing, or embedded Unicode whitespace, control characters (Cc), or format/invisible characters (Cf) are rejected. Roles are not trimmed or case-normalized.

New passwords must contain at least 10 characters and satisfy at least 3 of these 4 classes: uppercase letters, lowercase letters, non-repeating digits, and special characters. Common or simple patterns, including sequential or keyboard-like patterns, are rejected. A password may not equal or contain the username. Existing password hashes are not exposed by these commands.

Subcommand Reference Table

SubcommandFunctionality & Description
serveLaunches the full WAF daemon (Data Plane reverse proxy + Management Plane API and Web console)
setupInteractive or headless terminal initialization wizard for hardware profiling and initial credentials
rulesBatch imports, exports, and template generation for site custom regex rules
crpVerifies a local CRP package and can persist it in the local staged slot; it does not promote, execute, or distribute a plugin
temporary-onlineExplicit temporary outbound network probe; requires administrator stdin password and TLS leaf pin, records metadata-only audit
cliLaunches the interactive TUI terminal management panel (compatibility alias: panel)
statusChecks daemon health, process PID lease, and runtime status
healthcheckDiagnostic probes for admin API and outbound TLS (used in Docker healthcheck probes)
stopGracefully terminates the running local daemon process
restartGracefully stops and restarts the local daemon
userResets local admin credentials, renames users, repairs historical usernames, and manages 2FA credentials
clusterCluster controller init, worker node join, certificate rotation, token management, and runtime operations
logsPackages service logs into a compressed ZIP support bundle (logs pack)
langDisplays or persistently configures the default CLI interface language (lang show / lang set)
versionDisplays software version, build Git commit, release channel, and build timestamp

Subcommand Details & Examples

1. System Setup Wizard (setup)

Supports both interactive prompts and non-interactive scripted automation:

BASH
# Interactive setup wizard with hardware probing and password configuration
cheesewaf setup

# Headless unattended installation
cheesewaf setup --yes \
  --username admin \
  --password-stdin < /path/to/password.txt \
  --profile smart \
  --admin-listen 127.0.0.1:9443 \
  --skip-probe

Key flags:

  • -y, --yes: Skip interactive confirmation prompts and commit directly (headless setup requires --password-stdin to ensure strong credential generation).
  • --username / --password-stdin: Initial root administrator username and password read from standard input.
  • --profile: Hardware profile tuning (smart, low, medium, high, or custom; official aliases minimal, balanced, and performance are fully supported).
  • --admin-listen: Admin management API listen address (default 127.0.0.1:9443; prints http:// or https:// based on admin_tls).
  • --skip-probe / --skip-external: Skip hardware autodetection or skip external telemetry (GeoIP/Prometheus/VictoriaLogs) setup.

--username must satisfy the canonical username rule above. --password-stdin is the preferred automation input; the password is read from standard input and is not printed in the setup summary.

2. Custom Rules Management (rules)

Batch replaces or exports site custom_rules via YAML or JSON. On successful import, it automatically notifies the running daemon to perform a zero-downtime hot reload:

BASH
# Output official custom rules template
cheesewaf rules example --format yaml --file rules-template.yaml

# Validate and import custom rules for a target site
cheesewaf rules import --site site-demo --file my-rules.yaml

# Export custom rules of a site to JSON
cheesewaf rules export --site site-demo --format json --file exported-rules.json

3. Local User Administration (user)

BASH
# Set a local user's password by reading it from stdin (recommended; avoids shell history/process leakage)
cheesewaf user password admin --password-stdin < secret.txt

# Direct --password is less safe because the value can appear in shell history, environment variables, or process arguments
cheesewaf user password admin --password 'replace-with-new-password'

# Generate a strong temporary password and disable TOTP 2FA (emergency recovery)
cheesewaf user password admin --generate --reset-2fa

# Ensure an administrator account exists (creates or updates credentials)
cheesewaf user ensure-admin admin --password-stdin < secret.txt

# Rename an existing user
cheesewaf user rename old_admin new_admin

# Repair a historical username that contains whitespace or another now-invalid character
cheesewaf user repair-username USER_ID recovered_admin --reason 'Historical whitespace in imported account'

Use user rename for an account whose current username is already canonical. Both the old and new values must pass the canonical rule. The CLI updates that account and revokes all of its unrevoked sessions, but it does not create a historical-repair audit record; this path cannot select a historical non-canonical username. Only repair-username bundles the username change, session revocation, and audit insert in one transaction. Neither command silently trims or lowercases a username.

Use user repair-username only for a historical non-canonical username, and pass the immutable user ID rather than the username. The repair rejects a missing user, a canonical current username, or a target username already owned by another account; it never merges accounts. The username change, revocation of every unrevoked admin session for that user, and append-only audit record commit in one SQLite transaction. The existing user ID, password hash, role, TOTP enabled state, and TOTP secret remain unchanged. The audit records the current OS user ID, the supplied reason, the old and new usernames, the number of revoked sessions, and the timestamp.

To find the immutable ID without reading password hashes or TOTP secrets, use the SQLite CLI in read-only mode and select only the ID and a quoted username. Replace the path with the configured storage.sqlite.path or the active data directory:

BASH
DB=/var/lib/cheesewaf/cheesewaf.db
sqlite3 -readonly "$DB" \
  'SELECT id, quote(username) AS username FROM users ORDER BY username;'

quote(username) makes leading or trailing spaces visible in the result. Do not use SELECT *, and do not paste database output into tickets or logs.

The display note attached to a management API token is metadata, not an account username. It is not subject to the account username rule; do not use a token note as the user identity. Management API Tokens default to 90 days and may be set up to 365 days; expired or inactive (180 days) tokens are cleaned by a single coalesced worker and generate audit/notification attempts.

The user command manages user accounts, roles, and credentials within the local management store. For CRP plugin packages, crp verify provides local offline signature verification, and crp stage persists verified local packages into designated staged slots.

CRP local staging

BASH
cheesewaf crp stage \
  --package ./plugin.crp \
  --trust-roots ./trust-roots.json \
  --sources ./sources.json \
  --runtime-dir ./data/crp-runtime \
  --now 2026-09-08T12:00:00Z

The command requires explicit trust roots, source registrations, a runtime directory, and a deterministic --now. It verifies the archive and writes only local staged metadata/artifacts. It never promotes a package, starts a plugin, bypasses a confirmation requirement, or contacts a network source. --high-risk selects the high-risk signature threshold but does not grant confirmation.

BASH
# Execute an explicit, one-time temporary HTTPS outbound probe
# (requires admin password on stdin and pinned TLS leaf certificate)
cheesewaf temporary-online probe \
  --administrator admin \
  --password-stdin \
  --plugin-id my-plugin \
  --plugin-version 1.0.0 \
  --host updates.cheesesec.com \
  --leaf-pin sha256:0123456789abcdef... \
  --ttl 60s

The probe command executes only restricted HEAD/GET handshakes and writes a structured, read-only metadata audit record to <data-dir>/audit/netlease.jsonl. It does not start a persistent background downloader, nor does it participate in main proxy data routing.

4. Cluster Management (cluster)

BASH
# Initialize current node as a single-node cluster (does not mint a CA)
cheesewaf cluster init

# Create a temporary worker join token (default TTL: 15 minutes)
cheesewaf cluster token create --ttl 15m

# List or revoke join tokens
cheesewaf cluster token list
export CHEESEWAF_TOKEN_ID='token-id-to-revoke'
cheesewaf cluster token revoke "$CHEESEWAF_TOKEN_ID"

export CHEESEWAF_CONTROLLER='https://10.0.0.1:9443'
export CHEESEWAF_JOIN_TOKEN='one-time-join-token'
export CHEESEWAF_NODE_ID='node-worker-02'
export CHEESEWAF_ADVERTISE_ADDR='10.0.0.2:9444'
export CHEESEWAF_CONTROLLER_CA='/var/lib/cheesewaf/certs/admin-ca.crt'

# Join a worker node using a one-time token; the CLI creates the local key and CSR
cheesewaf cluster join \
  --controller "$CHEESEWAF_CONTROLLER" \
  --token "$CHEESEWAF_JOIN_TOKEN" \
  --node-id "$CHEESEWAF_NODE_ID" \
  --advertise-addr "$CHEESEWAF_ADVERTISE_ADDR" \
  --ca-file "$CHEESEWAF_CONTROLLER_CA" # --ca-cert is also accepted

export CHEESEWAF_API_TOKEN='management-token-with-write-cluster'

# Request replacement cluster mTLS files (requires existing local certificate paths; reload/restart afterward)
cheesewaf cluster cert rotate \
  --controller "$CHEESEWAF_CONTROLLER" \
  --ca-file "$CHEESEWAF_CONTROLLER_CA" \
  --api-token-env CHEESEWAF_API_TOKEN

# Inspect cluster health and consensus status
cheesewaf cluster status

# Export declarative cluster objects (redirect the YAML output to a file)
cheesewaf cluster export > cluster-export.yaml

# Run the local node heartbeat loop toward the HTTPS interconnect (mTLS) controller
export CHEESEWAF_CLUSTER_CONTROLLER='https://10.0.0.1:9444'
cheesewaf cluster monitor-node --controller "$CHEESEWAF_CLUSTER_CONTROLLER" --interval 10s

--ca-file for cluster join and cert rotate verifies the controller’s 9443 HTTPS management endpoint; it is not the cluster CA returned during enrollment. Omit it only when the controller certificate chains to the system trust store; pre-provision a private admin CA when needed. Joining generates a local key/CSR and writes the returned cluster CA and certificate under the node data directory. Certificate rotation requires exactly one token source (--api-token, --api-token-file, or --api-token-env), writes files locally, and takes effect after the service reload/restart procedure.

cluster monitor-node posts heartbeats to the cluster interconnect (normally HTTPS :9444) using the local configured cluster CA/certificate/key. The fallback environment variable is CHEESEWAF_CLUSTER_CONTROLLER; a custom --controller value must likewise be an HTTPS interconnect address. --insecure-skip-verify is for isolated laboratory testing only.

5. Support Bundle Packaging (logs)

BASH
# Package all runtime logs into a timestamped support ZIP archive
cheesewaf logs pack

# Specify target archive output path
cheesewaf logs pack --dir /tmp --name support-bundle.zip

6. CLI Language Configuration (lang)

BASH
# Show current locale and supported language list
cheesewaf lang show

# Persistently set default language
cheesewaf lang set en
cheesewaf lang set zh-CN

Operational Examples

BASH
# Launch with custom configuration and data paths
cheesewaf serve --config /etc/cheesewaf/cheesewaf.yaml --data-dir /var/lib/cheesewaf

# Check process execution status and PID lease
cheesewaf status

# Launch the interactive terminal UI
waf-cli

# Run container diagnostics and readiness check
cheesewaf healthcheck

On Windows systems, if you wish to run waf-cli directly by name, copy or create an alias from cheesewaf.exe to waf-cli.exe.

The TUI subcommand’s canonical spelling is cheesewaf cli; cheesewaf panel remains available as a compatibility alias.

cheesewaf user also accepts the users alias. cheesewaf healthcheck is intentionally hidden from normal --help output and is used by service/container probes.

1.19 - RESTful Management API Reference

Management API authentication mechanics, public and bootstrap endpoint inventory, granular RBAC permission matrix, and standard error formats.

CheeseWAF’s management API is hosted on the process’s dedicated Management Plane listener (default port 9443) under the /api route prefix, maintaining physical listener separation from business traffic on the Data Plane. This listener is not the future standalone commercial control-plane service.

Authentication & Authorization Schemes

The system supports two primary authentication models:

  1. Session-Based Authentication: Call POST /api/auth/login to authenticate; clients must include the returned Session Cookie in subsequent requests. All non-idempotent state-changing requests (POST, PUT, DELETE, PATCH) are verified by double-submit CSRF protection middleware.
  2. Bearer Management Tokens: Enable apisec.management_api.enabled, then invoke POST /api/system/api-tokens (requiring manage:api_tokens privileges) to generate a scoped API Token. Pass the token via the standard HTTP header: Authorization: Bearer <TOKEN>. The secret is returned only once in the creation response; list/read endpoints return metadata, not the secret.

Usernames and roles

Human account endpoints (POST /api/users, PUT /api/users/{id}), setup, login, storage, human JWT claims, and CAPTCHA receipts share one exact username rule: 3–32 ASCII characters, ASCII letter first, ASCII letter or digit last, and only ASCII letters, digits, ., _, and -. Non-ASCII characters, Unicode whitespace, control characters (Cc), and format/invisible characters (Cf) are rejected. The server never trims, lowercases, or otherwise normalizes the value.

When a request creates or updates a user, role must exactly match a configured key in apisec.permissions (normally admin or readonly). Empty or unknown roles, */: permission expressions, and roles containing leading, trailing, or embedded Unicode whitespace, controls (Cc), or format/invisible characters (Cf) are rejected. Invalid fields return USERNAME_INVALID or ROLE_INVALID. An existing historical non-canonical username cannot be repaired through ordinary API update; inspect its immutable ID and run the local CLI command cheesewaf user repair-username USER_ID NEW_USERNAME --reason '...'.

Public Unauthenticated Endpoints

The following read-only, login, or challenge endpoints can be accessed without a prior session or bearer token. A configured public Prometheus path is also unauthenticated when monitor.prometheus.public: true; its path is deployment-specific.

HTTP MethodRoute PathDescription & Purpose
GET/health, /health/live, /health/ready, /health/clusterSystem and cluster health diagnostic probes
GET/api/auth/login-optionsRetrieves login security settings (e.g., CAPTCHA/2FA requirements)
POST/api/auth/captcha, /api/auth/captcha/verifyGenerates and verifies login CAPTCHA challenges
POST/api/auth/loginAdministrator authentication endpoint
GET/api/setup/statusReports whether first-install setup is still required; does not mutate state

Bootstrap and Node-Authenticated Endpoints

These routes are mounted outside the normal management-token middleware, but they are not anonymous operations:

  • POST /api/setup and POST /api/setup/probe require the setup token in X-CheeseWAF-Setup-Token, and are accepted only while setup is incomplete.
  • GET /api/setup/draft requires the setup-session cookie issued by the probe; PATCH /api/setup/draft requires that cookie plus the setup token.
  • POST /api/cluster/join requires a one-time join token and a node CSR. The controller validates the token and enrolls the node; it is not a public membership endpoint.
  • POST /api/cluster/nodes/{id}/heartbeat requires a verified mTLS client certificate for an enrolled, non-revoked node (certificate identity/serial must match the registration).

First-install setup URL delivery

The service never prints the setup token or complete setup URL in its startup log. The log shows only the base setup URL (for example, http://127.0.0.1:9443/setup), the protected runtime file path (setup.url), and an opaque receipt.

The complete setup URL is stored in setup.url with mode 0600 and a 10-minute validity period. After setup completes, the setup token is revoked; expired setup.url files are cleaned up. The normal installation flow does not expose ReadURLOnce as a user-facing command.

The setup token remains required in X-CheeseWAF-Setup-Token until setup completes, when it is revoked. The browser reads the token from the URL fragment, clears the fragment from the address bar, and sends it only in that header. A token supplied through CHEESEWAF_SETUP_TOKEN before startup follows the same API validation rules and must stay out of logs and shell history.

GET /api/setup/status reports only whether setup is still needed. It never returns the setup URL or setup token.

RBAC Permission Matrix Reference

Router middleware validates token permissions against the following identifiers:

Permission PrefixFunctional Area & Covered Capabilities
read:sites / write:sitesQuery, create, update, and delete site definitions; issue ACME certificates
read:rules / write:rulesCustom regex security rule management
read:protection / write:protectionIP access lists, ACL rules, bot challenge policies, and ALAP decisions
read:threat_intel / write:threat_intelThreat intelligence feed management, synchronization, and IP lookups
read:edge / write:edgeEdge response headers, static caching rules, and compression profiles
read:ai / write:ai / use:ai / approve:aiAI LLM configurations, assistant conversations, and high-risk tool approvals
read:cluster / write:clusterCluster node monitoring, join token issuance, and rolling upgrades
read:system / write:systemSoftware version queries and NTP time synchronization; backup/restore routes are registered but currently return 501
manage:api_tokensCreate, query, and revoke management API tokens
read:users / write:usersAdministrator user accounts, roles, and TOTP 2FA configuration
read:logsQuery access logs and retrieve ALAP review queue items
read:monitorSystem performance metrics, Prometheus scraping, and notification channels
read:auditQuery operational audit logs
read:realtimeServer-Sent Events stream (/api/realtime/events) and WebSocket feeds
read:ops / write:opsBuilt-in task scheduler and automated maintenance routines
read:storage / write:storageStorage status, external log sink configuration, and disk cleanup
read:apisecDiscovered API asset inventory and OpenAPI schema definitions

Roles assigned admin: ["*"] possess unrestricted global API access.

Management API Tokens currently support scoped permissions, notes, optional TTL/expiry, revocation, last-used metadata, and one-time secret display. The platform default lifetime is 90 days; the maximum explicit lifetime is 365 days. The service runs one coalesced cleanup worker: new tokens slide the cleanup deadline by 10 minutes, bounded by the first creation plus 60 minutes, and expired or inactive tokens (180 days without activity) are removed; audit-entry and administrator-notification attempts are made after the configuration commit.

The Web console provides a two-step confirmation workflow for non-expiring tokens. Adhering to the principle of least privilege, creating a non-expiring token requires strong identity verification (such as password and TOTP two-factor confirmation), returning API_TOKEN_CONFIRMATION_UNAVAILABLE when verification conditions are not met.

The backup routes are not a working restore workflow yet: POST /api/backup/export and POST /api/backup/restore return HTTP 501 (BACKUP_EXPORT_NOT_IMPLEMENTED / BACKUP_RESTORE_NOT_IMPLEMENTED).

Standard Error Formats

API failures return appropriate HTTP status codes accompanied by a structured JSON error response:

JSON
{
  "error": {
    "code": "BAD_REQUEST",
    "message": "Invalid request parameter",
    "trace_id": "1a2b3c4d5e6f",
    "event_id": "1a2b3c4d5e6f"
  }
}

If a login attempt fails due to CAPTCHA validation (HTTP 401/403), request a new challenge context via /api/auth/captcha before re-submitting credentials.

1.20 - Configuration File Reference

Complete structure navigation for cheesewaf.yaml, top-level key index, timeout controls, and hot-reload scopes.

CheeseWAF automatically generates a default cheesewaf.yaml configuration file within its runtime data directory under config/ upon first launch (default ./data/config/cheesewaf.yaml). A baseline template is maintained in the source repository at configs/cheesewaf.yaml.

configs/cheesewaf.yaml is a source template, not a runtime state file. Setup, site management, and console saves write to the runtime configuration. For source builds, copy it first to ./data/config/cheesewaf.yaml or another dedicated data directory so database paths, certificates, secrets, and site changes never modify the Git working tree.

Top-Level Configuration Index

Top-Level KeyFunctional Area & RoleDocumentation Reference
serverNetwork listener sockets, management endpoints, and connection timeoutsArchitecture & Overview · TLS & Certificates
tlsData Plane TLS/HTTPS certificates and HSTS enforcementTLS & Certificates
setupInitialization state tracking and runtime data directory pathSystem Initialization · Storage & Scheduling
deployment / clusterDeployment topology (standalone vs. HA cluster) and interconnectsHigh Availability Clustering
consoleWeb console UI preferences and administrative login securityBot & CAPTCHA · Monitoring & Logs
sitesReverse proxy sites, domain bindings, and upstream origin poolsSite Management
protectionGlobal security baseline (AST engines, IP, Bot, rate limiting, ACL)Security Protection Policies
block_pageBlock response templates and custom HTML branding sanitizationBlock Response Pages
storagetemporary SQLite management profile; reserved, currently rejected production profile; optional external log sinksStorage & Scheduling
loggingAccess log verbosity, structured JSON formats, and log rotationMonitoring & Logs
aiALAP LLM provider endpoints and asynchronous review parametersALAP Review & Self-Learning
updateReserved OTA settings; updater worker is not implemented in the current runtimeSystem Operations
schedulerAutomated log cleanup, configuration snapshots, and daily security reports; snapshots are not complete database exportsStorage & Scheduling
edgeEdge response header manipulation, static caching, and Brotli compressionEdge Features
monitorPrometheus metrics export, Remote Write, and alert notifiersMonitoring & Logs
apisecAPI asset discovery, request schema contracts, and RBAC matrixAPI Security & Governance
performanceGo runtime Garbage Collection (GC) adaptive tuning (memory_limit_ratio / min_gogc)Architecture & Overview
time_syncNTP sources, synchronization intervals, and clock-offset consensus limitsMonitoring & Logs
captcha_assetsLocal or S3 CAPTCHA image/font assets and resource limitsBot & CAPTCHA
acmeACME certificate issuance and DNS challenge provider settingsTLS & Certificates
vulnerabilityVulnerability CVE feed subscription configurationsSystem Operations

Network Timeout Controls

  • Ingress Connection Timeouts: server.read_timeout, server.write_timeout, and server.idle_timeout govern the lifecycle of HTTP connections between clients and the WAF.
  • Reverse Proxy Timeouts: sites[].waf.performance.proxy_timeout defines the maximum allowable duration when connecting and streaming responses to/from backend origin servers.

Protection Modes & Request Body Limits

  • WAF Modes (waf.mode): Supports block (actively drops and mitigates attacks), monitor (logs alerts without blocking), and off (disables inspection). The legacy alias log is automatically recognized and normalized to monitor.
  • Request Body Size Guard (max_body_bytes): If an incoming request body exceeds the configured max_body_bytes limit, the data plane immediately responds with HTTP 413 Request Entity Too Large, preventing memory exhaustion and partial-body evasion.

Gateway Adapter Authentication & Proxy Ingress

  • Dedicated Adapter Token (CHEESEWAF_ADAPTER_TOKEN): When integrating with external reverse proxy adapters (CheeseWAF-Adapters), callers must supply the token via the dedicated X-CheeseWAF-Adapter-Token HTTP header. It is not a Bearer token and must never be placed in the Authorization header.
  • Trusted CIDR Blocks (trusted_cidrs): By default, the trusted CIDR list is empty. When running behind an upstream proxy (such as a CDN or cloud load balancer), configure sites[].waf.access_control.trusted_cidrs (e.g., 127.0.0.1/32 or ::1/128) to securely parse client IP addresses from X-Forwarded-For.

Dynamic Hot-Reload Scopes

  • Atomic In-Memory Hot Reload: Modifying site definitions, custom regex rules, IP access lists, bot challenge policies, or ACL rules via the Web console or REST API takes effect immediately in memory without process restarts.
  • Restart Required: Alterations to physical socket listeners (such as server.listen or server.admin_listen) require restarting the daemon process via cheesewaf restart or systemd.

1.21 - Operations & Security Hardening

User administration, TOTP two-factor authentication (2FA), NTP time synchronization, update capability status, and supply chain signature verification.

This section outlines standard operational procedures and hardening requirements for running CheeseWAF in production. Corresponding UI modules in the Web Console include Users, System, and Updates.

CheeseWAF uses embedded SQLite by default (storage.profile: temporary) to store users, sessions, and management state. When storage.profile: production is explicitly set, the service enforces strict environment validation and fails closed with ErrProductionStorageUnavailable if external production database dependencies are not configured.

storage.postgresql is an optional asynchronous access-log sink; it is not the management database. A configured storage.redis endpoint may be connectivity-tested, but bot challenge state still uses the in-process memory backend, and protection.bot.challenge_backend: redis is rejected. cheesewaf crp verify performs bounded offline verification, while cheesewaf crp stage persists a verified local package in a staged slot. Activation and rollback require explicit host support and fail closed when it is unavailable.

1. User Administration & CLI Credentials

  • One identity rule: Setup, the Web Console, REST API, CLI, storage, human JWT claims, and login CAPTCHA receipts use the same username form. Usernames are 3–32 ASCII characters, start with an ASCII letter, end with an ASCII letter or digit, and contain only ASCII letters, digits, ., _, and -. Non-ASCII characters, Unicode whitespace, control characters (Cc), and format/invisible characters (Cf) are rejected. The server preserves the exact input and never trims or lowercases usernames, so admin and admin are different strings and the latter is invalid.
  • Role input: A user role must exactly match a configured key in apisec.permissions (normally admin or readonly). Empty or unknown roles, */: permission expressions, and roles containing leading, trailing, or embedded Unicode whitespace, control characters (Cc), or format/invisible characters (Cf) are rejected. The server does not trim or case-normalize roles; invalid account fields return USERNAME_INVALID or ROLE_INVALID.
  • Web Console & REST API: Administer accounts programmatically via GET/POST /api/users and PUT /api/users/{id}. The same validation applies to Web Users, Setup, and login.
  • Command-Line Operations (cheesewaf user):
    BASH
    # Recommended for scripts: read the password from stdin (avoid shell history/process listings)
    cheesewaf user password admin --password-stdin < secret.txt
    
    # One-off shell use only: explicit password (choose exactly one input mode)
    read -r -s -p 'New password: ' CHEESEWAF_NEW_PASSWORD; printf '\n'
    cheesewaf user password admin --password "$CHEESEWAF_NEW_PASSWORD"
    
    # Auto-generate a strong password and disable TOTP 2FA (emergency recovery)
    cheesewaf user password admin --generate --reset-2fa
    
    # Ensure an admin user exists and read password from stdin (useful for automated scripts)
    cheesewaf user ensure-admin admin --password-stdin < secret.txt
    
    # Rename a local user
    cheesewaf user rename old_admin new_admin
    
    # Repair a historical non-canonical username by immutable user ID
    cheesewaf user repair-username USER_ID recovered_admin --reason 'Historical whitespace in imported account'
  • Use user rename when the current username is already canonical. Both the old and new values must pass the canonical rule. The CLI updates that account and revokes all of its unrevoked sessions, but it does not create a historical-repair audit record; this path cannot select a historical non-canonical username. Only repair-username bundles the username change, session revocation, and audit insert in one transaction.
  • Use user repair-username only for a historical non-canonical username such as admin. It requires --reason and an exact immutable user ID. It rejects a missing user, a canonical current username, or a target username owned by another account. It never merges accounts. The username update, revocation of every unrevoked admin session for that user, and append-only audit record commit in one SQLite transaction. The user ID, password hash, role, TOTP enabled state, and TOTP secret remain unchanged. The audit records the current OS user ID, supplied reason, old and new usernames, revoked-session count, and time. Neither path silently trims or lowercases a username.
  • Run the repair as the same OS account that owns the CheeseWAF data. The audit actor is derived from the current OS user ID; running the command through an unrelated account changes that evidence.
  • Password policy: New passwords need at least 10 characters and at least 3 of 4 classes: uppercase, lowercase, non-repeating digits, and special characters. Common or simple patterns, including sequential or keyboard-like patterns, are rejected. A password cannot equal or contain the username. Prefer --password-stdin; direct --password values can enter shell history or process listings.
  • Principle of Least Privilege: Create dedicated readonly accounts for operational auditing to avoid sharing root administrative credentials.
  • Two-Factor Authentication (2FA/TOTP): Configure TOTP using /api/users/{id}/2fa/setup to generate seeds and QR codes; manage state via enable, disable, and recover.
  • A management API token’s display note is metadata, not an account username. It is not validated with the account username rule and must not be used as the authenticated human identity. Management API Tokens default to 90 days and allow at most 365 days; the running service removes expired or 180-day-inactive tokens in a coalesced cleanup worker and attempts an audit entry plus administrator notification.
  • The Web System page contains a second-confirmation dialog for non-expiring Tokens, but the option is disabled until the confirmation verifier is configured. The current runtime does not yet connect ApprovalGate, current-password/TOTP verification, or the 10-second warning delay; non-expiring creation therefore returns API_TOKEN_CONFIRMATION_UNAVAILABLE.

To find a user ID without reading password hashes or TOTP secrets, use the SQLite CLI in read-only mode and select only the ID and a quoted username:

BASH
DB=/var/lib/cheesewaf/cheesewaf.db
sqlite3 -readonly "$DB" \
  'SELECT id, quote(username) AS username FROM users ORDER BY username;'

quote(username) makes leading or trailing spaces visible. Do not use SELECT *, and do not paste this output into tickets or logs.

2. Back Up and Migrate the SQLite Management Store

Before a username repair or binary upgrade, resolve the active database from storage.sqlite.path and confirm that the file and its parent directory are the expected runtime paths. The usual defaults are ./data/cheesewaf.db for a local run and /var/lib/cheesewaf/cheesewaf.db for a Linux service. Do not point these commands at the tracked configs/cheesewaf.yaml template.

An active SQLite database normally uses WAL mode. Do not copy only the main .db file while CheeseWAF is running; recent commits may still be in -wal, and the copy may not be restorable. An online backup reads a consistent snapshot while the service continues to run:

BASH
DB=/var/lib/cheesewaf/cheesewaf.db
BACKUP_DIR=/var/backups/cheesewaf
test -f "$DB" || { echo "database not found: $DB" >&2; exit 1; }
install -d -m 700 "$BACKUP_DIR"
df -h "$BACKUP_DIR"
du -h "$DB"
BACKUP="$BACKUP_DIR/cheesewaf-before-maintenance-$(date -u +%Y%m%dT%H%M%SZ).db"
test ! -e "$BACKUP" || { echo "backup path already exists: $BACKUP" >&2; exit 1; }
sqlite3 -readonly "$DB" ".backup '$BACKUP'"
chmod 600 "$BACKUP"
test -s "$BACKUP" || { echo "backup is empty: $BACKUP" >&2; exit 1; }
integrity=$(sqlite3 -readonly "$BACKUP" 'PRAGMA integrity_check;')
test "$integrity" = ok || { echo "backup integrity check failed: $integrity" >&2; exit 1; }
sha256sum "$BACKUP" > "$BACKUP.sha256"
sha256sum -c "$BACKUP.sha256"

The integrity check must return ok, and the final checksum command must report OK. Stop if either check fails. Keep the backup in a protected location and copy it off-host according to the retention policy. The backup contains sensitive management data; never upload it to a ticket or paste it into a chat. Check free disk space before starting, and monitor WAF health and disk latency during the backup. The single CheeseWAF binary serves both the data plane and management plane, so stopping it can interrupt protection and traffic.

If an online backup is not possible, stop only the exact CheeseWAF writer through its service manager, confirm that no CheeseWAF process is writing, and copy a consistent database set including any adjacent -wal and -shm files. Validate the copy with PRAGMA integrity_check; before restarting the service. Do not use a broad process-stop command.

The current binary applies ordered SQLite migrations when it opens the store. The current schema is version 5. Migration 3 to 4 creates the append-only user_username_repairs audit table, and migration 4 to 5 adds credential_epoch to users and admin_sessions. Security changes advance the user epoch, and active sessions must match the current epoch. These migrations do not trim, lowercase, merge, or otherwise rewrite existing accounts. A binary that supports only an older schema rejects a newer database with newer SQLite schema version.

For a downgrade, restore and validate the backup taken before the upgrade, then start the older binary only after the exact service and data paths have been checked. Do not lower PRAGMA user_version by hand. If a username repair succeeds but must be undone, restore the pre-repair backup during a planned maintenance window; repair-username intentionally refuses to turn a canonical username back into an invalid one.

3. Support Bundle Packaging & CLI Localization

  • Support Bundle Archiving: When troubleshooting issues, package all runtime logs into a standardized, timestamped ZIP archive:
    BASH
    cheesewaf logs pack --dir /tmp --name cheesewaf-support.zip
  • CLI Interface Language:
    BASH
    # Display current language and supported options
    cheesewaf lang show
    
    # Persistently set CLI locale (supports en and zh-CN)
    cheesewaf lang set en

4. NTP Time Synchronization

JWT signature verification, TOTP token calculations, and cluster consensus rely on synchronized clocks:

  • Query Clock Sources: Call GET /api/system/time-sync to inspect offsets and active NTP servers.
  • Force Resynchronization: Call POST /api/system/time-sync/sync to trigger immediate alignment.
  • Reselect Lowest-Latency Peer: Call POST /api/system/time-sync/reselect to discover and switch to the lowest-latency NTP pool.

5. OTA Capability Status

YAML
update:
  ota:
    enabled: false
    server: ""
    channel: "stable"
    check_interval: 6h
    auto_update_rules: true
    auto_update_binary: false
    verify_signature: true
  • Current runtime boundary: The configuration keys are reserved for the OTA updater, but the current binary has no updater worker. The Updates page reports NOT_IMPLEMENTED, and enabling OTA through the system API is rejected with OTA_UPDATES_UNAVAILABLE.
  • Configuration safety: Keep enabled: false until an updater worker is shipped. The validator still checks the server URL, channel, interval, and signature settings when OTA is enabled.
  • Future behavior: auto_update_rules, auto_update_binary, and verify_signature describe the intended signed-update policy; they do not mean that rule or binary downloads run today.

6. Software Supply Chain Security & Integrity

Use only the release metadata that is actually published for the version you are deploying. The runtime does not create or verify a release signature on your behalf:

  • SBOM: If the release publishes a CycloneDX or SPDX SBOM, retain it with the deployment record and compare the listed version and digest to the artifact you received.
  • Container signatures: If the release publishes a Cosign signature, verify it against the exact image reference before deployment.
  • Windows signatures: If a Windows package includes Authenticode metadata, verify the signer and certificate chain on the machine that will install it.
  • Checksums: If the release publishes a checksum file, verify the exact artifact with sha256sum -c checksums.txt or the platform equivalent.

1.22 - Building from Source & Developer Guide

Go and Node.js toolchain requirements, compiling frontend and backend assets, running automated test suites, and regression testing with attack corpora.

This guide is intended for developers contributing code or building CheeseWAF directly from source. For standard production deployments, using official pre-compiled releases from GitHub Releases is strongly recommended.

1. Development Toolchain Requirements

  • Go Compiler: Go 1.26 or higher
  • Frontend Environment: Node.js 24.x LTS and npm package manager

2. Compile Frontend Assets & Main Daemon

Console Assets Embedding Note: When compiling from source, run bash scripts/ci/build-web.sh before go build. The script uses npm ci --ignore-scripts and builds with CHEESEWAF_AGENT_EYES=0; @agent-eyes/agent-eyes is development-only and must not enter release packages or production images. Do not use a bare npm ci that triggers its monorepo postinstall.

BASH
# Clone the repository
git clone https://github.com/LaokeQwQ/CheeseWAF.git
cd CheeseWAF

# Build static assets for the React Web console and copy them into the Go embed directory
bash scripts/ci/build-web.sh

# Compile the Go single-binary executable
go build -o bin/cheesewaf ./cmd/cheesewaf

# Create a runtime config copy and launch the instance
mkdir -p ./data/config
cp ./configs/cheesewaf.yaml ./data/config/cheesewaf.yaml
./bin/cheesewaf serve --config ./data/config/cheesewaf.yaml --data-dir ./data

3. Running Automated Tests & Code Quality Checks

BASH
# Execute Go unit tests and static analysis
go test -v ./cmd/... ./internal/...
go vet ./cmd/... ./internal/...

# Install frontend dependencies without development lifecycle scripts, then run checks
cd web && npm ci --no-audit --no-fund --ignore-scripts && npm run typecheck && npm test && cd ..

# Execute AST semantic engine regression benchmarks against attack corpora
go run ./cmd/cheesewaf-corpus --mode analyzer

cheesewaf-corpus runs built-in attack samples and false-positive corpora against the AST semantic analyzer, ensuring high detection rates without regression.

1.23 - Open-Source License & Ecosystem Repositories

Apache License 2.0 open-source licensing terms, trademark usage notice, and ecosystem repository directory.

CheeseWAF source code is open-source under the Apache License 2.0.

The CheeseSec and CheeseWAF brand names, typography, and product logos are protected trademarks and are not granted under the Apache 2.0 open-source license. When redistributing or referencing project branding, adhere to the NOTICE guidelines located in the CheeseSec_pages repository.

Ecosystem Repository Directory

Project RepositoryFunctionality & Role
LaokeQwQ/CheeseWAFPrimary product source code, issue tracking, and pre-compiled release artifacts
LaokeQwQ/CheeseWAF-AdaptersGo-first self-hosted gateway adapters for NGINX, Envoy, and Kubernetes (adapterd)
LaokeQwQ/CheeseSec_PluginPlugin catalog, release metadata, and CRP admission policies
LaokeQwQ/CheeseSec_Plugin_DocsPlugin developer handbook, CRP v1 specification, and offline extension contracts
LaokeQwQ/CheeseSec_DocsOfficial documentation website repository and maintenance guides
LaokeQwQ/CheeseSec_pagesOfficial brand portal and marketing site

For general issue reporting, email contacts, and vulnerability disclosure procedures, refer to Feedback & Security Reporting.

For product functional bugs, feature proposals, and security disclosures, submit an issue to the CheeseWAF Issue Tracker. For documentation errors or translation feedback, please submit an issue to the CheeseSec_Docs Issue Tracker.

1.24 - Feedback & Security Reporting

Communication channels and procedures for issue reporting, feature suggestions, and critical security disclosures.

CheeseSec welcomes community contributions and operational feedback. Please use the appropriate channel below depending on the nature of your report:

General Feedback & Issue Tracking

1. GitHub Issues

For operational defects, bugs, runtime errors, documentation corrections, or feature proposals, open an issue in the corresponding GitHub repository:

Project ScopeRepository & Issue TrackerIntended Coverage
Core Engine & ServerLaokeQwQ/CheeseWAF IssuesWAF daemon, data plane proxy, AST semantic engine, CLI utilities, and Web console
Gateway AdaptersLaokeQwQ/CheeseWAF-Adapters IssuesNGINX auth_request, Envoy ext_authz, and the adapterd daemon
Plugin EcosystemLaokeQwQ/CheeseSec_Plugin IssuesCRP specification, package manifests, and registry admission policies
Technical DocumentationLaokeQwQ/CheeseSec_Docs IssuesDocumentation accuracy, clarity, and bilingual synchronization

Issue Submission Guidelines: Include your operating system, architecture, CheeseWAF version (cheesewaf version), deployment mode (systemd service or Docker), and minimal reproduction steps. Sanitize logs to ensure database credentials, API tokens, and private keys are never exposed in public issues.

2. Email Correspondence

For general questions, private deployment inquiries, or matters not suitable for a public tracker, contact the project team via email:

  • Contact Email: coqimax@gmail.com

Critical Vulnerabilities & Security Disclosures

CheeseSec treats security defects with the highest priority. If you identify a security vulnerability, detection bypass, or critical stability defect in CheeseWAF or its ecosystem components, please follow Responsible Disclosure practices and do not post exploit details in public channels (such as GitHub Issues or social media).

Dedicated Security Contact

  • Vulnerability Reporting Mailbox: sec@cheesesec.com

Scope of Security Reports

Reportable issues include, but are not limited to:

  • Remote Code Execution (RCE) or arbitrary command injection
  • Management plane authentication bypass, privilege escalation, or session forgery
  • Universal detection bypasses against the AST semantic engine or baseline rulesets
  • Uncontrolled resource consumption, memory leaks, or deadlocks causing high-severity Denial of Service (DoS)
  • Exposure or insecure handling of sensitive configuration data, credentials, or keys

To accelerate verification and resolution, please include:

  1. Description & Severity: Vulnerability class, affected endpoints or components, and estimated impact.
  2. Affected Versions: Specific release versions or Git commit hashes.
  3. Proof of Concept (PoC): Clear, reproducible steps, including sample HTTP payloads, curl commands, or scripts.
  4. Prerequisites: Required user roles, configuration flags, or network topology necessary to trigger the defect.
  5. Remediation (Optional): Suggested patches or workarounds, if available.

Response & Handling Workflow

  1. Acknowledgment: The security team confirms receipt of reports sent to sec@cheesesec.com and opens an internal tracking case.
  2. Triage & Reproduction: Engineers reproduce the PoC in an isolated environment, evaluate severity, and prioritize a patch.
  3. Patch & Advisory: Once a fix is implemented and verified, a security patch release and corresponding Security Advisory are published. We request that reporters maintain confidentiality until the patch is publicly available.

1.25 - Words from the Developer

Design motivations, engineering philosophy, and personal reflections from the creator and core developer of CheeseWAF.

Beyond standard technical specifications and operational references, this section provides an open space for the project author and core developer to share reflections, architectural motivations, and perspectives on the journey of building CheeseWAF.

Personal reflections and engineering insights on building CheeseWAF, design trade-offs, and perspectives on self-hosted Web security.

1.25.1 - Words from the Developer

Personal reflections, architectural convictions, and perspectives from the author of CheeseWAF.

“Security should not be an expensive, closed black box that exhausts operations teams. It should be transparent, elegant, and dependable engineering infrastructure.”


Preface

If you are reading this document, perhaps you are preparing to deploy CheeseWAF on your servers, troubleshooting an elusive security incident, or simply exploring web security and application architecture as a fellow practitioner or enthusiast.

Whichever brings you here, I welcome you with all my heart.

Here, without cold CLI parameters or cryptic regular expression syntax, I want to use my own straightforward words to share why CheeseWAF came to life, and everything I have stood by and reflected upon throughout this journey.


Why CheeseWAF Was Created

Before committing to the project and writing the very first line of code for CheeseWAF, like many website operations and security engineers facing increasingly intricate web requests, I found myself caught in a difficult dilemma between exorbitant commercial WAF licensing quotes and the grueling rule maintenance, high false-positive, and false-negative rates of traditional open-source tools.

We often found ourselves trapped between two extremes:

  • Over-reliance on traditional regex signatures: As signatures accumulate, maintenance overhead multiplies exponentially, yet a slight variation in multi-layer encoding or character nesting can bypass them;
  • Blindly forcing LLMs into the synchronous request path: In the name of “intelligence,” forcing synchronous waits for remote LLM inferences within the reverse proxy pipeline turns a simple HTTP exchange into hundreds of milliseconds or even seconds of latency, ultimately crippling the entire business service.

We firmly believe that accuracy, low latency, and maintainability are the lifeline of the Data Plane, while deep semantic understanding should be entrusted to an asynchronous sidecar capable of decoupled execution and continuous self-learning. This is where CheeseWAF began: we aspire to build a truly commercial-grade, self-contained, out-of-the-box self-hosted WAF, empowering every developer and operations team to take full ownership of their application security, unconstrained by cloud vendors and expensive commercial licenses.


Architectural Convictions

Throughout the evolution of CheeseWAF, several engineering principles have been held as non-negotiable baselines:

  1. Self-Contained Single Binary: Consolidating complex components, the Web management console, and security engines into a single executable without wrestling with databases, middleware, or external dependencies beforehand. Written 100% in Go, CheeseWAF inherently possesses outstanding robustness and excellent portability, running directly across mainstream Linux, Windows, and macOS platforms. Furthermore, we natively support the LoongArch architecture, enabling seamless execution on hardware powered by domestic Loongson processors.
  2. Zero Compromise on the Request Path: An inspection pipeline capable of sub-millisecond to microsecond processing, rooted in clear Abstract Syntax Tree (AST) semantic parsing. Dynamically tuned to hardware performance profiles and refined through extensive GC tuning and hardware acceleration, it relentlessly pursues ultimate performance and concurrency.
  3. Defensive Authority Stays with the Operator: From gradual paranoia level progression to automated adoption of threat reviews, you can freely choose between autonomous AI remediation and manual alert approval. The ultimate control and final voice over your defense line always rest in your hands.

A Note to the Community

Building a serious Web application security product is by no means easy. It demands continuous adaptation to rapidly shifting attack vectors, modern Web protocols, and diverse production constraints.

As a newly launched, independently maintained open-source project in its formative stages, CheeseWAF continues to mature. If it helps you ward off an unexpected attack late at night, relieves your startup or small business from the heavy burden of commercial WAF licensing or cloud security costs, or simply makes your daily operations a bit easier and more dependable, that is already my greatest honor.

Anyone with ideas, feedback, or constructive critiques is warmly invited to connect via GitHub Issues or email (coqimax@gmail.com).

Finally, my sincere gratitude for your trust and confidence in CheeseWAF, and my deepest respect to everyone who loves open source and security craftsmanship.

— Laoke , Creator & Core Developer of CheeseWAF
September 2026

2 - CheeseSec Plugins

CheeseSec Plugins is an independent product shared across the CheeseSec ecosystem. It provides a common way to discover and develop plugins.

Each plugin declares its compatible hosts, versions, and capabilities. Check both the plugin description and the host documentation before installing it. A shared catalog does not mean every CheeseSec product supports installation or execution.

Browse plugins

Visit the plugin store to view published plugins without signing in. Only published entries are available; an example or an empty catalog is not an installable plugin.

Applications can read the v1 plugin catalog and the v1 stable update index.

Hello CheeseSec example

Hello CheeseSec 0.1.0 demonstrates startup, health checks, mode promotion, and shutdown. It does not detect attacks, collect data, or provide protection.

The store offers separate Linux amd64 and macOS arm64 packages. Each requires its matching platform and a compatible CheeseWAF process-plugin host. Other CheeseSec products must implement a compatible host before they can run it. Listing and downloading a package do not imply automatic installation or activation.

Packages carry two Ed25519 signatures. Before installation, check the package SHA-256, signatures, and host requirements. Confirm publisher keys through a trusted channel; downloading a package and its public keys from the same website alone does not establish trust in an unknown publisher.

Browse and download the example · Download reproducible source

Develop a plugin

Choose a supported host and follow its package and capability requirements. Include clear compatibility information and usage instructions, and verify the package signature before installation.

For the CheeseWAF host, see its plugin and CRP documentation. These host-specific instructions do not establish compatibility with other CheeseSec products.