Test the report receiver and redaction against attacks
shellcheck / shellcheck (push) Failing after 19s
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:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user