Test the report receiver and redaction against attacks
shellcheck / shellcheck (push) Failing after 19s

server/report-receiver/test_security.py sends the receiver what anyone
on the internet could, and the Redaction tests in tests/report.bats feed
report logs full of secrets. Each test was checked to fail before its fix.

The receiver now refuses a negative Content-Length (read without limit),
parts nested thousands deep (a RecursionError dropped the connection)
and more than 20 parts (thousands took seconds of CPU to parse). It
counts an IPv6 address's /64 for the rate limit, since a home has a
whole /64 to send from. Report fields go into the Gitea issue as inline
code, and titles keep only the characters of step names and versions,
so a report can't @mention the team, link issues, or show a tracking
image. It refuses reports while its disk has less than 2 GB free.

report now also takes out passwords in URLs, Bearer and Basic tokens,
password= and token: values, API keys by their prefixes, Nextcloud app
passwords, private keys, IPv6 and MAC addresses, the Cores' domains and
the user's name. It reads the Core settings rather than sourcing them,
and escapes extended regex characters in names, which it didn't before.

The plan for the checks still to do, in the smoketest VM (the agent
sandbox, network exposure, what root runs, the install path), is a
Claude Code skill: /coredesktop-security-checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 12:27:17 -07:00
co-authored by Claude Opus 5.5
parent 9dc5eb193d
commit 143473e798
8 changed files with 636 additions and 23 deletions
+10 -3
View File
@@ -11,10 +11,17 @@ files each as an issue in the private Gitea repository
Saved reports are deleted after 90 days; the Gitea issues stay.
- It turns away more than 5 reports an hour or 20 a day from one address, and
more than 500 a day in all. It keeps addresses for that in memory only, for
at most a day, and doesn't write them to its log. It also turns away logs
bigger than 10 MB compressed or 64 MB uncompressed.
at most a day, and doesn't write them to its log. An IPv6 address counts as
its /64, which a single home or server has to itself. It also turns away
logs bigger than 10 MB compressed or 64 MB uncompressed, requests of more
than 20 parts, and every report while its disk has less than 2 GB free.
- What a report says goes into the issue as inline code (the log in a code
block), and its title keeps only the characters of step names and versions,
so a report can't @mention anyone, link to issues, or show links, images or
HTML in Gitea.
- `make test` in the repository runs `test_receiver.py`, which sends reports
with the real `report` client to the receiver and a fake Gitea.
with the real `report` client to the receiver and a fake Gitea, and
`test_security.py`, which sends it what an attacker could.
## Deploying on federated.sh
+73 -12
View File
@@ -23,6 +23,7 @@ import email.policy
import gzip
import http.server
import io
import ipaddress
import json
import os
import re
@@ -43,6 +44,8 @@ FIELD_LIMITS = {"kind": 20, "version": 100, "failed": 1000, "kernel": 100, "sibl
KINDS = {"install", "update", "other"}
PER_ADDRESS_LIMITS = [(3600, 5), (86400, 20)] # (seconds, reports) per client address
DAILY_LIMIT = 500 # from everyone together
MAX_PARTS = 20 # a report has 6 fields; the parser takes seconds over thousands
MIN_FREE_BYTES = 2 * 1024 * 1024 * 1024 # to leave on the state directory's disk
EXCERPT_LINES = 150
RETRY_SECONDS = 600
KEEP_DAYS = 90
@@ -57,6 +60,20 @@ class Rejected(Exception):
self.message = message
def client_key(address):
"""What the rate limit counts reports by: an IPv4 address, or an IPv6
address's /64, since one home or server has a whole /64 to send from."""
try:
ip = ipaddress.ip_address(address)
except ValueError:
return address
if ip.version == 6 and ip.ipv4_mapped:
return str(ip.ipv4_mapped)
if ip.version == 6:
return str(ipaddress.ip_network(f"{ip}/64", strict=False))
return str(ip)
class RateLimiter:
def __init__(self, per_address=PER_ADDRESS_LIMITS, daily=DAILY_LIMIT):
self.per_address = per_address
@@ -68,6 +85,7 @@ class RateLimiter:
def check(self, address, now=None):
"""Count a report from address, or raise Rejected if it's one too many."""
now = time.time() if now is None else now
address = client_key(address)
longest = max(window for window, _ in self.per_address)
with self.lock:
while self.everyone and self.everyone[0] <= now - 86400:
@@ -92,14 +110,26 @@ def parse_multipart(content_type, body):
if not content_type.lower().startswith("multipart/form-data"):
raise Rejected(400, "That doesn't look like a CoreDesktop report.")
head = f"Content-Type: {content_type}\r\nMIME-Version: 1.0\r\n\r\n".encode()
message = email.parser.BytesParser(policy=email.policy.HTTP).parsebytes(head + body)
if not message.is_multipart():
parser = email.parser.BytesParser(policy=email.policy.HTTP)
boundary = parser.parsebytes(head, headersonly=True).get_boundary()
if not boundary:
raise Rejected(400, "That doesn't look like a CoreDesktop report.")
# Counted before parsing: the parser takes seconds over thousands of parts
if body.count(b"--" + boundary.encode("utf-8", errors="replace")) > MAX_PARTS + 1:
raise Rejected(400, "That doesn't look like a CoreDesktop report.")
try:
message = parser.parsebytes(head + body)
if not message.is_multipart():
raise Rejected(400, "That doesn't look like a CoreDesktop report.")
fields = {}
for part in message.iter_parts():
name = part.get_param("name", header="content-disposition")
if name and name not in fields:
fields[name] = part.get_payload(decode=True) or b""
# Parts nested thousands deep run the parser out of stack (RecursionError),
# and odd encodings can make the email package raise
except (RecursionError, ValueError, TypeError, LookupError, AttributeError):
raise Rejected(400, "That doesn't look like a CoreDesktop report.")
fields = {}
for part in message.iter_parts():
name = part.get_param("name", header="content-disposition")
if name and name not in fields:
fields[name] = part.get_payload(decode=True) or b""
return fields
@@ -139,16 +169,33 @@ def fence(text):
return "`" * max(3, longest + 1)
def code(text):
"""text as inline code, so Gitea shows it as it is: no @mentions that
notify anyone, #references, links, images or HTML."""
marks = "`" * (max((len(run) for run in re.findall(r"`+", text)), default=0) + 1)
pad = " " if text.startswith("`") or text.endswith("`") else ""
return f"{marks}{pad}{text}{pad}{marks}"
def cell(text):
"""text for one cell of a Markdown table."""
return text.replace("\\", "\\\\").replace("|", "\\|").replace("\n", "<br>") or "–"
"""text for one cell of a Markdown table: each line as inline code, with
its pipes escaped, which a table needs even inside code."""
lines = [line.strip() for line in text.split("\n") if line.strip()]
return "<br>".join(code(line).replace("|", "\\|") for line in lines) or "–"
def title_text(text):
"""text for an issue title, which can't be inline code: only the
characters step names and versions use, so no @mention, #reference, link
or right-to-left override gets into it."""
return re.sub(r"[^A-Za-z0-9 ._,:()+-]", "_", text.replace("\n", " "))
def issue_title(details):
failed = details["failed"].replace("\n", " ") or "an unknown step"
failed = title_text(details["failed"]) or "an unknown step"
title = f"{details['kind'].capitalize()} failed in {failed}"
if details["version"]:
title += f" ({details['version']})"
title += f" ({title_text(details['version'])})"
return title[:200]
@@ -175,7 +222,8 @@ def issue_body(report_id, details, log, received):
marks,
"",
"Sent with `report` from a CoreDesktop machine. Its user name, host name, home folder, "
"email and IP addresses were replaced before sending.",
"email, IP and MAC addresses, Tailscale names, Core domains, the user's name, and "
"passwords, tokens and keys it recognized were replaced before sending.",
])
@@ -227,6 +275,15 @@ class Store:
self.lock = threading.Lock() # one delivery at a time, so none is filed twice
def save(self, details, log):
# Only someone sending reports on purpose fills the disk faster than
# they're pruned; leave room for everything else on it
try:
free = shutil.disk_usage(self.directory if self.directory.exists() else self.directory.parent).free
except OSError:
free = None
if free is not None and free < MIN_FREE_BYTES + len(log.encode("utf-8", errors="replace")):
print("Refused a report: the disk is nearly full", file=sys.stderr, flush=True)
raise Rejected(503, "The report couldn't be saved; please try again later.")
received = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
for _ in range(10):
report_id = new_id()
@@ -316,6 +373,10 @@ def make_handler(store, limiter):
except ValueError:
self.reply(411, "A report needs a Content-Length.")
return
# read(-1) would read until the client hangs up, however much it sends
if length < 0:
self.reply(400, "That doesn't look like a CoreDesktop report.")
return
if length > MAX_REQUEST_BYTES:
self.reply(413, "This report is too big.")
return
+3 -3
View File
@@ -208,10 +208,10 @@ class PartsTest(unittest.TestCase):
def test_issue_text_cant_break_out_of_its_table_or_code_block(self):
details = {"kind": "update", "version": "v | 1", "failed": "a\nb", "kernel": "", "siblings": ""}
body = receiver.issue_body("CD-TEST23", details, "````\nlog\n", "now")
self.assertIn("| CoreDesktop | v \\| 1 |", body)
self.assertIn("| Failed | a<br>b |", body)
self.assertIn("| CoreDesktop | `v \\| 1` |", body)
self.assertIn("| Failed | `a`<br>`b` |", body)
self.assertIn("`````\n````\nlog\n`````", body)
self.assertEqual(receiver.issue_title(details), "Update failed in a b (v | 1)")
self.assertEqual(receiver.issue_title(details), "Update failed in a b (v _ 1)")
def test_ids_are_easy_to_read_out(self):
for _ in range(100):
+258
View File
@@ -0,0 +1,258 @@
"""Attacks on receiver.py: what someone on the internet could send to
federated.sh/report. Run with the other tests:
python3 -I -m unittest discover -s server/report-receiver
Each test sends what an attacker would, to the receiver on a free port with a
fake Gitea, and checks it's turned away without harm, or filed harmlessly."""
import contextlib
import gzip
import http.server
import io
import re
import shutil
import socket
import sys
import tempfile
import threading
import time
import unittest
import urllib.error
import urllib.request
from pathlib import Path
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parent))
import receiver # noqa: E402
from test_receiver import FakeGitea # noqa: E402
def multipart(fields, boundary="x"):
"""A multipart/form-data body; the log field is gzipped."""
chunks = []
for name, value in fields.items():
if name == "log":
chunks.append(f'--{boundary}\r\nContent-Disposition: form-data; name="log"; filename="log.gz"\r\n'
f'Content-Type: application/gzip\r\n\r\n'.encode() + gzip.compress(value) + b"\r\n")
else:
chunks.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n'.encode()
+ value + b"\r\n")
return b"".join(chunks) + f"--{boundary}--\r\n".encode()
def report(**overrides):
fields = {"kind": b"update", "version": b"2026.11.16 (5d7db2c)", "failed": b"10-pacman.sh",
"kernel": b"6.17.1-arch1-1", "siblings": b"", "log": b"Updating CoreDesktop...\n"}
fields.update(overrides)
return multipart(fields)
class AttackTest(unittest.TestCase):
def setUp(self):
self.stderr = io.StringIO()
self.enterContext(contextlib.redirect_stderr(self.stderr))
self.tmp = Path(tempfile.mkdtemp())
self.gitea = FakeGitea()
self.store = receiver.Store(self.tmp / "state", receiver.Gitea(self.gitea.url, "o/r", "secret"))
self.limiter = receiver.RateLimiter()
handler = receiver.make_handler(self.store, self.limiter)
handler.log_message = lambda *args: None
handler.timeout = 2
self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)
self.port = self.server.server_port
threading.Thread(target=self.server.serve_forever, daemon=True).start()
def tearDown(self):
self.server.shutdown()
self.server.server_close()
self.gitea.close()
shutil.rmtree(self.tmp)
def post(self, body, content_type="multipart/form-data; boundary=x", headers=None):
request = urllib.request.Request(f"http://127.0.0.1:{self.port}/report", data=body, method="POST",
headers={"Content-Type": content_type, **(headers or {})})
try:
with urllib.request.urlopen(request, timeout=30) as response:
return response.status, response.read().decode()
except urllib.error.HTTPError as error:
with error:
return error.code, error.read().decode()
def raw(self, request, timeout=5):
"""Send request bytes as they are and return the reply's status code,
or None if the connection closed without a reply."""
with socket.create_connection(("127.0.0.1", self.port), timeout=timeout) as sock:
sock.sendall(request)
reply = b""
with contextlib.suppress(socket.timeout):
while chunk := sock.recv(4096):
reply += chunk
match = re.match(rb"HTTP/1\.[01] (\d{3}) ", reply)
return int(match.group(1)) if match else None
def filed(self):
"""The issue the last report became, once it's filed."""
for _ in range(100):
if self.gitea.issues and self.gitea.attachments:
return self.gitea.issues[-1]
time.sleep(0.05)
self.fail("the report wasn't filed")
# --- Requests that would tie up or crash the receiver ----------------------
def test_a_negative_content_length_is_refused_at_once(self):
# read(-1) would read until the client hung up: unlimited memory
started = time.time()
status = self.raw(b"POST /report HTTP/1.1\r\nHost: x\r\nContent-Type: multipart/form-data; boundary=x\r\n"
b"Content-Length: -1\r\n\r\n")
self.assertEqual(status, 400)
self.assertLess(time.time() - started, 2)
def test_a_content_length_too_big_is_refused_without_reading_the_body(self):
status = self.raw(b"POST /report HTTP/1.1\r\nHost: x\r\nContent-Type: multipart/form-data; boundary=x\r\n"
b"Content-Length: 999999999999\r\n\r\n")
self.assertEqual(status, 413)
def test_a_missing_or_garbled_content_length_is_refused(self):
for length in (b"", b"Content-Length: abc\r\n", b"Content-Length: 1e9\r\n"):
status = self.raw(b"POST /report HTTP/1.1\r\nHost: x\r\n" + length + b"\r\n")
self.assertEqual(status, 411)
def test_parts_nested_thousands_deep_are_refused_not_crashed_on(self):
body = b"".join(f"--b{i}\r\nContent-Type: multipart/mixed; boundary=b{i + 1}\r\n\r\n".encode()
for i in range(3000))
self.assertEqual(self.post(body, "multipart/form-data; boundary=b0")[0], 400)
def test_thousands_of_parts_are_refused_before_parsing(self):
body = b"".join(b'--x\r\nContent-Disposition: form-data; name="f%d"\r\n\r\na\r\n' % i
for i in range(100000)) + b"--x--\r\n"
started = time.time()
self.assertEqual(self.post(body)[0], 400)
self.assertLess(time.time() - started, 2)
def test_a_body_without_a_boundary_is_refused(self):
self.assertEqual(self.post(report(), "multipart/form-data")[0], 400)
self.assertEqual(self.post(report(), 'multipart/form-data; boundary=""')[0], 400)
def test_a_log_that_isnt_gzip_or_is_cut_off_is_refused(self):
whole = report()
start = whole.index(b"\x1f\x8b")
cut = whole[:start + 20] + b"\r\n--x--\r\n"
self.assertEqual(self.post(cut)[0], 400)
self.assertEqual(self.gitea.issues, [])
def test_a_disk_nearly_full_refuses_reports_instead_of_filling_it(self):
with mock.patch.object(receiver, "MIN_FREE_BYTES", 1 << 62):
self.assertEqual(self.post(report())[0], 503)
self.assertFalse((self.tmp / "state").exists() and any((self.tmp / "state").iterdir()))
def test_the_receiver_keeps_answering_after_all_of_these(self):
self.raw(b"POST /report HTTP/1.1\r\nContent-Length: -1\r\n\r\n")
self.raw(b"\x00\xff garbage\r\n\r\n")
self.raw(b"GET /" + b"a" * 70000 + b" HTTP/1.1\r\n\r\n")
with urllib.request.urlopen(f"http://127.0.0.1:{self.port}/report/health", timeout=5) as response:
self.assertEqual(response.read(), b"ok\n")
# --- Getting around the rate limit ---------------------------------------
def test_addresses_in_one_ipv6_64_share_a_rate_limit(self):
limiter = receiver.RateLimiter(per_address=[(3600, 2)], daily=100)
limiter.check("2001:db8:1:2::1", now=0)
limiter.check("2001:db8:1:2:ffff::9", now=1)
with self.assertRaises(receiver.Rejected):
limiter.check("2001:db8:1:2:abcd:1234:5678:9abc", now=2)
limiter.check("2001:db8:1:3::1", now=3) # another /64
def test_an_ipv4_address_written_as_ipv6_is_the_same_address(self):
limiter = receiver.RateLimiter(per_address=[(3600, 1)], daily=100)
limiter.check("192.0.2.7", now=0)
with self.assertRaises(receiver.Rejected):
limiter.check("::ffff:192.0.2.7", now=1)
def test_behind_caddy_the_first_forwarded_address_is_the_one_counted(self):
# Caddy replaces X-Forwarded-For from clients it doesn't trust, so the
# first address is the real client's
for _ in range(5):
self.assertEqual(self.post(report(), headers={"X-Forwarded-For": "192.0.2.7"})[0], 200)
self.assertEqual(self.post(report(), headers={"X-Forwarded-For": "192.0.2.7, 203.0.113.1"})[0], 429)
self.assertEqual(self.post(report(), headers={"X-Forwarded-For": "192.0.2.8"})[0], 200)
def test_a_forwarded_address_from_anywhere_but_caddy_is_ignored(self):
handler = receiver.make_handler(self.store, self.limiter)
request = handler.__new__(handler)
request.client_address = ("198.51.100.9", 4000)
request.headers = {"X-Forwarded-For": "192.0.2.7"}
self.assertEqual(request.client_address_seen(), "198.51.100.9")
# --- Getting something into the Gitea issue ---------------------------------
def test_report_fields_cant_mention_link_or_embed_anything_in_the_issue(self):
attacks = {
"version": b"@david please look <img src=https://evil.example/pixel.png>",
"failed": b"Federated_Computer/coredesktop#1 [click](https://evil.example) <script>x</script>",
"kernel": b"`` @david `` ![x](https://evil.example/i.png)",
"siblings": b"connector 1.0\n@everyone 2.0\n| --- |",
}
self.assertEqual(self.post(report(**attacks))[0], 200)
issue = self.filed()
table = [line for line in issue["body"].split("\n") if line.startswith("| ")]
for line in table[2:]:
value = line.split(" | ", 1)[1].rsplit(" |", 1)[0]
if value == "–":
continue
# Each line of a value is one inline code span, and nothing else
for piece in value.split("<br>"):
self.assertRegex(piece, r"^(`+)( ?)[^`]*(?:`(?!\1)[^`]*)*\2\1$", line)
self.assertNotIn("\n@", issue["body"])
self.assertNotIn(" @", issue["title"])
self.assertNotIn("#", issue["title"])
self.assertNotIn("<", issue["title"])
self.assertNotIn("](", issue["title"])
def test_the_log_cant_break_out_of_its_code_block(self):
log = b"ok\n```\n@david [click](https://evil.example)\n````\n<img src=x>\n"
self.assertEqual(self.post(report(log=log))[0], 200)
body = self.filed()["body"]
fence = re.search(r"\n(`{3,})\n", body).group(1)
start = body.index(f"\n{fence}\n") + len(fence) + 2
end = body.index(f"\n{fence}\n", start)
self.assertIn("@david", body[start:end])
self.assertNotIn("@david", body[:start] + body[end:])
def test_control_characters_and_direction_overrides_dont_reach_the_title(self):
failed = "10-pacman.sh\x1b[31m‮gnp.exe​\r".encode()
self.assertEqual(self.post(report(failed=failed))[0], 200)
title = self.filed()["title"]
self.assertNotRegex(title, r"[\x00-\x1f\x7f​-‏‪-‮⁦-⁩]")
self.assertTrue(title.startswith("Update failed in 10-pacman.sh"))
def test_an_unknown_kind_cant_change_the_attachments_name(self):
self.assertEqual(self.post(report(kind=b"../../etc/passwd"))[0], 200)
self.filed()
attachment = self.gitea.attachments[-1]
self.assertEqual(self.gitea.issues[-1]["title"].split()[0], "Other")
report_id = next(p.name for p in (self.tmp / "state").iterdir())
self.assertEqual(attachment["path"], "/api/v1/repos/o/r/issues/1/assets")
self.assertTrue((self.tmp / "state" / report_id / "log.txt").exists())
def test_the_reply_is_only_an_id_and_never_the_gitea_token(self):
status, body = self.post(report())
self.assertEqual(status, 200)
self.assertRegex(body, r"^CD-[2-9A-HJ-NP-Z]{6}\n$")
self.filed()
self.assertNotIn("secret", self.stderr.getvalue())
class TextTest(unittest.TestCase):
def test_code_survives_backticks_at_either_end(self):
self.assertEqual(receiver.code("a"), "`a`")
self.assertEqual(receiver.code("a`b"), "``a`b``")
self.assertEqual(receiver.code("`a``"), "``` `a`` ```")
def test_title_text_keeps_step_names_and_versions(self):
text = "71-siblings.sh, git pull, install.sh (2026.11.16 (5d7db2c)) 1.2+3:4"
self.assertEqual(receiver.title_text(text), text)
if __name__ == "__main__":
unittest.main()