Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

Two stale comments, and the distinct count the unreachable rules needed (#737)

Beenu Arora7400531f98d1
diff --git a/infra/helm/aisoc/charts/postgresql-13.4.4.tgz b/infra/helm/aisoc/charts/postgresql-13.4.4.tgz
new file mode 100644
index 000000000..ef982e19d
Binary files /dev/null and b/infra/helm/aisoc/charts/postgresql-13.4.4.tgz differ
diff --git a/infra/helm/aisoc/charts/redis-18.19.4.tgz b/infra/helm/aisoc/charts/redis-18.19.4.tgz
new file mode 100644
index 000000000..d5f0248bb
Binary files /dev/null and b/infra/helm/aisoc/charts/redis-18.19.4.tgz differ
diff --git a/scripts/check_detection_fields.py b/scripts/check_detection_fields.py
index 4846b8034..a30ab14b8 100644
--- a/scripts/check_detection_fields.py
+++ b/scripts/check_detection_fields.py
@@ -63,10 +63,21 @@ MAX_UNREACHABLE = 133
#: actor/target comparisons. A rule naming one of these cannot fire no matter
#: which connector is attached, because nothing computes it.
#:
-#: They need one of two things that do not exist yet: evaluation in
-#: `services/fusion/app/services/windowed_detection.py` (which has three
-#: hardcoded rules and no loader), or a fusion-time enrichment step that
-#: resolves the predicate. Until then they are honest work items.
+#: They need one of two things. The windowed family needs a `wd-*` rule in
+#: `services/fusion/app/services/windowed_detection.py`; the rest need a
+#: fusion-time enrichment step that resolves the predicate.
+#:
+#: This comment used to say the windowed engine "has three hardcoded rules
+#: and no loader". That was true when written and has not been true since the
+#: exporter landed: the engine loads `app/data/windowed_ruleset.json` on top
+#: of its builtins, runs in the fusion consumer, and fires real alerts. The
+#: stale half mattered, because it told a reader the engine was unusable when
+#: the actual gap is narrower and more actionable — **nobody has translated
+#: these `det-*` rules into windowed form.** The two corpora are disjoint:
+#: not one of the `wd-*` ids appears in `detections/`, so building the engine
+#: moved none of these rules off this list and the count did not move either.
+#:
+#: Migrating one means *authoring* a `wd-*` rule, not flipping a flag.
_DERIVED_FIELD_PATTERN = re.compile(
r"(_count$|^count_|_per_|time_window|_window_"
r"|_in_allowlist$|_not_in_allowlist$"
diff --git a/scripts/export_windowed_ruleset.py b/scripts/export_windowed_ruleset.py
index 6349d8dbd..d5b346104 100644
--- a/scripts/export_windowed_ruleset.py
+++ b/scripts/export_windowed_ruleset.py
@@ -9,9 +9,18 @@ because that matcher evaluates one event in isolation, and until now they had
nowhere else to go — which is most of why the quarantine has stayed at ~2,000
rules.
-This mirrors `export_detection_ruleset.py` exactly: specs are the source of
-truth, the JSON is a build artifact, and `--check` fails CI when the two drift
-so the deployed engine cannot silently diverge from the committed corpus.
+The JSON is a build artifact and `--check` fails CI when it drifts from this
+file, so the deployed engine cannot silently diverge from the committed
+corpus.
+
+This used to claim it "mirrors `export_detection_ruleset.py` exactly: specs
+are the source of truth". It does not, and the difference is worth stating
+rather than papering over: the stateless exporter reads spec *modules*, while
+the rules here are a literal list in this script. That is a deliberate
+tradeoff at this corpus size — eight rules do not need a module per rule, and
+a reader can see the whole windowed corpus on one screen — but it is a
+different arrangement, and describing it as identical sent anyone looking for
+`detections/windowed/` somewhere that does not exist.
A windowed rule is deliberately a narrow shape — match, group by one entity,
count, threshold, window. It is not a general aggregation language. Anything
@@ -114,6 +123,69 @@ WINDOWED_RULES: list[dict] = [
"threshold": 200,
"window_seconds": 300,
},
+ {
+ # `events_per_minute_gt` is the single largest unreachable family —
+ # sixteen `det-*` rules name it and none of them can fire, because
+ # nothing computes a per-minute rate for a single event.
+ "id": "wd-high-rate-activity-per-actor",
+ "name": "Sustained high-rate activity from one actor",
+ "severity": "medium",
+ "category": "identity",
+ "mitre": ["T1078"],
+ "match_when": {},
+ "group_by": "user",
+ "threshold": 120,
+ "window_seconds": 60,
+ },
+ {
+ "id": "wd-high-rate-activity-per-source",
+ "name": "Sustained high-rate activity from one source address",
+ "severity": "medium",
+ "category": "network",
+ "mitre": ["T1071"],
+ "match_when": {},
+ "group_by": "src_ip",
+ "threshold": 300,
+ "window_seconds": 60,
+ },
+ {
+ # Distinct, not count. "Fifty reads by one principal" is a script
+ # retrying; "fifty *different* secrets read by one principal" is a
+ # vault being walked. Counting events cannot tell those apart.
+ "id": "wd-secret-enumeration",
+ "name": "Many distinct secrets read by one principal",
+ "severity": "high",
+ "category": "identity",
+ "mitre": ["T1552.007"],
+ "match_when": {"event_type": "secret_access"},
+ "group_by": "user",
+ "distinct_by": "secret_name",
+ "threshold": 15,
+ "window_seconds": 300,
+ },
+ {
+ "id": "wd-horizontal-scan",
+ "name": "One source touching many distinct destinations",
+ "severity": "medium",
+ "category": "network",
+ "mitre": ["T1046"],
+ "match_when": {"event_type": "network"},
+ "group_by": "src_ip",
+ "distinct_by": "dst_ip",
+ "threshold": 40,
+ "window_seconds": 120,
+ },
+ {
+ "id": "wd-bulk-object-deletion",
+ "name": "Bulk object deletion by one principal",
+ "severity": "high",
+ "category": "cloud",
+ "mitre": ["T1485"],
+ "match_when": {"event_type": "delete"},
+ "group_by": "user",
+ "threshold": 50,
+ "window_seconds": 300,
+ },
]
diff --git a/services/fusion/app/data/windowed_ruleset.json b/services/fusion/app/data/windowed_ruleset.json
index b79fe15ea..f2659f2da 100644
--- a/services/fusion/app/data/windowed_ruleset.json
+++ b/services/fusion/app/data/windowed_ruleset.json
@@ -1,5 +1,5 @@
{
- "count": 5,
+ "count": 10,
"rules": [
{
"category": "application",
@@ -76,6 +76,79 @@
"severity": "high",
"threshold": 200,
"window_seconds": 300
+ },
+ {
+ "category": "identity",
+ "group_by": "user",
+ "id": "wd-high-rate-activity-per-actor",
+ "match_when": {},
+ "mitre": [
+ "T1078"
+ ],
+ "name": "Sustained high-rate activity from one actor",
+ "severity": "medium",
+ "threshold": 120,
+ "window_seconds": 60
+ },
+ {
+ "category": "network",
+ "group_by": "src_ip",
+ "id": "wd-high-rate-activity-per-source",
+ "match_when": {},
+ "mitre": [
+ "T1071"
+ ],
+ "name": "Sustained high-rate activity from one source address",
+ "severity": "medium",
+ "threshold": 300,
+ "window_seconds": 60
+ },
+ {
+ "category": "identity",
+ "distinct_by": "secret_name",
+ "group_by": "user",
+ "id": "wd-secret-enumeration",
+ "match_when": {
+ "event_type": "secret_access"
+ },
+ "mitre": [
+ "T1552.007"
+ ],
+ "name": "Many distinct secrets read by one principal",
+ "severity": "high",
+ "threshold": 15,
+ "window_seconds": 300
+ },
+ {
+ "category": "network",
+ "distinct_by": "dst_ip",
+ "group_by": "src_ip",
+ "id": "wd-horizontal-scan",
+ "match_when": {
+ "event_type": "network"
+ },
+ "mitre": [
+ "T1046"
+ ],
+ "name": "One source touching many distinct destinations",
+ "severity": "medium",
+ "threshold": 40,
+ "window_seconds": 120
+ },
+ {
+ "category": "cloud",
+ "group_by": "user",
+ "id": "wd-bulk-object-deletion",
+ "match_when": {
+ "event_type": "delete"
+ },
+ "mitre": [
+ "T1485"
+ ],
+ "name": "Bulk object deletion by one principal",
+ "severity": "high",
+ "threshold": 50,
+ "window_seconds": 300
}
]
}
diff --git a/services/fusion/app/services/windowed_detection.py b/services/fusion/app/services/windowed_detection.py
index 8031a9d44..f92820ff0 100644
--- a/services/fusion/app/services/windowed_detection.py
+++ b/services/fusion/app/services/windowed_detection.py
@@ -57,6 +57,16 @@ class WindowRule:
group_by: str
threshold: int
window_seconds: int
+ # When set, count DISTINCT values of this field rather than events.
+ #
+ # "Fifty requests from one source" and "fifty *different* secrets read by
+ # one principal" are different detections, and the second is the one that
+ # says enumeration. Counting events conflates a script retrying once with
+ # a script walking a vault: the first is noise, the second is the
+ # incident. Twenty-one of the rules the reachability gate lists as
+ # needing a windowed evaluator name a `distinct_*` field, so without this
+ # they had nowhere to go even after the engine existed.
+ distinct_by: str = ""
# Built-in windowed rules. Intentionally small + high-signal; the corpus can grow
@@ -148,6 +158,7 @@ def load_window_rules(path: Path | None = None) -> tuple[WindowRule, ...]:
group_by=str(entry["group_by"]),
threshold=int(entry["threshold"]),
window_seconds=int(entry["window_seconds"]),
+ distinct_by=str(entry.get("distinct_by") or ""),
)
except (KeyError, TypeError, ValueError) as exc:
logger.warning("windowed_detection.rule_skipped", rule_id=rule_id, error=str(exc))
@@ -232,7 +243,17 @@ class WindowedDetectionEngine:
entity = fields.get(rule.group_by)
if not entity:
continue
- if await self._observe_and_check(rule, tenant, str(entity), now):
+ observed = str(entity)
+ member: str | None = None
+ if rule.distinct_by:
+ value = fields.get(rule.distinct_by)
+ if not value:
+ # A distinct rule with nothing to be distinct about
+ # must not fall back to counting events — that is a
+ # different, louder detection wearing this one's id.
+ continue
+ member = str(value)
+ if await self._observe_and_check(rule, tenant, observed, now, member=member):
hits.append(
DetectionHit(
rule_id=rule.id,
@@ -246,9 +267,21 @@ class WindowedDetectionEngine:
logger.debug("windowed_detection.rule_error", rule=rule.id, error=str(exc))
return hits
- async def _observe_and_check(self, rule: WindowRule, tenant: str, entity: str, now: float) -> bool:
+ async def _observe_and_check(
+ self,
+ rule: WindowRule,
+ tenant: str,
+ entity: str,
+ now: float,
+ *,
+ member: str | None = None,
+ ) -> bool:
key = f"{self._prefix}:{tenant}:{rule.id}:{entity}"
- member = uuid.uuid4().hex
+ # A random member counts events; the observed value counts distinct
+ # ones, because ZADD on an existing member updates its score instead
+ # of adding a row. So the same sorted set serves both, and a repeated
+ # value refreshes its recency rather than inflating the count.
+ member = member if member is not None else uuid.uuid4().hex
await self._redis.zadd(key, {member: now})
await self._redis.zremrangebyscore(key, 0, now - rule.window_seconds)
# Expire the key a window after the last event so idle entities are reaped.
diff --git a/services/fusion/tests/test_windowed_detection.py b/services/fusion/tests/test_windowed_detection.py
index 9e4fa4e31..c04dab80b 100644
--- a/services/fusion/tests/test_windowed_detection.py
+++ b/services/fusion/tests/test_windowed_detection.py
@@ -7,7 +7,7 @@ import json
from uuid import uuid4
import pytest
-from app.services.windowed_detection import WindowedDetectionEngine
+from app.services.windowed_detection import WindowedDetectionEngine, WindowRule
class _FakeRedis:
@@ -102,3 +102,87 @@ async def test_build_alert_from_hit():
assert alert is not None
assert alert.source == "detection:wd-bruteforce-auth"
assert alert.username == "alice"
+
+
+# ── distinct counting ────────────────────────────────────────────────────────
+#
+# "Fifty reads by one principal" is a script retrying. "Fifty *different*
+# secrets read by one principal" is a vault being walked. Counting events
+# cannot tell those apart, and 21 of the rules the reachability gate lists as
+# needing a windowed evaluator name a `distinct_*` field — so without this
+# they had nowhere to go even after the engine existed.
+
+
+_TENANT = str(uuid4())
+
+
+def _secret_event(user: str, secret: str) -> dict:
+ return {
+ "tenant_id": _TENANT,
+ "ocsf_event": {
+ "raw_event": {"event_type": "secret_access", "user": user, "secret_name": secret},
+ },
+ }
+
+
+DISTINCT_RULE = WindowRule(
+ id="wd-test-distinct",
+ name="Many distinct secrets by one principal",
+ severity="high",
+ category="identity",
+ mitre=["T1552.007"],
+ match_when={"event_type": "secret_access"},
+ group_by="user",
+ distinct_by="secret_name",
+ threshold=3,
+ window_seconds=300,
+)
+
+
+async def test_repeating_one_value_never_crosses_a_distinct_threshold():
+ """The regression this exists for: a script reading the same secret in a
+ loop is not enumeration, and must not be reported as it."""
+ engine = WindowedDetectionEngine(_FakeRedis(), rules=(DISTINCT_RULE,))
+ for _ in range(20):
+ assert await engine.evaluate(_secret_event("alice", "db-password")) == []
+
+
+async def test_distinct_values_cross_the_threshold():
+ engine = WindowedDetectionEngine(_FakeRedis(), rules=(DISTINCT_RULE,))
+ assert await engine.evaluate(_secret_event("alice", "s1")) == []
+ assert await engine.evaluate(_secret_event("alice", "s2")) == []
+ hits = await engine.evaluate(_secret_event("alice", "s3"))
+ assert [h.rule_id for h in hits] == ["wd-test-distinct"]
+
+
+async def test_distinct_counts_are_per_entity():
+ engine = WindowedDetectionEngine(_FakeRedis(), rules=(DISTINCT_RULE,))
+ for secret in ("s1", "s2"):
+ await engine.evaluate(_secret_event("alice", secret))
+ # Bob's two are his own; neither principal has reached three.
+ for secret in ("s1", "s2"):
+ assert await engine.evaluate(_secret_event("bob", secret)) == []
+
+
+async def test_an_event_missing_the_distinct_field_is_skipped_not_counted():
+ """Falling back to counting events would be a different, louder detection
+ wearing this one's id."""
+ engine = WindowedDetectionEngine(_FakeRedis(), rules=(DISTINCT_RULE,))
+ bare = {"tenant_id": _TENANT, "ocsf_event": {"raw_event": {"event_type": "secret_access", "user": "alice"}}}
+ for _ in range(10):
+ assert await engine.evaluate(bare) == []
+
+
+def test_the_loader_carries_distinct_by():
+ from app.services.windowed_detection import load_window_rules
+
+ rules = load_window_rules()
+ distinct = [r for r in rules if r.distinct_by]
+ assert distinct, "no exported rule uses distinct_by; the capability has no corpus"
+ assert all(
+ r.group_by and r.distinct_by != r.group_by for r in distinct
+ ), "a rule counting distinct values of its own grouping key counts 1 forever"