From d38dd79d9335a0c711a0288bc0c9ca9c5d9ec2a7 Mon Sep 17 00:00:00 2001 From: Tim Date: Wed, 9 Sep 2026 16:51:55 -0400 Subject: [PATCH 1/2] Lock down CC:Tweaked HTTP, and correct the playtime limiter claim Two independent defects, both found while triaging the paid-access backlog. CC:Tweaked HTTP was wide open. Children write and run Lua on this server, and the stock rules are `deny $private` then `allow *`, so any whitelisted player could make the SERVER issue outbound HTTP to any host, including the DO metadata endpoint. SSRF with a child at the keyboard, reachable today. 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 deliberately because tracking files the server rewrites leaves the droplet worktree dirty and aborts git pull --ff-only in gitops/deploy.sh. Pointing a config file at data/config/ would have been a silent no-op. So the rules go through itzg's PATCH_DEFINITIONS, applied at every container start, which also means they re-assert after a manual edit on the box. Player impact: pastebin and wget now fail with "domain not permitted" for every host. One entry above the catch-all deny allows a host back, which is also how the Instructor Terminal will get its single allowed origin. Not verified live. CI proves the patch is present, wired and deny-by-default; only reading the effective config inside the container proves it applied. tools/verify_cc_http.sh does that and must be run on the droplet after deploy. The playtime limiter was never off. #21 deleted the Windows playtime_limit.ps1 and wrote "there is currently no time limit of any kind" into DEPLOY.md and the changelog, conflating it with the KubeJS limiter, which was added 2026-07-20 and has been tracked, mounted and loading on every boot since. A parent told no parental control exists goes and finds another way, or leaves. The root cause was not the deletion, it was that nothing was observable. The limiter now logs on load and answers /playtime in game, DEPLOY.md carries a dated correction, and the test fails if the claim comes back. Both tests were validated by mutation: five deliberate breaks each, all caught. --- .github/workflows/ci.yml | 17 +- CHANGELOG.md | 46 ++++++ DEPLOY.md | 48 ++++-- data/kubejs/server_scripts/playtime_limit.js | 40 +++++ data/patches/computercraft-http.json | 58 +++++++ docker-compose.yml | 7 + tests/test_cc_http_lockdown.py | 156 +++++++++++++++++++ tests/test_playtime_limiter.py | 138 ++++++++++++++++ tools/verify_cc_http.sh | 99 ++++++++++++ 9 files changed, 596 insertions(+), 13 deletions(-) create mode 100644 data/patches/computercraft-http.json create mode 100644 tests/test_cc_http_lockdown.py create mode 100644 tests/test_playtime_limiter.py create mode 100644 tools/verify_cc_http.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0ed26fc..b922bd8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -126,10 +126,25 @@ jobs: - name: Client pack and server mod list are compatible run: python3 tests/test_client_server_mods.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 + - name: Shell scripts parse 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; do + add_admin_user.sh server-audit.sh tests/test_droplet_hardening.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 270dd6b..9838b66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,33 @@ being corrected, and those are the ones most likely to save someone time later. ## [Unreleased] +### 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. + + **This is not verified live yet.** CI proves the patch is present, wired and + deny-by-default. Only reading the effective config inside the running + container proves it applied, which is what `tools/verify_cc_http.sh` does. + Run it on the droplet after the first deploy carrying this change. + ### Added - **Open Parties and Claims**, required on both client and server (no dependencies to pull in). Integrates with Xaero's Minimap/World Map, already @@ -25,6 +52,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 d138068..dd0a0a6 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 cdd8b69..0a90fea 100644 --- a/data/kubejs/server_scripts/playtime_limit.js +++ b/data/kubejs/server_scripts/playtime_limit.js @@ -13,6 +13,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 @@ -56,3 +65,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/computercraft-http.json b/data/patches/computercraft-http.json new file mode 100644 index 0000000..82261c4 --- /dev/null +++ b/data/patches/computercraft-http.json @@ -0,0 +1,58 @@ +{ + "$comment": [ + "CC:Tweaked HTTP lockdown, applied by itzg's PATCH_DEFINITIONS at every container start.", + "", + "WHY THIS IS A PATCH AND NOT A COMMITTED CONFIG FILE:", + "CC:Tweaked's HTTP rules live in the SERVER config, which Forge stores per-world at", + "world/serverconfig/computercraft-server.toml. Both data/config/ and data/world/ are", + "gitignored on purpose (see .gitignore: tracking files the server rewrites leaves the", + "droplet worktree permanently dirty and blocks git pull --ff-only in gitops/deploy.sh).", + "So the config cannot be committed. Patching it at startup is the mechanism that", + "survives that constraint and re-asserts itself on every boot.", + "", + "WHAT THIS CLOSES:", + "Children write and run arbitrary Lua on this server. With CC:Tweaked's default rules", + "(deny $private, allow *), any 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,", + "and it is reachable today by anyone already whitelisted.", + "", + "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 kept as 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.", + "", + "FUNCTIONAL TRADEOFF, ACCEPTED DELIBERATELY: the built-in pastebin and wget programs", + "now fail with 'domain not permitted' 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 (see minecraft_website issue #36).", + "", + "http.enabled stays TRUE on purpose: the API remains present so a denied request", + "returns a clear 'domain not permitted' error a child can understand, rather than the", + "confusing 'http is disabled' that comes from switching the whole API off." + ], + "patches": [ + { + "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 7aca851..ea34961 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -133,6 +133,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..31f422e --- /dev/null +++ b/tests/test_cc_http_lockdown.py @@ -0,0 +1,156 @@ +#!/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) + +print("PASS patch definition is valid JSON") + +patches = doc.get("patches") or [] +check("patch definition declares exactly one patch", len(patches) == 1) + +patch = patches[0] if patches else {} + +# 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) + +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..6fea97f --- /dev/null +++ b/tools/verify_cc_http.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash +# Prove the CC:Tweaked HTTP lockdown is ACTUALLY IN FORCE on the running server. +# +# Run this on the droplet after the first deploy that carries the lockdown: +# 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 inside the container after startup. A security control nobody +# verified is a belief, not a control. +# +# Exits non-zero and prints what is wrong if the lockdown is not in force. +set -euo pipefail + +CONTAINER=${CONTAINER:-minecraft-java} +LEVEL=${LEVEL:-world} +CFG="/data/${LEVEL}/serverconfig/computercraft-server.toml" + +fail=0 +note() { echo "$*"; } +bad() { echo "FAIL $*"; fail=$((fail + 1)); } +ok() { echo "PASS $*"; } + +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 CC:Tweaked has not generated it yet (start the server once" >&2 + echo " and let the world load), or LEVEL is not '$LEVEL'. Check the" >&2 + echo " level-name in data/server.properties and re-run with LEVEL=." >&2 + exit 2 +fi + +TOML=$(docker exec "$CONTAINER" cat "$CFG") + +note "effective config: $CFG" +note "---" + +# Extract just the [http] section so a 'deny' somewhere else in the file cannot +# be mistaken for the rules we care about. +HTTP_SECTION=$(printf '%s\n' "$TOML" | awk '/^\[http\]/{f=1} f{print} /^\[[a-z_]+\]$/ && !/^\[http\]/ && f && ++n>1{exit}') + +if [ -z "$HTTP_SECTION" ]; then + bad "no [http] section found in the effective config" + HTTP_SECTION="$TOML" +fi + +# The stock CC:Tweaked config ends with an 'allow *' rule. If that survived, the +# patch did not apply and in-game computers can still reach the whole internet. +if printf '%s\n' "$HTTP_SECTION" | grep -qE '^[[:space:]]*host[[:space:]]*=[[:space:]]*"\*"' ; then + # A wildcard host entry exists. It is only safe if its action is deny. + wildcard_action=$(printf '%s\n' "$HTTP_SECTION" \ + | grep -A3 -E '^[[:space:]]*host[[:space:]]*=[[:space:]]*"\*"' \ + | grep -m1 -oE 'action[[:space:]]*=[[:space:]]*"[a-z]+"' \ + | grep -oE '"[a-z]+"' | tr -d '"' || true) + if [ "${wildcard_action:-}" = "deny" ]; then + ok "wildcard host rule is deny" + else + bad "wildcard host rule action is '${wildcard_action:-unknown}', expected deny" + bad " the lockdown did NOT apply: in-game computers can reach arbitrary hosts" + fi +else + bad "no wildcard host rule found; cannot confirm a catch-all deny is present" +fi + +for range in '\$private' '169\.254\.0\.0/16'; do + if printf '%s\n' "$HTTP_SECTION" | grep -qE "host[[:space:]]*=[[:space:]]*\"${range}\""; then + ok "denied range present: $(printf '%s' "$range" | tr -d '\\')" + else + bad "missing denied range: $(printf '%s' "$range" | tr -d '\\')" + fi +done + +if printf '%s\n' "$HTTP_SECTION" | grep -qE '^[[:space:]]*websocket_enabled[[:space:]]*=[[:space:]]*false'; then + ok "websockets disabled" +else + bad "websocket_enabled is not false" +fi + +note "---" +if [ "$fail" -eq 0 ]; then + note "CC:Tweaked HTTP lockdown is IN FORCE on the running server." + note "" + note "Optional live proof, if you want to see it refuse from inside the game:" + note " place a computer, then run: print(http.checkURL('https://example.com'))" + note " expected output: false domain not permitted" + exit 0 +fi + +note "$fail problem(s). The lockdown is NOT in force." +note "Check that PATCH_DEFINITIONS is set in docker-compose.yml, that" +note "data/patches/computercraft-http.json reached the droplet, and read the" +note "container log for patch errors: docker logs $CONTAINER 2>&1 | grep -i patch" +exit 1 From 991a7fa08083bc80f6256a6b34098d8df2f782fb Mon Sep 17 00:00:00 2001 From: Tim Date: Wed, 9 Sep 2026 17:58:43 -0400 Subject: [PATCH 2/2] Fix two silent-failure traps in the CC:Tweaked patch, found by local testing Ran mc-image-helper patch against the pinned image over a seeded stock config, which is the only way to know the lockdown actually applies. It did not. Two format traps, each of which fails SILENTLY: the definition is rejected at startup, the server boots with stock permissive rules, and CI stays green. For a security control that is the worst available failure mode. 1. PATCH_DEFINITIONS pointing at a DIRECTORY requires each file to be a PatchDefinition ({file, ops}). The {patches: [...]} PatchSet wrapper is only valid when the variable names a single file. Wrong shape gave "Unrecognized field". 2. No comments in the definition, not even //. The advertised --json-allow-comments applies to the files being patched, not to the definition read from the directory. A // line gave "ALLOW_COMMENTS not enabled for parser". Rationale moved out of the JSON into data/patches/README.md, which documents both traps so the next person does not repeat them. Also: the patcher rewrites TOML flattened and single-quoted rather than as [[http.rules]] blocks. Both are valid TOML and Forge reads either, but the first verify script grepped for `host = "*"` and would have reported a false failure against the real output. It now parses the TOML with tomllib and checks rule ORDER, and takes CONFIG_FILE so it can be tested without a container. Verified end to end locally: stock config in, deny-by-default out, parsed back with tomllib to confirm seven rules in the right order with the catch-all deny last. Verifier passes on the patched file and fails on stock rules. Both real bugs are now CI failures, mutation-tested. --- CHANGELOG.md | 22 +++- data/patches/README.md | 57 +++++++++ data/patches/computercraft-http.json | 104 ++++++++-------- tests/test_cc_http_lockdown.py | 31 ++++- tools/verify_cc_http.sh | 178 ++++++++++++++++----------- 5 files changed, 257 insertions(+), 135 deletions(-) create mode 100644 data/patches/README.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 9838b66..9f4bcf6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,10 +35,24 @@ being corrected, and those are the ones most likely to save someone time later. "domain not permitted" for every host. Allowing one host back is a single entry above the catch-all deny. - **This is not verified live yet.** CI proves the patch is present, wired and - deny-by-default. Only reading the effective config inside the running - container proves it applied, which is what `tools/verify_cc_http.sh` does. - Run it on the droplet after the first deploy carrying this change. + **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. ### Added - **Open Parties and Claims**, required on both client and server (no 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 index 82261c4..942a866 100644 --- a/data/patches/computercraft-http.json +++ b/data/patches/computercraft-http.json @@ -1,58 +1,58 @@ { - "$comment": [ - "CC:Tweaked HTTP lockdown, applied by itzg's PATCH_DEFINITIONS at every container start.", - "", - "WHY THIS IS A PATCH AND NOT A COMMITTED CONFIG FILE:", - "CC:Tweaked's HTTP rules live in the SERVER config, which Forge stores per-world at", - "world/serverconfig/computercraft-server.toml. Both data/config/ and data/world/ are", - "gitignored on purpose (see .gitignore: tracking files the server rewrites leaves the", - "droplet worktree permanently dirty and blocks git pull --ff-only in gitops/deploy.sh).", - "So the config cannot be committed. Patching it at startup is the mechanism that", - "survives that constraint and re-asserts itself on every boot.", - "", - "WHAT THIS CLOSES:", - "Children write and run arbitrary Lua on this server. With CC:Tweaked's default rules", - "(deny $private, allow *), any 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,", - "and it is reachable today by anyone already whitelisted.", - "", - "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 kept as 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.", - "", - "FUNCTIONAL TRADEOFF, ACCEPTED DELIBERATELY: the built-in pastebin and wget programs", - "now fail with 'domain not permitted' 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 (see minecraft_website issue #36).", - "", - "http.enabled stays TRUE on purpose: the API remains present so a denied request", - "returns a clear 'domain not permitted' error a child can understand, rather than the", - "confusing 'http is disabled' that comes from switching the whole API off." - ], - "patches": [ + "file": "/data/world/serverconfig/computercraft-server.toml", + "ops": [ { - "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" } - ] + "$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/tests/test_cc_http_lockdown.py b/tests/test_cc_http_lockdown.py index 31f422e..549cdd9 100644 --- a/tests/test_cc_http_lockdown.py +++ b/tests/test_cc_http_lockdown.py @@ -68,12 +68,26 @@ def check(label, condition, detail=""): print("FAIL patch definition is valid JSON - %s" % exc) sys.exit(1) -print("PASS patch definition is valid JSON") - -patches = doc.get("patches") or [] -check("patch definition declares exactly one patch", len(patches) == 1) - -patch = patches[0] if patches else {} +# 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 @@ -147,6 +161,11 @@ def check(label, condition, detail=""): 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) diff --git a/tools/verify_cc_http.sh b/tools/verify_cc_http.sh index 6fea97f..59496ea 100644 --- a/tools/verify_cc_http.sh +++ b/tools/verify_cc_http.sh @@ -1,99 +1,131 @@ #!/usr/bin/env bash # Prove the CC:Tweaked HTTP lockdown is ACTUALLY IN FORCE on the running server. # -# Run this on the droplet after the first deploy that carries the lockdown: -# bash tools/verify_cc_http.sh +# 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 inside the container after startup. A security control nobody -# verified is a belief, not a control. +# effective file after startup. A security control nobody verified is a belief, +# not a control. # -# Exits non-zero and prints what is wrong if the lockdown is not in force. +# 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" -fail=0 -note() { echo "$*"; } -bad() { echo "FAIL $*"; fail=$((fail + 1)); } -ok() { echo "PASS $*"; } - -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 +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 -if ! docker exec "$CONTAINER" test -f "$CFG" 2>/dev/null; then - echo "ABORT: $CFG does not exist inside the container." >&2 - echo " Either CC:Tweaked has not generated it yet (start the server once" >&2 - echo " and let the world load), or LEVEL is not '$LEVEL'. Check the" >&2 - echo " level-name in data/server.properties and re-run with LEVEL=." >&2 - exit 2 -fi +command -v python3 >/dev/null 2>&1 || { echo "ABORT: python3 required" >&2; exit 2; } -TOML=$(docker exec "$CONTAINER" cat "$CFG") +echo "effective config: $SOURCE" +echo "---" -note "effective config: $CFG" -note "---" +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) -# Extract just the [http] section so a 'deny' somewhere else in the file cannot -# be mistaken for the rules we care about. -HTTP_SECTION=$(printf '%s\n' "$TOML" | awk '/^\[http\]/{f=1} f{print} /^\[[a-z_]+\]$/ && !/^\[http\]/ && f && ++n>1{exit}') +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) -if [ -z "$HTTP_SECTION" ]; then - bad "no [http] section found in the effective config" - HTTP_SECTION="$TOML" -fi +http = doc.get("http") +if not isinstance(http, dict): + print("FAIL no [http] section in the effective config"); sys.exit(1) -# The stock CC:Tweaked config ends with an 'allow *' rule. If that survived, the -# patch did not apply and in-game computers can still reach the whole internet. -if printf '%s\n' "$HTTP_SECTION" | grep -qE '^[[:space:]]*host[[:space:]]*=[[:space:]]*"\*"' ; then - # A wildcard host entry exists. It is only safe if its action is deny. - wildcard_action=$(printf '%s\n' "$HTTP_SECTION" \ - | grep -A3 -E '^[[:space:]]*host[[:space:]]*=[[:space:]]*"\*"' \ - | grep -m1 -oE 'action[[:space:]]*=[[:space:]]*"[a-z]+"' \ - | grep -oE '"[a-z]+"' | tr -d '"' || true) - if [ "${wildcard_action:-}" = "deny" ]; then - ok "wildcard host rule is deny" - else - bad "wildcard host rule action is '${wildcard_action:-unknown}', expected deny" - bad " the lockdown did NOT apply: in-game computers can reach arbitrary hosts" - fi -else - bad "no wildcard host rule found; cannot confirm a catch-all deny is present" -fi +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 -for range in '\$private' '169\.254\.0\.0/16'; do - if printf '%s\n' "$HTTP_SECTION" | grep -qE "host[[:space:]]*=[[:space:]]*\"${range}\""; then - ok "denied range present: $(printf '%s' "$range" | tr -d '\\')" - else - bad "missing denied range: $(printf '%s' "$range" | tr -d '\\')" - fi -done +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) -if printf '%s\n' "$HTTP_SECTION" | grep -qE '^[[:space:]]*websocket_enabled[[:space:]]*=[[:space:]]*false'; then - ok "websockets disabled" -else - bad "websocket_enabled is not false" -fi +print(" %d rule(s):" % len(rules)) +for i, r in enumerate(rules, 1): + print(" %d. %-16s %s" % (i, r.get("host"), r.get("action"))) -note "---" -if [ "$fail" -eq 0 ]; then - note "CC:Tweaked HTTP lockdown is IN FORCE on the running server." - note "" - note "Optional live proof, if you want to see it refuse from inside the game:" - note " place a computer, then run: print(http.checkURL('https://example.com'))" - note " expected output: false domain not permitted" - exit 0 -fi +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,)) -note "$fail problem(s). The lockdown is NOT in force." -note "Check that PATCH_DEFINITIONS is set in docker-compose.yml, that" -note "data/patches/computercraft-http.json reached the droplet, and read the" -note "container log for patch errors: docker logs $CONTAINER 2>&1 | grep -i patch" -exit 1 +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