diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 971f9a6..3dc9166 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -160,6 +160,20 @@ jobs: - name: No per-player data tracked in data/world/ (public repo) run: python3 tests/test_world_no_player_data.py + # CC:Tweaked hands children a programmable computer with an HTTP API. Its + # stock rules allow every host, so any whitelisted player could make the + # server issue outbound requests anywhere. This gate keeps the lockdown + # deny-by-default and correctly targeted; liveness is proved separately on + # the droplet with tools/verify_cc_http.sh. + - name: In-game computers cannot call arbitrary hosts + run: python3 tests/test_cc_http_lockdown.py + + # A parental control that is silently off is worse than one that is + # absent, and this repo shipped a month of documentation claiming the + # limiter was dead while it was running. Guard the control and the claim. + - name: Playtime limiter is present, wired and observable + run: python3 tests/test_playtime_limiter.py + # Generated and binary artefacts must not be tracked. A compiled .pyc for # .github/scripts/server_health.py rode along for months because # .gitignore had no __pycache__ rule, and `sync_client_pack.py --write` @@ -212,7 +226,7 @@ jobs: run: | for f in gitops/deploy.sh gitops/install_gitops.sh bootstrap_droplet.sh harden_sshd.sh \ add_admin_user.sh server-audit.sh tests/test_droplet_hardening.sh \ - alerts/security_alert.sh alerts/install_alerts.sh; do + alerts/security_alert.sh alerts/install_alerts.sh tools/verify_cc_http.sh; do [ -f "$f" ] && bash -n "$f" && echo "OK $f" done diff --git a/CHANGELOG.md b/CHANGELOG.md index 9336079..947f385 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,46 @@ being corrected, and those are the ones most likely to save someone time later. verify before anything goes back in. **No pack re-import required.** ### Security +- **In-game computers can no longer call arbitrary hosts.** CC:Tweaked ships + every child a programmable computer with an HTTP API, and its stock rules are + `deny $private` then `allow *`. Any whitelisted player could write four lines + of Lua and make the server issue outbound requests to anything on the + internet, including the DigitalOcean metadata endpoint. That is server-side + request forgery with a child at the keyboard, and it was reachable on the + live server. + + The rules cannot be committed: they are Forge SERVER config, stored per-world + at `world/serverconfig/computercraft-server.toml`, and both `data/config/` and + `data/world/` are gitignored on purpose because tracking files the server + rewrites leaves the droplet worktree dirty and blocks `git pull --ff-only`. + So they are applied at every container start through itzg's + `PATCH_DEFINITIONS`, which has the useful property of re-asserting itself on + every boot rather than being an edit someone can undo by hand on the box. + See `data/patches/computercraft-http.json`. + + **Player impact:** the built-in `pastebin` and `wget` programs now fail with + "domain not permitted" for every host. Allowing one host back is a single + entry above the catch-all deny. + + **Verified locally against the pinned image before shipping**, by running + `mc-image-helper patch` over a seeded stock config and parsing the result. + That caught two format traps that would each have failed silently on the + droplet with CI green: a file in a `PATCH_DEFINITIONS` *directory* must be a + PatchDefinition (`file` + `ops`) and not a PatchSet (`patches: [...]`), and it + must be strict JSON, because `--json-allow-comments` applies to the files + being patched and not to the definition itself. Both are now CI failures and + are written up in `data/patches/README.md`. + + Note the patcher rewrites TOML in a flattened single-quoted form rather than + `[[http.rules]]` blocks. Both are valid TOML, but it means grepping for + `host = "*"` finds nothing, so `tools/verify_cc_http.sh` parses the TOML + properly instead of pattern-matching it. + + **Still not verified on the droplet.** Local proof is that the patch applies + and produces correct rules; only reading the effective config inside the + running container proves it applied there. Run `tools/verify_cc_http.sh` after + the first deploy carrying this change. + - **Removed unused base-image binaries and upgraded OpenSSL** (`Dockerfile`). `gosu` (22 Trivy findings) only runs when the container starts as root, and this one runs as uid 1000. `restify` (8) is only used for Bukkit/Spigot. @@ -84,6 +124,25 @@ being corrected, and those are the ones most likely to save someone time later. droplet; see `alerts/`. [#25, #26] ### Fixed +- **The daily playtime limiter was never actually off, and this repo said it + was for a month.** #21 deleted the Windows `playtime_limit.ps1` and wrote + "there is currently no time limit of any kind" into DEPLOY.md and this + changelog. That conflated two different limiters: the KubeJS one, + `data/kubejs/server_scripts/playtime_limit.js`, was added 2026-07-20 and has + been tracked, mounted and loading on every boot the whole time. + + A parent told no parental control exists goes looking for another way to + limit their child, or concludes the server is unsuitable. Being wrong in the + alarming direction is still being wrong. + + The root cause was not the deletion, it was that nothing was observable. The + limiter now announces itself on load (`[playtime] limiter ACTIVE ...`, so + `docker logs minecraft-java | grep playtime` answers the question), and any + player can run `/playtime` to see their usage and remaining time. Ops, who + are exempt and whose own numbers prove nothing, see the limiter's configured + state instead. DEPLOY.md now carries a dated correction, and + `tests/test_playtime_limiter.py` fails if the claim is reintroduced. + - Health check and security alerts rebuilt around zero false positives. Three collectors fired during normal operation, one of which (`RestartCount > 0`) would have alerted on **every run forever** after any deploy, because that diff --git a/DEPLOY.md b/DEPLOY.md index f21a7fc..be0f81f 100644 --- a/DEPLOY.md +++ b/DEPLOY.md @@ -100,21 +100,45 @@ with a cron job instead: tar czf ~/mc-backup-$(date +\%F).tgz -C ~/minecraft/data world ops.json whitelist.json server.properties ``` -> ### Daily playtime limits are NOT running +> ### Daily playtime limits: what is actually running > -> There used to be a Windows script (`playtime_limit.ps1`) that read each kid's -> `play_time` from the server stats, and once they passed a daily cap (default -> 120 minutes) removed them from the whitelist, which `ENFORCE_WHITELIST` turns -> into an instant kick. It put them back at the next day rollover. +> **CORRECTION (2026-09-09).** This section previously said "no time limit of any kind." +> That was wrong, and had been wrong since 2026-08-15. Read this before trusting +> either claim. > -> It only ever worked against a local Windows host and has not run since the move -> to the droplet. It was deleted rather than left in the repo pretending to be a -> control that was actually switched off. +> Two different limiters existed. The Windows one, `playtime_limit.ps1`, read +> each kid's `play_time` from the server stats and removed them from the +> whitelist past a daily cap, which `ENFORCE_WHITELIST` turns into an instant +> kick. It only ever worked against a local Windows host, never ran on the +> droplet, and was correctly deleted in #21. > -> **So there is currently no time limit of any kind.** If you want one back, it -> needs writing for Linux: a cron job every few minutes calling -> `docker exec minecraft-java rcon-cli` to read stats and adjust the whitelist. -> The original logic is in git history if it is ever wanted as a starting point. +> The KubeJS one, `data/kubejs/server_scripts/playtime_limit.js`, was added +> 2026-07-20 and has been tracked and mounted the whole time. #21 deleted the +> PowerShell script and declared there was no limit at all, conflating the two. +> `data/` is bind-mounted to `/data` and KubeJS reads `server_scripts/` from +> there, so this script loads on every boot. +> +> **What it does.** Counts each player's seconds in `persistentData`, warns at +> 10, 5 and 1 minutes remaining, and kicks at zero. Resets on the local date +> rolling over in the server timezone, so no external scheduler is involved. +> Ops are exempt, checked live against `ops.json`. The cap is +> `data/kubejs/config/playtime_limits.json`: `default_minutes` for everyone, +> `players` for per-child overrides, `exempt` for non-ops with no cap. +> +> **How to check it is running**, so nobody has to take this document's word +> for it again: +> +> ```bash +> docker logs minecraft-java 2>&1 | grep playtime +> # expect: [playtime] limiter ACTIVE - default 120 min/day, ... +> ``` +> +> In game, any player can run `/playtime` for their own usage and remaining +> time. An op sees the limiter's configured state instead, because ops are +> exempt and their own numbers would prove nothing. +> +> After editing the config, apply it with `/kubejs reload server_scripts` or +> restart the container. The config is read once at script load. ## Later: add a domain diff --git a/data/kubejs/server_scripts/playtime_limit.js b/data/kubejs/server_scripts/playtime_limit.js index 0ad6227..c523bcc 100644 --- a/data/kubejs/server_scripts/playtime_limit.js +++ b/data/kubejs/server_scripts/playtime_limit.js @@ -1,6 +1,15 @@ const LocalDate = Java.loadClass('java.time.LocalDate') const CONFIG = JsonIO.read('kubejs/config/playtime_limits.json') || { default_minutes: 120, exempt: [], players: {} } +// Announce on load. DEPLOY.md and the CHANGELOG both claimed for a month that +// there was "no time limit of any kind" while this script was tracked, mounted +// and running, because the Windows playtime_limit.ps1 was deleted at the same +// time and the two got conflated. Nothing in the server output said either way. +// This line is how anyone checks in future: `docker logs minecraft-java | grep playtime`. +console.info('[playtime] limiter ACTIVE - default ' + CONFIG.default_minutes + + ' min/day, ' + ((CONFIG.exempt || []).length) + ' exempt, ' + + Object.keys(CONFIG.players || {}).length + ' per-player override(s). Ops are always exempt.') + function limitSecondsFor(player) { if (player.isOp()) return -1 // ops are always unlimited, checked live against ops.json - no config needed const username = player.username @@ -44,3 +53,34 @@ PlayerEvents.tick(event => { player.kick(Text.red("Your playtime for today is up! Come back tomorrow.")) } }) + +ServerEvents.commandRegistry(event => { + const { commands: Commands } = event + event.register( + Commands.literal('playtime') + .executes(ctx => { + const player = ctx.source.player + if (!player) return 0 + + const limitSeconds = limitSecondsFor(player) + const used = player.persistentData.getInt('ptSeconds') + const usedMin = Math.floor(used / 60) + + if (limitSeconds < 0) { + // Ops and exempt players have no cap, so their own numbers say + // nothing about whether the limiter works. Report its state + // instead: this is the admin answer to "is it actually on?". + player.tell(Text.gold('Playtime limiter: ACTIVE')) + player.tell(Text.white('- You are exempt, so no cap applies to you.')) + player.tell(Text.white('- Default cap for everyone else: ' + CONFIG.default_minutes + ' minutes per day.')) + player.tell(Text.white('- You have played ' + usedMin + ' minute(s) today.')) + return 1 + } + + const remainingMin = Math.max(0, Math.ceil((limitSeconds - used) / 60)) + player.tell(Text.gold('You have played ' + usedMin + ' minute(s) today.')) + player.tell(Text.white(remainingMin + ' minute(s) left before the daily limit.')) + return 1 + }) + ) +}) diff --git a/data/patches/README.md b/data/patches/README.md new file mode 100644 index 0000000..913ba19 --- /dev/null +++ b/data/patches/README.md @@ -0,0 +1,57 @@ +# Startup config patches + +Files here are applied by `mc-image-helper patch` at every container start, wired +through `PATCH_DEFINITIONS: "/data/patches"` in `docker-compose.yml`. + +## Two format rules, both learned the hard way + +Both of these fail **silently in effect**: the patch is rejected at startup, the +server boots with stock config, and CI stays green. Local testing against the +pinned image caught both before they reached the droplet. + +1. **A file in this directory must be a PatchDefinition, not a PatchSet.** + PatchDefinition is `{"file": ..., "ops": [...]}`. The `{"patches": [...]}` + wrapper is a PatchSet and is only valid when `PATCH_DEFINITIONS` points at a + single file rather than a directory. Getting it wrong produces + `Unrecognized field "patches"`. + +2. **No comments. Not even `//`.** `mc-image-helper patch --help` advertises + `--json-allow-comments` defaulting to true, but that applies to the files + being *patched*, not to the definition read from this directory. A `//` line + here produces `ALLOW_COMMENTS not enabled for parser`. That is why this + README exists instead of comments in the JSON. + +Verify a change applied by re-reading the effective file inside the container, +which is what `tools/verify_cc_http.sh` does. Never assume a patch landed. + +## computercraft-http.json + +Locks CC:Tweaked's HTTP API down to deny-by-default. + +**What it closes.** Children write and run arbitrary Lua on this server. +CC:Tweaked's stock rules are `deny $private` then `allow *`, so any whitelisted +player could make the SERVER issue outbound HTTP to any host on the internet. +That is server-side request forgery with a child at the keyboard. + +**Why a patch and not a committed config file.** CC:Tweaked's HTTP rules are +Forge SERVER config, stored per-world at +`world/serverconfig/computercraft-server.toml`. Both `data/config/` and +`data/world/` are gitignored deliberately: tracking files the server rewrites +leaves the droplet worktree permanently dirty and makes `git pull --ff-only` in +`gitops/deploy.sh` abort every run. So the rules cannot be committed. Patching at +startup also re-asserts them after any manual edit on the box. + +**Rule order matters.** CC:Tweaked evaluates `http.rules` top to bottom, first +match wins. The private-range denies come first, then the catch-all deny. +`$private` already covers loopback, RFC1918 and link-local; the explicit CIDRs +are belt-and-braces in case `$private` is unsupported on a future version, and +because `169.254.169.254` is the cloud metadata endpoint on this DigitalOcean +droplet and deserves to be named. + +**`http.enabled` stays true on purpose**, so a denied request returns a readable +"domain not permitted" instead of the confusing "http is disabled". + +**Functional tradeoff, accepted deliberately.** The built-in `pastebin` and +`wget` programs now fail for every host. To allow one host back, insert a single +`{host, action: allow}` entry **above** the catch-all deny. That is also how the +Instructor Terminal gets its one allowed origin. diff --git a/data/patches/computercraft-http.json b/data/patches/computercraft-http.json new file mode 100644 index 0000000..942a866 --- /dev/null +++ b/data/patches/computercraft-http.json @@ -0,0 +1,58 @@ +{ + "file": "/data/world/serverconfig/computercraft-server.toml", + "ops": [ + { + "$set": { + "path": "$.http.enabled", + "value": true + } + }, + { + "$set": { + "path": "$.http.websocket_enabled", + "value": false + } + }, + { + "$set": { + "path": "$.http.max_requests", + "value": 8 + } + }, + { + "$set": { + "path": "$.http.rules", + "value": [ + { + "host": "$private", + "action": "deny" + }, + { + "host": "127.0.0.0/8", + "action": "deny" + }, + { + "host": "10.0.0.0/8", + "action": "deny" + }, + { + "host": "172.16.0.0/12", + "action": "deny" + }, + { + "host": "192.168.0.0/16", + "action": "deny" + }, + { + "host": "169.254.0.0/16", + "action": "deny" + }, + { + "host": "*", + "action": "deny" + } + ] + } + } + ] +} diff --git a/docker-compose.yml b/docker-compose.yml index dc43221..e2d57e8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -164,6 +164,13 @@ services: # Wipe mods not in the list above on each boot, so version bumps replace # cleanly instead of leaving a stale jar behind (a classic mismatch cause). REMOVE_OLD_MODS: "TRUE" + + # CC:Tweaked HTTP lockdown. In-game computers could otherwise make the + # SERVER issue outbound HTTP to any host on the internet, which is SSRF + # with a child at the keyboard. The rules live in the per-world server + # config, which is gitignored and cannot be committed, so they are applied + # here at every container start instead. See data/patches/ for the why. + PATCH_DEFINITIONS: "/data/patches" # Raised for Ad Astra, which adds five dimensions (Moon, Mars, Venus, # Mercury, Glacio) on top of Terralith and When Dungeons Arise. # 5G heap inside a 6.5g container cap, NOT 6G. A JVM needs meaningful diff --git a/tests/test_cc_http_lockdown.py b/tests/test_cc_http_lockdown.py new file mode 100644 index 0000000..549cdd9 --- /dev/null +++ b/tests/test_cc_http_lockdown.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +"""In-game computers must not be able to make the server call arbitrary hosts. + +CC:Tweaked ships children a programmable computer with an HTTP API. Its stock +rules are `deny $private` followed by `allow *`, which means any whitelisted +player can write four lines of Lua and make THIS SERVER issue outbound requests +to anything on the internet. That is server-side request forgery, the attacker +is a nine-year-old, and it is reachable on the live server today. + +The fix cannot be a committed config file. CC:Tweaked's HTTP rules are Forge +SERVER config, stored per-world at `world/serverconfig/computercraft-server.toml`, +and both `data/config/` and `data/world/` are gitignored deliberately: tracking +files the server rewrites leaves the droplet worktree permanently dirty and +makes `git pull --ff-only` in gitops/deploy.sh abort every run. So the rules are +applied at container start through itzg's PATCH_DEFINITIONS instead, which has +the useful property of re-asserting itself on every boot rather than being a +one-time edit somebody can undo by hand on the box. + +WHAT THIS TEST IS NOT. It cannot prove the rules are live on the droplet. It +proves the patch is present, wired, and says the right thing. The only proof +that the control is actually in force is reading the effective TOML inside the +running container, which is what `tools/verify_cc_http.sh` does. Run that once +after the first deploy that carries this change, then treat this test as the +tripwire that stops the lockdown being loosened later without review. +""" +import io +import json +import os +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +PATCH_DIR = os.path.join(ROOT, "data", "patches") +PATCH_FILE = os.path.join(PATCH_DIR, "computercraft-http.json") +COMPOSE = os.path.join(ROOT, "docker-compose.yml") + +# Everything CC:Tweaked must be refused. $private is CC:Tweaked's own matcher for +# loopback, RFC1918 and link-local. The CIDRs are belt-and-braces in case a +# future version drops $private, and 169.254.0.0/16 is the DigitalOcean metadata +# endpoint, which is the single most valuable SSRF target on this box. +REQUIRED_DENIES = { + "$private", + "127.0.0.0/8", + "10.0.0.0/8", + "172.16.0.0/12", + "192.168.0.0/16", + "169.254.0.0/16", +} + +failures = [] + + +def check(label, condition, detail=""): + if condition: + print("PASS %s" % label) + else: + print("FAIL %s%s" % (label, (" - " + detail) if detail else "")) + failures.append(label) + + +if not os.path.isfile(PATCH_FILE): + print("FAIL patch definition exists at data/patches/computercraft-http.json") + sys.exit(1) + +with io.open(PATCH_FILE, encoding="utf-8") as fh: + try: + doc = json.load(fh) + except ValueError as exc: + print("FAIL patch definition is valid JSON - %s" % exc) + sys.exit(1) + +# Strict JSON on purpose. mc-image-helper advertises --json-allow-comments, but +# that applies to the files being PATCHED, not to the definition read from this +# directory: a // line here fails with "ALLOW_COMMENTS not enabled for parser" +# and the patch is silently skipped. Rationale lives in data/patches/README.md. +print("PASS patch definition is strict JSON (no comments, which the loader rejects)") + +# SHAPE. PATCH_DEFINITIONS points at a DIRECTORY, so every file in it must be a +# PatchDefinition ({"file", "ops"}). The {"patches": [...]} PatchSet wrapper is +# only valid when the env var names a single file, and using it here makes +# mc-image-helper reject the definition at startup with "Unrecognized field". +# The server then boots with stock permissive rules while CI stays green, which +# is the worst possible failure mode for a security control. Caught exactly this +# way by running the real patch tool against the pinned image before shipping. +check("definition is a PatchDefinition, not a PatchSet", + "patches" not in doc, + 'a file in the patches directory must use {"file", "ops"}, not {"patches": [...]}') +check("definition declares a target file", "file" in doc) +check("definition declares ops", isinstance(doc.get("ops"), list) and bool(doc["ops"])) + +patch = doc + +# The path is the whole ballgame. Forge keeps CC:Tweaked's SERVER config inside +# the world folder, not in config/. Pointing this at /data/config/ would produce +# a patch that applies cleanly to nothing and a security fix that is a no-op. +check( + "patch targets the per-world serverconfig, not config/", + patch.get("file") == "/data/world/serverconfig/computercraft-server.toml", + "got %r" % patch.get("file"), +) + +ops = patch.get("ops") or [] +sets = {} +for op in ops: + body = op.get("$set") + if body: + sets[body.get("path")] = body.get("value") + +check("http API stays enabled so denials give a readable error", + sets.get("$.http.enabled") is True) +check("websockets are disabled", sets.get("$.http.websocket_enabled") is False) + +rules = sets.get("$.http.rules") +check("patch replaces the whole http.rules list", isinstance(rules, list) and bool(rules)) + +if isinstance(rules, list) and rules: + denied = {r.get("host") for r in rules if r.get("action") == "deny"} + allowed = [r.get("host") for r in rules if r.get("action") == "allow"] + + missing = REQUIRED_DENIES - denied + check("every private and metadata range is denied", + not missing, "missing %s" % sorted(missing)) + + # Order matters: CC:Tweaked takes the first matching rule. A wildcard allow + # anywhere, or a catch-all that is not last and not a deny, reopens the hole. + check("the last rule is a catch-all deny", + rules[-1].get("host") == "*" and rules[-1].get("action") == "deny", + "last rule is %r" % (rules[-1],)) + + check("no rule allows the wildcard host", + "*" not in allowed, "wildcard allow present") + + # An allow entry above the catch-all is legitimate and expected once the + # Instructor Terminal lands, but it must be a specific host, never a wildcard + # pattern that matches most of the internet. + for host in allowed: + check("allow entry %r is a specific host" % host, + isinstance(host, str) and not host.startswith("*"), + "wildcard allow entries defeat the allowlist") + + # Denies must precede the first allow, or a permissive entry wins first. + first_allow = next((i for i, r in enumerate(rules) if r.get("action") == "allow"), None) + if first_allow is not None: + preceding = {r.get("host") for r in rules[:first_allow] if r.get("action") == "deny"} + check("private ranges are denied before the first allow", + not (REQUIRED_DENIES - preceding), + "an allow rule is evaluated before the private-range denies") + +with io.open(COMPOSE, encoding="utf-8") as fh: + compose = fh.read() + +# A perfect patch file that the container never reads is worth nothing. +check("compose wires PATCH_DEFINITIONS", + 'PATCH_DEFINITIONS: "/data/patches"' in compose) +check("the patch file lives in the wired directory", + os.path.dirname(PATCH_FILE) == PATCH_DIR) + +# data/patches must not be gitignored, or the droplet clones without it and the +# container starts with stock permissive rules while CI stays green. +with io.open(os.path.join(ROOT, ".gitignore"), encoding="utf-8") as fh: + ignored = fh.read() +check("data/patches is not gitignored", + "data/patches" not in ignored) + +# The format rules above are invisible in the JSON itself, so they must be +# written down next to it or the next person repeats both mistakes. +check("data/patches/README.md documents the format traps", + os.path.isfile(os.path.join(PATCH_DIR, "README.md"))) + +if failures: + print("\n%d check(s) failed" % len(failures)) + sys.exit(1) + +print("\nCC:Tweaked HTTP lockdown is present, wired and deny-by-default.") +print("NOTE: this does not prove it is live. Run tools/verify_cc_http.sh on the") +print("droplet after the first deploy carrying this change.") diff --git a/tests/test_playtime_limiter.py b/tests/test_playtime_limiter.py new file mode 100644 index 0000000..23db6bf --- /dev/null +++ b/tests/test_playtime_limiter.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""The daily playtime limiter must exist, be wired, and be observable. + +BACKGROUND, and the reason this test exists at all. + +For roughly a month this repository told operators that no playtime limit was +running. It was wrong. `playtime_limit.ps1` (Windows, genuinely dead on the +droplet) and `data/kubejs/server_scripts/playtime_limit.js` (KubeJS, tracked, +mounted and loading on every boot) are two different limiters. PR #21 deleted +the first and wrote "there is currently no time limit of any kind" into +DEPLOY.md and the CHANGELOG, conflating them. + +That is a worse failure than the one it described. A parent told no control +exists goes and finds another way to limit their child's screen time, or +decides this server is unsuitable. Being wrong in the reassuring direction is +bad; being wrong in the alarming direction is also bad, and this was the second. + +The root cause was not the deletion. It was that NOTHING was observable: no log +line, no command, no way to answer "is it on?" without reading source. So this +test guards three things: + + 1. the limiter script is present and still does what it claims, + 2. it announces itself, so the question is answerable from `docker logs`, + 3. the documentation does not re-assert the falsehood. + +It cannot prove the limiter runs on the droplet. `docker logs minecraft-java | +grep playtime` proves that, and DEPLOY.md now says so. +""" +import io +import json +import os +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SCRIPT = os.path.join(ROOT, "data", "kubejs", "server_scripts", "playtime_limit.js") +CONFIG = os.path.join(ROOT, "data", "kubejs", "config", "playtime_limits.json") +DEPLOY = os.path.join(ROOT, "DEPLOY.md") +COMPOSE = os.path.join(ROOT, "docker-compose.yml") +GITIGNORE = os.path.join(ROOT, ".gitignore") + +failures = [] + + +def check(label, condition, detail=""): + if condition: + print("PASS %s" % label) + else: + print("FAIL %s%s" % (label, (" - " + detail) if detail else "")) + failures.append(label) + + +check("limiter script exists", os.path.isfile(SCRIPT)) +check("limiter config exists", os.path.isfile(CONFIG)) +if failures: + sys.exit(1) + +with io.open(SCRIPT, encoding="utf-8") as fh: + src = fh.read() + +# The behaviours the limiter is documented as having. If one of these is removed, +# DEPLOY.md becomes wrong again in the other direction. +check("counts playtime per player", "ptSeconds" in src) +check("resets on date rollover", "ptDate" in src and "LocalDate" in src) +check("warns before the cap", "playtime left today" in src) +check("kicks at the cap", ".kick(" in src) +check("ops are exempt, checked live", "isOp()" in src) +check("reads the config file", "playtime_limits.json" in src) + +# The observability that was missing, and whose absence is why a wrong claim +# survived a month unchallenged. +check("announces itself on load", "[playtime] limiter ACTIVE" in src) +check("registers the /playtime command", + "Commands.literal('playtime')" in src) +check("uses the same command idiom as onboarding.js", + "ServerEvents.commandRegistry" in src) + +with io.open(CONFIG, encoding="utf-8") as fh: + try: + cfg = json.load(fh) + except ValueError as exc: + cfg = None + check("limiter config is valid JSON", False, str(exc)) + +if cfg is not None: + print("PASS limiter config is valid JSON") + check("config sets a default cap", + isinstance(cfg.get("default_minutes"), int) and cfg["default_minutes"] > 0, + "default_minutes=%r" % cfg.get("default_minutes")) + check("config has an exempt list", isinstance(cfg.get("exempt"), list)) + check("config has a per-player override map", isinstance(cfg.get("players"), dict)) + +# The script only runs because data/ is bind-mounted and KubeJS reads +# server_scripts/ from it. If that mount changes, the limiter silently stops. +with io.open(COMPOSE, encoding="utf-8") as fh: + compose = fh.read() +check("data/ is bind-mounted so KubeJS can load the script", + "./data:/data" in compose) + +with io.open(GITIGNORE, encoding="utf-8") as fh: + ignored = fh.read() +check("the limiter script is not gitignored", + "data/kubejs/server_scripts/playtime_limit.js" not in ignored) + +# The documentation tripwire. This is the part that actually prevents a repeat. +with io.open(DEPLOY, encoding="utf-8") as fh: + deploy = fh.read() + +# The correction deliberately QUOTES the old claim so a reader understands what +# changed, so a naive substring search would flag the fix as the defect. What +# must not come back is the claim asserted in the document's own voice, and the +# heading that framed it as current fact. +check("the old 'limits are NOT running' section is gone", + "Daily playtime limits are NOT running" not in deploy) + +stray = [ + line.strip() + for line in deploy.splitlines() + if "no time limit of any kind" in line and "previously said" not in line +] +check("DEPLOY.md never asserts there is no time limit in its own voice", + not stray, + "asserted at: %s" % (stray[:1] or "")) + +check("DEPLOY.md carries the dated correction notice", + "CORRECTION (2026-09-09)" in deploy) +check("DEPLOY.md documents how to verify the limiter is running", + "grep playtime" in deploy, + "the verification recipe is missing") +check("DEPLOY.md mentions the /playtime command", + "/playtime" in deploy) + +if failures: + print("\n%d check(s) failed" % len(failures)) + sys.exit(1) + +print("\nPlaytime limiter is present, wired, observable and honestly documented.") +print("NOTE: liveness is proved on the droplet with:") +print(" docker logs minecraft-java 2>&1 | grep playtime") diff --git a/tools/verify_cc_http.sh b/tools/verify_cc_http.sh new file mode 100644 index 0000000..59496ea --- /dev/null +++ b/tools/verify_cc_http.sh @@ -0,0 +1,131 @@ +#!/usr/bin/env bash +# Prove the CC:Tweaked HTTP lockdown is ACTUALLY IN FORCE on the running server. +# +# On the droplet: bash tools/verify_cc_http.sh +# Against a local file: CONFIG_FILE=/path/to/computercraft-server.toml bash tools/verify_cc_http.sh +# +# Why this exists as a separate step. tests/test_cc_http_lockdown.py runs in CI +# and proves the patch is present, wired and says the right thing. It cannot +# prove the patch APPLIED. The rules live in the per-world server config, which +# is gitignored and generated at runtime, so the only honest proof is reading the +# effective file after startup. A security control nobody verified is a belief, +# not a control. +# +# Format note, learned by testing against the pinned image: mc-image-helper +# rewrites TOML in a flattened form with single quotes +# http.rules = [{host = '$private', action = 'deny'}, ...] +# rather than the pretty [[http.rules]] blocks CC:Tweaked ships. Both are valid +# TOML and Forge reads either, but it means grepping for `host = "*"` finds +# nothing and reports a false failure. So this parses the TOML properly instead. +set -euo pipefail + +CONTAINER=${CONTAINER:-minecraft-java} +LEVEL=${LEVEL:-world} +CFG="/data/${LEVEL}/serverconfig/computercraft-server.toml" + +if [ -n "${CONFIG_FILE:-}" ]; then + [ -f "$CONFIG_FILE" ] || { echo "ABORT: $CONFIG_FILE not found" >&2; exit 2; } + TOML=$(cat "$CONFIG_FILE") + SOURCE="$CONFIG_FILE" +else + if ! docker inspect -f '{{.State.Running}}' "$CONTAINER" 2>/dev/null | grep -q true; then + echo "ABORT: container '$CONTAINER' is not running; start it and retry" >&2 + exit 2 + fi + if ! docker exec "$CONTAINER" test -f "$CFG" 2>/dev/null; then + echo "ABORT: $CFG does not exist inside the container." >&2 + echo " Either the world has not generated yet, or LEVEL is not '$LEVEL'." >&2 + echo " Check level-name in data/server.properties, then re-run with LEVEL=." >&2 + exit 2 + fi + TOML=$(docker exec "$CONTAINER" cat "$CFG") + SOURCE="$CONTAINER:$CFG" +fi + +command -v python3 >/dev/null 2>&1 || { echo "ABORT: python3 required" >&2; exit 2; } + +echo "effective config: $SOURCE" +echo "---" + +printf '%s\n' "$TOML" | python3 -c ' +import sys +try: + import tomllib +except ImportError: + print("ABORT: python3.11+ needed for tomllib", file=sys.stderr); sys.exit(2) + +raw = sys.stdin.buffer.read() +try: + doc = tomllib.loads(raw.decode("utf-8")) +except Exception as exc: + print("FAIL effective config is not parseable TOML: %s" % exc); sys.exit(1) + +http = doc.get("http") +if not isinstance(http, dict): + print("FAIL no [http] section in the effective config"); sys.exit(1) + +fails = 0 +def check(label, cond, detail=""): + global fails + if cond: + print("PASS %s" % label) + else: + print("FAIL %s%s" % (label, (" - " + detail) if detail else "")) + fails += 1 + +rules = http.get("rules") +check("http.rules is present", isinstance(rules, list) and bool(rules)) +if not isinstance(rules, list) or not rules: + sys.exit(1) + +print(" %d rule(s):" % len(rules)) +for i, r in enumerate(rules, 1): + print(" %d. %-16s %s" % (i, r.get("host"), r.get("action"))) + +last = rules[-1] +check("the last rule is a catch-all deny", + last.get("host") == "*" and last.get("action") == "deny", + "last rule is %r; the lockdown did NOT apply and in-game computers can reach arbitrary hosts" % (last,)) + +required = ["$private", "169.254.0.0/16"] +denied = {r.get("host") for r in rules if r.get("action") == "deny"} +for want in required: + check("denied: %s" % want, want in denied) + +first_allow = next((i for i, r in enumerate(rules) if r.get("action") == "allow"), None) +if first_allow is None: + print("PASS no allow rules (fully closed)") +else: + before = {r.get("host") for r in rules[:first_allow] if r.get("action") == "deny"} + check("private ranges denied before the first allow", + all(w in before for w in required), + "an allow rule at index %d is evaluated before the private-range denies" % first_allow) + for r in rules[:first_allow+1]: + if r.get("action") == "allow": + check("allow entry %r is a specific host" % r.get("host"), + isinstance(r.get("host"), str) and not r.get("host", "").startswith("*")) + +check("websockets disabled", http.get("websocket_enabled") is False, + "websocket_enabled=%r" % http.get("websocket_enabled")) +check("http API left enabled for readable denials", http.get("enabled") is True) + +print("---") +if fails: + print("%d problem(s). The lockdown is NOT in force." % fails) + sys.exit(1) +print("CC:Tweaked HTTP lockdown is IN FORCE.") +print("") +print("Optional in-game proof: place a computer and run") +print(" print(http.checkURL(\"https://example.com\"))") +print("expected: false domain not permitted") +sys.exit(0) +' +rc=$? +if [ "$rc" -ne 0 ] && [ -z "${CONFIG_FILE:-}" ]; then + echo "" + echo "Check PATCH_DEFINITIONS is set in docker-compose.yml, that" + echo "data/patches/computercraft-http.json reached the droplet, and read the" + echo "startup log for a rejected definition:" + echo " docker logs $CONTAINER 2>&1 | grep -i 'patch\|mc-image-helper'" +fi +exit $rc