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.
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_idas a credential or proof of identity. A player can connect to the relay IP directly and supply any route key listed inroutes.json, regardless of which DNS name they actually resolved. - Do not rely on hidden hostnames for access control. Because every entry in
routes.jsonis 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_connectionnever forwards traffic: it replies with the status JSON (includingsculkworm.relayandsculkworm.route, or omittingsculkwormwhenSCULKWORM_PUBLIC_URLis unset) or the Login Disconnect message fromsrc/closed.rsand 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_connectioninsrc/relay.rslogsevent=unknown_hostand closes the socket with zero bytes written. - When an open route's backend is unreachable or refuses the connection, sculkworm logs
event=backend_unreachableand 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.
read_handshakeinsrc/relay.rsbuffers bytes only untilparse_handshakeinsrc/handshake.rsfinishes reading the initial Handshake packet (0x00).Relay::handle_connectionreplays 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 callstokio::io::copy_bidirectional.- 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, default1024, bounds1..=100000). Enforced with atokio::sync::Semaphore(global_permits) inRelay::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 withlevel=warn event=connection_rejected reason=max_connections. - Handshake packet ceiling (
MAX_HANDSHAKE_PACKET_LEN = 4096bytes,src/handshake.rs). Any packet declaring a length<= 0or> 4096bytes is rejected immediately withreason=bad_lengthbefore buffering the body. VarInts longer than 5 bytes are rejected withreason=varint_too_long. Eachread_handshakeiteration reads into a fixed 4096-byte stack buffer (READ_CHUNK_SIZE). - Handshake read deadline (
SCULKWORM_HANDSHAKE_TIMEOUT_SECONDS, default10s, bounds1..=120). Slow or idle connections that do not send a complete Handshake within the deadline are closed withreason=timeout. - Backend connect deadline (
SCULKWORM_CONNECT_TIMEOUT_SECONDS, default5s, bounds1..=60). Bounds DNS resolution (tokio::net::lookup_host) and TCP connect across resolved addresses inconnect_target(src/relay.rs). - Graceful shutdown drain (
DRAIN_TIMEOUT = 5seconds,src/relay.rs). OnSIGTERMorSIGINT, 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), 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, orreason=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_fileinsrc/auth/secrets.rsrefuses to load a secrets file on Unix unless its mode is0600or0400. 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'stenantmatches the caller or is explicitly"*". Probing another tenant's client name returns the same422 invalid_authorizermessage (is not in the secrets file) as an unknown client. Client secrets and login keys are never written toSCULKWORM_STATE_FILE, never returned by the admin API, and redacted fromDebugoutput. -
Agent tokens.
POST /v1/routes/{host}/agent-tokengenerates 32 random bytes from the OS CSPRNG (ring::rand::SystemRandom), returns the rawswa_token once, and persists only its 16-hexid,created_at, and the lowercase hex SHA-256 of the full token string. OnHELLO, the tunnel listener (src/tunnel/listener.rs) checks theidand 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 sendsGOAWAY revokedto 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 withGOAWAY revokedorGOAWAY 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 (sculkwormfor the tunnel protocol,http/1.1or no ALPN for public HTTPS endpoints), and enforces a per-source-IP concurrent TCP cap (default16, closed before TLS) and aHELLOfailure block (10failures per minute blocks the source IP for10minutes with status6before step 5, never burning a connect ticket).sculkworm-agentverifies the server certificate against the OS root store (or--ca-fileexclusively), verifies the SNI hostname, requires ALPNsculkworm, and when--pin sha256/<base64>is passed verifies the leaf certificate's DERSubjectPublicKeyInfoSHA-256 in constant time (event=tls_pin_mismatchon mismatch). -
Outbound IdP HTTP rules (
src/auth/idp_http.rs). Every outbound request to an IdP (including OIDC discovery duringPUT /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 (3xxfails ashttp_<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 unlessSCULKWORM_IDP_ALLOW_PRIVATE=1. The connection dials the checked address directly so DNS cannot change between validation and connect. OIDC discovery requiresissuerto match verbatim and requirestoken_endpointanduserinfo_endpointto share the issuer's origin unless the operator listedendpointsexplicitly in the secrets file. -
Sealed logins, PKCE loopback flow, OIDC, Discord preset, device flow, tickets, and per-
OPENre-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'slogin_keys(swl_...) and AADsculkworm-login || header;sculkworm-connectstores only this opaque blob inlogins.json(0600on Unix, refusing looser modes; the defaultsculkwormconfig directory is created/tightened to0700and symlinks are refused, while pre-existing parent directories of custom--logins-filepaths are left untouched). The login flow uses independent PKCE S256 challenges on both the connect-to-relay and relay-to-IdP hops, validates loopbackredirect_uristrictly (http://127.0.0.1:<port>/callbackorhttp://[::1]:<port>/callback), comparesstate, relay codes, device codes, user codes, CSRF tokens, and PKCE verifiers in constant time, and escapes all HTML interpolations withContent-Security-Policy: default-src 'none'; ...,X-Content-Type-Options: nosniff, andReferrer-Policy: no-referrer. OIDC clients cache validated discovery documents in memory for 24 hours, validateiss,aud,exp,nonce, andsubon the ID token obtained over TLS from the token endpoint, require userinfosubto match, and evaluateallow.claimrules against string and string-array claims as well asallow.sculk_serverrules against the live userinfosculk_serversarray (addingsculk:serversautomatically and admitting only when an object hasid == <server id>andis_player == true, failing closed on missing, malformed, or non-array claims, revoked grants/401 responses, blocked subjects, or provider outages). The Discord preset fetchesusers/@me(id/username) and, whenallow.discord_guildis set, adds theguildsscope and checks live membership viausers/@me/guildson login and every re-check (failing closed on any IdP error). The RFC 8628 device flow uses unambiguous 8-character codes (BCDFGHJKLMNPQRSTVWXZ), omitsverification_uri_complete, ignoresuser_codequery parameters onGET /login/device, enforces__Host-swdevdouble-submit CSRF cookie +Sec-Fetch-Site: same-origin+ per-IP (IPv6/64), per-code, and global miss brute-force rate limits onPOST /login/device/approve, caps pending device codes both globally and per route, shows a phishing warning confirmation page before redirecting withprompt=consent(OIDC and Discord), bindsconfirm=1to/login/callbackvia 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. EveryPOST /ticketsand every connect streamOPENolder than 60 seconds re-checks revocations and the live IdP (503 idp_unavailable/RESETcode7on outage,401 login_revoked/RESETcode6on revocation); revoking a subject or changing a route's authorizer immediately sendsGOAWAY revokedandRESETcode6to affected connect sessions. Concurrent refreshes perlidare 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,
statevalues, andAuthorizationheaders are never logged; log lines recordtoken_id,lid, sanitizedroute/subject/name,session, andpeer. -
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 behindsculkworm-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.