From c4d78743d850accbea8b64bd60829dfb27d9d337 Mon Sep 17 00:00:00 2001 From: drobison00 Date: Sat, 31 Oct 2026 18:56:45 +0000 Subject: [PATCH 1/2] Make the private-key and JWT redaction shapes linear, and measure every shape The private-key shape searched lazily for an END from every BEGIN, so text with many BEGINs and no END was rescanned to its end from each one: quadratic in a journal message, a model's answer or an SSH key comment, all of which reach redact() with no length cap (112 KB took 2.9 s, on the service loop or as root). A block with no END now takes the rest of the text: one scan, and a key cut short by a field cap is no longer passed through in clear, which the old shape also did. The JWT shape started at \b, which allows a fresh start after every `-` in one run (`eyJ-eyJ-...`), each scanning to the run's end. It is now anchored at the start of a run, as the KEY= shape is; a JWT glued after a hyphen is no longer cut. The shapes are now named (SHAPES), and redact_test holds a hostile repetition for every name, with a test that the two key sets match. The timing list had grown one fix at a time and covered every shape but these two; a new shape without its measurement now fails the suite. --- neonwatch/redact.py | 68 ++++++++++++++++++++++++---------------- neonwatch/redact_test.py | 61 ++++++++++++++++++++++++++++++----- 2 files changed, 94 insertions(+), 35 deletions(-) diff --git a/neonwatch/redact.py b/neonwatch/redact.py index 8c07ff1..dfa05a7 100644 --- a/neonwatch/redact.py +++ b/neonwatch/redact.py @@ -18,8 +18,10 @@ Every pattern starts at a fixed anchor (a lookbehind, a literal, or a bounded gap), so no pattern retries from every character of a long word, and where an anchor can recur within one -word (`-u` after any non-word character) the run that follows it is bounded, so each start scans -a bounded distance: linear in what a local user controls. +word (`-u` after any non-word character) the run that follows it is bounded, or a search that +fails is not repeated from the next start (a private key block with no END takes the rest of the +text), so each start scans a bounded distance: linear in what a local user controls. That is a +claim about every shape, so `redact_test` times a hostile repetition of every shape by name. """ from __future__ import annotations @@ -35,16 +37,24 @@ r"(?i)^.*(pass(word|wd|phrase)?|_pwd|secret|token|api[_-]?key|private[_-]?key|credential|" r"auth(orization)?|cookie|session[_-]?id|access[_-]?key)s?$") -TOKENS = re.compile("|".join([ - r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----", - r"(?i:bearer|basic)\s+[A-Za-z0-9._~+/=-]{8,}", - r"\bfga?_[A-Za-z0-9]{16,}", - r"\b(?:sk|pk|rk)-[A-Za-z0-9_-]{16,}", - r"\bgh[pousr]_[A-Za-z0-9]{20,}", - r"\bgithub_pat_[A-Za-z0-9_]{20,}", - r"\bxox[abprs]-[A-Za-z0-9-]{10,}", - r"\bAKIA[0-9A-Z]{16}\b", - r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}", # a JWT +#: Each token shape by name. `redact_test` holds a hostile repetition for every name, so a shape +#: added without one fails there rather than shipping unmeasured. +SHAPES = { + # A block with no END is cut to the end of the text. Searching on for an END that is not + # there, from every BEGIN, is quadratic in a journal message or a model's answer; and a + # key cut short (a field capped mid-block) is still key material. + "private_key": r"-----BEGIN [A-Z ]*PRIVATE KEY-----" + r"(?:[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----|[\s\S]*)", + "bearer": r"(?i:bearer|basic)\s+[A-Za-z0-9._~+/=-]{8,}", + "forge_gate": r"\bfga?_[A-Za-z0-9]{16,}", + "api_key": r"\b(?:sk|pk|rk)-[A-Za-z0-9_-]{16,}", + "github": r"\bgh[pousr]_[A-Za-z0-9]{20,}", + "github_pat": r"\bgithub_pat_[A-Za-z0-9_]{20,}", + "slack": r"\bxox[abprs]-[A-Za-z0-9-]{10,}", + "aws": r"\bAKIA[0-9A-Z]{16}\b", + # A JWT. Anchored at the start of a run rather than at `\b`, which allows a fresh start + # after every `-` in one long run (`eyJ-eyJ-...`), each scanning to the run's end: quadratic. + "jwt": r"(? str: diff --git a/neonwatch/redact_test.py b/neonwatch/redact_test.py index 452dec9..7117fdc 100644 --- a/neonwatch/redact_test.py +++ b/neonwatch/redact_test.py @@ -4,7 +4,7 @@ import pytest -from neonwatch.redact import MASK, redact, redact_mapping +from neonwatch.redact import MASK, SHAPES, redact, redact_mapping @pytest.mark.parametrize("secret", [ @@ -116,14 +116,42 @@ def test_a_long_unbroken_word_is_linear_not_quadratic(): assert time.perf_counter() - start < 0.5 -@pytest.mark.parametrize("text", [ - "atoken" * 4000, "a_pwd" * 4000, "xsecret" * 3000, "mysql " * 4000 + "-p", - "mysql" + " a" * 10000, "-u " * 7000, "-ua" * 7000 + ":", "sshpass " * 3000, "-U a" * 5000, - "Authorization: " * 1500, "X-API-Key:" * 2000, "?key" * 5000, "://" + ":" * 20000, - "://" + "a:" * 10000, "basic " * 4000, +#: A hostile repetition of every shape in `SHAPES`, by name: text a user can put in a journal +#: message, a process argument or a model's answer, built to make that shape rescan. Each runs +#: well under the bound when the shape is linear and far over it when it is not. +HOSTILE = { + "private_key": ("-----BEGIN PRIVATE KEY----- " * 2000, + "-----BEGIN RSA PRIVATE KEY-----\n" * 2000), + "bearer": ("basic " * 4000, "bearer\t" * 4000), + "forge_gate": ("fg_" * 8000, "fga_" * 6000), + "api_key": ("sk-" * 8000, "-sk-a" * 5000), + "github": ("ghp_" * 6000,), + "github_pat": ("github_pat_" * 2000, "github_pat-" * 2000), + "slack": ("xoxb-" * 5000, "xoxb" * 6000), + "aws": ("AKIA" * 6000, "AKIA-" * 5000), + "jwt": ("eyJ-" * 8000, "eyJaaaaaaaaaa." * 2000), + "assignment": ("atoken" * 4000, "a_pwd" * 4000, "xsecret" * 3000), + "flag": ("--password" * 3000, "--token" * 4000), + "url": ("://" + ":" * 20000, "://" + "a:" * 10000), # A fresh -u/-U start after every non-word character, no `:`/`%` to end the user. - "(-u" * 7000, "@-u" * 7000, "(--user=" * 3000, "(-U" * 7000, "(-u'" * 5000, -], ids=lambda text: text[:8].replace(" ", "_")) + "user": ("-u " * 7000, "-ua" * 7000 + ":", "(-u" * 7000, "@-u" * 7000, "(--user=" * 3000, + "(-u'" * 5000), + "mysql": ("mysql " * 4000 + "-p", "mysql" + " a" * 10000), + "sshpass": ("sshpass " * 3000,), + "smbclient": ("-U a" * 5000, "(-U" * 7000), + "authorization": ("Authorization: " * 1500,), + "header": ("X-API-Key:" * 2000, "token :" * 3000), + "query": ("?key" * 5000,), +} + + +def test_every_shape_has_a_hostile_repetition(): + """Linearity is claimed of every shape, so a shape is not added without its measurement.""" + assert HOSTILE.keys() == SHAPES.keys() + + +@pytest.mark.parametrize("text", [text for texts in HOSTILE.values() for text in texts], + ids=lambda text: text[:8].replace(" ", "_")) def test_every_shape_is_linear_in_a_hostile_repetition(text): import time start = time.perf_counter() @@ -132,6 +160,23 @@ def test_every_shape_is_linear_in_a_hostile_repetition(text): assert time.perf_counter() - start < 0.5 +def test_a_private_key_block_with_no_end_is_cut_to_the_end_of_the_text(): + """A field capped mid-block still holds key material, and searching for the missing END + from every BEGIN is what made the shape quadratic.""" + cleaned, count = redact("key: -----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaA\nAAAA more") + assert (cleaned, count) == (f"key: {MASK}", 1) + + +def test_a_jwt_is_cut_only_at_the_start_of_a_run(): + """The anchor that keeps the shape linear: after `=`, a space or a quote it is a JWT; inside + a run of token characters (`-eyJ...`) it is part of that word.""" + jwt = ("eyJhbGciOiJIUzI1NiJ9" + "." + "eyJzdWIiOiIxMjM0NTY3ODkwIn0" + "." + + "dozjgNryP4J3jVmNHl0w5N") + for lead in ("id=", "x ", '"'): + assert redact(lead + jwt) == (lead + MASK, 1) + assert redact("x-" + jwt)[1] == 0 + + def test_a_user_is_read_up_to_its_bound_and_no_further(): """The bound that keeps -u/-U linear: a 256-character user is still one, a longer one not.""" for flag, sep in (("-u ", ":"), ("--user=", ":"), ("-U ", "%")): From 18f6b76cea8a099187a691af54af802efc79b300 Mon Sep 17 00:00:00 2001 From: drobison00 Date: Sat, 31 Oct 2026 18:56:45 +0000 Subject: [PATCH 2/2] Bound what one authorized_keys observation keeps, and cut its comments Four valid authorized_keys files of 3000 keys fit the GLOB read caps but expanded about threefold into key records, past the 1 MiB event limit, so the whole ssh.keys.home observation failed to publish and every home's keys went unread for the day. Crontabs already have a budget for this (_table); the key parser did not. Each file now keeps at most MAX_KEYS_PER_FILE keys, and all files together KEPT_BYTES of JSON, as _table does; what is not kept is counted per file and in all (`dropped`), and the evaluator's keys view carries it. A comment goes through _clean like every other free-text field: redacted from its first REDACT_CHARS and cut to ARGS_CHARS, rather than reaching the collector's redaction whole. The key type is cut to IDENT_CHARS. --- neonwatch/evaluator.py | 2 +- neonwatch/probes/parsers.py | 27 ++++++++++++----- neonwatch/probes/parsers_test.py | 51 +++++++++++++++++++++++++++++++- 3 files changed, 71 insertions(+), 9 deletions(-) diff --git a/neonwatch/evaluator.py b/neonwatch/evaluator.py index f7c84a6..92da25b 100644 --- a/neonwatch/evaluator.py +++ b/neonwatch/evaluator.py @@ -745,7 +745,7 @@ def _modules(d: dict[str, Any], p: dict[str, Any] | None, dt: float | None) -> A def _keys(d: dict[str, Any], p: dict[str, Any] | None, dt: float | None) -> Any: keys = _rows(d, "keys") - return {"files": [{k: f.get(k) for k in ("path", "keys", "invalid_lines")} + return {"files": [{k: f.get(k) for k in ("path", "keys", "dropped", "invalid_lines")} for f in _rows(d, "files")], "keys": [{k: key.get(k) for k in ("path", "type", "fingerprint", "comment", "options")} for key in keys][:30], diff --git a/neonwatch/probes/parsers.py b/neonwatch/probes/parsers.py index 8127b74..910a09d 100644 --- a/neonwatch/probes/parsers.py +++ b/neonwatch/probes/parsers.py @@ -960,12 +960,17 @@ def parse_reboot_required(raw: bytes) -> Data: # --- daily tier ------------------------------------------------------------------------------- KEY = re.compile(r"(?:^|\s)((?:ssh|ecdsa|sk)-[\w@.-]+)\s+([A-Za-z0-9+/]+={0,2})(?:\s+(.*))?$") +#: Keys kept from one authorized_keys file. With `KEPT_BYTES` over all of them, it bounds the +#: observation as `_table` bounds crontabs: a valid file within the read caps grows +#: about threefold into key records, so without them one user's file could make the observation +#: too large to publish, blanking every home's keys. What is not kept is counted (`dropped`). +MAX_KEYS_PER_FILE = 100 def parse_authorized_keys(raw: bytes) -> Data: - files, keys = [], [] + files, keys, spent = [], [], 0 for path, text in sorted(_files(raw).items()): - count = invalid = 0 + count = invalid = kept = 0 for line in text.splitlines(): line = line.strip() if not line or line.startswith("#"): @@ -979,13 +984,21 @@ def parse_authorized_keys(raw: bytes) -> Data: invalid += 1 continue digest = base64.b64encode(hashlib.sha256(blob).digest()).decode().rstrip("=") - keys.append({"path": path, "type": match.group(1), "fingerprint": f"SHA256:{digest}", - "comment": (match.group(3) or "").strip(), - "options": bool(line[: match.start(1)].strip())}) + key = {"path": path, "type": match.group(1)[:IDENT_CHARS], + "fingerprint": f"SHA256:{digest}", + "comment": _clean((match.group(3) or "").strip(), ARGS_CHARS)[0], + "options": bool(line[: match.start(1)].strip())} count += 1 - files.append({"path": path, "keys": count, "invalid_lines": invalid, + cost = _json_bytes(key) + if kept < MAX_KEYS_PER_FILE and spent + cost <= KEPT_BYTES: + keys.append(key) + spent += cost + kept += 1 + files.append({"path": path, "keys": count, "dropped": count - kept, + "invalid_lines": invalid, "sha256": hashlib.sha256(text.encode()).hexdigest()}) - return {"files": files, "keys": keys, "count": len(keys)} + return {"files": files, "keys": keys, "count": len(keys), + "dropped": sum(f["dropped"] for f in files)} def _unit_file(item: Any) -> Data: diff --git a/neonwatch/probes/parsers_test.py b/neonwatch/probes/parsers_test.py index 1fa9473..0c02f8a 100644 --- a/neonwatch/probes/parsers_test.py +++ b/neonwatch/probes/parsers_test.py @@ -9,6 +9,7 @@ from __future__ import annotations +import base64 import json from typing import Any @@ -26,6 +27,7 @@ MAX_ENTRIES_PER_FILE, MAX_ENTRIES_TOTAL, MAX_ENV_PER_FILE, + MAX_KEYS_PER_FILE, MESSAGE_CHARS, PARSERS, REDACT_CHARS, @@ -1161,7 +1163,54 @@ def test_authorized_keys() -> None: def test_authorized_keys_absent() -> None: - assert p("ssh.keys.root", frame_files({})) == {"files": [], "keys": [], "count": 0} + assert p("ssh.keys.root", frame_files({})) == {"files": [], "keys": [], "count": 0, + "dropped": 0} + + +def ssh_keys(n: int, comment: bytes = b"x") -> bytes: + """`n` distinct, validly encoded ed25519-shaped keys.""" + return b"".join(b"ssh-ed25519 " + base64.b64encode(i.to_bytes(4, "big") + bytes(28)) + + b" " + comment + b"\n" for i in range(n)) + + +def test_authorized_keys_keep_a_bounded_number_and_count_the_rest() -> None: + """One home's file cannot crowd out another's: each keeps at most MAX_KEYS_PER_FILE.""" + data = p("ssh.keys.home", frame_files({ + "/home/aaa/.ssh/authorized_keys": ssh_keys(3000), + "/home/zoe/.ssh/authorized_keys": f"{ED25519}\n".encode()})) + files = {f["path"]: f for f in data["files"]} + assert files["/home/aaa/.ssh/authorized_keys"]["keys"] == 3000 + assert files["/home/aaa/.ssh/authorized_keys"]["dropped"] == 3000 - MAX_KEYS_PER_FILE + assert files["/home/zoe/.ssh/authorized_keys"]["dropped"] == 0 + assert data["keys"][-1]["fingerprint"] == ED25519_FP + assert (data["count"], data["dropped"]) == (MAX_KEYS_PER_FILE + 1, 3000 - MAX_KEYS_PER_FILE) + + +def test_an_authorized_key_comment_is_redacted_and_cut() -> None: + """A comment is free text: a private key block pasted into one is cut, and a long one kept + to ARGS_CHARS, without reading past REDACT_CHARS (it reached redaction whole).""" + hostile = b"-----BEGIN PRIVATE KEY----- " * 8000 + (key,) = p("ssh.keys.home", frame_files({"/home/a/.ssh/authorized_keys": ssh_keys( + 1, b"me -----BEGIN OPENSSH PRIVATE KEY-----\x01b3Blbn")}))["keys"] + assert key["comment"] == f"me {MASK}" + (key,) = p("ssh.keys.home", frame_files({"/home/a/.ssh/authorized_keys": ssh_keys( + 1, b"a" * (ARGS_CHARS + 50) + hostile)}))["keys"] + assert key["comment"] == "a" * ARGS_CHARS + + +def test_the_worst_authorized_keys_the_caps_allow_still_publishes() -> None: + """Four files of 3000 keys fit the read caps and grew into an event over the + 1 MiB limit, so the whole observation was dropped. Comments here are at their cap in the + characters JSON escapes longest, as in the crontab case above.""" + worst = ("\U0001f600" * 2).encode() + b"\x01\xff" + for comment in (b"x", worst * (ARGS_CHARS // 2)): + parsed = parse("ssh.keys.home", frame_files({f"/home/u{i}/.ssh/authorized_keys": + ssh_keys(3000, comment) for i in range(4)})) + assert parsed["dropped"] > 0 + data, _ = redact_mapping(parsed) + event = schema.Event(schema.Kind.OBSERVATION, 1.0, "agent", "obs.ssh.keys.home", + schema.to_body(schema.Observation("ssh.keys.home", data, 1000, True))) + assert len(schema.encode_event(event)) < schema.MAX_BYTES def test_scheduled_directory_names() -> None: