"""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 ", "failed": b"Federated_Computer/coredesktop#1 [click](https://evil.example) ", "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("
"): 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\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()