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
@@ -0,0 +1,140 @@
---
name: coredesktop-security-checks
description: Plan and progress for CoreDesktop's security test suite. The report receiver and report's redaction are tested; the checks still to write run in the smoketest VM (the agent sandbox, network exposure, what root runs, the install path). Use when resuming, continuing, checking the status of, or changing CoreDesktop's security or penetration tests.
---
# CoreDesktop's security checks
Written on 2026-11-16. Work out the current state before doing anything:
```
git -C ~/Projects/coredesktop fetch && git -C ~/Projects/coredesktop log --oneline origin/main -15
ls ~/Projects/coredesktop/smoketest/scenarios/ ~/Projects/coredesktop/server/report-receiver/
```
Tell the user which step is next and confirm before starting it.
## Scope
The suite covers what CoreDesktop itself adds. It doesn't test Arch or GNOME,
which upstream looks after. It goes after the places where a mistake would
leak data or give away control, in this order:
1. The report receiver, the only part on the public internet. **Done.**
2. `report`'s redaction, which decides what leaves a user's computer. **Done.**
3. The agent sandbox: the one place that runs code CoreDesktop doesn't trust.
4. Network exposure from outside.
5. Files root runs, and secrets only root may read.
6. The install path (federated.sh, the `[federated]` repo).
The pacman guard (`system/pacman-guard`) is
a safety net against mistakes, not a security control: anyone with sudo gets
past it by design. Don't test it as a boundary.
## Done: steps 1 and 2 (the commit "Test the report receiver and redaction against attacks")
- `server/report-receiver/test_security.py` sends the receiver what an
attacker could. It found, and the commit fixed:
- a negative Content-Length (read without limit)
- parts nested thousands deep (RecursionError, connection dropped)
- thousands of parts (8 s of CPU for 5.7 MB)
- a rate limit per IPv6 address instead of per /64
- Markdown in report fields reaching the Gitea issue: @mentions, issue
references, links, tracking images
- no guard against filling the disk
- `tests/report.bats` (the "Redaction" section) found `report` sending:
- passwords in URLs
- tokens, API keys, Nextcloud app passwords and private keys
- IPv6 and MAC addresses
- the Core's domain and the user's name
- user and host names with regex characters, unredacted
All fixed. A test also checks it doesn't over-redact (pacman's `::`, times,
epoch versions, `std::string`).
- Each test was checked to fail against the code before the fix.
Still open from these steps:
- **Deploy** the new `receiver.py` on federated.sh (server/report-receiver/README.md, "To update it later").
- **Slow uploads.** Caddy streams them to the receiver, one thread each. Try
`request_buffers 11MB` in Caddyfile.example's `reverse_proxy`, and check
that `caddy validate` accepts it.
- **Gitea attachments.** Check on the real server that Gitea serves attached
`.log` files as text or as downloads, never as HTML (a log can contain
`<script>`).
- **The daily limit.** The 500-a-day limit for everyone lets one sender block
reports for a day. That was left as a design trade-off; ask before changing it.
## Next: steps 3 to 6 in the smoketest VM
Write them as one new scenario, `smoketest/scenarios/60-security.sh`,
`IMAGE=installed`, `TIER="nightly"`, with `assert_vm`/`refute_vm` checks (see
`smoketest/lib/scenario.sh` and `44-low-disk.sh` for the style). Where a
check needs a second machine, say so in the scenario and skip it, rather than
faking it. The VM comes from the `coredesktop-dev` sibling project (see
smoketest/README.md); it isn't in this repository.
### 3. The agent sandbox (sandbox/, `sandbox/agent`, `sandbox/bin`)
Run a script as an agent would (through `sandbox/bin`'s wrappers, the way
opencode and Hermes start) and check that each of these fails:
- reading `~/.ssh`, `~/.gnupg`, the GNOME keyring (`~/.local/share/keyrings`),
Bitwarden's data, `~/.config/coredesktop` (Core settings),
`/etc/coredesktop/smb` and `~/.winboat` (hidden unless `configure sandbox`
shows it)
- writing outside the folder it was started in and its own state
- reaching a LAN address that isn't allowed (`configure ai-servers` adds
allowed ones), and anything not through its proxy
- seeing other users' processes, or the D-Bus session bus (which could ask
GNOME to run things outside the sandbox)
Also check that the same reads work from outside the sandbox, so a passing
test means the sandbox blocked them, not that the files were missing.
`tests/sandbox.bats` checks only the sandbox's configuration.
### 4. Network exposure
`system/firewall.sh` allows only 22/tcp (SSH), 5353/udp (mDNS), 53317
(LocalSend) and anything on tailscale0. Check:
- a scan from another machine finds only those
- SSH refuses passwords (`system/sshd.sh`, `PasswordAuthentication no`)
- a port a Docker container publishes isn't reachable from outside, which is
what `ufw-docker` is for: Docker otherwise goes around ufw
Open question: the scan has to come from outside the VM. With QEMU's user
networking, the host reaches only forwarded ports, and a scan from inside the
VM against itself goes through loopback, which ufw allows. Find out from
`coredesktop-dev` whether the VM can get a bridged or tap network, or a second
VM, before writing this one.
### 5. What root runs, and root-only secrets
Every file root runs must be owned by root and not writable by the user, and
so must every folder above it. Check it with `stat`, walking up to `/`. As of
2026-11-16:
- `/etc/coredesktop/smb` (mode 600, root), sshd's
`10-coredesktop-keys-only.conf`, the ufw rules, and the systemd drop-ins in
`system/defaults.sh`.
- Added with the Omarchy features (commit 9dc5eb1):
- the pacman hook `/etc/pacman.d/hooks/00-coredesktop-guard.hook` and
`/usr/local/lib/coredesktop/pacman-guard`
- `/etc/NetworkManager/dispatcher.d/90-coredesktop-captive-portal`
- after `configure security-key` and `configure fingerprint`:
`/usr/local/lib/coredesktop/lid-closed`, `/etc/pam.d/sudo`,
`/etc/pam.d/polkit-1` and `/etc/u2f_mappings`
Also check that nothing root runs reads a path in a user's home. That's why
the pacman guard and the lid check are copies in /usr/local, not run from
~/.local/share/coredesktop.
For `/etc/pam.d/sudo`: after the fingerprint or security-key item, a wrong
password must still fail, and `sudo -k; sudo true` without the key must still
ask for the password.
### 6. The install path
- `https://federated.sh` sends `wget` (User-Agent not starting with
`Mozilla`) to the HTTPS URL of `install.sh` on Gitea, never to plain HTTP.
- The `[federated]` repo's signing key in pacman is the one `utils.sh` pins
(`FEDERATED_REPO_KEY`), and the repo is `SigLevel = Required DatabaseRequired`.
- pacman refuses a package from `[federated]` that isn't signed by that key.
Serve one from the VM's own stand-in repo to check.
+1 -1
View File
@@ -227,7 +227,7 @@ If a step fails, the other steps still run, and the failed ones are listed at th
Each run's full output is saved in ~/.local/state/coredesktop/logs/, so you can read what went wrong after the terminal is gone. `update` keeps the logs of the last 10 updates and the last 3 installs or refreshes. Each run's full output is saved in ~/.local/state/coredesktop/logs/, so you can read what went wrong after the terminal is gone. `update` keeps the logs of the last 10 updates and the last 3 installs or refreshes.
If an install or update fails, it offers to send its log to the CoreDesktop team so we can find and fix the problem. Nothing is sent unless you say yes, and you can read exactly what would be sent first: your user name, host name, home folder, email addresses, IP addresses and Tailscale names are taken out. Along with the log go CoreDesktop's version, the kernel's, the names of the steps that failed and your sibling projects' versions. You get a report ID to mention if you contact us. To send a log later, run `report` (the newest log) or `report <file>`; `report --view` shows what would be sent without sending anything. If an install or update fails, it offers to send its log to the CoreDesktop team so we can find and fix the problem. Nothing is sent unless you say yes, and you can read exactly what would be sent first: your user name, host name, home folder, email addresses, IP and MAC addresses, Tailscale names, your Core's domain and your name are taken out, and so are passwords, tokens, API keys and private keys that turn up in it. Along with the log go CoreDesktop's version, the kernel's, the names of the steps that failed and your sibling projects' versions. You get a report ID to mention if you contact us. To send a log later, run `report` (the newest log) or `report <file>`; `report --view` shows what would be sent without sending anything.
If the update installed a newer kernel, or upgraded firmware, CPU microcode, the NVIDIA driver, systemd or glibc, it says so at the end and asks whether to reboot now. The answer is no unless you type y. If the update installed a newer kernel, or upgraded firmware, CPU microcode, the NVIDIA driver, systemd or glibc, it says so at the end and asks whether to reboot now. The answer is no unless you type y.
+43 -4
View File
@@ -11,8 +11,10 @@
# the terminal whether to send FILE. STEP names what failed. # the terminal whether to send FILE. STEP names what failed.
# #
# Nothing is sent unless the user says yes. Before sending, the log is cleaned # Nothing is sent unless the user says yes. Before sending, the log is cleaned
# of terminal codes and personal details are replaced: the home folder, user # of terminal codes, and personal details and secrets are replaced: the home
# name, host name, email addresses, IPv4 addresses and Tailscale names. # folder, user name, host name, email, IP and MAC addresses, Tailscale names,
# the Cores' domains and the user's name, passwords, tokens, API keys and
# private keys (see redact).
# #
# What's sent (the receiver on federated.sh implements the other side): an # What's sent (the receiver on federated.sh implements the other side): an
# HTTPS POST of multipart/form-data to $COREDESKTOP_REPORT_URL, with fields # HTTPS POST of multipart/form-data to $COREDESKTOP_REPORT_URL, with fields
@@ -46,9 +48,9 @@ newest_log() {
[ "${#logs[@]}" -gt 0 ] && echo "${logs[0]}" [ "${#logs[@]}" -gt 0 ] && echo "${logs[0]}"
} }
# Escape $1 for use in a sed regular expression # Escape $1 for use in a sed extended regular expression, between / or #
regex_escape() { regex_escape() {
printf '%s' "$1" | sed 's/[][\.*^$/]/\\&/g' printf '%s' "$1" | sed 's/[][\.*^$/+?(){}|#]/\\&/g'
} }
# Print log $1 as it would be sent: without script(1)'s header and footer, # Print log $1 as it would be sent: without script(1)'s header and footer,
@@ -58,15 +60,35 @@ regex_escape() {
# can be the one before the next; dotted versions such as 1.0.4.1.3 are kept, # can be the one before the next; dotted versions such as 1.0.4.1.3 are kept,
# and so are four-part ones after v or == (v26.11.10.1, not1mm==26.11.10.1). # and so are four-part ones after v or == (v26.11.10.1, not1mm==26.11.10.1).
# A single = doesn't count, so addr=192.168.1.20 is still replaced. # A single = doesn't count, so addr=192.168.1.20 is still replaced.
#
# Secrets go first, before the rules below can take part of one: private keys,
# passwords in URLs (https://user:password@host), Bearer and Basic tokens,
# password=..., token: ... and the like, API keys by their prefixes (Anthropic,
# OpenAI, GitHub, GitLab, Slack, Tailscale, AWS, Hugging Face) and Nextcloud
# app passwords. Then MAC and IPv6 addresses (not 12:34:56, 1:2.3-4 or pacman's
# ":: "), and your Cores' domains and your name, as configure core saved them.
redact() { redact() {
local home user host local home user host
home="$(regex_escape "$HOME")" home="$(regex_escape "$HOME")"
user="$(regex_escape "${USER:-$(id -un)}")" user="$(regex_escape "${USER:-$(id -un)}")"
host="$(regex_escape "$(uname -n)")" host="$(regex_escape "$(uname -n)")"
local hex='[0-9A-Fa-f]{1,4}' personal=() value
while IFS= read -r value; do
[ -n "$value" ] && personal+=(-e "s/(^|[^A-Za-z0-9-])$(regex_escape "$value")([^A-Za-z0-9-]|\$)/\\1<core-domain>\\2/gI")
done < <(core_values CORE_DOMAIN)
while IFS= read -r value; do
[ -n "$value" ] && personal+=(-e "s/(^|[^A-Za-z0-9])$(regex_escape "$value")([^A-Za-z0-9]|\$)/\\1<name>\\2/gI")
done < <(core_values CORE_NAME)
LC_ALL=C sed -E \ LC_ALL=C sed -E \
-e '1{/^Script started on /d}' -e '/^Script done on .*COMMAND_EXIT_CODE/d' \ -e '1{/^Script started on /d}' -e '/^Script done on .*COMMAND_EXIT_CODE/d' \
-e 's/\x1b\][^\x07\x1b]*(\x07|\x1b\\)//g' -e 's#\x1b\[[0-9;?]*[ -/]*[@-~]##g' \ -e 's/\x1b\][^\x07\x1b]*(\x07|\x1b\\)//g' -e 's#\x1b\[[0-9;?]*[ -/]*[@-~]##g' \
-e 's/\x1b[()][0-9A-Za-z]//g' -e 's/\x1b[=>]//g' -e 's/\r+$//' -e 's/.*\r//' \ -e 's/\x1b[()][0-9A-Za-z]//g' -e 's/\x1b[=>]//g' -e 's/\r+$//' -e 's/.*\r//' \
-e '/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,/-----END [A-Z0-9 ]*PRIVATE KEY-----/c <private key>' \
-e 's#([A-Za-z][A-Za-z0-9+.-]*://)[^/@[:space:]]+@#\1<credentials>@#g' \
-e 's#(Bearer|Basic)[[:space:]]+[A-Za-z0-9._~+/=-]{8,}#\1 <secret>#gI' \
-e "s/((password|passwd|passphrase|secret|token|api[_-]?key|access[_-]?key|private[_-]?key)[\"']?[[:space:]]*[:=][[:space:]]*[\"']?)[^[:space:]\"',;&]+/\\1<secret>/gI" \
-e 's/(sk-ant-[A-Za-z0-9_-]{8,}|sk-[A-Za-z0-9_-]{20,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{20,}|xox[abprs]-[A-Za-z0-9-]{10,}|tskey-[A-Za-z0-9-]{8,}|AKIA[0-9A-Z]{16}|hf_[A-Za-z0-9]{20,})/<secret>/g' \
-e 's/(^|[^A-Za-z0-9-])([A-Za-z0-9]{5}-){4}[A-Za-z0-9]{5}([^A-Za-z0-9-]|$)/\1<secret>\3/g' \
-e "s#${home}([/[:space:]'\":]|\$)#~\\1#g" \ -e "s#${home}([/[:space:]'\":]|\$)#~\\1#g" \
-e 's/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/<email>/g' \ -e 's/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/<email>/g' \
-e 's/[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*\.ts\.net/<tailscale-name>/g' \ -e 's/[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*\.ts\.net/<tailscale-name>/g' \
@@ -74,9 +96,26 @@ redact() {
-e 's/(^=?|[^0-9.vV=]|[^=]=)([0-9]{1,3}\.){3}[0-9]{1,3}([^0-9.]|$)/\1<ip>\3/g' \ -e 's/(^=?|[^0-9.vV=]|[^=]=)([0-9]{1,3}\.){3}[0-9]{1,3}([^0-9.]|$)/\1<ip>\3/g' \
-e "s/(^|[^A-Za-z0-9_-])${user}([^A-Za-z0-9_-]|\$)/\\1<user>\\2/g" \ -e "s/(^|[^A-Za-z0-9_-])${user}([^A-Za-z0-9_-]|\$)/\\1<user>\\2/g" \
-e "s/(^|[^A-Za-z0-9_-])${host}([^A-Za-z0-9_-]|\$)/\\1<host>\\2/g" \ -e "s/(^|[^A-Za-z0-9_-])${host}([^A-Za-z0-9_-]|\$)/\\1<host>\\2/g" \
-e 's/(^|[^0-9A-Fa-f:])([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}([^0-9A-Fa-f:]|$)/\1<mac>\3/g' \
-e "s#(^|[^0-9A-Za-z:])($hex:){4,7}$hex(/[0-9]{1,3})?([^0-9A-Za-z:]|\$)#\\1<ip>\\4#g" \
-e "s#(^|[^0-9A-Za-z:])$hex(:$hex){0,6}::($hex(:$hex){0,6})?(/[0-9]{1,3})?([^0-9A-Za-z:]|\$)#\\1<ip>\\6#g" \
-e "s#(^|[^0-9A-Za-z:])::$hex(:$hex){0,6}(/[0-9]{1,3})?([^0-9A-Za-z:]|\$)#\\1<ip>\\4#g" \
"${personal[@]}" \
"$1" "$1"
} }
# Each value of setting $1 (CORE_DOMAIN, CORE_NAME) in your Cores' settings,
# as configure core saved them
core_values() {
local file
for file in "$HOME/.config/coredesktop/core.conf" "$HOME/.config/coredesktop/cores/"*.conf; do
[ -f "$file" ] || continue
# Read, not sourced, so nothing in the file runs. configure core writes
# each value with printf %q: take out its backslashes and quotes.
sed -nE "s/^$1=//p" "$file" | sed -E "s/^\\\$?'(.*)'\$/\\1/; s/\\\\(.)/\\1/g"
done | sort -u
}
coredesktop_version() { coredesktop_version() {
git -C "$COREDESKTOP" log -1 --format='%cd (%h)' --date=format:%Y.%m.%d 2> /dev/null || echo unknown git -C "$COREDESKTOP" log -1 --format='%cd (%h)' --date=format:%Y.%m.%d 2> /dev/null || echo unknown
} }
+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. 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 - 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 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 at most a day, and doesn't write them to its log. An IPv6 address counts as
bigger than 10 MB compressed or 64 MB uncompressed. 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 - `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 ## Deploying on federated.sh
+73 -12
View File
@@ -23,6 +23,7 @@ import email.policy
import gzip import gzip
import http.server import http.server
import io import io
import ipaddress
import json import json
import os import os
import re import re
@@ -43,6 +44,8 @@ FIELD_LIMITS = {"kind": 20, "version": 100, "failed": 1000, "kernel": 100, "sibl
KINDS = {"install", "update", "other"} KINDS = {"install", "update", "other"}
PER_ADDRESS_LIMITS = [(3600, 5), (86400, 20)] # (seconds, reports) per client address PER_ADDRESS_LIMITS = [(3600, 5), (86400, 20)] # (seconds, reports) per client address
DAILY_LIMIT = 500 # from everyone together 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 EXCERPT_LINES = 150
RETRY_SECONDS = 600 RETRY_SECONDS = 600
KEEP_DAYS = 90 KEEP_DAYS = 90
@@ -57,6 +60,20 @@ class Rejected(Exception):
self.message = message 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: class RateLimiter:
def __init__(self, per_address=PER_ADDRESS_LIMITS, daily=DAILY_LIMIT): def __init__(self, per_address=PER_ADDRESS_LIMITS, daily=DAILY_LIMIT):
self.per_address = per_address self.per_address = per_address
@@ -68,6 +85,7 @@ class RateLimiter:
def check(self, address, now=None): def check(self, address, now=None):
"""Count a report from address, or raise Rejected if it's one too many.""" """Count a report from address, or raise Rejected if it's one too many."""
now = time.time() if now is None else now now = time.time() if now is None else now
address = client_key(address)
longest = max(window for window, _ in self.per_address) longest = max(window for window, _ in self.per_address)
with self.lock: with self.lock:
while self.everyone and self.everyone[0] <= now - 86400: 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"): if not content_type.lower().startswith("multipart/form-data"):
raise Rejected(400, "That doesn't look like a CoreDesktop report.") 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() 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) parser = email.parser.BytesParser(policy=email.policy.HTTP)
if not message.is_multipart(): 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.") 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 return fields
@@ -139,16 +169,33 @@ def fence(text):
return "`" * max(3, longest + 1) 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): def cell(text):
"""text for one cell of a Markdown table.""" """text for one cell of a Markdown table: each line as inline code, with
return text.replace("\\", "\\\\").replace("|", "\\|").replace("\n", "<br>") or "–" 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): 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}" title = f"{details['kind'].capitalize()} failed in {failed}"
if details["version"]: if details["version"]:
title += f" ({details['version']})" title += f" ({title_text(details['version'])})"
return title[:200] return title[:200]
@@ -175,7 +222,8 @@ def issue_body(report_id, details, log, received):
marks, marks,
"", "",
"Sent with `report` from a CoreDesktop machine. Its user name, host name, home folder, " "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 self.lock = threading.Lock() # one delivery at a time, so none is filed twice
def save(self, details, log): 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") received = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
for _ in range(10): for _ in range(10):
report_id = new_id() report_id = new_id()
@@ -316,6 +373,10 @@ def make_handler(store, limiter):
except ValueError: except ValueError:
self.reply(411, "A report needs a Content-Length.") self.reply(411, "A report needs a Content-Length.")
return 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: if length > MAX_REQUEST_BYTES:
self.reply(413, "This report is too big.") self.reply(413, "This report is too big.")
return 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): 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": ""} details = {"kind": "update", "version": "v | 1", "failed": "a\nb", "kernel": "", "siblings": ""}
body = receiver.issue_body("CD-TEST23", details, "````\nlog\n", "now") body = receiver.issue_body("CD-TEST23", details, "````\nlog\n", "now")
self.assertIn("| CoreDesktop | v \\| 1 |", body) self.assertIn("| CoreDesktop | `v \\| 1` |", body)
self.assertIn("| Failed | a<br>b |", body) self.assertIn("| Failed | `a`<br>`b` |", body)
self.assertIn("`````\n````\nlog\n`````", 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): def test_ids_are_easy_to_read_out(self):
for _ in range(100): 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()
+108
View File
@@ -159,3 +159,111 @@ field() {
[ "$status" -eq 0 ] [ "$status" -eq 0 ]
[[ "$output" == *"Your report's ID is CD-7Q2K;"* ]] [[ "$output" == *"Your report's ID is CD-7Q2K;"* ]]
} }
# --- Redaction: what mustn't leave this computer -------------------------------
# view LINE...: what report would send for a log of these lines
view() {
printf '%s\n' "$@" > "$LOG"
run bash "$REPO/report" --view "$LOG"
[ "$status" -eq 0 ]
}
# sent_as LINE...: the output of the last view is exactly these lines
sent_as() {
[ "$output" = "$(printf '%s\n' "$@")" ] || { printf 'got:\n%s\n' "$output" >&2; return 1; }
}
@test "redaction takes passwords out of URLs" {
view "Cloning https://bob:s3cr3t!pw@gitea.example.com/x.git" \
"rclone: http://bob:hunter2@localhost:8080/dav/" \
"fetch ssh://git@github.com/x.git and https://github.com/x.git"
sent_as "Cloning https://<credentials>@gitea.example.com/x.git" \
"rclone: http://<credentials>@localhost:8080/dav/" \
"fetch ssh://<credentials>@github.com/x.git and https://github.com/x.git"
}
@test "redaction takes out tokens, passwords and API keys" {
view "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.c2lnbmF0dXJl" \
"curl -H 'Authorization: Basic Ym9iOmh1bnRlcjI='" \
"password=hunter2 PASSWORD: hunter3 passphrase='correct horse' api_key: abc123" \
"GET /callback?code=1&access_token=ya29.a0AfH6&state=2" \
'export ANTHROPIC_API_KEY="sk-ant-api03-AbCdEfGhIjKlMnOp-QrStUv"' \
"keys sk-proj-abcdefghijklmnopqrstuvwx ghp_abcdefghijklmnopqrstuvwxyz0123456789" \
"github_pat_11ABCDEFG0123456789_abcdefghijklmnop glpat-abcdefghijklmnopqrst" \
"xoxb-1234567890-abcdefghij tskey-auth-kAbCdEf1CNTRL-xyz AKIAIOSFODNN7EXAMPLE hf_abcdefghijklmnopqrstuvwx" \
"app password Ab3dE-fG4hI-jK5lM-nO6pQ-rS7tU in use"
sent_as "Authorization: Bearer <secret>" \
"curl -H 'Authorization: Basic <secret>'" \
"password=<secret> PASSWORD: <secret> passphrase='<secret> horse' api_key: <secret>" \
"GET /callback?code=1&access_token=<secret>&state=2" \
'export ANTHROPIC_API_KEY="<secret>"' \
"keys <secret> <secret>" \
"<secret> <secret>" \
"<secret> <secret> <secret> <secret>" \
"app password <secret> in use"
}
@test "redaction takes out private keys whole" {
view "Adding key:" "-----BEGIN OPENSSH PRIVATE KEY-----" "b3BlbnNzaC1rZXktdjEAAAAA" \
"AAAAC3NzaC1lZDI1NTE5AAAA" "-----END OPENSSH PRIVATE KEY-----" "done" \
"-----BEGIN RSA PRIVATE KEY-----" "MIIEpAIBAAKCAQEA" "-----END RSA PRIVATE KEY-----"
sent_as "Adding key:" "<private key>" "done" "<private key>"
}
@test "redaction takes out IPv6 and MAC addresses" {
view "inet6 2001:db8:85a3::8a2e:370:7334/64 scope global" \
"tailscale fd7a:115c:a1e0::1 and fd7a:115c:a1e0:ab12:4843:cd96:6258:b240" \
"link fe80::1ff:fe23:4567:890a%wlan0, loopback ::1" \
"full 2001:0db8:0000:0000:0000:ff00:0042:8329." \
"[2001:db8::7]:443 ether 3c:22:fb:12:34:56 brd ff:ff:ff:ff:ff:ff"
sent_as "inet6 <ip> scope global" \
"tailscale <ip> and <ip>" \
"link <ip>%wlan0, loopback <ip>" \
"full <ip>." \
"[<ip>]:443 ether <mac> brd <mac>"
}
@test "redaction keeps what only looks like an address or a secret" {
view ":: Synchronizing package databases..." \
"[2026-11-08T11:03:07-0500] [ALPM] upgraded foo (1:2.3-1 -> 1:2.4-1)" \
"std::string Foo::Bar::baz() at 12:34:56" \
"[sudo] password for alice: " "Password: " \
"sha256 e3b0c44298fc1c14 tokens: 5 secrets.toml" \
"Bearer token missing" "sk-1 risk-assessment hf_x"
sent_as ":: Synchronizing package databases..." \
"[2026-11-08T11:03:07-0500] [ALPM] upgraded foo (1:2.3-1 -> 1:2.4-1)" \
"std::string Foo::Bar::baz() at 12:34:56" \
"[sudo] password for <user>: " "Password: " \
"sha256 e3b0c44298fc1c14 tokens: 5 secrets.toml" \
"Bearer token missing" "sk-1 risk-assessment hf_x"
}
@test "redaction takes out your Cores' domains and your name, whatever their case" {
mkdir -p "$HOME/.config/coredesktop/cores"
printf 'CORE_DOMAIN=%q\nCORE_EMAIL=%q\nCORE_NAME=%q\n' acme.org alice@acme.org "Alice Smith (Acme)" \
> "$HOME/.config/coredesktop/cores/acme.org.conf"
cp "$HOME/.config/coredesktop/cores/acme.org.conf" "$HOME/.config/coredesktop/core.conf"
printf 'CORE_DOMAIN=%q\nCORE_NAME=%q\n' my-core.example "Al O'Neil" > "$HOME/.config/coredesktop/cores/my-core.example.conf"
view "Mounting https://nextcloud.acme.org/remote.php for Alice Smith (Acme)" \
"headscale.ACME.ORG and my-core.example, mail alice@acme.org, Al O'Neil" \
"notacme.org.uk and acme.organic stay"
sent_as "Mounting https://nextcloud.<core-domain>/remote.php for <name>" \
"headscale.<core-domain> and <core-domain>, mail <email>, <name>" \
"notacme.org.uk and acme.organic stay"
}
@test "a Core's settings can't run anything when report reads them" {
mkdir -p "$HOME/.config/coredesktop/cores"
printf 'CORE_DOMAIN=acme.org\ntouch "%s/ran"\n' "$BATS_TEST_TMPDIR" > "$HOME/.config/coredesktop/cores/acme.org.conf"
view "acme.org"
sent_as "<core-domain>"
[ ! -e "$BATS_TEST_TMPDIR/ran" ]
}
@test "a user or host name with regular expression characters is still replaced" {
export USER='a.b+c'
stub uname '[ "$1" = -n ] && echo "lab(1)" || /usr/bin/uname "$@"'
view "a.b+c on lab(1); axbbc on lab1"
sent_as "<user> on <host>; axbbc on lab1"
}