Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion neonwatch/evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down
27 changes: 20 additions & 7 deletions neonwatch/probes/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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("#"):
Expand All @@ -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:
Expand Down
51 changes: 50 additions & 1 deletion neonwatch/probes/parsers_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from __future__ import annotations

import base64
import json
from typing import Any

Expand All @@ -26,6 +27,7 @@
MAX_ENTRIES_PER_FILE,
MAX_ENTRIES_TOTAL,
MAX_ENV_PER_FILE,
MAX_KEYS_PER_FILE,
MESSAGE_CHARS,
PARSERS,
REDACT_CHARS,
Expand Down Expand Up @@ -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:
Expand Down
68 changes: 41 additions & 27 deletions neonwatch/redact.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -35,45 +37,57 @@
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"(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{10,}+\.[A-Za-z0-9_-]{10,}+\.[A-Za-z0-9_-]{10,}",
# Hyphens count as part of a key: `-dev-root-token-id=value` is a live command-line shape.
# The lookbehind anchors the match to the START of a key: without it the engine retries
# from every character of an unbroken word, which is quadratic in a length any local user
# controls (a journal message, a process argument) — CPU burned as root.
# The key is then taken whole and never given back (`++`), with a lookahead for the secret
# word: `[A-Z0-9_-]*word[A-Z0-9_-]*` backtracks over every occurrence of the word in one long
# key, quadratic again (`atokenatoken...`, 1.3 s for 24 KB before this).
r"(?<![A-Za-z0-9_-])(?i:(?=[A-Z0-9_-]*?(?:pass(?:word|wd)?|_pwd|secret|token|api[_-]?key|"
r"credential))[A-Z0-9_-]++)"
r"\s*[=:]\s*[\"']?[^\s\"',;]{4,}",
r"(?i:--(?:password|passwd|token|secret|api-key))[= ]\S+",
r"://[^/\s:@]*:[^/\s@]+@", # credentials in a URL, the user possibly empty
"assignment": r"(?<![A-Za-z0-9_-])(?i:(?=[A-Z0-9_-]*?(?:pass(?:word|wd)?|_pwd|secret|token|"
r"api[_-]?key|credential))[A-Z0-9_-]++)"
r"\s*[=:]\s*[\"']?[^\s\"',;]{4,}",
"flag": r"(?i:--(?:password|passwd|token|secret|api-key))[= ]\S+",
"url": r"://[^/\s:@]*:[^/\s@]+@", # credentials in a URL, the user possibly empty
# From here on, a pattern's one capturing group is the harmless lead kept before the mask.
# curl -u/--user user:pass; a password that is all digits is a uid:gid (`docker -u 0:0`).
# The user is bounded and never given back: every `-u` after a non-word character is a fresh
# start, so an unbounded user made each one scan to the end of the word, quadratic in a word
# of `(-u(-u...` (0.45 s for 24 KB; `(--user=` 1.2 s). A longer user is not taken for one.
r"(?<![\w-])(?:-u\s*+|--user[=\s]\s*+)[\"']?[^\s:\"']{1,256}+:(?!/)"
r"(?=[^\s\"']*[^\d\s\"'])[^\s\"']+",
"user": r"(?<![\w-])(?:-u\s*+|--user[=\s]\s*+)[\"']?[^\s:\"']{1,256}+:(?!/)"
r"(?=[^\s\"']*[^\d\s\"'])[^\s\"']+",
# -pPASS (no space: `-p` alone prompts) within 256 characters of a mysql/mariadb word.
r"((?<![\w-])(?:mysql|mysqldump|mysqladmin|mariadb|mariadb-dump)(?![\w-])[^\n|;&]{0,256}?"
r"\s)-p[\"']?[^\s\"']+[\"']?",
r"((?<![\w-])sshpass\s+)-p\s*[\"']?[^\s\"']+",
"mysql": r"((?<![\w-])(?:mysql|mysqldump|mysqladmin|mariadb|mariadb-dump)(?![\w-])"
r"[^\n|;&]{0,256}?\s)-p[\"']?[^\s\"']+[\"']?",
"sshpass": r"((?<![\w-])sshpass\s+)-p\s*[\"']?[^\s\"']+",
# smbclient -U user%pass; the user bounded for the same reason as `-u`'s.
r"(?<![\w-])-U\s*+[\"']?[^\s%\"']{1,256}+%[^\s\"']+",
r"((?<![\w-])(?i:proxy-)?(?i:authorization)\s*:\s*)[^\s\"']+(?:[ \t]+[^\s\"']+)?",
r"((?<![\w-])(?i:x-api-key|api-key|x-auth-token|token)\s*:\s*)[^\s\"']+",
r"([?&](?i:key|apikey|api_key|token|access_token|auth|sig|signature|password)=)[^&\s\"'#]+",
]))
"smbclient": r"(?<![\w-])-U\s*+[\"']?[^\s%\"']{1,256}+%[^\s\"']+",
"authorization": r"((?<![\w-])(?i:proxy-)?(?i:authorization)\s*:\s*)"
r"[^\s\"']+(?:[ \t]+[^\s\"']+)?",
"header": r"((?<![\w-])(?i:x-api-key|api-key|x-auth-token|token)\s*:\s*)[^\s\"']+",
"query": r"([?&](?i:key|apikey|api_key|token|access_token|auth|sig|signature|password)=)"
r"[^&\s\"'#]+",
}

TOKENS = re.compile("|".join(SHAPES.values()))


def _mask(match: re.Match[str]) -> str:
Expand Down
61 changes: 53 additions & 8 deletions neonwatch/redact_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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", [
Expand Down Expand Up @@ -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()
Expand All @@ -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 ", "%")):
Expand Down
Loading