Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Configuration

CSM is configured via /etc/csm/csm.yaml, with --config <path> to override. Legacy installs that only have /opt/csm/csm.yaml keep working; packaged upgrades migrate that file into /etc/csm/csm.yaml and leave the old path as a compatibility link. Optional drop-in fragments under /etc/csm/conf.d/*.yaml are merged on top of the main file at startup; see conf.d drop-ins below.

Environment-backed tokens and signing secrets use the environment inherited at daemon startup. After changing an environment file, restart the daemon; configuration reload alone does not import those changes. See credential rotation for the systemd procedure.

Installation defaults

Packages and csm install write the same commented configuration, so a new host starts with the same settings whichever way it was installed. A key left out of the file takes the built-in default, which can differ from the value the shipped file sets. Left out or left blank, backdoor_ports and firewall.smtp_allow_users take the shipped lists; write [] for none. Users missing from the host are skipped.

The CLI generates a fresh Web UI admin token and issue time, validates the result, and writes the new configuration with mode 0600. Invalid templates stop installation without replacing the destination configuration.

Operating mode

mode declares what CSM may do to the host. enforce (default) leaves every subsystem under its own switch; observe runs detection and alerting without automatic host remediation or integration updates. Full reference, including required switch settings: Observe mode.

mode: enforce

Platform & Web Server

CSM auto-detects the host OS (Ubuntu, Debian, AlmaLinux, Rocky, RHEL, CloudLinux), control panel (cPanel, Plesk, DirectAdmin, or none), and web server (Apache, Nginx, LiteSpeed, or none) at daemon startup. The detected platform is logged as:

[2026-04-10 08:13:37] platform: os=ubuntu/24.04 panel=none webserver=nginx

The daemon then chooses the correct log paths, config candidates, and check set without any configuration from you. Verify with:

journalctl -u csm.service | grep platform:

Web server overrides

For hosts with a custom layout (reverse proxy, non-standard package locations, chroot), add a web_server: section to csm.yaml. Every field is optional – anything left blank falls back to auto-detection.

web_server:
  type: "nginx"                          # apache | nginx | litespeed -- overrides auto-detect
  config_dir: "/etc/nginx"               # Apache or nginx configuration root
  access_logs:                           # tried in order until one exists
    - "/var/log/nginx/access.log"
    - "/srv/logs/nginx/access.log"
  error_logs:                            # used by ModSecurity deny watcher
    - "/var/log/nginx/error.log"
  modsec_audit_logs:
    - "/var/log/nginx/modsec_audit.log"

modsec_error_log (legacy single-path override) is still honored and takes precedence over web_server.error_logs for the ModSecurity watcher only:

modsec_error_log: "/opt/myapp/logs/modsec_audit.log"

Account roots (plain Linux web-scan coverage)

By default, web-root performance checks iterate /home/*/public_html, which is the cPanel layout. The WP-Cron check and remediation also use cPanel’s domain map for validated addon and subdomain document roots. On a plain Linux host, point CSM at the actual web roots:

account_roots:
  - "/var/www/*/public"            # e.g. Laravel/Symfony sites
  - "/srv/http/*"                  # Arch / generic layouts
  - "/home/*/public_html"          # add if you also have cPanel-style accounts

Each entry is an absolute, normalized glob pattern expanded at scan time. Configured directories also define remediation and restore scope. Custom locations need service write access; see Custom account roots. Non-existent matches are silently dropped. If account_roots is empty and CSM is not on a cPanel host, the account-scan checks return no findings (they run but find nothing, which is the correct behavior for a plain-Linux host with no configured web roots).

The setting covers perf_error_logs, perf_wp_config, perf_wp_transients, perf_wp_cron, real-time php.ini monitoring, and WP-Cron remediation roots. CMS integrity, phishing, .htaccess, and file-index scans use the platform’s account layout: every directory under /home on cPanel, DirectAdmin and plain hosts, under /var/www/vhosts on Plesk.

Minimal Config

hostname: "csm.example.com"

alerts:
  email:
    enabled: true
    to: ["admin@example.com"]
    disabled_checks: []                   # optional: suppress these checks from email only
    smtp: "localhost:25"

webui:
  enabled: true
  listen: "0.0.0.0:9443"
  auth_token: "<fresh random token>"
  auth_token_issued_at: "<UTC RFC3339 time when the token was generated>"

infra_ips: ["10.0.0.0/8"]

Full Reference

hostname: "csm.example.com"

# --- Alerts ---
# Email and webhook may both be off; findings then show only in the web UI and API.
alerts:
  email:
    enabled: true
    to: ["admin@example.com"]
    from: "csm@csm.example.com"
    smtp: "localhost:25"
    disabled_checks: []                 # check names to keep in web/history but exclude from email
  webhook:
    enabled: false
    url: ""
    type: "slack"                       # slack, discord, generic, phpanel
    hmac_secret: ""                     # phpanel webhook signing secret
    hmac_secret_env: ""                 # env var containing phpanel signing secret
  heartbeat:
    enabled: false
    url: ""                             # healthchecks.io, cronitor, dead man's switch
  max_per_hour: 10                      # alert emails/hour; CRITICAL always bypasses and is not counted. Code default 30; the shipped csm.yaml template sets 10
  block_digest:
    enabled: false                      # add per-country counts of auto-blocked IPs to the daily summary
    countries: []                       # empty = trusted countries, then all countries
    interval: "1h"                      # how often counts fold into the summary; live alert dedup window; below 1m runs as 1m and warns
    live: false                         # also send one alert per qualifying block
    send_on: "any"                      # live alerts: any | customer
    channel: ""                         # live alerts only: email | webhook; empty = enabled alert channels
    min_block: 1                        # watched blocks needed to show the summary section; 0 always shows it
  audit_log:                            # SIEM-friendly per-finding stream
    file:
      enabled: false
      path: /var/log/csm/audit.jsonl    # default; logrotate fragment ships with the package
    syslog:
      enabled: false
      network: udp                      # udp | tcp | unix | unixgram | tls
      address: 127.0.0.1:514            # host:port, or filesystem path for unix variants
      facility: local0                  # default: local0
      tls_ca: ""                        # optional CA cert for tls transport

# --- Integrity ---
integrity:
  binary_hash: ""                       # populated by baseline/rehash
  config_hash: ""                       # populated by baseline/rehash/reload
  confd_hash: ""                        # populated by baseline/rehash/reload
  immutable: true                       # apply chattr +i to the installed binary during install/rehash

# --- conf.d drop-in policy ---
confd:
  integrity_exempt: []                  # fragments an integration rewrites; left out of confd_hash (bare filenames)

# --- Thresholds ---
thresholds:
  mail_queue_warn: 500                  # default: 500
  mail_queue_crit: 2000                 # default: 2000
  deep_scan_interval_min: 60            # minutes between deep scans (default: 60)
  exposed_file_scan_depth: 2            # directory levels below each web docroot (default: 2, max: 10)
  multi_ip_login_threshold: 3           # IPs per account before alert (default: 3)
  multi_ip_login_window_min: 60         # time window for multi-IP check (default: 60)
  cred_stuffing_distinct_accounts: 5    # failed accounts from one IP before credential_stuffing (default: 5)
  pam_bruteforce_threshold: 5           # PAM auth failures from one IP before pam_bruteforce + auto-block (default: 5)
  pam_bruteforce_window_min: 10         # window for counting PAM failures per IP (default: 10)
  plugin_check_interval_min: 1440       # WordPress plugin check interval (default: 1440)
  brute_force_window: 5000              # failed auth attempts window (default: 5000)
  domlog_max_files: 500                 # per-domain access logs per WP brute-force scan (default: 500)
  domlog_tail_lines: 500                # trailing lines tailed from each domlog per scan (default: 500)
  domlog_max_age_min: 30                # skip per-domain access logs untouched in this many minutes (default: 30)
  mail_log_tail_lines: 500              # trailing lines of /var/log/exim_mainlog read by the mail-per-account scanner (default: 500)
  syslog_messages_tail_lines: 200       # legacy direct-check FTP tail only; daemon FTP detection follows the log forward and ignores this setting (default: 200)
  ftp_fail_window_min: 30               # sliding window (minutes) for per-IP pure-ftpd auth-failure accumulation before ftp_bruteforce; reported when a scan reads a new failure; diagnostic scans do not consume failures (default: 30)
  account_scan_max_files: 10000         # account and mail-domain paths per scanner cycle (default: 10000)
  # If this cap clips /home/<account>/ paths, account_scan_truncated names the affected account.
  # Rolling content coverage spends this cap once per cycle across the whole host, not once per account.
  crontab_base64_blob_max_bytes: 16384  # encoded bytes per crontab base64 candidate before decoded-content matching; must be a multiple of 4 (default: 16384)

  # Full-scan subsystem (`csm scan --full`) and rolling content coverage.
  full_scan_max_file_mb: 16            # cap on a single file scanned by a full scan, in MiB (default: 16)
  scan_job_retention: 20               # completed full-scan job records kept in the store (default: 20)
  rolling_coverage: true               # tri-state; default on. Normal periodic cycles prioritize new and changed PHP source under discovered document roots, then scan a slice of dormant files. Both share the account_scan_max_files budget; unfinished work resumes across cycles and accounts take turns. Set false to disable
  # Cursor write failures keep progress in memory until storage recovers; a restart loses that unpersisted progress.
  # Changed scans retry incomplete reads and directory listings, preserving earlier findings until coverage succeeds. Clock corrections rewind their progress when needed.
  # Rolling windows also preserve earlier findings when a content read fails. Reboots retain changed-scan progress instead of queuing all old files again.
  # Existing files on first discovery remain the rolling window's job. Coverage follows the same PHP extensions and depth limit as rolling scans.
  # Periodic forced rescans skip rolling coverage and expire old clean-file records without resetting changed-scan progress.
  dropper_detection: true              # tri-state; default on. Real-time flag for a PHP/executable created under a web docroot and unlinked before the TTL probe. Set false to disable
  dropper_unlink_ttl_sec: 300          # seconds a fresh docroot PHP/executable is tracked before the self-delete probe (default: 300, range 30-3600)

  # HTTP request flood, User-Agent spoof, and distributed HTTP detection.
  # These detectors scan the same per-vhost access-log stream as the WP
  # brute-force scanner; no extra log tailer is needed.
  #
  # http_flood_threshold: minimum per-IP request count inside the window
  # that emits http_request_flood. 0 disables the detector. The detector
  # ships disabled so operators can sample local baseline traffic first.
  # Adjust up for CDNs or CGNAT-heavy visitor pools before enabling.
  http_flood_threshold: 0              # 0 = disabled; set after sampling baseline traffic
  http_flood_window_min: 5             # rate window in minutes (default: 5)

  # http_ua_spoof_threshold: per-IP per-window count for non-browser UA
  # kinds (including claimed search-engine bots such as Googlebot/Bingbot/
  # Applebot that fail reverse-DNS confirmation) before http_ua_spoof fires.
  # A single bot-like request from a residential or mobile client no longer
  # hard-blocks it; sustained activity is required. Raise this for visitor
  # pools that legitimately send unusual User-Agents.
  http_ua_spoof_threshold: 30          # default: 30

  # xmlrpc_threshold: per-IP POST /xmlrpc.php count before xmlrpc_abuse fires
  # in access-log based detectors (a hard auto-block). WordPress sites using
  # Jetpack, the mobile app, or WooCommerce make many legitimate xmlrpc.php
  # calls, so this defaults higher than the legacy value. Set 0 to disable the
  # check entirely; an absent key uses the built-in default.
  xmlrpc_threshold: 100                # default: 100; 0 = disabled

  # http_distributed_min_ips: distinct already-abusive source IPs that hit
  # the same vhost in one scan window before a per-vhost distributed flood
  # finding fires. 0 disables the rollup for existing configs that do not
  # opt in.
  http_distributed_min_ips: 10         # sample setting; omit or set 0 to disable

  # URL scanner profile: fires http_scanner_profile for source IPs whose
  # in-window traffic is almost entirely probe-error responses spread
  # across many distinct request paths -- the shape of random-URL
  # enumeration hunting for downloadable files, exposed backups, and
  # dormant shells. Three gates must all pass: a minimum request volume,
  # a minimum error percentage, and a minimum count of distinct error
  # paths (query strings stripped, so cache-buster URLs on one missing
  # endpoint count once). A visitor following dead links, a broken image
  # hammered by one page, and a site migration all stay out of scope.
  #
  # 301 is deliberately not in the default status set: http->https and
  # www redirects make every legitimate visitor 301-heavy, and a site
  # migration redirects entire domains. Add 301 to
  # http_scanner_status_codes only on hosts where that traffic shape is
  # impossible.
  http_scanner_min_requests: 0         # volume gate; 0 = disabled (default); 30 is a safe start
  http_scanner_error_pct: 90           # min % of requests with probe-error status (default: 90)
  http_scanner_min_distinct_paths: 10  # min distinct error paths, max 512 (default: 10)
  http_scanner_status_codes: [404, 403] # statuses counted as probe errors (default: 404, 403)

  # Distributed expensive-request crawl from one ASN. The detector fires
  # only when request breadth, uncacheable volume, account share, and PHP
  # worker saturation agree. Set min_ips to 0 to disable.
  http_asn_crawl_window_min: 60
  http_asn_crawl_min_ips: 25
  http_asn_crawl_min_expensive: 250
  http_asn_crawl_min_share_pct: 50
  http_asn_crawl_high_amp_pct: 50
  http_asn_crawl_high_volume_mult: 4
  http_asn_crawl_saturation: 0          # 0 = performance.php_process_warn_per_user
  http_asn_crawl_max_prefix: 8
  http_asn_crawl_16_pref_pct: 60
  http_asn_crawl_max_tracked_ips: 20000
  http_asn_crawl_allowlist_asns: []
  http_asn_crawl_reverse_proxy_asns: [13335, 54113, 20940]

  # These three opt-in flags extend UA spoof detection to additional UA
  # classes. Leave disabled on busy shared hosts; scripting-language agents
  # and headless browsers appear on many legitimate monitoring stacks.
  http_ua_scripting_enabled: false     # flag curl/wget/python-requests/Go-http style UAs
  http_ua_headless_enabled: false      # flag Puppeteer/Playwright/PhantomJS UAs
  http_ua_empty_enabled: false         # flag requests with no UA at all

  # SMTP brute-force tracker (Exim mainlog, dovecot SASL on submission ports)
  smtp_bruteforce_threshold: 5            # per-IP failed auths before block (default: 5)
  smtp_bruteforce_window_min: 10          # sliding window in minutes (default: 10)
  smtp_bruteforce_suppress_min: 60        # cooldown between repeat findings (default: 60)
  smtp_bruteforce_subnet_threshold: 8     # unique IPs per /24 before subnet block (default: 8)
  smtp_account_spray_threshold: 12        # unique IPs targeting one mailbox before visibility finding (default: 12)
  smtp_bruteforce_max_tracked: 20000      # soft cap on tracked entries; oldest evicted (default: 20000)
  # Slow-brute pair: failed auths from one IP across 3+ distinct mailboxes
  # within the long window. Catches attackers pacing below the fast window.
  # Also fires on breadth alone: 10+ distinct walked mailboxes trigger the
  # block regardless of the failure count. A successful SMTP auth from the
  # source inside the window disqualifies it (live office NAT, not a walker).
  smtp_bruteforce_slow_threshold: 40      # failures before block (default: 40; 3-1024; explicit 0 disables)
  smtp_bruteforce_slow_window_min: 360    # slow sliding window in minutes (default: 360; 1-10080)

  # SMTP probe-abuse tracker (raw connect-rate per IP; catches scanners that
  # never reach AUTH). Threshold sized well above any legitimate MUA usage.
  smtp_probe_threshold: 100               # per-IP connects before block (default: 100; explicit 0 disables)
  smtp_probe_window_min: 5                # sliding window in minutes (default: 5)
  smtp_probe_suppress_min: 60             # cooldown between repeat findings (default: 60)
  smtp_probe_max_tracked: 20000           # soft cap on tracked entries; oldest evicted (default: 20000)

  # Mail brute-force tracker (IMAP/POP3/ManageSieve via mail_logs source)
  mail_bruteforce_threshold: 5            # per-IP failed auths before block (default: 5)
  mail_bruteforce_window_min: 10          # sliding window in minutes (default: 10)
  mail_bruteforce_suppress_min: 60        # cooldown between repeat findings (default: 60)
  mail_bruteforce_subnet_threshold: 8     # unique IPs per /24 before subnet block (default: 8)
  mail_account_spray_threshold: 12        # unique IPs targeting one mailbox before visibility finding (default: 12)
  mail_bruteforce_max_tracked: 20000      # soft cap on tracked entries; oldest evicted (default: 20000)
  # Slow-brute pair, as above. A recent successful login from the source or
  # failures confined to mailboxes it holds established good standing for
  # keep the source on the advisory path instead of blocking. Also fires on
  # breadth alone: 10+ distinct walked mailboxes trigger regardless of count.
  mail_bruteforce_slow_threshold: 40      # failures before block (default: 40; 3-1024; explicit 0 disables)
  mail_bruteforce_slow_window_min: 360    # slow sliding window in minutes (default: 360; 1-10080)
  mail_brute_account_key: "builtin:dovecot-user" # builtin:dovecot-user | builtin:postfix-sasl | regex:<capture>
  # Mail login spray rules (SMTP and IMAP/POP3): long memory of failed and
  # clean logins per IP. A clean login earns the IP trust on that mailbox.
  # Enforce mode blocks last far longer than other blocks, so a busy host
  # holds many at once: size firewall.deny_temp_ip_limit before enabling it.
  mail_spray_mode: observe                # off | observe (findings only) | enforce (block) (default: observe)
  mail_spray_window_min: 10080            # memory of failed and clean logins in minutes (default: 10080; 60-10080)
  mail_spray_breadth_mailboxes: 2         # finding once one IP (an IPv6 /64) has failed on this many untrusted mailboxes, the current one included (default: 2; 2-10; explicit 0 disables)
  mail_spray_missing_networks: 3          # finding once this many networks have tried one non-existent mailbox, the current one included (default: 3; 1-50; explicit 0 disables)
  mail_spray_block_expiry: "720h"         # how long an enforce mode spray block lasts; other blocks keep block_expiry (default: 720h; 24h-2160h)
  modsec_escalation_hits: 3          # denies from one IP before ModSecurity escalation (default: 3)
  modsec_escalation_window_min: 10   # ModSecurity escalation window in minutes (default: 10)
  modsec_low_confidence_escalation_hits: 30 # low-confidence-only backstop (default: 30)

# --- Web server overrides ---
# Leave these empty to use auto-detected paths for the running platform.
web_server:
  type: ""                              # apache | nginx | litespeed; empty = detect
  config_dir: ""                        # optional Apache/Nginx config root
  access_logs: []                       # candidate access logs, replacing detected paths
  error_logs: []                        # candidate error logs, replacing detected paths
  modsec_audit_logs: []                 # candidate ModSecurity audit logs
  # Override the per-vhost access-log glob patterns. Empty uses the
  # auto-detected default for the panel (cPanel, Plesk, DirectAdmin,
  # bare Apache, or bare Nginx).
  domlog_globs: []
  # IPs or CIDRs trusted by periodic access-log scans and the challenge server
  # to append or replace X-Forwarded-For with their observed peer. Other
  # HTTP readers protect these addresses without reading that header.
  # Automatic single-address responses never challenge or block a listed
  # address; queued blocks are discarded even while blocking is deferred.
  # This protection does not cover subnet blocks or manual operator blocks.
  # challenge.trusted_proxies entries count too. Addresses of this host
  # are never trusted. CSM skips an empty or unreadable entry and never
  # trusts one covering every address; csm validate warns about both,
  # and the daemon raises a High finding until a config without them runs.
  # Restart after correcting the lists; a reload keeps the running lists.
  # Legacy null or non-string scalar entries do not prevent startup,
  # reload or plain csm doctor; usable entries beside them still work.
  # Leave both lists empty to use the direct peer.
  trusted_proxies: []

# --- Infrastructure ---
infra_ips: []                           # management IPs/CIDRs/hostnames - never blocked

# --- Mail Logs ---
# Packaged releases include journald support. Custom builds need
# `make JOURNAL=1 build-yara` before `source: journal` can be selected.
mail_logs:
  source: auto                          # auto | file | journal
  file: ""                              # optional path override for file source
  units: ["postfix", "postfix@-", "dovecot"]  # journal units for source=journal or auto fallback; postfix@- is the Debian/Ubuntu instance

# --- Stalwart ---
# Read only on hosts where the stalwart service is the mail server.
stalwart:
  log_dir: /var/log/stalwart            # where Stalwart writes stalwart.log.YYYY-MM-DD
  log_prefix: stalwart.log              # file name before the date suffix
  ports: []                             # non-standard listeners as PORT:PROTOCOL (smtp, imap, pop3, sieve, http), e.g. ["10465:smtp"]
  api_url: http://127.0.0.1:8080        # Stalwart admin API for csm stalwart setup and csm doctor; https unless on this host; file-only. Supply the admin login when running setup
  api_key_file: /etc/csm/stalwart-api.key  # API key CSM uses to act on Stalwart; a regular file owned by root with no group or other access (0600); file-only

# --- State ---
state_path: "/var/lib/csm/state"        # bbolt DB and state files

# --- Suppressions ---
suppressions:
  upcp_window_start: "00:30"            # cPanel nightly update window start
  upcp_window_end: "02:00"              # cPanel nightly update window end
  known_api_tokens: []                  # API tokens to ignore in auth logs (e.g. ["phclient"])
  ignore_paths: []                      # glob patterns to skip in file scans; keep empty, an exempt directory is where an attacker hides
  suppress_webmail_alerts: true         # don't alert on webmail logins
  suppress_cpanel_login_alerts: false   # don't alert on cPanel direct logins
  trusted_countries: ["RO"]             # requires a loaded GeoLite2-City database; download credentials alone do not supply country data

# --- Auto-Response ---
auto_response:
  enabled: false
  kill_processes: false                 # kill malicious processes
  quarantine_files: false               # move malware to quarantine
  max_file_actions_per_hour: 50         # shared quarantine and file-cleaning attempt budget
  max_file_actions_per_account_per_hour: 10  # per-account share of the same rolling hour
  max_file_action_failures_per_hour: 3   # pause automatic file response after repeated failures
  block_ips: false                      # block attacker IPs via firewall
  block_expiry: "24h"                   # positive temporary block duration; omit for the 24h default; admission caps new temporary lifetimes; retries keep their first expiry
  http_asn_crawl_tempban: "24h"         # Critical ASN-crawl subnet ban duration
  # Shared scan-driven block budget; 0/omitted selects 50.
  # Also sets the admission ledger ceiling: 0/omitted selects 2000, capped at 20000.
  # A value sets both, so leave it out unless the ceiling should be lower too.
  # Outside dry run, with the firewall on, the ledger caps the IP blocks it applies.
  # See Automatic response admission in the API reference.
  # max_blocks_per_hour: 0
  enforce_permissions: false            # auto-chmod 644 world/group-writable PHP files
  fix_wp_cron: false                    # on perf_wp_cron findings, auto-disable WP-Cron and install a per-user system cron
  http_scanner_action: "challenge"      # response for http_scanner_profile: "challenge" (default) routes to the PoW page, "block" bans the IP
  block_cpanel_logins: false            # block IPs on cPanel/webmail/FTP/API thresholded brute findings (multi-IP login, webmail/API brute, FTP brute). Single direct cPanel form logins stay audit-only regardless of this flag.
  netblock: false                       # auto-block IPv4 /24 or IPv6 /64 subnets
  netblock_threshold: 3                 # IPs from same IPv4 /24 or IPv6 /64 before subnet block; minimum 2, omit for the default
  netblock_window: "168h"              # blocked IPs count this far back, expired blocks included; omit for the 168h default
  permblock: false                      # promote temp blocks to permanent
  permblock_count: 4                    # temp blocks before promotion; minimum 2, omit for the default
  permblock_interval: "24h"             # positive counting window; omit for the 24h default
  clean_database: false                 # auto-drop confirmed malicious DB objects after backup
  clean_htaccess: false                 # auto-clean .htaccess directives flagged by hardened detectors (backups under /opt/csm/quarantine/pre_clean/)
  virtual_patch_exposed_files: "off"    # off, manual CLI apply, or dry-run-gated auto apply except sample SQL
  disable_enforce_af_alg: false         # suspend periodic AF_ALG hardening re-assertion
  copy_fail_kill_process: false         # kill processes caught opening AF_ALG sockets via the live listener
  mail_auth_recovery:
    restart_enabled: false              # opt-in restart after sustained cPanel mail auth backend outage
    down_grace: "10m"                   # continuously-down duration before restart
    max_restarts_per_hour: 3            # hourly restart-attempt cap
    restart_command: "/usr/local/cpanel/scripts/restartsrv_dovecot"
  dry_run: true                         # safe default; previews IP blocks and web-exposed-file virtual patches
  verdict_callback:
    enabled: false                      # call panel before each auto-block
    url: ""                             # POST target for verdict requests
    hmac_secret: ""                     # signing secret, or use hmac_secret_env
    hmac_secret_env: ""                 # env var read at call time
    allow_unsigned: false               # true only for staged unsigned rollouts
    require_response_signature: true    # reject unsigned callback replies
    timeout_sec: 2                      # callback request timeout

  # PHP-relay auto-freeze. Off by default; only kicks in on cPanel hosts
  # where email_protection.php_relay.enabled is true. dry_run defaults to
  # true even when freeze is true, so an operator who enables freeze
  # without thinking gets a dry-run rather than a live exim -Mf storm.
  # Override at runtime with `csm phprelay dry-run on|off|reset`.
  php_relay:
    freeze: false                       # opt in to wire the exim -Mf hook into the alert pipeline
    dry_run: true                       # safe default; flip with `csm phprelay dry-run off [--persist]`
    max_actions_per_minute: 60          # rolling 60s cap on exim -Mf invocations

# --- Detection ---
detection:
  # Known-vulnerable WordPress plugin matching is default-on and alert-only.
  # Omit for the default, or set false to disable it. Allow entries suppress
  # only the exact reviewed slug and installed version.
  # vulnerable_plugin_scanning: true
  vulnerable_plugin_allow: []           # entries: <slug>@<version>, case-insensitive
  # db_object_scanning is tri-state: omit for the default (on),
  # `false` to explicitly disable. When off, the MySQL persistence
  # scanner emits no findings; the manual `csm db-clean --drop-object`
  # CLI keeps working for operator-driven cleanup.
  # db_object_scanning: true
  db_object_allowlist: []               # entries: <account>:<schema>:<type>:<name> -- suppresses db_unexpected_* warnings only
  admin_overlap_min_accounts: 2         # raise only if routine shared-admin accounts are expected on this host
  admin_overlap_trusted_emails: []       # exact reviewed admin emails that may manage multiple cPanel accounts
  admin_overlap_trusted_domains: []      # exact reviewed email domains for developer or reseller admin accounts
  # rescan_on_signature_update: true    # tri-state; omit for default-on, false pauses queued rescans
  af_alg_backend: "auto"                # auto | bpf | auditd | none
  connection_tracker_backend: "auto"    # auto | bpf | legacy | none
  connection_poll_interval: 30s         # legacy connection tracker interval
  exec_monitor_backend: "auto"          # auto | bpf | legacy | none
  exec_monitor_poll_interval: 30m       # legacy process monitor interval
  sensitive_files_backend: "auto"       # auto | bpf | legacy | none
  sensitive_files_poll_interval: 5m     # sensitive-file poll/watchset refresh interval
  placement_backend: "auto"             # auto | bpf | legacy | none; files renamed or hard-linked into a site; restart required
  direct_smtp_egress:
    enabled: false                      # detect non-MTA local processes opening outbound SMTP
    backend: "auto"                     # auto | bpf | legacy | none
    dry_run: true                       # safe default for detector-scoped action
    ports: [25, 465, 587]               # destination ports to inspect
  bad_asn_outbound:
    enabled: false                      # off by default; third leg of the host_takeover chain. Needs the GeoLite2-ASN database and operator-supplied ASN lists
    blocked_asns: []                    # ASNs always treated as bad (e.g. known bulletproof hosters)
    allowed_asns: []                    # non-empty switches to allowlist mode: any destination ASN outside this set is treated as bad

# --- BPF Enforcement ---
bpf_enforcement:
  enabled: false                        # master switch for in-kernel denial
  dry_run: true                         # log intended denials, allow the connect
  direct_smtp_egress: false             # gate enforcement on direct SMTP egress matches
  verdict_callback: false               # userspace advisory callback after the BPF decision

# --- Challenge Pages ---
challenge:
  enabled: false                        # enable PoW challenge pages instead of hard block
  listen_addr: 127.0.0.1                # bind address; 0.0.0.0 for direct redirects, unix:/run/csm/challenge.sock for a proxy on this host
  listen_port: 8439                     # TCP port; ignored when listen_addr uses unix:
  listen_group: ""                      # group allowed to open the unix: socket; the group your proxy runs as
  tls_cert: ""                          # optional HTTPS cert for direct/public challenge listener
  tls_key: ""                           # optional HTTPS key for direct/public challenge listener
  public_url: ""                        # required by webserver-integration, e.g. https://host:8439/challenge
  secret: ""                            # HMAC secret for tokens (auto-generated if empty)
  difficulty: 2                         # SHA-256 proof-of-work difficulty 0-5 (default: 2)
  trusted_proxies: []                   # proxies in front of this listener; HTTP checks trust them too
  port_gate:
    enabled: false                      # nftables gate for non-loopback challenge listener
  captcha_fallback:                     # widget for JS-disabled visitors (default off)
    provider: ""                        # "turnstile" | "hcaptcha" | "" (off)
    site_key: ""                        # public key embedded in the widget
    secret_key: ""                      # verified server-side
    timeout: 10s
  verified_session:                     # signed-cookie bypass for authenticated operators
    enabled: false
    cookie_name: csm_admin_session
    ttl: 4h
    admin_secret: ""                    # POST'd to /challenge/admin-token to mint cookie
  verified_crawlers:                    # reverse-DNS forward-confirm for search crawlers
    enabled: false
    providers: []                       # names: googlebot | bingbot
    cache_ttl: 15m

# --- PHP Shield ---
php_shield:
  # On CloudLinux, PHP runs inside a CageFS cage that cannot see the Shield
  # event socket. Installing or upgrading the Shield registers its root-owned,
  # non-writable directory in /etc/cagefs/cagefs.mp. Existing cages must be
  # remounted during a maintenance window: cagefsctl --remount-all recreates
  # every LVE on the host and disrupts running cages. A conflicting mount entry
  # is left unchanged.
  # csm doctor checks the event mount in running tenant cages. CSM's own
  # worker services are not cages and are left out of that check.
  # Rewritten command-parameter probes are quieted only when the Shield's
  # source fingerprint matches CSM's verified CMS content cache. Install the
  # updated Shield with csm install --php-shield-only; older events, unverified or
  # modified scripts, and incomplete request paths still alert. All recognized
  # observations remain in the root-only event archive, including quiet probes.
  # This does not verify code included by the entry script; content scanning
  # and runtime protection remain necessary.
  # A failed eval() is High, except when the reported eval() call sits in a
  # root-owned file that no account can change, such as the wp-cli bundled with
  # WP Toolkit running "wp eval". That file and every directory above it must be
  # root-owned, not symlinks, and not group or world writable when the event
  # arrives; such a failure is Warning. Tenants can already disable the
  # Shield in their own PHP processes. Every event field can be forged, so
  # this verifies only the reported path's ownership and permissions, not
  # the sender or evaluated code. A web request reaching such an eval() is
  # still reported at Warning. An ownership check that fails or times out
  # keeps the event at High, and a hung check does not delay later events.
  enabled: false                        # receive PHP Shield events and emit alerts

# --- Reputation ---
reputation:
  abuseipdb_key: ""                     # AbuseIPDB API key for IP reputation lookups
  whitelist: []                         # IPs to never flag as malicious
  # Async PTR + forward-A verification for IPs that claim search-engine
  # bot UAs (Googlebot, Bingbot, Applebot). When an IP claims a bot UA
  # but reverse DNS does not confirm it, the request counts toward
  # http_ua_spoof. Transient DNS lookup failures fail open and are
  # retried later. Set false only if your resolver is unreliable. See
  # docs/src/auto-response.md for the always-block behavior.
  bot_verify_enabled: true              # default: true
  verified_bots: []                     # optional custom crawler identities
  # verified_bots:
  #   - name: "seranking"               # rDNS-verified crawler
  #     ua_substrings: ["serankingbacklinksbot"]
  #     rdns_suffixes: ["seranking.com"]
  #   - name: "perplexitybot"           # AI agent verified by published IP ranges
  #     ua_substrings: ["perplexitybot"]
  #     ip_ranges: ["18.97.9.96/29", "18.97.1.228/30"]
  bot_ranges:                           # built-in AI-crawler range refresh
    auto_update: true                   # default: true; restart required to change
    update_interval: "24h"              # default: 24h, minimum: 1h
  rspamd:
    enabled: false                      # include rspamd rolling history in IP reputation
    url: "http://127.0.0.1:11334"       # rspamd controller URL
    token: ""                           # controller password, or use token_env; not needed for a loopback url
    token_env: ""                       # env var read at query time
  upstream:
    enabled: false                      # include panel-side threat-intel cache scores
    url: ""                             # HTTPS base URL; HTTP only allowed for loopback
    token: ""                           # bearer token, or use token_env
    token_env: ""                       # env var read at query time
    cache_ttl_min: 15                   # local cache TTL for upstream scores
    timeout_sec: 5                      # upstream request timeout
  report:
    enabled: false                      # opt-in abuse report delivery; restart required
    classes: []                         # bruteforce | php_relay | credential_stuffing | bad_asn_egress | spam
    spool_path: ""                      # default: <state_path>/abuse_reports.db
    spool_max: 10000                    # max queued reports, shared by all targets
    targets:
      - name: ""                        # stable target name
        url: ""                         # HTTPS collector URL; HTTP only allowed for loopback
        transport: "hmac"               # hmac | ed25519 (the central abuse database accepts ed25519 only)
        node_id: ""                     # sender node ID
        key_id: ""                      # receiver key ID
        key_env: ""                     # HMAC secret or Ed25519 private key env var
        token_env: ""                   # optional bearer token env var for HMAC targets
  central:
    enabled: false                      # opt-in central scored-set consume; restart required
    set_url: ""                         # HTTPS scored-set endpoint; HTTP only for loopback
    pubkey_env: ""                      # env var with Ed25519 public key hex
    auth_target: ""                     # report target whose node key signs downloads
    refresh_interval: 6h                # pull interval; default 6h
    action: "challenge"                 # off | challenge | block_if_local_corroborated
    block_threshold: 60                 # score needed before local corroboration can block

# --- Signatures ---
signatures:
  rules_dir: "/opt/csm/rules"           # YAML signature rules directory
  update_url: ""                        # remote URL to fetch rule updates
  auto_update: false                    # auto-download rules on schedule
  update_interval: ""                   # how often to check (e.g. "24h")
  signing_key: ""                       # required for any remote rule update path; 64-char hex Ed25519 public key
  allow_rule_count_decrease: false      # permit a deliberate drop below half the installed YAML rule count
  yara_forge:
    enabled: false                      # auto-fetch YARA Forge community rules
    tier: "core"                        # "core", "extended", "full" (default: "core")
    update_interval: "168h"             # how often to check for updates (default: weekly)
    download_url: ""                    # signed ZIP URL/template; supports {tier} and {version}
  disabled_rules: []                    # rule names to switch off, in Forge and in the shipped rules
  # yara_worker_enabled: true           # omit for the default: YARA-X runs in locked-down worker units; `false` runs it inside the root daemon

# signatures.signing_key is mandatory whenever either signatures.update_url
# is set or signatures.yara_forge.enabled is true. It must be the hex
# Ed25519 public key used to verify detached .sig files for rule bundles.
# Remote update URLs must use HTTPS and must not point at localhost,
# loopback, link-local, unspecified, or RFC1918 / ULA private addresses.
#
# YARA Forge upstream GitHub releases do not publish CSM detached signatures.
# To enable automatic Forge updates, mirror the ZIPs, sign each ZIP, publish
# the signature at the ZIP URL plus .sig, and set yara_forge.download_url to
# that signed mirror. Otherwise leave update_url empty and yara_forge.enabled
# false.

# --- Web UI ---
webui:
  enabled: true
  listen: "0.0.0.0:9443"               # address:port for HTTPS server
  auth_token: ""                        # API/login credential (auto-generated on install)
  auth_token_issued_at: ""              # optional UTC RFC3339 issue time; recorded on install
  auth_token_expires_at: ""             # optional UTC RFC3339 expiry; empty never expires
  session_lifetime: "24h"               # browser absolute expiry; maximum 720h; restart required
  session_idle_timeout: "30m"           # browser idle expiry; restart required
  tokens: []                            # scoped tokens: name/token/scope, optional issued_at, expires_at and allowed_ips (scope: admin, read or unban)
  metrics_token: ""                     # optional Bearer token for /metrics only
  metrics_token_issued_at: ""           # optional UTC RFC3339 issue time; rotate with metrics_token, then SIGHUP
  metrics_token_expires_at: ""          # optional UTC RFC3339 expiry; empty never expires
  tls_cert: ""                          # path to TLS certificate PEM file
  tls_key: ""                           # path to TLS private key PEM file
  ui_dir: ""                            # path to UI files on disk (default: /opt/csm/ui)
  allowed_origins: []                   # extra browser origins ("https://host[:port]") allowed to call the API; loopback is always allowed

# --- MCP (read-only endpoint for support agents) ---
mcp:
  enabled: false                        # serves /mcp on the Web UI listener; needs webui.enabled: true; restart required
  tokens: []                            # name/token, optional issued_at, expires_at and allowed_ips; all read-only, never valid on the Web UI

# --- Email AV ---
email_av:
  enabled: false
  clamd_socket: "/var/run/clamd.scan/clamd.sock"  # path to ClamAV daemon socket
  scan_timeout: "30s"                   # per-attachment scan timeout
  max_attachment_size: 26214400         # max single attachment size in bytes (25MB)
  max_archive_depth: 1                  # archive levels unpacked (1: attached archives only); a deeper archive counts as not fully scanned
  max_archive_files: 50                 # max files extracted per archive; also caps encrypted member names reported per message
  max_extraction_size: 104857600        # max total extraction size in bytes (100MB)
  quarantine_infected: false            # true moves infected messages to quarantine; false delivers them with a Critical email_malware finding
  scan_concurrency: 4                   # parallel scan workers
  fail_mode: "open"                     # behavior when a scan cannot complete: "open" (default) delivers; "tempfail" defers so Exim retries
  # Permission events have a five-second scan hold budget. When it expires,
  # the open is allowed ("open") or denied for retry ("tempfail"); an admitted
  # scan continues. A full scan queue applies the same policy immediately.
  # When messages repeatedly cannot start scanning within the hold budget, or
  # find the scan queue full, CSM raises email_av_hold_bypass and stops
  # queueing new scans for five minutes. A hold that runs out while the
  # message is already being scanned does not count. During this cooldown new
  # opens are allowed unscanned ("open") or deferred ("tempfail"). Scanning
  # resumes automatically afterwards; bypassed messages are not scanned later.
  # One sender's messages normally use at most half the scan_concurrency
  # slots (at least one), leaving slots for others when concurrency exceeds
  # one. The sender is the authenticated user, else the sending address (an
  # IPv6 /64), else the local account. Incomplete sender fields are ignored
  # when choosing the sender. Mail relayed through a filtering gateway,
  # unauthenticated mail submitted over SMTP from localhost, and bounces Exim
  # creates each count as one sender. Further messages wait without taking a slot;
  # when their hold budget runs out they follow fail_mode and are still
  # scanned afterwards. When too many messages from one sender are waiting,
  # further ones are scanned at once without waiting their turn. This overflow
  # can use every scan slot; email_av_source_backlog names the sender, at most
  # once a minute.
  # An archive that lists more than ten times max_archive_files entries, or
  # whose decompressed data passes max_extraction_size, counts as not fully
  # scanned and follows fail_mode. Nested archives share that budget. So do
  # corrupt gzip trailers, data after a tar end marker, legacy sparse tar
  # members and zip directory entries that carry data, at any nesting level.
  # Empty members and directories remain valid.
  # Late malware results can quarantine only the original, unlocked message.
  # Messages in active delivery, replaced spool files, and messages with a
  # pending delivery journal are left untouched with email_av_quarantine_error.
  # email_av_late_verdict means an allowed open later received a scan decision
  # to stop delivery; it does not mean a previously deferred message escaped.
  # Password-protected archive attachments are outside fail_mode. Their members
  # cannot be read without the password, so no retry ever makes them scannable
  # and "tempfail" would defer the message until it bounced. CSM delivers them
  # and reports email_av_encrypted_archive naming the archive and the member,
  # at most once an hour. A full alert queue does not consume this allowance.
  # Encrypted member names are capped at max_archive_files per message; the
  # warning counts any additional encrypted members without deferring delivery.
  # Both encryption schemes are covered:
  # legacy ZipCrypto and WinZip AES. Blocking such mail outright is an Exim
  # policy decision and is not something CSM does for you.
  # Attachments are unpacked in locked-down worker processes, one per
  # scan_concurrency slot, started on first use. When a worker cannot finish,
  # the message counts as not fully scanned:
  #   worker deadline reached     "parse worker timed out"
  #   worker memory cap reached   "parse worker ran out of memory"
  #   worker crashed or exited    "parse worker crashed"
  #   reply failed validation     "parse worker reply rejected"
  #   worker unit cannot start    "parse isolation unavailable"
  #   unit keeps failing to start "parse worker failing repeatedly"
  #   message failed twice before "parse worker failed on this message before"
  # The first four and the last are caused by the message. Outside observe
  # mode they request deferral whatever fail_mode says, so Exim retries it.
  # Deferral requires a permission event that is still holding delivery;
  # notification-only mode cannot block it. The two unit failures, and a unit
  # still starting when the scan deadline passes, follow fail_mode.
  # The first four raise email_av_parse_worker_failed, naming the message and
  # its sender, at most once a minute; a rejected reply also raises a Critical
  # email_av_parse_worker_rejected. The next two raise a Critical
  # email_av_isolation_unavailable. Each Critical finding is raised at most
  # once an hour. A message whose worker failed twice within a day is not
  # unpacked again on later delivery attempts, including after a spool watcher
  # restart. Failed starts, cancellation and local descriptor exhaustion do
  # not count against messages or senders. When messages from one sender
  # make workers fail three times, each within ten minutes of the one before,
  # a High email_av_parse_worker_source names the sender, at most once every
  # ten minutes. This advisory reports scan failures, not delivery outcomes.
  # It never blocks automatically, and blocking an address does not hide it.
  worker_memory_limit: 536870912        # memory and swap cap of each attachment worker in bytes (512 MiB); minimum 134217728 (128 MiB)
  # Up to scan_concurrency attachment workers run at once, and each may use up
  # to worker_memory_limit. A worker that reaches it is killed and the message
  # is deferred as "parse worker ran out of memory"; raise the limit if
  # ordinary mail reaches it. The phishing-kit zip worker keeps the default
  # cap. Changing it takes effect after a daemon restart.
  keep_crash_samples: false             # keep copies of messages and tenant zips that crash an attachment worker
  # Crash samples are for diagnosing worker crashes. They hold customer mail
  # and tenant files: they are readable by root only, stored in parse-crashes
  # under the state directory, capped at 20 samples and 500 MiB, and deleted
  # after 7 days, also after this setting is turned off. A link in place of
  # the parse-crashes directory is refused. Failed or incomplete copies are
  # discarded without changing the scan verdict or findings.

# --- Email Protection ---
email_protection:
  password_check_interval_min: 1440     # how often to audit email passwords (default: 1440)
  high_volume_senders: []               # accounts expected to send high volume (skip rate alerts)
  rate_warn_threshold: 50               # emails per window before warning (default: 50)
  rate_crit_threshold: 100              # emails per window before critical (default: 100)
  rate_window_min: 10                   # rate check window in minutes (default: 10)
  known_forwarders: []                  # expected forwarders and Sieve :copy rules

  # PHP-relay detector (cPanel only; gated by platform.IsCPanel at startup).
  # Off by default. When enabled, the daemon spawns the inotify spool
  # watcher, runs a startup spool walk, and starts the Path 2b retro scan
  # on /var/log/exim_mainlog. See docs/src/detection-realtime.md#php-relay
  # for what each path actually triggers on.
  php_relay:
    enabled: false                      # opt in to start the watcher
    rate_window_min: 5                  # Path 1 rolling window
    header_score_volume_min: 5          # Path 1: don't score until script has emitted N msgs
    absolute_volume_per_hour: 30        # Path 2 threshold per script
    account_volume_per_hour: 0          # Path 2b operator override; 0 = auto-derive from cpanel.config maxemailsperhour
    fanout_distinct_scripts: 3          # Path 4 threshold
    fanout_distinct_recipients: 5       # Path 2 + Path 4 recipient-diversity gate; 0 disables only this gate
    fanout_window_min: 5                # Path 4 window
    ip_recipient_spread: 5              # Path 6 threshold: distinct outside recipients per client IP (1-100); whole number; 0 disables Path 6
    ip_recipient_window_hours: 24       # Path 6 window in hours (1-168); whole number; 0 uses the default (24)
    ip_recipient_mode: observe          # Path 6 response: observe (findings only, default) or enforce (challenge, then block)
    policies_dir: "/opt/csm/policies/php_relay"  # optional mailer_classes.yaml + http_proxy_ranges.yaml (replaces the built-in proxy list); SIGHUP-reloadable
  cloud_relay:
    allow_users: []                     # full mailbox opt-outs for cloud-relay detection
    allow_domains: []                   # domain-wide opt-outs for cloud-relay detection

  # Email forward guard (cPanel only). Opt-in MTA-native enforcement for
  # external forward copies. Enforce mode can hold null-sender backscatter,
  # bad-sender-IP and spam-flagged copies before they relay to an external
  # provider, while the local mailbox copy still delivers. Spam-flagged means
  # the message carries X-Spam-Status: Yes, as antispam adds when it tags.
  # Any X-Spam-Status field with a Yes verdict counts, ignoring letter case.
  # Other text does not count as a spam verdict.
  # Malware and auth-fail signals are accounted in dry-run until Exim content
  # scanning is wired. CSM is not in the live mail path; an installed Exim rule
  # can keep holding matching copies even if the daemon is down. Held copies can
  # be released or deleted from the Email page.
  forward_guard:
    enabled: false                      # master switch (default off)
    dry_run: true                       # account/log only, do not actually hold (default true)
    quarantine_retention_days: 14       # held copies older than this are deleted; 0 keeps them
    hold_signals:                       # signal toggles, each default true
      bounce_backscatter: true          # null-sender bounce backscatter (enforceable)
      spam_flagged: true                # message carries X-Spam-Status: Yes (enforceable)
      malware: true                     # message carries malware (dry-run/accounting only)
      bad_sender_ip: true               # originating IP has bad reputation (enforceable)
      auth_fail: true                   # sender failed SPF/DKIM/DMARC auth (dry-run/accounting only)

  # Inbound spam filtering through rspamd on cPanel and Postfix hosts. Opt-in.
  # The operator installs rspamd and adds the scan socket. On cPanel CSM writes
  # the Exim hooks and its own rspamd settings, and each account's Spam Filters
  # switch decides whether its mail is filtered. On Postfix CSM writes only
  # rspamd files, every local domain is filtered and `exempt` lists the
  # exceptions. See docs/src/antispam.md.
  antispam:
    enabled: false                      # master switch (default off)
    dry_run: true                       # scan and log only; no reject, tag or split (default true)
    rspamd_socket: /run/rspamd/csm-normal.sock  # rspamd scan socket, not the reputation.rspamd controller
    reject_score: 15                    # reject at or above this rspamd score (default 15)
    tag_score: 6                        # add X-Spam-Status: Yes at or above this score (default 6)
    feeds:
      enabled: []                       # optional feeds, e.g. [mailspike, psbl]; see docs/src/antispam.md
      spamhaus_dqs_key_file: ""         # root-owned file holding the Spamhaus DQS key; needed only for spamhaus_dqs
    learning:
      enabled: false                    # learn from mail users move to Spam (cPanel) or Junk (Postfix) and keep one message per cluster; needs antispam; see docs/src/antispam.md
      redis_socket: ""                  # Unix socket of a Redis used only by learning, e.g. /run/redis-csm/redis.sock; Postfix needs one, cPanel uses rspamd's Redis when empty
      reporter: domain                  # Postfix only: one learning vote per mail domain (domain) or per mailbox (mailbox)
    exempt: []                          # Postfix only: recipient domains and mailboxes never filtered or learned from, e.g. [example.com, postmaster@example.net]

# --- Firewall ---
firewall:
  enabled: false

  # Open ports (IPv4). SSH (22) is intentionally absent; uncomment in
  # the YAML lists if sshd listens on 22. TCP 853 is DNS-over-TLS;
  # UDP 853 is DNS-over-QUIC.
  # 6277/24441 are DCC/Pyzor network checks used by SpamAssassin.
  tcp_in: [20,21,25,26,53,80,110,143,443,465,587,853,993,995,2077,2078,2079,2080,2082,2083,2091,2095,2096]
  tcp_out: [20,21,25,26,37,43,53,80,110,113,443,465,587,853,873,993,995,2082,2083,2086,2087,2089,2195,2325,2703]
  udp_in: [53,443,853]
  udp_out: [53,113,123,443,853,873,6277,24441]

  # IPv6
  ipv6: false
  tcp6_in: []                           # if empty, uses tcp_in
  tcp6_out: []                          # if empty, uses tcp_out
  udp6_in: []                           # if empty, uses udp_in
  udp6_out: []                          # if empty, uses udp_out

  # Restricted ports (infra IPs only)
  restricted_tcp: [2086,2087,2325,9443] # WHM and CSM Web UI ports

  # One TCP port opened to listed sources only. See firewall.tcp_in_allow
  # below.
  tcp_in_allow: []
  # tcp_in_allow:
  #   - port: 3306
  #     sources: [203.0.113.10, 198.51.100.0/28]

  # Outbound ports a service on this host needs. Checked, never added to
  # the policy: validation warns when an effective family policy omits one.
  # Integrations declare theirs in their own conf.d fragment.
  required_tcp_out: []

  # Passive FTP data ports. Left unset, 49152-65534 is opened on cPanel hosts
  # and hosts with pure-ftpd, proftpd or vsftpd installed, and stays closed
  # elsewhere. Explicit values take precedence; set both to 0 to close it.
  # passive_ftp_start: 49152
  # passive_ftp_end: 65534

  # Destination-scoped outbound TCP. tcp_out holds single ports only, so a
  # port range can only be expressed here -- needed when this host is an FTP
  # *client* and must open passive data connections to a known source.
  # dst takes an IP or CIDR. 0.0.0.0/0 means any IPv4 destination; ::/0 means
  # any IPv6 destination. Each rule applies to its own address family, and
  # validation warns: a wide range to anywhere is the outbound path the
  # output chain exists to close. When smtp_block is on, these rules follow
  # its guard and ranges that overlap smtp_ports are rejected.
  # An IPv6 destination emits no rule unless firewall.ipv6 is true.
  # IPv4-mapped prefixes under ::ffff:0:0/96 are treated as IPv4 prefixes.
  # Lockout warnings only credit valid rules in the connection's family;
  # scoped exceptions still warn because hostname resolution is not checked.
  tcp_out_allow: []
  # tcp_out_allow:
  #   - dst: 203.0.113.10/32
  #     port_start: 49152
  #     port_end: 65534

  # Peer-scoped protocols without ports, such as VRRP between the members of
  # a high-availability pair. See firewall.protocol_allow below.
  protocol_allow: []
  # protocol_allow:
  #   - protocol: vrrp
  #     peers: [192.0.2.11, 2001:db8::11]

  # Infra IPs/CIDRs/hostnames for firewall rules
  infra_ips: []

  # Rate limiting. SYN/conn-rate/UDP are dual-stack (IPv6 keyed per /64);
  # conn_limit is IPv4-only.
  conn_rate_limit: 200                  # new connections/min per source (CGNAT-tolerant; IPv6 per /64; 0 = disabled; null = default)
  syn_flood_protection: true            # per-source SYN flood meter (IPv6 per /64)
  conn_limit: 400                       # max concurrent connections per IPv4 source, IPv4 only (0 = disabled)
  drop_ipv4_options: true               # drop inbound IPv4 TCP carrying IP options, ahead of every accept (CVE-2026-98432 trigger)

  # Per-port flood protection: rate-limit new connections per source IP and IP family.
  # Defaults are sized for a busy mail host: 600/300s = 120 new conns/min/IP,
  # which tolerates a Thunderbird/iPhone client opening 5-15 parallel sessions
  # while still capping single-IP flood storms.
  port_flood:
    - port: 25
      proto: tcp
      hits: 600
      seconds: 300
    - port: 465
      proto: tcp
      hits: 600
      seconds: 300
    - port: 587
      proto: tcp
      hits: 600
      seconds: 300

  # DoS-exempt ranges: bypass configured DoS meters and subnet auto-blocks.
  # See firewall.dos_exempt_ranges below for full details.
  dos_exempt_ranges: []                 # CIDRs or single IPs exempt from connection/mail-port meters and subnet auto-blocks; /0 and bare hostnames rejected at load
  dos_exempt_known_mail_providers: true # also exempt Google and Microsoft mail-provider egress ranges; dynamic, cached, updated every 12h (default: true)

  # UDP flood protection (per-source meter; IPv6 per /64)
  udp_flood: true
  udp_flood_rate: 100                   # packets per second
  udp_flood_burst: 500                  # burst allowance

  # Country blocking
  country_block: []                     # ISO country codes to block
  country_db_path: ""                   # country CIDR directory (default: <state_path>/geoip, filled by `csm firewall update-geoip`)

  # Silent drop (no logging)
  drop_nolog: [23,67,68,111,113,135,136,137,138,139,445,500,513,520]

  # IP limits
  deny_ip_limit: 3000                   # max permanent blocked IPs
  deny_temp_ip_limit: 500               # max temporary blocked IPs; 0 = unlimited for existing blocking; admission forecasts then plan for 10000; a negative value reads as 0 with a warning

  # Outbound SMTP restriction
  smtp_block: false                     # block outgoing mail except allowed users
  smtp_allow_users: [cpanel, mailman]   # extra outbound SMTP users, also exempt from direct SMTP egress detection and BPF enforcement; root and mailnull are always allowed
  smtp_ports: [25,465,587]

  # Local port locks: "PORT:user,user"; only these users and root may open
  # new connections to the port on this host
  local_port_locks: []

  # Dynamic DNS
  dyndns_hosts: []                      # hostnames to resolve and whitelist periodically

  # Logging
  log_dropped: true                     # log dropped packets
  log_rate: 5                           # log entries per minute

# --- GeoIP ---
geoip:
  account_id: ""                        # MaxMind account ID
  license_key: ""                       # MaxMind license key
  editions:                             # MaxMind database editions
    - GeoLite2-City
    - GeoLite2-ASN
  auto_update: true                     # auto-update GeoIP databases (default: true when credentials set)
  update_interval: "24h"                # update check interval

# --- ModSecurity ---
modsec_error_log: ""                    # path to Apache/LiteSpeed error log for ModSec parsing
modsec:
  rules_file: ""                        # path to modsec2.user.conf
  overrides_file: ""                    # path to csm-overrides.conf
  reload_command: ""                    # command to reload web server (e.g. "/usr/sbin/apachectl graceful"); also activates CSM rule updates

# --- Performance ---
performance:
  enabled: true
  load_high_multiplier: 1.0             # load average / CPU cores multiplier for warning (default: 1.0)
  load_critical_multiplier: 2.0         # load average / CPU cores multiplier for critical (default: 2.0)
  php_process_warn_per_user: 20         # per-user PHP process count warning (default: 20)
  php_process_critical_total_multiplier: 5  # total PHP processes / CPU cores for critical (default: 5)
  error_log_warn_size_mb: 50            # error log size warning threshold (default: 50)
  error_log_critical_size_mb: 1024      # error log size that raises the finding to High (default: 1024)
  mysql_join_buffer_max_mb: 64          # MySQL join_buffer_size warning threshold (default: 64)
  mysql_wait_timeout_max: 3600          # MySQL wait_timeout warning threshold (default: 3600)
  mysql_max_connections_per_user: 10    # per-user MySQL connections warning (default: 10)
  redis_bgsave_min_interval: 900        # minimum seconds between Redis BGSAVE (default: 900)
  redis_large_dataset_gb: 4             # Redis dataset size warning threshold in GB (default: 4)
  wp_memory_limit_max_mb: 512           # WordPress memory_limit warning threshold (default: 512)
  wp_transient_warn_mb: 1               # WordPress transient data warning in MB (default: 1)
  wp_transient_critical_mb: 10          # WordPress transient data critical in MB (default: 10)
  wp_cron_fix:                          # tuning for the WP-Cron remediation (manual fix from the Web UI or auto_response.fix_wp_cron)
    interval_minutes: 15                # system cron frequency; default 15, clamped to [1, 60]
    php_bin: ""                         # override interpreter; empty = per-vhost PHP (inherit: .htaccess handler), then auto-detect

# --- Cloudflare ---
cloudflare:
  enabled: false                        # auto-whitelist Cloudflare IP ranges
  refresh_hours: 6                      # how often to refresh Cloudflare IPs (default: 6)

# --- Threat Intel ---
c2_blocklist: []                        # known C2 server IPs; connections with them are blocked
backdoor_ports: [4444,5555,55553,55555,31337]  # ports indicating backdoor activity

# --- Update check ---
updates:
  check_enabled: true                   # notify only; CSM never downloads or applies updates
  interval: "24h"                       # release check interval
  github_api_url: ""                    # optional release API mirror or test endpoint
  package_name: "csm"                   # apt/dnf package name for package-manager fallback

# --- Incidents ---
incidents:
  auto_close:
    enabled: true                       # auto-close idle open/contained incidents
    dry_run: false                      # log decisions without writing status changes
    by_kind:
      mailbox_takeover: 24h
      mailbox_bruteforce: 24h
      credential_spray: 24h
      web_attack: 24h
      web_account_compromise: 168h
  spray_suppression:
    enabled: false                      # collapse one-source credential spray into one incident
    dry_run: true
    distinct_mailboxes: 10
    severity_escalate_at: 50
    per_check: [email_auth_failure_realtime, pam_bruteforce, credential_stuffing]
    max_tracked_ips: 10000
    block_at_severity: ""              # "" | high | critical
  auto_block:
    enabled: false                      # block source IPs from incident correlations
    block_at_severity: ""              # "" | high | critical
    kinds: []                           # empty means all non-spray kinds with remote_ip

# --- Disabled checks (skip whole categories per host) ---
# Listed finding names disable the scheduled check runner(s) that emit them,
# including sibling findings from the same runner. Realtime findings are not
# affected. Use for whole categories that don't apply to a host (e.g. WAF/web
# checks on DNS-only cPanel servers, where httpd is installed but no virtual
# hosts serve traffic).
# For email-only suppression, use `alerts.email.disabled_checks` instead.
disabled_checks: []                     # e.g. [waf_status, waf_rules, waf_detection_only]

# --- Retention (bbolt growth control) ---
retention:
  enabled: false                        # opt-in; when true, a daily sweep prunes old entries
  findings_days: 90                     # keep active findings this long (0 disables the findings sweep)
  history_days: 30                      # keep findings-history entries and proven firewall
                                        # outcomes this long; it also sets how far back a
                                        # durable firewall action can be undone
  reputation_days: 180                  # keep IP reputation/attack entries this long
  sweep_interval: "24h"                 # how often the retention goroutine runs
  compact_min_size_mb: 128              # startup compaction floor; 0 disables auto-compaction
  compact_fill_ratio: 0.5               # compact when used_bytes / file_size drops below this

# --- Debug / diagnostics ---
debug:
  pprof_listen: ""                      # e.g. "127.0.0.1:6060"; MUST be loopback. Empty disables.
                                        # Reach it over SSH: go tool pprof http://127.0.0.1:6060/debug/pprof/heap
                                        # While listening, samples mutex and block contention; adds CPU overhead even without a profile request.

# --- Sentry (error reporting) ---
sentry:
  enabled: false                        # ship panics and selected errors to a Sentry server
  dsn: ""                               # Sentry project DSN
  environment: "production"             # e.g. "production", "staging"
  sample_rate: 1.0                      # 0.0 -> 1.0 (capture all errors)
  debug: false                          # SDK debug logs to stderr

Alert classes

Every finding CSM reports is immediate or summary class. Summary class covers what CSM already handled on its own:

  • an attack from an address CSM blocked, before or in the same batch, including by a subnet block or netblock;
  • an attack a challenge answers, while the address is on the challenge list or was routed there in the same batch. A challenge does not answer FTP or mail authentication failures, critical reputation sightings, or checks configured to require a hard block;
  • applied block and challenge notices, including permanent, subnet and netblock blocks, dry-run block verdicts, and the periodic count of applied automatic responses;
  • mail login advisories that never block, such as spray observe mode;
  • PHP relay freeze dry runs and rate-limit deferrals that need no follow-up.

Summary-class findings are left out of alert email and the generic alert webhook and are counted for the daily summary instead. They never spend the hourly alert budget. The findings page, history, incidents, the audit log, the event stream and the phpanel webhook still receive them. Only findings that would otherwise notify are counted: a suppression rule, or a check that never notifies, keeps its findings out of the summary too. Such a finding can still show that CSM blocked or challenged an address. If the summary fails to take its findings, the alert run reports an error and immediate alerts still go out.

Everything else is immediate. That includes attacks whose source CSM did not block: auto-response off or in dry run, a block that failed, was refused or is still queued, and checks that never block. Compromise evidence, successful logins, unauthenticated WHM script requests, suspicious mail content and findings that summarize several sources stay immediate even when the address is blocked, because blocking one address does not resolve them. A block of an address inside a Cloudflare allow range leaves ports 80 and 443 open, so its notice and the web attacks from that address stay immediate. Failed, paused or skipped automatic actions and auto-block queue and accounting notices are immediate too.

The generic webhook follows the same classes as email. alerts.email.disabled_checks mutes email only: a muted immediate finding still goes to the webhook, and a muted summary finding is still counted in the summary.

There is no setting for this policy, and the same classes decide what csm scan --alert sends. The former suppressions.suppress_blocked_alerts key is ignored; a config that still sets it loads, and csm validate warns so the key can be deleted.

Daily summary

CSM sends one summary of the findings it handled each day at 08:00 server local time. It goes by alert email when email alerts are on, and to the generic alert webhook when that is on, as event daily_summary with the counts under csm.summary (see the API reference). A phpanel webhook does not receive it. alerts.block_digest.channel selects live block alerts only; the daily summary uses every enabled alert channel. It goes out even with nothing to report.

It covers the window since the previous summary:

  • summary-class findings by check and severity, and how many of them come from checks muted by alerts.email.disabled_checks;
  • blocks applied, by kind, including netblocks and promotions to a permanent block;
  • challenges, and mail login advisories that never block, such as spray observe mode;
  • the 10 addresses with the most summary findings, with their country when GeoIP knows it;
  • automatic blocks that hit a known customer, as their immediate alert named them, so a failed alert still reaches you: up to 50 a day, then a count of further blocks;
  • dry-run block verdicts and spray observe-mode verdicts that would have blocked a known customer, listed alongside their finding counts: up to 50 blocked addresses or networks a day, each listed once, then a count of further verdicts;
  • with alerts.block_digest.enabled, watched-country blocks by country and category, once they reach min_block.

CSM tracks up to 1,000 source addresses a day. Past that, a new address takes the place of the one with the fewest findings, so heavy sources stay listed and a count can be overstated, never understated.

Counts are saved at each block_digest.interval (one hour by default), after the final shutdown drain and before delivery. A crash can lose counts since the last save. If the host was down at 08:00, the missed summary goes out at the next start. A failed destination is retried after one minute, then with the wait doubling up to one hour; a restart retries it at once. CSM logs its first failure and again when the wait reaches an hour, and destinations already saved as successful are not retried. While a delivery is pending, new findings accumulate in the next window. When the next summary is due and a destination still has not taken the previous one, CSM drops the previous one for that destination, logs it once and counts it as one lost notification, then sends the new summary to every destination. A summary whose state cannot be saved is still sent; the save warning backs off the same way as a failing destination.

A crash after a destination accepts a summary but before CSM saves that success can repeat it. Clock corrections are checked every minute. Moving back across one or more morning sends does not resend dates already covered, including after a restart. Sending resumes on the first unsent local date. A send recorded more than two days ahead of the clock comes from a clock fault: CSM logs it once, ignores it and sends the next morning.

Only the daemon counts findings. A one-off csm scan --alert prints every finding; its summary-class findings are neither emailed nor counted in the daily summary. The hourly block digest email no longer exists.

Customer login history records the source addresses of authenticated cPanel, webmail, SMTP, IMAP, POP and FTP logins for 30 days. Buffered logs keep their original login time, so reading old logs does not renew expired history. FTP logins retain their authenticated account even when the displayed log record is shortened. FTP command text and failed login names do not count as successful logins. An applied automatic block of a known customer is alerted at once; see the known-customer block alert.

An IPv6 customer is recorded by its /64, so a host that changes privacy addresses stays known. Each account holds a bounded number of addresses per log source; logins without an account name share one budget, and an FTP login counts against the hosting account that owns the FTP account.

History has two fixed halves: logins read from syslog (FTP, IMAP, POP and Postfix SMTP) and logins read from cPanel’s session log and the Exim mainlog. Any local user can write to syslog, so each half trims only itself, and a syslog login never replaces a session log or Exim login for the same address. When a half is full, the accounts holding the most addresses lose their oldest logins first, so a flood of logins evicts only its own accounts. History is saved every minute and after log readers stop during a clean shutdown.

Web UI Exposure

An admin token can change firewall rules, files under account homes and most settings, so treat the Web UI as privileged access. The shipped listen: "0.0.0.0:9443" answers on every interface, which the WHM addon needs. csm validate and csm doctor warn when the UI listens on a non-loopback address, an admin token has no allowed_ips or allows an entire address family, and the CSM firewall policy does not restrict that family. These warnings do not make either command fail.

Enabling the firewall alone does not clear the warning. Keep the UI port out of public tcp_in and tcp6_in entries, or add it to restricted_tcp (which includes 9443 by default). Keep it outside the passive FTP range. Wildcard listeners can accept both address families, so also enable firewall.ipv6. Except for localhost, hostnames are checked against both families without resolving DNS. Alternatively, limit admin tokens with allowed_ips, or listen on 127.0.0.1:9443 and reach the UI through an SSH tunnel. An external firewall may already restrict access, but configuration validation cannot verify it.

TLS Certificates

The Web UI serves over HTTPS. Configure TLS certificates under webui:

webui:
  tls_cert: "/var/cpanel/ssl/cpanel/mycpanel.pem"   # certificate PEM file
  tls_key: "/var/cpanel/ssl/cpanel/mycpanel.pem"     # private key PEM file

On cPanel servers, you can reuse the cPanel self-signed certificate (both cert and key are in the same PEM file). For production, use a proper certificate from Let’s Encrypt or your CA.

The private key may appear before or after the certificates. The first certificate must be the leaf served by the Web UI, followed by any chain certificates. Renewal only replaces an expiring CSM-generated leaf; it preserves the private key and all other contents of a combined file. Certificates issued outside CSM are left unchanged.

If both paths are empty, CSM generates an ECDSA self-signed certificate and key under state_path. Set both paths to use an operator-managed certificate. Configuring only one of the pair is invalid.

Validation

csm validate           # syntax check
csm validate --deep    # syntax + connectivity probes (SMTP, webhooks)
csm config show        # display config with secrets redacted

Editing csm.yaml by hand

CSM stores a sha256 of the main config in integrity.config_hash and a separate digest of loaded drop-ins in integrity.confd_hash. It refuses to start if the on-disk files disagree with those values. This is a tamper-detection feature. It catches edits that were never recorded, but it does not stop anyone who can write /etc/csm, because they can record new hashes too. There are two supported edit workflows depending on which fields you touch.

Fast path: SIGHUP reload (safe fields only)

For fields tagged as hot-reload-safe (alerts, thresholds, detection, suppressions, auto_response, bpf_enforcement, reputation, email_protection, disabled_checks, confd), the daemon can accept the change without a restart:

sudo cp /etc/csm/csm.yaml /etc/csm/csm.yaml.bak-$(date +%s)

# edit /etc/csm/csm.yaml with your favourite editor

sudo systemctl reload csm
sudo journalctl -u csm -n 20 --no-pager

Every save CSM makes itself (the Settings page, csm rehash, the installer) first copies the current file to csm.yaml.bak next to it, so the previous version is one cp away. For a symlinked config, the backup sits beside the resolved target. A first write creates no backup; an unchanged save keeps the previous backup. Backups have mode 0600.

Retired settings are ignored with validation warnings, including settings in YAML merges and conf.d fragments. Removing them does not require a restart.

A reload after a comment edit or retired-setting removal updates the live integrity hashes even when no setting changes. This includes edits to conf.d fragments. If csm rehash already signed the edit, reload adopts the verified hashes without rewriting the main config. A reload with no edits neither rewrites the config nor republishes it, so it leaves dry-run history alone. Signing failures emit a Critical config_reload_error finding and count as reload errors.

systemctl reload sends SIGHUP (wired via ExecReload= in the unit file). The daemon re-reads the file, validates it, diffs it against the running config, and if every change is on a field tagged hotreload:"safe" it swaps the new values into the live config and re-records the integrity hashes on disk. The next check tick sees the new thresholds; fanotify marks are not dropped.

Reloads and Web UI saves share one config-write lock. If a reload signs the config but cannot open the phpanel delivery queue, it reports a reload error and keeps the previous settings and mail account parser active. The live integrity hashes still follow the signed config, so scheduled checks continue.

The tagged-safe top-level fields are alerts, thresholds, detection, suppressions, auto_response, bpf_enforcement, reputation, email_protection, disabled_checks, and confd. The Settings API derives its restart hints from the same manifest that drives config.Diff, so UI hints and SIGHUP behavior cannot drift silently. A save from the Settings page runs the same apply steps as a SIGHUP, so a changed threshold, reputation whitelist, verified-bot list, forward-guard setting or response ceiling reaches the live daemon at once. Changes to their sub-keys are picked up on the next tick by the periodic scanners, the auto-response helpers (block/kill/quarantine/challenge/permission-fix), alert dispatch, and the heartbeat.

reputation.verified_bots is reconciled on reload and the bot-verifier cache is restamped when the list changes.

reputation.bot_ranges controls a long-lived updater goroutine and is tagged restart-required. A reload that changes it emits config_reload_restart_required; restart the daemon to change the auto-update switch or interval.

Two sub-keys are runtime-state exceptions. They live under a safe-tagged parent and SIGHUP accepts edits to them, but they seed long-lived in-memory state at daemon startup. Restart the daemon if you need the running process to use the new value:

  • reputation.whitelist – seeded into the threat database at startup and replaced on every successful reload, so editing the list in csm.yaml and sending SIGHUP takes effect at once. The threat database also exposes its own runtime API for adding and removing whitelist entries (via the Threat Intelligence page in the Web UI or the /api/v1/threat/* endpoints); those entries are persisted to disk and are kept separate from the configured list, so a reload never drops them.
  • email_protection.known_forwarders – captured by the forwarder watcher at startup and read by scheduled forwarder and mail-filter checks. No runtime API yet; send a restart if you edit this list.

auto_response.mail_auth_recovery is a restart-required sub-key under the otherwise safe auto_response section. It is captured by the cPanel mail auth backend probe at startup, so a reload that changes it emits config_reload_restart_required and leaves the live config unchanged.

alerts.block_digest is restart-required under the otherwise safe alerts section. The collector and ticker are built at startup, so a reload that changes these settings emits config_reload_restart_required and leaves the live config unchanged. When countries is empty, the fallback to suppressions.trusted_countries still follows safe reloads. Delivery uses the current email and webhook settings. The daily summary section gives by-country and by-category counts, and live alerts add by-reason counts; WAF categories group ModSecurity escalations and high-volume WAF attacker blocks together.

If you turn off alerts.block_digest.enabled in Settings, restart before turning off the last alert channel. Until the restart the watched-country section and live alerts stay on, and Settings rejects a channel change that would leave them with no channel. Once the running configuration has the watch off, email and webhook may both be off, and then no daily summary is sent.

The rest of the sub-keys in every safe-tagged section are read per-call (inside check functions, auto-response helpers, alert dispatchers) and hot-reload cleanly on the next tick.

Look for one of three log shapes in the journal:

  • SIGHUP: config reloaded; safe fields updated: [thresholds] – success. The new values are live.
  • config_reload_restart_required: SIGHUP reload: restart-required fields changed: [hostname ...]; live config unchanged – the edit touched a field that cannot be hot-swapped. A Warning config_reload_restart_required finding is also emitted. Fall back to the restart path below.
  • config_reload_error: SIGHUP reload: parse failed ... or ... validation error ... – the file on disk is not loadable or fails csm validate. A Critical config_reload_error finding is emitted. The live config is unchanged; fix the file and repeat.

Restart path: unsafe fields

Fields not tagged hotreload:"safe" (the majority, including hostname, state_path, webui.listen, firewall.*, email_av.* and anything that survives only one re-init per daemon lifetime) require a full restart. The integrity hashes must be re-recorded first:

sudo cp /etc/csm/csm.yaml /etc/csm/csm.yaml.bak-$(date +%s)

# edit /etc/csm/csm.yaml with your favourite editor

sudo /opt/csm/csm rehash     # re-records integrity hashes
sudo /opt/csm/csm validate   # syntax + value sanity
sudo systemctl restart csm
sudo systemctl status csm    # confirm active, no crash-loop

If the restart fails (most commonly because rehash was skipped), roll back with sudo cp <backup> /etc/csm/csm.yaml && sudo systemctl restart csm. The backup carries its own matching hash so no second rehash is needed.

Config-management tools

Config-management workflows (Ansible, Puppet, Chef) should:

  • For safe changes, notify systemctl reload csm instead of restart. The daemon re-records the hash itself; no separate csm rehash step is required.
  • For any change that may touch a restart-required field, run csm rehash before the restart notify fires. Or always send reload first, read the journal, and promote to restart only when the reload logs restart-required.

conf.d drop-ins

Files matching /etc/csm/conf.d/*.yaml are loaded after the main config and deep-merged on top of it. Override with --config-dir <path> or CSM_CONFIG_DIR; the flag wins when both are set.

Explicit operator overrides require an existing directory.

  • Order: lexicographic by filename. Scalar keys in 20-overrides.yaml override the same keys in 10-base.yaml. Use a numeric prefix.
  • Merge semantics: maps merge recursively; scalars replace the value from the main file; lists append in fragment order. All-scalar lists drop duplicate entries while keeping the first occurrence; structured lists such as webui.tokens keep every entry.
  • Trust: override directories must be absolute, must exist, and must be owned by root or the running process. The directory and every loaded fragment must not be group- or world-writable. Safe symlinked fragments are allowed, so packaged profiles can still be linked into /etc/csm/conf.d/.
  • Integrity ownership: drop-ins cannot set the integrity block. Integrity metadata is stored only in the main config.
  • Hash: integrity.config_hash covers the main file and integrity.confd_hash covers loaded drop-ins. After editing a drop-in by hand, run csm rehash before restarting, or use systemctl reload csm so the daemon can re-hash after validating the merged config. Rehash re-hashes the resolved main file only; when a real legacy copy still exists at /opt/csm/csm.yaml with the same operator content, rehash replaces it with the compatibility symlink so the two never drift. Web settings saves refuse to bless a drop-in change that has not already been re-hashed. A mismatch is refused at the next daemon start with an error that names csm rehash. Until then the running daemon keeps its old hashes, but its periodic integrity check raises a tamper finding and skips the scheduled checks on every cycle; csm doctor reports the same mismatch, so it can be fixed before a restart turns it into an outage.
  • Integration-owned fragments: a fragment its owning package rewrites on its own schedule (phpanel-server-agent rewrites 10-phpanel-runtime.yaml on every bootstrap) cannot be pinned by a static hash without making every one of those rewrites a failed restart. List such fragments by bare filename under confd.integrity_exempt in the main config, then run csm rehash once. Their content is left out of confd_hash; every other fragment stays covered. The list lives in the main config, outside the integrity block, so it is itself covered by config_hash, and a fragment cannot set confd to exempt itself.
  • Scoped re-hash: an integration that rewrites a covered fragment of its own runs csm rehash --fragment <file> (repeat the flag for several files) instead of a full csm rehash. It re-records hashes only when the named files are the only change since the last recorded state. If the binary, the main config or any other fragment changed, it records nothing and names what changed. A named file may be new, edited or deleted; a deleted one must have been part of the recorded state. Fragments under confd.integrity_exempt stay outside the recorded state either way. CSM keeps a per-fragment record in csm.yaml.confd-fragments.json beside the main config. Every hash update writes it, and each daemon start that verifies conf.d writes one when it is missing or out of date, so upgraded hosts need no extra step. Exit codes:
    • 0: re-hashed, or nothing had changed.
    • 4: refused because something besides the named files changed; stderr lists it.
    • 5: no per-fragment record for the current recorded state yet. A full csm rehash re-hashes everything and writes one.
    • Any other non-zero code: an error, including a corrupt record, an incomplete option, an invalid fragment name or a file that never existed. Do not fall back to a full csm rehash on these errors.
  • Record privacy: the per-fragment record retains covered fragment contents to validate them against the recorded digest. It is written with owner-only access beside the resolved main config and must be protected like the config itself. A corrupt record never authorizes a fallback to a full rehash; a successful startup verification can rebuild it from verified fragments.
  • Use cases: packaged integration profiles (e.g. /usr/lib/csm/profiles/phpanel-agent.yaml symlinked into conf.d/), per-host automation that should not touch the operator’s csm.yaml, secret material rendered from a vault.
ls /etc/csm/conf.d/
# 10-phpanel-agent.yaml   20-tenant-overrides.yaml

csm validate                # validates the merged config
csm config show             # prints the merged, redacted config
csm config schema           # JSON Schema for editor / CI validation

csm validate and csm config show always operate on the merged config so you can audit the effective state without grepping fragments.

detection.direct_smtp_egress

The direct SMTP detector’s backend accepts auto, bpf, legacy, or none; ports must contain TCP ports in the 1-65535 range. See Direct SMTP egress.

bpf_enforcement

BPF enforcement requires a BPF-capable connection tracker at runtime; auto falls back to legacy detection on older servers. See BPF enforcement.

firewall.tcp_in_allow

tcp_in_allow opens one TCP port to listed sources only. Each entry names a port and its sources:

firewall:
  tcp_in_allow:
    - port: 3306
      sources:
        - 203.0.113.10
        - 198.51.100.0/28
        - 2001:db8::11

Use it for a database, replication or monitoring port that a few known hosts need and nobody else should reach. The port does not need to be in tcp_in, and it may be in restricted_tcp. infra_ips is the wrong tool for this: it opens every port to the address.

port is a single TCP port. sources is required and takes IPv4 and IPv6 addresses or CIDRs; a bare address means that one host, the same as /32 or /128. A port out of range, an empty list, a malformed address and a world-wide prefix (0.0.0.0/0, ::/0) are validation errors; open a port to everyone in tcp_in instead. IPv6 sources need firewall.ipv6: true; with it off, IPv6 is not filtered at all and validation warns.

The Web UI and sshd lockout warnings treat a port with at least one usable source here as deliberate and stay quiet for it, in both IP families. An entry whose sources render no rule, such as IPv6 sources while firewall.ipv6 is off, does not count. A usable source also keeps a port in restricted_tcp reachable without infra_ips.

The accepts come right after infra_ips and before the blocked address, blocked subnet and country rules, and before the rate limits. A listed source therefore keeps reaching its port while it is blocked, and only that port: every other port still follows the blocklists. csm firewall deny on a listed source does not close the port for it. Remove the source from the entry and run csm firewall restart instead.

Entries from conf.d fragments are added to the ones in csm.yaml. A change takes effect on csm firewall restart. csm firewall status and csm firewall ports list the applied entries, including changes made by a firewall restart or rollback, and the Web UI firewall page shows and counts the entries with its port exceptions. That page reads the config the daemon loaded, so after a firewall restart or rollback it can differ from the applied policy until the daemon reloads; the CLI shows what is applied. Hosts that support the key report the firewall.tcp_in_allow.v1 capability.

For a single address on one host without a config change, csm firewall allow-port still works. That allow is a soft one: it sits after the blocklists, so an operator block overrides it.

firewall.protocol_allow

protocol_allow opens an IP protocol that has no ports to listed peers only. Each entry names a protocol and its peers:

firewall:
  protocol_allow:
    - protocol: vrrp
      peers:
        - 192.0.2.11
        - 2001:db8::11

The only protocol today is vrrp (IP protocol 112), for keepalived and other VRRP speakers on database or load-balancer pairs. tcp, udp, icmp and icmpv6 have their own keys and are refused here. peers is required and takes IPv4 and IPv6 addresses or CIDRs. An empty list, an unknown protocol, a malformed address and a world-wide prefix (0.0.0.0/0, ::/0) are validation errors.

For each peer the input chain accepts the protocol from that address and the output chain accepts it to that address. For vrrp the output chain also accepts advertisements to the VRRP multicast group of each family that has a peer (224.0.0.18, ff02::12). Advertisements a peer sends to the group match its input rule. IPv6 peers need firewall.ipv6: true; with it off, IPv6 is not filtered at all.

The input accepts come right after infra_ips and before the blocked address, blocked subnet and country rules. A blocked peer therefore still exchanges VRRP with this host, and only VRRP. Without this, a block on a peer makes both members claim the shared address. Blocks of other addresses do not affect these rules.

csm firewall status and csm firewall ports list the applied entries, including changes made by a firewall restart or rollback. Hosts that support the key report the firewall.protocol_allow.v1 capability.

firewall.dos_exempt_ranges

dos_exempt_ranges is a list of CIDRs or single IPs (/32 for IPv4, /128 for IPv6) declared by the operator. Entries are validated at startup; /0 default routes, bare hostnames, and malformed CIDRs are rejected before the daemon starts. Default: empty (no declared ranges).

dos_exempt_known_mail_providers (bool, default true) adds Google and Microsoft outbound mail IP ranges to the effective exempt set automatically. The ranges are sourced dynamically and cached on disk; a built-in snapshot covers startup before the first live refresh. The cache is refreshed every 12 hours.

Sources in the effective exempt set bypass the new-connection rate-limit for their IP family, the IPv4 concurrent connection-limit, and the TCP port 25/465/587 flood meters for their IP family. Subnet auto-block (spray, ASN-crawl, and netblock escalation) skips CIDRs that intersect an exempt range, and exempt IPs do not count toward the netblock threshold.

Exempt sources do not bypass: manual blocks (csm firewall deny or csm firewall deny-subnet), SYN flood protection, UDP flood protection, country blocking, and port policy. A manual block placed inside an exempt range still takes effect because blocked sets are evaluated before the DoS meters. See Firewall - DoS-exempt ranges.