# Security model

This document describes the threat model, trust boundaries, and operational limits of Sculkworm as currently implemented.

For the full wire-level and login-flow threat table for closed routes (agent, connect, and IdP-gated access), see [Closed routes: security considerations](https://docs.sculk.network/nightly/sculkworm/tunnel.md#9-security-considerations).

## Handshake hostnames are unauthenticated routing hints

Minecraft Java Edition sends the Handshake packet (`0x00`) in plain text before authentication or encryption begins. Because Sculkworm routes exclusively on the Server Address field parsed by `HostField::parse` in `src/domain.rs`, any client that can reach the relay port can send any hostname string—including arbitrary `_o` (origin) or `_id` query parameters.

- **Never treat the hostname, `_o`, or `_id` as a credential or proof of identity.** A player can connect to the relay IP directly and supply any route key listed in `routes.json`, regardless of which DNS name they actually resolved.
- **Do not rely on hidden hostnames for access control.** Because every entry in `routes.json` is reachable from the single listening port, guessing or learning a routed hostname is enough to reach that backend.

## Open relay behavior (not access control)

Open routes are Layer 4 hostname routes: every client that can reach `SCULKWORM_LISTEN` can reach every open backend configured in `routes.json` or registered as an open dynamic route.

- Access control, whitelists, online-mode authentication, ban lists, and gameplay permissions for open routes belong on the backend Minecraft servers (or on a network firewall in front of the relay).
- When a client sends a hostname that matches a **closed** dynamic route on `SCULKWORM_LISTEN`, `Relay::handle_connection` never forwards traffic: it replies with the status JSON (including `sculkworm.relay` and `sculkworm.route`, or omitting `sculkworm` when `SCULKWORM_PUBLIC_URL` is unset) or the Login Disconnect message from `src/closed.rs` and closes the socket after at most 2 seconds. This intentionally tells vanilla clients that the hostname is a closed server and which relay URL handles it; unknown hostnames still close with zero bytes written (`event=unknown_host`), and no authorizer details, tenant names, client ids, or agent state are exposed on the Minecraft port.
- When a client sends a hostname that has no matching route, `Relay::handle_connection` in `src/relay.rs` logs `event=unknown_host` and closes the socket with zero bytes written.
- When an open route's backend is unreachable or refuses the connection, Sculkworm logs `event=backend_unreachable` and closes the client socket with zero bytes written.

## Transport encryption passes through untouched

Sculkworm does not add TLS and does not terminate, inspect, or strip Minecraft's own encryption.

1. `read_handshake` in `src/relay.rs` buffers bytes only until `parse_handshake` in `src/handshake.rs` finishes reading the initial Handshake packet (`0x00`).
2. `Relay::handle_connection` replays the exact buffered client bytes (including any trailing bytes that arrived in the same TCP read, such as Status Request or Login Start) to the backend and then calls `tokio::io::copy_bidirectional`.
3. Every subsequent packet—including Minecraft's RSA key exchange, AES-128-CFB8 stream encryption, compression, Configuration, and Play traffic—passes through opaque.

Traffic between the relay and backend servers travels over plain TCP unless the Minecraft protocol itself negotiates online-mode encryption (which starts after Login Start and runs end-to-end between the Minecraft client and the backend server). Status pings and the initial Handshake and Login Start packets are unencrypted in the Minecraft protocol; run the relay-to-backend hop over a private network or tunnel you control.

## Log injection protection

Because the Handshake host field is attacker-controlled UTF-8, `Relay::handle_connection` passes the route key through `sanitize_log_value` in `src/relay.rs` before writing `host=` to stderr:

- An empty string is logged as `<empty>`.
- Any byte or character that is not printable ASCII graphic (`0x21..=0x7E`), or that is `"` or `\`, is replaced with `?`.

This blocks newline injection (forging fake `level=... event=...` lines), whitespace field-splitting, terminal escape sequences, and quote breaks in log parsers. Error strings (`error=`) and reload paths (`path=`) are formatted with Rust's `{:?}` debug escaping in `src/main.rs` and `src/relay.rs`.

## Resource and denial-of-service limits

Sculkworm bounds memory and socket usage per connection and globally:

- **Global concurrency cap (`SCULKWORM_MAX_CONNECTIONS`, default `1024`, bounds `1..=100000`).** Enforced with a `tokio::sync::Semaphore` (`global_permits`) in `Relay::serve` (`src/relay.rs`). Every accepted socket—including connections still waiting for a Handshake—holds one permit until the task exits. Excess connections are closed immediately with `level=warn event=connection_rejected reason=max_connections`.
- **Handshake packet ceiling (`MAX_HANDSHAKE_PACKET_LEN = 4096` bytes, `src/handshake.rs`).** Any packet declaring a length `<= 0` or `> 4096` bytes is rejected immediately with `reason=bad_length` before buffering the body. VarInts longer than 5 bytes are rejected with `reason=varint_too_long`. Each `read_handshake` iteration reads into a fixed 4096-byte stack buffer (`READ_CHUNK_SIZE`).
- **Handshake read deadline (`SCULKWORM_HANDSHAKE_TIMEOUT_SECONDS`, default `10` s, bounds `1..=120`).** Slow or idle connections that do not send a complete Handshake within the deadline are closed with `reason=timeout`.
- **Backend connect deadline (`SCULKWORM_CONNECT_TIMEOUT_SECONDS`, default `5` s, bounds `1..=60`).** Bounds DNS resolution (`tokio::net::lookup_host`) and TCP connect across resolved addresses in `connect_target` (`src/relay.rs`).
- **Graceful shutdown drain (`DRAIN_TIMEOUT = 5` seconds, `src/relay.rs`).** On `SIGTERM` or `SIGINT`, Sculkworm closes the listener and waits up to 5 seconds for active tasks to release their semaphore permits before exiting.

### Limits Sculkworm does not enforce

On the public Minecraft port (`SCULKWORM_LISTEN`), Sculkworm has **no per-IP connection limit** and **no per-IP rate limit**. A single source IP that opens `SCULKWORM_MAX_CONNECTIONS` idle sockets (or long-lived connections) can exhaust the global semaphore for other clients. Put OS-level (`nftables`/`iptables`) or L4 firewall connection limits per source IP in front of Sculkworm when exposing it on the public internet.

On the closed-mode tunnel listener (`SCULKWORM_TUNNEL_LISTEN`), Sculkworm enforces per-IP concurrent TCP limits, `HELLO` failure blocks, per-IP and per-login/code HTTP rate limits, and per-subject/session stream caps (see [Closed routes: rate limits and caps](https://docs.sculk.network/nightly/sculkworm/tunnel.md#92-rate-limits-and-caps)), while still sharing the global `SCULKWORM_MAX_CONNECTIONS` semaphore.

## Backend targets and SSRF boundary

`Target::parse` in `src/routes.rs` accepts any syntactically valid `host:port` or `[ipv6]:port` with a non-zero port, including loopback (`127.0.0.1`), RFC 1918 addresses, cloud metadata IPs (`169.254.169.254`), and internal hostnames.

Static routes come from the operator-controlled JSON file at `SCULKWORM_ROUTES_FILE`; dynamic open routes are bounded by each tenant's optional `allowed_targets` policy in `SCULKWORM_TENANTS_FILE` (closed routes have no `target` and are served only by an authenticated agent). Keep `SCULKWORM_ROUTES_FILE` and `SCULKWORM_TENANTS_FILE` writable only by the operator, and restrict outbound egress from the Sculkworm container to the network containing your Minecraft backends so a misconfigured target cannot reach unrelated internal services.

## PROXY protocol and player IP visibility

Sculkworm does not parse or emit HAProxy PROXY protocol headers (v1 or v2):

- **Inbound:** placing Sculkworm behind an upstream proxy that prepends PROXY protocol headers breaks Handshake parsing (`reason=unexpected_packet_id`, `reason=timeout`, or `reason=eof`).
- **Outbound:** Sculkworm opens a plain TCP connection to each backend server, so every backend sees the **Sculkworm host or container IP** as the player's source IP address rather than the player's real IP.

Because backends see Sculkworm's IP instead of each player's IP:

- Do not rely on IP bans (`ban-ip`) on backend Minecraft servers behind Sculkworm; banning a player's IP on the backend will block every player routed through the relay.
- Use account-based bans (UUID) and whitelists on backends, and enforce IP-level blocks or rate limits at the firewall in front of Sculkworm.
- Sculkworm logs the TCP peer IP it saw in `peer=` on every connection event (`route`, `closed`, `unknown_host`, `handshake_rejected`, `backend_unreachable`, `connection_rejected`).

## Secrets file, agent tokens, and IdP request boundaries

When closed mode is configured (`SCULKWORM_TUNNEL_LISTEN` and `SCULKWORM_SECRETS_FILE`):

- **Secrets file permissions and isolation.** `SecretsConfig::from_file` in `src/auth/secrets.rs` refuses to load a secrets file on Unix unless its mode is `0600` or `0400`. IdP URLs, client ids, client secrets, and login keys live only in the operator-controlled secrets file; tenants can only reference a client by name, and only when the client's `tenant` matches the caller or is explicitly `"*"`. Probing another tenant's client name returns the same `422 invalid_authorizer` message (`is not in the secrets file`) as an unknown client. Client secrets and login keys are never written to `SCULKWORM_STATE_FILE`, never returned by the admin API, and redacted from `Debug` output.
- **Agent tokens.** `POST /v1/routes/{host}/agent-token` generates 32 random bytes from the OS CSPRNG (`ring::rand::SystemRandom`), returns the raw `swa_` token once, and persists only its 16-hex `id`, `created_at`, and the lowercase hex SHA-256 of the full token string. On `HELLO`, the tunnel listener (`src/tunnel/listener.rs`) checks the `id` and SHA-256 in constant time (`subtle::ConstantTimeEq`) against the route's stored token; a token for one route is rejected (`status 3 unauthorized`) for any other route. Rotating or deleting a token sends `GOAWAY revoked` to the live agent session. Before registering the new agent session under the registry write lock (and before demoting any existing agent), the listener re-checks that the route is still closed and active and that the token still matches, refusing stale sessions with `GOAWAY revoked` or `GOAWAY route_changed`.
- **TLS tunnel transport, ALPN split, and SPKI pinning (`src/tunnel/tls.rs`).** The tunnel listener accepts TLS 1.3 and TLS 1.2 (no plaintext fallback), splits connections by ALPN (`sculkworm` for the tunnel protocol, `http/1.1` or no ALPN for public HTTPS endpoints), and enforces a per-source-IP concurrent TCP cap (default `16`, closed before TLS) and a `HELLO` failure block (`10` failures per minute blocks the source IP for `10` minutes with status `6` before step 5, never burning a connect ticket). `sculkworm-agent` verifies the server certificate against the OS root store (or `--ca-file` exclusively), verifies the SNI hostname, requires ALPN `sculkworm`, and when `--pin sha256/<base64>` is passed verifies the leaf certificate's DER `SubjectPublicKeyInfo` SHA-256 in constant time (`event=tls_pin_mismatch` on mismatch).
- **Outbound IdP HTTP rules (`src/auth/idp_http.rs`).** Every outbound request to an IdP (including OIDC discovery during `PUT /v1/routes/{host}`) requires HTTPS with the OS root store, enforces a 5-second total timeout, caps response bodies at 1 MiB, does not follow redirects (`3xx` fails as `http_<status>`), and resolves DNS first to refuse loopback, RFC 1918 private, link-local (`169.254.0.0/16`, `fe80::/10`), CGNAT (`100.64.0.0/10`), unique local (`fc00::/7`), unspecified, broadcast, and multicast addresses unless `SCULKWORM_IDP_ALLOW_PRIVATE=1`. The connection dials the checked address directly so DNS cannot change between validation and connect. OIDC discovery requires `issuer` to match verbatim and requires `token_endpoint` and `userinfo_endpoint` to share the issuer's origin unless the operator listed `endpoints` explicitly in the secrets file.
- **Sealed logins, PKCE loopback flow, OIDC, Discord preset, device flow, tickets, and per-`OPEN` re-checks (`src/auth/sealed.rs`, `src/auth/oauth2.rs`, `src/auth/oidc.rs`, `src/auth/public_http.rs`, `src/tunnel/connect.rs`).** IdP access and refresh tokens are encrypted with ChaCha20-Poly1305 (`ring`) using the relay's `login_keys` (`swl_...`) and AAD `sculkworm-login || header`; `sculkworm-connect` stores only this opaque blob in `logins.json` (`0600` on Unix, refusing looser modes; the default `sculkworm` config directory is created/tightened to `0700` and symlinks are refused, while pre-existing parent directories of custom `--logins-file` paths are left untouched). The login flow uses independent PKCE S256 challenges on both the connect-to-relay and relay-to-IdP hops, validates loopback `redirect_uri` strictly (`http://127.0.0.1:<port>/callback` or `http://[::1]:<port>/callback`), compares `state`, relay codes, device codes, user codes, CSRF tokens, and PKCE verifiers in constant time, and escapes all HTML interpolations with `Content-Security-Policy: default-src 'none'; ...`, `X-Content-Type-Options: nosniff`, and `Referrer-Policy: no-referrer`. OIDC clients cache validated discovery documents in memory for 24 hours, validate `iss`, `aud`, `exp`, `nonce`, and `sub` on the ID token obtained over TLS from the token endpoint, require userinfo `sub` to match, and evaluate `allow.claim` rules against string and string-array claims as well as `allow.sculk_server` rules against the live userinfo `sculk_servers` array (adding `sculk:servers` automatically and admitting only when an object has `id == <server id>` and `is_player == true`, failing closed on missing, malformed, or non-array claims, revoked grants/401 responses, blocked subjects, or provider outages). The Discord preset fetches `users/@me` (`id`/`username`) and, when `allow.discord_guild` is set, adds the `guilds` scope and checks live membership via `users/@me/guilds` on login and every re-check (failing closed on any IdP error). The RFC 8628 device flow uses unambiguous 8-character codes (`BCDFGHJKLMNPQRSTVWXZ`), omits `verification_uri_complete`, ignores `user_code` query parameters on `GET /login/device`, enforces `__Host-swdev` double-submit CSRF cookie + `Sec-Fetch-Site: same-origin` + per-IP (IPv6 `/64`), per-code, and global miss brute-force rate limits on `POST /login/device/approve`, caps pending device codes both globally and per route, shows a phishing warning confirmation page before redirecting with `prompt=consent` (OIDC and Discord), binds `confirm=1` to `/login/callback` via a random `__Host-swdevcb` (`SameSite=Lax`) cookie verified in constant time (marking the code denied on mismatch and clearing the cookie on callback), and ensures each device code can only be approved once and consumed once. Every `POST /tickets` and every connect stream `OPEN` older than 60 seconds re-checks revocations and the live IdP (`503 idp_unavailable` / `RESET` code `7` on outage, `401 login_revoked` / `RESET` code `6` on revocation); revoking a subject or changing a route's authorizer immediately sends `GOAWAY revoked` and `RESET` code `6` to affected connect sessions. Concurrent refreshes per `lid` are coalesced (single flight) with a 5-minute in-memory rotated-token cache (kept separate from verified admission results) so rotating IdP refresh tokens are never reused.

- **Log redaction.** Client secrets, login keys, agent tokens, tickets, sealed logins, relay codes, device codes, IdP access/refresh/ID tokens, PKCE verifiers, `state` values, and `Authorization` headers are never logged; log lines record `token_id`, `lid`, sanitized `route`/`subject`/`name`, `session`, and `peer`.
- **What closed mode does not protect against.** Closed mode proves an IdP identity, not a Minecraft account: keep `online-mode=true` (and a whitelist if usernames matter) on the Minecraft server behind `sculkworm-agent`. It does not stop an admitted player from sharing their computer or login, does not hide offline-mode Minecraft traffic from the relay operator, and does not protect against a compromised IdP account.

## Legacy ping rejection

`parse_handshake` in `src/handshake.rs` rejects connections starting with the 3-byte Minecraft 1.6 legacy Server List Ping prefix `FE 01 FA` with `reason=legacy_ping` and closes the socket without forwarding to any backend. A single leading `0xFE` byte is not rejected immediately because a modern 254-byte Handshake packet begins with the VarInt `FE 01`; shorter legacy pings (1 or 2 bytes) time out after `SCULKWORM_HANDSHAKE_TIMEOUT_SECONDS` with `reason=timeout`.
