# Threat Model

URL: https://scalws.com/docs/threat-model/
Source: `docs/THREAT_MODEL.md` in the ScalWS repository

Status: living document, revised at every milestone's security review.
Scope: `scalwsd` as released in 1.0.0, section by section from the M1 serving core
(listeners, TLS, HTTP/1.1 + HTTP/2, routing, static files, reverse proxy, metrics endpoint,
config reload) and M2 managed runtimes onward. The console has its own threat model
([console security](https://scalws.com/docs/console/security/)); the service sandbox is described in the
[sandbox guide](https://scalws.com/docs/guide/sandbox/).

## 1. Assets

| Asset | Why it matters |
|---|---|
| Availability of the server and of unrelated tenants | Shared process serves many tenants. |
| TLS private keys | Impersonation of hosted domains. |
| Files outside configured document roots | Source code, `.env`, credentials, other tenants' data. |
| Upstream applications | Must only receive requests the operator routed to them; must not be fooled by spoofed forwarding headers. |
| Configuration and its integrity | A bad or malicious config can expose files or take the server down. |
| Logs and metrics | May leak secrets or become a DoS vector via cardinality. |

## 2. Trust boundaries

1. **Network clients → listener.** Fully untrusted: bytes, timing, TLS ClientHello, headers, bodies.
2. **scalwsd → upstream applications.** Semi-trusted: apps are tenant code. Their responses are forwarded but must not crash or stall the server.
3. **Filesystem.** Document roots are tenant-controlled content; tenants may create symlinks.
4. **Operator → configuration / signals / admin socket.** Trusted principal, but input is still validated (typos are a threat to availability).
5. **Metrics endpoint.** Exposes operational data; bound to loopback by default.

## 3. Threats and mitigations

Legend: ✅ implemented and tested · 🟡 partial · ⏳ planned (milestone)

### Network / protocol

| Threat | Mitigation | Status |
|---|---|---|
| Slowloris (slow headers) | h1 `header_read_timeout` (also bounds keep-alive idle); TLS handshake timeout | ✅ |
| Slow request body | Per-frame body read timeout in `LimitedBody` | ✅ |
| Slow response reader | Write timeout below TLS (`limits.write_timeout`) closes connections whose writes stall; on HTTP/2, a response whose body makes no send progress within it (a client that grants no flow-control credit makes nothing to write) gives up its body, permit and upstream while the connection's other streams go on (the connection ends when all its responses are stalled and no request is in service, or when it drains with only dropped responses left), the body going out in 16 KiB steps (audit run-6) | ✅ tested |
| Connection exhaustion | Global `max_connections` semaphore; accept pauses instead of queueing in user space | ✅ |
| One source exhausting connections or request capacity | Per-source (IPv4 / IPv6 /64) connection limit at accept and request token bucket (429); sharded, size-capped state that cannot grow with the number of attacking addresses | ✅ tested (incl. 100k-address flood) |
| Per-tenant request floods | Tenant concurrency and rate quotas (M3) | ✅ tested |
| Oversized headers / URI / body | `max_header_bytes`, `max_headers`, h2 `max_header_list_size`, URI length → 414, Content-Length precheck → 413, streaming cap | ✅ |
| HTTP/2 rapid reset (CVE-2023-44487) and stream floods | `max_concurrent_streams`, `max_pending_accept_reset_streams`, `max_local_error_reset_streams` | ✅ (config) |
| Request smuggling (CL/TE ambiguity, obs-fold, invalid chunking) | strict HTTP/1 parsers (by default `scalws-h1` for requests and the own client's response parser in `scalws-proxy`; hyper's with `http1_server: hyper` / `upstream_client: hyper`); proxy always re-frames the upstream request and strips hop-by-hop headers; never forwards `Transfer-Encoding` from the client verbatim | ✅ tested for CL+TE |
| Host header ambiguity | Multiple `Host` headers → 400; HTTP/1.1 without Host → 400; absolute-form authority wins and must agree with Host | ✅ |
| SNI / Host mismatch (domain fronting across tenants) | `strict_sni` listeners answer 421 when Host differs from SNI | ✅ tested (opt-in) |
| TLS downgrade / weak ciphers | rustls defaults (TLS 1.2+ only, AEAD suites only) | ✅ |
| Header injection into upstream | Inbound `X-Forwarded-*`, `Forwarded`, `X-Real-IP` removed and replaced; `X-Request-Id` regenerated | ✅ |
| WebSocket tunnel exhaustion | Server-wide tunnel limit (`max_upgraded_connections`, 503 when exhausted) and idle timeout; only `Upgrade: websocket` on HTTP/1.1 GET is honoured, other upgrades are stripped | ✅ (tunnel + idle pump tested) |
| Upstream TLS spoofing | `https://` upstreams verify the certificate against system roots (+ optional CA file) and the configured host name | ✅ tested |

### Filesystem

| Threat | Mitigation | Status |
|---|---|---|
| Path traversal (`..`, encoded `%2e%2e`, `%2f`, backslash, NUL) | Decode once, reject `..` / NUL / `\` / encoded slash; reject before touching the filesystem | ✅ tested |
| Symlink escape | Canonicalise and require the result to stay beneath the canonical root | ✅ tested (Linux) |
| TOCTOU symlink swap between check and open | Linux: `openat2(RESOLVE_BENEATH \| RESOLVE_NO_MAGICLINKS)` from a root dir fd (kernel-enforced); fallback platforms keep the residual risk | ✅ Linux / 🟡 fallback |
| A tenant who owns the directories on the way replaces its document root by a link to ScalWS's state (the ACME keys, readable by the serving process) | `root_symlinks: refuse` opens the root without following links (panel mode); with `follow` a root whose link leads into or over `/etc/scalws`, `/var/lib/scalws*`, `/run/scalws*`, `/var/cache/scalws`, the configured ACME state, runtime and cache directories, the controller's state or the directory of a configured TLS certificate or key (listeners, remote admin, and where their links lead) is refused. Under the controller's sandbox no Landlock read rule lies in or over the controller's state (a link to a file beside it opens no directory there), checked again on the descriptor opened when the rules are applied; a writable rule whose descriptor lies in or over it fails the start (audit run-6). A protected directory that does not exist yet (ACME state, disk cache) is judged by its nearest existing ancestor, and a reload that protects a new directory opens followed roots again instead of keeping them (audit run-6) | ✅ tested |
| Opening a FIFO/device blocks a thread | `O_NONBLOCK` on open, type checked with `fstat` on the opened fd | ✅ |
| Dotfile exposure (`.env`, `.git`) | Any path segment starting with `.` is 404 except `.well-known` | ✅ tested |
| Directory listing | Never generated | ✅ |

### Managed applications (M2)

| Threat | Mitigation | Status |
|---|---|---|
| Shell injection through configured commands | argv is executed directly, never through a shell | ✅ |
| Secrets in scalws's environment leaking to applications | Child environment is cleared; only `PATH`, `LANG`, `HOME`, configured `env` and `SCALWS_*` listen variables | ✅ tested |
| Injection into the generated PHP-FPM pool file | ini keys/values, env values and `runtime_dir` restricted to safe character sets at validation | ✅ |
| PHP source disclosure | `.php` files are never served by the static handler next to a PHP runtime | ✅ tested |
| Executing scripts outside the document root | `SCRIPT_FILENAME` only from the confined lookup (ADR-0006); `security.limit_extensions = .php` (empty for `.htaccess` sites, whose handler lines may map other extensions) | ✅ tested |
| httpoxy (`Proxy:` header → `HTTP_PROXY`) | `Proxy` header never forwarded to FastCGI; underscore header names dropped | ✅ tested |
| Spoofed client identity towards applications | `REMOTE_ADDR`/`X-Forwarded-*` set from the connection; client values discarded, also `Forwarded`, `X-Real-IP` and spellings with `_` (`x_forwarded_for`) that CGI-style upstreams read as the same variable | ✅ tested |
| Other local users reaching application sockets | Socket directory 0700, FPM socket 0600. Residual: a `listen: tcp` application's loopback port is reachable by every local process, which bypasses ScalWS and can set `X-Forwarded-For`/`-Proto` (Python servers trust them only from the loopback address, which local processes share); `listen: unix` is the default and recommended | 🟡 documented |
| Response mix-up on reused FastCGI connections | Connection returned to the pool only after `END_REQUEST`; stale detection; replay limited to buffered requests | ✅ tested (worker recycling under concurrency) |
| A crashing / crash-looping application | Supervisor restarts with backoff; `Failed` after 5 crashes/minute; 503 + Retry-After; unrelated apps unaffected | ✅ tested |
| Orphaned application processes if scalwsd is killed | Own process group per worker, group killed on stop/crash; on SIGKILL of scalwsd the systemd unit's control-group kill is required | 🟡 |
| Applications of different tenants reading each other's files | By default all applications run as the scalws user (PHP workers as `nobody` when scalws runs as root); opt-in per-tenant Unix users (`tenants[].user`, ADR-0026) separate them, at the cost of four more capabilities for scalwsd | 🟡 opt-in |
| Runaway application memory / fork bombs / CPU hogging | cgroup v2 `memory.max` (+ `memory.swap.max`), `pids.max`, `cpu.max` per tenant; OOM kill confined to the tenant's group; workers join their group before their first instruction | ✅ tested (OOM isolation, live limit change) |
| A tenant exhausting the shared server (request floods) | Per-tenant `max_concurrent_requests` (503) and token-bucket rate (429) with bounded state | ✅ tested |
| Limits silently not enforced | `server.cgroups.mode: required` refuses to start without delegation; `auto` logs a warning and exports `scalws_cgroups_enabled 0` | ✅ |

### Cache and request rules (M5)

| Threat | Mitigation | Status |
|---|---|---|
| Serving one user's personalised response to another | Only explicitly cacheable responses; never with `Set-Cookie`, `private`, `no-store`, `no-cache`; requests with `Authorization` or personalisation cookies (profile rules) bypass the cache; no AI involvement | ✅ tested |
| Cache poisoning via unkeyed headers | `Vary` variants keyed by request header values; `Vary: *` not stored | ✅ tested |
| Cache memory exhaustion | Size-weighted budget with eviction, per-entry size cap | ✅ tested |
| Brute force on specific paths (login, password reset) | `security.rate_limits` per client address and path | ✅ tested |
| Cache stampede (many concurrent misses hitting a slow upstream) | Miss coalescing: one upstream request per URL, bounded 5 s wait | ✅ tested |
| Orphaned application processes after a crash of scalwsd | `setpriv --pdeathsig TERM`; cgroup leaves reaped at start | ✅ tested |
| Cache disk exhaustion / stale files | Disk tier bounded by `size` (LRU), expired and partial files removed at start, writes dropped when the queue is full | ✅ tested |
| Unauthenticated purge | Purge only on the admin socket (ADR-0017) | ✅ |
| Sensitive files of known frameworks (`wp-config.php`, `.env`, uploaded PHP) | Profile deny rules + configured deny paths, case-insensitive on the normalised path | ✅ tested |

### Detection (M4)

| Threat | Mitigation | Status |
|---|---|---|
| A hostile application tree (symlinks to `/etc`, huge files, deep trees) abusing `scalwsctl detect` | Symlinks never followed; reads capped at 256 KiB per file, depth 3, 4000 entries; dependency dirs skipped; nothing executed | ✅ tested (symlink escape) |
| Detected values injecting configuration | Facts are escaped into quoted YAML strings or JSON arrays and the result is parsed and validated like any configuration | ✅ |
| A deploy silently changing how an application runs | Configuration loading never inspects application files; detection only proposes | ✅ tested |

### Optimizer (M6)

| Threat | Mitigation | Status |
|---|---|---|
| Load spike makes the optimizer exhaust host resources | Worker targets bounded by configured `min`/`max`; scale-up blocked at ≥ 85 % tenant memory; tenant cgroup limits still apply | ✅ tested |
| Oscillation (flapping) | Separate up/down bands, consecutive-window streaks, per-rule cooldowns; property test proves single steps and cooldown spacing for arbitrary telemetry | ✅ tested |
| A change makes things worse | Outcome observed for 3 windows; regression in 5xx ratio or p95 rolls back and suppresses the rule for 10 min | ✅ tested |
| Unexpected automatic changes | Recommend-only by default; `autoscale: auto` per application; every decision audited | ✅ |
| Journal disclosure | Served only on the loopback admin listener; contains tenant/app names and aggregate numbers, no request data | ✅ |

### Diagnostics (M7)

| Threat | Mitigation | Status |
|---|---|---|
| Leaking request data through diagnostics | Ring buffer keeps method, path without query (truncated to 256 bytes), status and timings; no headers, cookies or bodies | ✅ |
| Unbounded diagnostic memory | Ring buffer capped per application (`recent_requests`, max 10000); one evidence/finding set per application | ✅ |
| Exposure of `/diagnose` | Read-only, loopback metrics listener and admin socket | ✅ |
| Misleading root cause | Findings state correlation (`related`), carry their evidence and are fully deterministic and unit-tested | ✅ |

### Local AI advisor (M8)

| Threat | Mitigation | Status |
|---|---|---|
| Telemetry or customer data leaving the host | Disabled by default; loopback endpoint unless `allow_remote: true`; only aggregated diagnostics, recent request paths and optimizer decisions are sent | ✅ tested |
| Secrets in the model input | Every string redacted (query strings, userinfo, Bearer/Basic credentials, secret `key=value`, JWTs, e-mail addresses, opaque tokens); secret-named fields dropped; no headers, cookies or bodies collected | ✅ tested (unit, property, end to end) |
| Prompt injection via request paths | Model output is advisory text only; strict schema, bounded lengths, causes must reference real finding codes; the advisor cannot act | ✅ |
| Terminal escape injection via model output | Control characters removed from every output field | ✅ tested |
| LLM-generated commands executed | Never: investigations are displayed only; no code path executes them | ✅ |
| Model down/slow/hostile degrades serving | Separate task, bounded queue (429 when full), per-call timeout, size-capped response (256 KiB); request path never waits | ✅ tested |
| API key exposure | Read from an environment variable named in the configuration, never stored in YAML or logs | ✅ |

### ACME (M10)

| Threat | Mitigation | Status |
|---|---|---|
| Theft of private keys / account key | `state_dir` 0700, keys and account 0600, atomic writes; unit `StateDirectoryMode=0750` | ✅ tested |
| Challenge endpoint abuse | Only tokens of pending orders are answered; everything else falls through to the application; plain HTTP only | ✅ |
| Issuance for names the operator did not configure | Only `domains` of applications with `acme: true`; wildcards and IPs rejected at validation | ✅ tested |
| CA outage / rate limits | Failures back off per application (5 min doubling to 24 h); existing certificates keep being served; renewal starts 30 days before expiry | ✅ |
| A bad issued file breaks serving | Managed certificates are verified (key match, names) at prepare; invalid ones are skipped with a warning | ✅ tested |

### HTTP/3 (M10; in the packages, opt-in per listener)

| Threat | Mitigation | Status |
|---|---|---|
| QUIC connection floods | Global connection permits before the handshake (`refuse`), the handshake bounded by `tls_handshake_timeout`; handshakes of unvalidated addresses hold at most a quarter of the permits, counted over every HTTP/3 listener of the instance, and at most that many start per `tls_handshake_timeout` (a sender that never receives can end each one at once), beyond either a Retry (audit run-5, run-6); the per-source limit before the handshake: a source whose open connections and unvalidated handshakes reach it gets a Retry and, validated, is refused before any TLS work; stream limit and idle timeout from `limits` | ✅ tested |
| Amplification / address spoofing | quinn's address validation and anti-amplification limits (RFC 9000 §8); Retry under handshake load or at the claimed source's limit, so forged addresses cannot hold more than a quarter of the permits, nor any of another address's slots for validated connections (at most they make that address's new handshakes take a Retry); their entries in the per-source table are always evictable, so they cannot leave a source untracked | ✅ tested |
| Memory per stream (frames buffered whole by `h3` 0.0.x) | Frame headers of request and control streams are read as they arrive: any frame but DATA that declares more than `max_header_bytes` plus 1 KiB resets the stream before its payload is read (audit run-5); the peer's QPACK streams, which `h3` never reads, are read and discarded, and the receive windows are 1 MiB per stream and that plus 1 MiB per connection, as on HTTP/2 (audit run-6) | ✅ tested |
| Slow readers (no flow-control credit, connection kept alive) | Every response send must progress within `write_timeout` (body frames go out in 16 KiB steps, each under the timeout), otherwise the stream is reset and the response (tenant concurrency slot, upstream connection) released (audit run-5); HTTP/2 has the same bound per stream (the stalled response's body is dropped; the connection ends only when all its responses are stalled and no request is in service, or when it drains with only dropped responses left) (audit run-6) | ✅ tested |
| Shared UDP socket behind the demux (`listen: inherited`) | Instances only send on it: their seccomp filter allows only the socket options ScalWS sets (socket filters, device binding, `UDP_ENCAP`, `UDP_CORK`, `IPV6_ADDRFORM`, `IP_TTL` and the rest are refused); instances with inherited listeners and the demux are refused `SO_REUSEADDR`/`SO_REUSEPORT` too (a more specific bind could take an address's traffic); the controller undoes a cleared `O_NONBLOCK`, a connect, a shrunk receive buffer and every allowed option a holder can set to another value (`IP_RECVERR`, whose never-read error queue filled the receive buffer, the options quinn-udp sets, `UDP_ENCAP`, `UDP_CORK`, `UDP_SEGMENT`, `SO_REUSEADDR`, `SO_REUSEPORT`; a test checks the list against the filter's), and `IP_TTL`, hop limit and device binding, every tick, detaches a filter that is not locked and reports a locked one or an `IPV6_ADDRFORM` it cannot undo; a socket held by a process without the enforced filter is tainted and reported (it cannot be replaced while held); server ids are never shared by two running instances, the demux refuses, with an answer, a second owner of one (audit run-5) and any id the controller did not issue to the registering process, and holds one id per connection, released when it ends (audit run-6) | ✅ tested |
| Replay via 0-RTT | 0-RTT disabled (`max_early_data_size = 0`) | ✅ |
| Immature HTTP/3 implementation (`h3` 0.0.x) | Off by default (`http3: false` on every listener, the packaged configuration and the panel generators included); requests pass the same pipeline checks as TCP; the version is pinned and covered by the HTTP/3 tests | 🟡 opt-in |
| UDP 443 open without HTTP/3 | The package never opens UDP 443; the operator opens it after enabling `http3`. An upgrade narrows a ufw rule `ScalWS` that older packages added with 443/udp (`ufw app update ScalWS`) | ✅ |

### Containers (M10)

| Threat | Mitigation | Status |
|---|---|---|
| Option injection into the engine CLI (`--privileged` as image, mounts with `,`) | argv only, no shell; image, user, mount paths and env keys validated | ✅ tested |
| Container escaping tenant limits | podman: `--cgroup-parent` = application group (tenant memory/CPU/pids apply); docker: daemon-placed, warning at validation | ✅ tested (podman) / 🟡 docker |
| Privilege escalation inside the container | `no-new-privileges` always; `drop_capabilities`, `read_only`, `user` options | ✅ |
| Orphaned containers keep serving or consuming resources | `--init` for signal delivery; `rm --force` after every worker exit; names unique per start | ✅ tested |
| Exposure of the published port | Published on 127.0.0.1 only; reached through scalws | ✅ |

### Client address (trusted proxies)

| Threat | Mitigation | Status |
|---|---|---|
| Client spoofs `X-Forwarded-For` to evade per-IP limits or fake log entries | Header used only from `trusted_proxies` peers; right-most untrusted entry wins; otherwise replaced | ✅ tested |
| Forged PROXY headers | Only from trusted peers; malformed/late headers close the connection; parser never reads past the header and is property-tested | ✅ tested |
| Direct visitor sends `CF-Connecting-IP`, `True-Client-IP`, `X-Real-IP`, `Forwarded` or `X-Forwarded-For` | A peer outside every trusted group is the client; configured single-value headers (and underscore spellings such as `cf_connecting_ip`) are removed from its request before any handler | ✅ tested |
| Client behind a trusted CDN chooses its address (a Cloudflare Worker behind a load balancer, extra or malformed header entries, `Forwarded` quoting tricks, huge chains) | Right-most untrusted entry; at a preset address the operator's hop appended, the client is the vendor's `CF-Connecting-IP` (one address, else the edge), never an entry left of the edge; strict `Forwarded` and single-value parsing; at most 32 entries; unparseable means unknown client `::`, never the proxy or an entry further left; fuzz targets `forwarded`, `forwarded_for`, `client_header` | ✅ tested / fuzzed |
| Poisoned or broken preset list (bad download, HTML page, `0.0.0.0/0`, private ranges, a file planted by the server user) | `update` runs as root over TLS with size, syntax, prefix floor, special-purpose and coverage checks (`--force` skips only coverage); atomic write; `presets_dir` and the file must be root-owned, not links, not group or other writable, else the shipped list is used with a warning | ✅ tested (live refresh checked at the release gate) |
| Panel settings widen trust (tenant file, `Include`, loopback or broad ranges, hostnames) | Only global root-owned regular files in fixed directories are read; no links; per-site settings and `Include` ignored; loopback, special-purpose and broad ranges refused; the generated file holds only fixed keys and re-formatted CIDRs and is checked on every load | ✅ tested / 🟡 live panels at the release gate |
| Client inside trusted ranges (Cloudflare Worker, imported networks) opens many connections | Residual: peers in presets and imported networks are exempt from per-source connection and handshake limits; per-client request limits and the global connection limit remain; a firewall restricting the origin to the CDN does not help (Workers connect from its ranges), Cloudflare-side controls do (Authenticated Origin Pulls, Cloudflare rate limiting) | 🟡 documented |
| Balancer throttled as one client | Trusted peers exempt from the per-source connection limit; requests limited per reported client | ✅ tested |

### ScalPanel mode (1.1)

Setting ([ScalPanel mode](https://scalws.com/docs/guide/scalpanel/)): one `scalwsd` per website container,
running as the website's user (UID 200000-999999, GID = UID), no capabilities, read-only
root filesystem, `/tmp` writable and `noexec`, ScalPanel's edge nginx ([redacted address]) in front
terminating TLS, PHP-FPM as the same user on `unix:/tmp/php-fpm.sock`. ScalPanel's network
lets only the edge and the container itself reach a site's port (owner, 2026-11-15).

| Threat | Mitigation | Status |
|---|---|---|
| A stale edge route or a reused container address sends site B's visitors to site A | `server.required_header` (`X-ScalPanel-Site`, exactly one, exact value, constant-time compare) checked before routing, files, `.htaccess`, the page cache or PHP; 421 otherwise. A routing check, not authentication: the site ID is not a secret | ✅ tested (`required_header_gates_everything`) |
| A peer other than the edge claims a client address or HTTPS | `X-Forwarded-For` and `X-Forwarded-Proto` are read only from `trusted_proxies` ([redacted address], 127.0.0.1; never presets); another peer's `X-Forwarded-Proto` is removed before PHP; trust rests on the TCP peer, which ScalPanel's network keeps others from spoofing | ✅ tested (`proto_only_from_trusted_peers`) |
| Loopback trust | 127.0.0.1 is the container itself (its own PHP); trusting it gives nothing beyond what the site's code can already do | accepted |
| `/healthz` as a bypass | Only exact path, `GET`/`HEAD`, no query, TCP peer loopback, never through a proxy-reported address or a PROXY-protocol listener; answers `ok`/`draining` only, no site data | ✅ tested (`healthz_only_for_loopback_peers`) |
| Tenant-written `.htaccess` (CPU, memory, regex) | ADR-0031 budgets unchanged (`<Files>` globs charged like `<FilesMatch>` regular expressions); the cost lands in the site's own container | ✅ |
| `htaccess_recheck: 0s` as a cost amplifier | Each directory level is looked up again on every request (the directory and its `.htaccess`), at most 128 levels per walk, charged to the request's scan budget per path component: a walk of d levels costs (d + 1)² x 256 bytes of 8 MiB, so two walks of a path of 127 levels or more (one internal rewrite), or three of about 104, answer 500 | ✅ tested (`recheck_zero_walk_is_charged`) |
| Symbolic links to files the site should not reach | `security.symlinks: owner_only` (link owner must own the target, walk from directory descriptors, no second lookup by path); in this mode the server is the site user, so it reads nothing the site cannot | ✅ tested (`owner_only_links`) |
| PHP-FPM opens `SCRIPT_FILENAME` by path after the check | A site swapping its own link in that window (plan reuse up to 2 s) can run the new target; FPM runs as the site user, whose `include` already has that power | 🟡 documented |
| Dotfiles (`.env`, `.git`, `.htaccess`, `.htpasswds`) | 403 before any file access (`security.dotfiles: forbidden`); the front controller never catches them; password files live outside `document_root` | ✅ tested |
| PHP source disclosure | `.php` never served as a file (403); last-extension rule (`x.html.jpg` is an image); names with a line break or NUL refused; `php_flag engine off` answers 403, also with `PATH_INFO` | ✅ tested |
| Front controller as a bypass of blocked paths | Dotfiles, refused links, denied paths, `Options -Indexes` folders and `.htaccess` denials answer before the fallback; an `ErrorDocument` subrequest that falls back passes the controller's checks too; the controller checked is the one of the runtime serving the path (a route's own PHP runtime, else the default one), and the PHP handler never runs a fallback `.htaccess` did not approve for its own controller; a missing controller is 404 | ✅ tested (`front_controller_never_catches_blocked_paths`, `errordocument_subrequest_never_runs_an_unchecked_controller`, `route_controller_is_checked_as_its_own`) |
| BREACH | `compression.mode: static` (default) never compresses a dynamic response, decided by handler kind, not `Content-Type`; `all`/`types` are documented opt-ins | ✅ tested (`static_mode_never_compresses_dynamic`) |
| Compression CPU and memory | Streaming at fast levels within a memory budget; variant cache bounded (8 MiB in this mode) and filled behind `max(1, cpus/4)` permits; no decompression anywhere. A stream of cache misses raises other requests' p99 on one CPU (ADR-0053) | ✅ / 🟡 measured |
| Page cache serving a gated or private page | Every gate (required header, dotfiles, deny rules, `.htaccess` access and logins) runs before the lookup; logins, bypass cookies and `.htaccess` edits of caching headers bypass it; static files never stored; key holds `Host` (set by the edge) | ✅ tested (`cache_never_skips_the_gates`) |
| Directory listing XSS or information leak | HTML escaping and percent-encoded links, no dotfiles, refused links, denied names, PHP script and source names or `IndexIgnore` names, at most 10 000 entries and 2 MiB, `nosniff` and a script-free CSP; only with `Options +Indexes` | ✅ tested |
| Log injection into the panel's parsers | Combined format escaping (`\"`, `\\`, `\xhh` for every byte outside printable ASCII) of request line, referer, user agent and user; one `write(2)` per line; no log path through a symbolic link | ✅ tested |
| Malformed `site.json` | 1 MiB cap, regular file only, strict types, version checked first, normal validation, one-line error, exit 1 (the container restarts and the panel sees the error) | ✅ tested, fuzzed (`site_json`) |
| Writes outside `/tmp` and the logs | `runtime_dir` and spooled request bodies under `temp_dir`; admin socket, metrics listener and cgroups off; with the sandbox in force Landlock refuses writes outside `temp_dir`, the system temporary directory, the log folders, `/var/log/scalws`, `/var/cache/scalws` and the device files. `temp_dir` cannot widen that: `/`, a top-level folder but `/tmp`, and a folder overlapping the document root, `.htpasswds` or the log folders are refused at start and on reload | ✅ tested (`scalpanel_selftest_refuses_writes_outside_the_rules`, `temp_dir_must_not_widen_the_sandbox`, `scalpanel_mode_reloads_are_checked`) |
| A compromised `scalwsd` | It holds only the site user's rights in the site's container. Sandbox floor `auto` (plan ruling 10): Landlock (writes only below `temp_dir`, the system temporary directory and the log folders, no program runs) and the seccomp allowlist, applied where the kernel and the container's seccomp profile allow it, in force under Docker's default profile with `--read-only`, `--cap-drop ALL` and the site user (contract suite). Where they do not (no Landlock, `seccomp()` refused, arm64, root) one warning and no sandbox; `SCALWS_SANDBOX_FLOOR=off` turns it off. PHP-FPM is started by the image before `scalwsd` and is never under it | ✅ tested (`scalpanel_mode_applies_the_floor_unless_it_is_off`, `scalpanel_mode_keeps_an_explicit_floor_on`, contract) / 🟡 without Landlock |
| `site.json` `runtime.upstream` steers the proxy elsewhere | A `unix:` path must be absolute, without `..` or NUL, inside the parent of `document_root` and outside `document_root`; a TCP upstream must be a literal loopback `IP:port` (the container's own loopback). The socket path is checked for a symbolic link only when the configuration is loaded: the model is one `scalwsd` per site container running as the site user, so a link swapped in later reaches nothing the site user cannot reach | ✅ tested (`python_ruby_and_container_proxy_to_a_unix_socket`, site.json unit tests) / 🟡 no-follow connect in 1.2 |
| PHP source served as text by a non-PHP runtime | `static`, `node`, `python`, `ruby` and `container` deny `.php`, `.php3` to `.php8`, `.phtml`, `.phar`, `.phps` and `.inc` in any case (403, or 404 without `deny_dotfiles`), never proxy them and drop them from the index list; the `php` block is ignored there | ✅ tested (`static_serves_files_only_and_ignores_the_front_controller`, `static_ignores_the_php_block`, `source_is_404_without_deny_dotfiles`) |

### Edge features for ScalPanel (1.1)

Setting ([ScalPanel edge](https://scalws.com/docs/guide/scalpanel-edge/), ADR-0054): ScalWS as the internet-facing
edge of a ScalPanel node, configured by ScalPanel's generator, in front of the website
containers. Every key is opt-in; the threats apply where a configuration uses it.

| Threat | Mitigation | Status |
|---|---|---|
| Spoofed `X-Forwarded-For` or `CF-Connecting-IP` to escape `deny` or `deny_networks` | The client is resolved only from peers in `server.trusted_proxies` (header `server.client_address.header`) and in the networks of `server.client_address.presets` (the vendor's header, such as `CF-Connecting-IP`); headers of other peers are not read. A header from such a peer is believed as sent: a trusted peer, or anything able to send from a preset's networks, decides the client address | ✅ tested for `trusted_proxies` (`networks_use_the_resolved_client`) / 🟡 presets trust the vendor's networks |
| Country sets as access control | A country lookup is an estimate (database accuracy, ranges move between builds); clients behind a VPN, proxy, Tor or cloud host carry the country of their exit, and a legitimate client may be misplaced. Country sets are a coarse filter, not access control; use `allow`, `allow_networks` or authentication for anything that must hold | 🟡 documented |
| IPv4-mapped IPv6 to bypass an IPv4 network | Lookups map to IPv4; mapped entries are stored as IPv4 | ✅ tested (`mapped_addresses_match_ipv4`) |
| Range-table arithmetic (`/0`, `/32`, `/128`, adjacent, nested) | Sorted, merged tables, compared with a linear scan | ✅ tested (`ranges_match_linear_scan`), fuzzed (`ip_ranges`) |
| Huge or hostile network files (memory, time, a link to a secret file) | 32 MiB per file, 1 000 000 entries, regular file opened with `O_NOFOLLOW`, errors name the line, not its content | ✅ tested (`network_file_checks`), fuzzed (`network_file`) |
| A swapped or writable country database | Read into memory (no `mmap`, no SIGBUS on writes in place); regular file, not a link, 1 KiB to 256 MiB, owned by root or scalwsd's user, not group or world writable; `geoip update` writes by rename as root after plausibility checks | ✅ tested (`open_refuses_writable_files`, `reload_swaps_the_database`), fuzzed (`mmdb_country`) |
| `chmod g+w` on a loaded database goes unnoticed | Owner and mode are checked when the file is read (start, a reload that finds the file changed); a mode change alone does not trigger a read | 🟡 documented |
| Hostile download in `geoip update` (redirect, bomb, wrong file) | TLS with system roots, no redirects, 64 MiB compressed and 256 MiB decompressed caps, type, age and known-address checks; nothing written on an error | ✅ tested |
| Referer tricks (query, path, suffix, userinfo, backslash, two headers, port, case, trailing dot, `//host`, non-ASCII) | Strict parser, label-boundary suffix match, invalid hosts refused | ✅ tested (`referer_tricks`), fuzzed (`referer`) |
| Hotlink bypass through route order | `route_order: nginx` tries regex routes before prefix routes; the contract test drives the generator's routes | ✅ tested (`regex_routes_precede_prefix_routes`, contract) |
| Referer spoofing | `Referer` is chosen by the client: a non-browser client sends any value or none, and `allow_empty` admits pages with `Referrer-Policy: no-referrer`. Hotlink protection stops casual embedding only, as nginx `valid_referers` | 🟡 documented |
| A cache keeping a referer refusal or a referer-dependent page | Refusals carry `Cache-Control: no-store`; routes with `referer` or network lists never use ScalWS's own response cache. Allowed answers carry neither `no-store` nor `Vary: Referer`, so a CDN or shared cache in front may serve them to any referer: keep those paths uncached there, or add `Vary: Referer` with the route's `response_headers.add` | ✅ tested (`referer_routes_are_not_cached`) / 🟡 behind a CDN, documented |
| The site sees the panel's webmail session | `remove_cookies` on every route of the site, every `Cookie` line, upgrade requests too | ✅ tested (`remove_cookies_all_headers`, contract), fuzzed (`cookie_strip`) |
| A forwarded chain reaching the site container | `forwarded_for: client` sends one value in `X-Forwarded-For` and `X-Real-IP` | ✅ tested (`forwarded_for_client_is_single`) |
| Open redirect through `rewrite_location` (`//evil`) | Only values starting with `/` change, and the inserted prefix is percent-encoded, so the result is always a path on the same host | ✅ tested (`rewrite_location_never_changes_the_host`) |
| A wrong prefix inferred by `rewrite_location` | The removed prefix is inferred from the paths, so a path rewrite that happens to end like the client's path adds a prefix nothing removed; the result stays a same-host path | 🟡 documented |
| Cookie attribute injection through rewriting | Only `Path` and `Domain` values change, to validated configuration text or the normalised host | ✅ tested (`cookie_rewrite_keeps_other_attributes`), fuzzed (`set_cookie_rewrite`) |
| Log injection (quote, backslash, newline, bytes 0x00 to 0x1f and 0x7f to 0xff) | nginx `\xHH` escaping of every `scalpanel` variable | ✅ tested (`scalpanel_line_escapes`), fuzzed (`access_line`) |
| A log file swapped for a link, or hard-linked to another file | No symbolic link in the path, no second hard link, append only, created `0640`. The link checks run when a file is opened, so a hard link made later is noticed at the next reopen | ✅ tested (`log_file_refuses_links`) |
| A configuration widening what scalwsd may write | With the sandbox on, the folders of the `access_log` files a configuration names at start become write paths (create and append only); a reload cannot add one (refused, the running configuration stays). `scalws-geoip-update.service` may write only below `/var/lib/scalws/geoip` | ✅ tested (sandbox plan tests) |
| Log queue exhaustion by a flood | One bounded queue (65 536 lines), drops counted, a request never waits | ✅ tested (`log_queue_drops_under_load`) |
| WebSocket exhaustion from one address | `max_upgraded` per address and IPv6 `/64`; under scalws-controller each instance enforces its share, so one address may hold up to one share per instance | ✅ tested (`max_upgraded_answers_429`) / 🟡 per instance |
| BREACH through edge compression of dynamic pages | Same exposure as nginx's edge (it compresses proxied HTML); `Cache-Control: no-transform` honoured; documented | ✅ tested (`edge_gzip_follows_the_types`) / 🟡 accepted |
| Upstream version disclosure | Proxied responses carry `Server: scalws`; a `101` keeps the upstream's | ✅ tested |

### Replicas (1.1.1)

Setting ([replicas guide](https://scalws.com/docs/guide/replicas/), ADR-0055): a ScalPanel site on two nodes. Each
edge sends to its own container and, over a mutual-TLS link, to the other edge. Nodes share
no state at run time; each decides on its own.

| Threat | Mitigation | Status |
|---|---|---|
| A client without a node certificate reaches the peer listener | `client_ca_file` makes the handshake fail before any HTTP byte; no session tickets or cache, so every connection is checked against the current CA | ✅ tested (`peer_listener_needs_a_client_cert`, `ca_change_applies_to_new_handshakes_without_resumption`) |
| Any certificate of the link CA is accepted | `client_names` matches SAN DNS names exactly (no wildcards); without it validation warns and any CA certificate passes | ✅ tested / 🟡 operator must set `client_names` |
| A stolen node certificate and key | The CA is the link's own; revoke by a new CA file or `client_names` without the node (a reload applies it to new handshakes, and an open connection of the revoked node gets `403` from its next request on). The pool key is not checked beyond a warning for world access | 🟡 operator rotation |
| A sender on the node link forges `X-Forwarded-For` on the public listener | Trust in `trusted_proxies` goes by the sender's address on every listener; the guide lists only the other node's address and keeps the public listener off the link address. Whether anything but the two edges can send from the link is ScalPanel's network (audit replica R1, needs validation) | 🟡 ScalPanel's network |
| A public client sends `X-ScalPanel-Via` to reach the local-only route | The route is scoped with `listeners: [peer]`; a request on another listener never matches it | ✅ tested (`listeners_scope_ignores_public_header`) |
| A forwarded request travels back and loops | The peer route lists only the local backend, and the peer's probe carries `X-ScalPanel-Via` too, so each edge measures the other's container | ✅ tested (`no_loop_when_both_down`) |
| A forged or replayed sticky cookie | HMAC-SHA256 (16-byte tag) under the shared key, with the member part keyed too; a bad tag gets a normal choice and a new cookie; a constant-time compare | ✅ tested (`forged_cookie_gets_a_new_choice`), fuzzed (`sticky_cookie`) |
| A readable or swapped key file | A regular file (no link), owner root, the effective user, or (as root) `scalws`; no group or other permission bits (`0600`); 32 to 1024 bytes; read whole, rechecked on reload | ✅ tested (`key_file_permissions`) |
| A leaked sticky key | An attacker can only choose among the healthy backends of the route (no address, no privilege); replace the file on both nodes and reload | 🟡 accepted |
| A write executed twice (retry or failover) | A written POST or PATCH is never resent; writes pinned by `write_backend` move only to another member of the same pool, only after a connect error | ✅ tested (`written_post_is_never_retried`, `write_retry_only_same_pool_on_connect_error`) |
| A write reaches the secondary | `write_backend` answers 503 when its pool has no healthy member (with `active_health`) and never uses another backend | ✅ tested |
| A fenced node still takes writes | `read_only` is read per request on every stack, so the next request of an open connection is answered; WebSocket tunnels of the runtime are closed before the reload returns. Not fenced: requests already past the check, and a reload that was not acknowledged (`409`, `504`, a timeout, or `SIGHUP`) | ✅ tested (`read_only_after_reload_on_open_connections`, `fencing_read_only`) / 🟡 the fencing window |
| A probe leaks client data or is steered | A probe is `GET` of a configured path with the configured `Host` and fixed headers, nothing from any request; forbidden header names are refused | ✅ tested (`probe_request_carries_no_client_data`) |
| Probes overload a member | One task per member and process, jittered, bounded by `interval` (at least 1 s); under scalws-controller the load is multiplied by the instance count | 🟡 documented |
| `upstream_status` shows the topology | Member addresses and health only, no request data, `no-store`; a warning when a route is reachable from a non-loopback listener. It lists the pools of every application, so keep it on the agent's loopback listener | 🟡 documented |
| Both nodes believe they are primary | Not decided by ScalWS: the generator sets `read_only` on the node that is not primary; a node whose control plane is lost is fenced by ScalPanel | 🟡 ScalPanel's side |

### Configuration and operations

| Threat | Mitigation | Status |
|---|---|---|
| Typo / invalid config takes server down | `deny_unknown_fields`, semantic validation, full `prepare` before atomic swap; failure keeps active state | ✅ tested |
| Unimplemented features silently ignored | Runtime types not available in this build are rejected at validation | ✅ |
| Metrics endpoint exposure | Loopback by default; separate listener | ✅ |
| Admin API abuse | Unix socket (`0660`, directory `0750`, owner/group `scalws`); optional remote API only with mutual TLS (client certificate from a configured CA, TLS 1.3); mutations refused (403) on the TCP metrics listener; every mutation audited (peer uid/gid/pid or certificate subject); a live socket of another instance is never replaced | ✅ tested (incl. package smoke test: outsider denied, group member allowed) |
| Running as root | Packaged unit runs as `scalws` with only `CAP_NET_BIND_SERVICE`; warning when started as root; no in-process privilege drop (avoids multi-threaded setuid) | ✅ |
| Bad configuration applied by an operator | Same validate/prepare path as reload; rollback to any of the last 10 configurations; `restore` is a dry run unless `--apply` and keeps `.bak` files | ✅ tested |
| Tampered backup manifest writing outside intended paths | Only absolute paths without `..` are accepted; sizes verified; dry run by default | ✅ tested |

### Logging / metrics

| Threat | Mitigation | Status |
|---|---|---|
| Secrets in logs | The event access log (`logging.access_log`) records the path **without** the query string, plus Host and User-Agent (cut at 256 bytes). The access file (`logging.access_file`, combined format, as Apache and nginx write it; ScalPanel mode's `logs.access`) records the request target **with** its query string as received, Referer, User-Agent and the `.htaccess` Basic login user. No other headers (no Cookie, no Authorization) and no bodies are logged anywhere. A token an application puts in a query string or a Referer reaches the access file, which must be kept as private as an Apache access log | 🟡 documented |
| Metric cardinality explosion | Labels limited to configured tenant/app names, listener name, normalised method and status class; unmatched hosts collapse to `_unmatched` | ✅ |

### Supply chain

| Threat | Mitigation | Status |
|---|---|---|
| Vulnerable / malicious dependencies | `cargo deny` (advisories, licences, sources, bans) and `cargo audit` in CI; `Cargo.lock` committed | ✅ (CI config) |
| Unsafe code bugs | `unsafe_code = "forbid"` workspace-wide | ✅ |
| Parser bugs | Property-based fuzzing (proptest) of path and host normalisation, range, Cache-Control, CGI headers, units and the configuration parser; coverage-guided fuzzing (cargo-fuzz, `fuzz/`) of 32 targets (HTTP/1 requests and connections, chunked bodies, upstream response heads and bodies, PROXY protocol, `X-Forwarded-For`, `Forwarded` and single-value client headers, CDN preset lists, panel remote-IP settings, host and path normalisation, ranges, Cache-Control, `Accept-Encoding`, `Referer` checks, cookie removal and `Set-Cookie` rewriting, CGI heads, FastCGI responses, HTTP/3 frame headers, `.htaccess`, `.htpasswd` and `php_value` lines, PHP information and pool files, network files and range tables, country databases, access log lines, ScalPanel `site.json`, the configuration), every night in CI (`.github/workflows/fuzz.yml`) against the vendored crates and the dependency versions ScalWS ships (`fuzz/Cargo.lock`) | ✅ |

## 4. Residual risks accepted for M1

* TOCTOU on symlink replacement inside a document root on platforms/kernels without
  `openat2` (fallback path only).
* No write/response timeout for slow readers while a response is streaming (since then:
  `write_timeout`, also for HTTP/2 and HTTP/3 flow control, audit run-6).
* No per-client rate limiting; a single client can consume up to `max_connections`.
* No WAF.
* Applications of different tenants share a Unix user (per-tenant users are a designed
  but unimplemented hardening step).
* The cgroup trampoline relies on `/bin/sh` (a fixed script; user argv stays positional).
