Files
AiSOC/scripts/ip_class_dataset.py
Beenu Arora 4bb84f0fd5 feat(ingest): anonymizer and hosting classes stamped at ingest (depth2 1.6) (#1586)
* depth2 Phase 0: kickoff, re-derived baseline and the SIEM-scope decision

Phase 0.1-0.4 of the wave-2 depth plan, which lands here locked beside the
other four plans.

0.2 re-derives every figure the plan captured. All twenty reproduce exactly
except the cloud/identity/SaaS/code condition count, which the plan itself
flagged as approximate: measured 344 against 'about 358'. D1 records why,
and the finding underneath it — no script in the tree implements that
sentence, so every published value of it was hand-counted with a slightly
different product set, and windowed rules contribute zero because they
carry no product field at all. Phase 2.1's gate has to decide that
explicitly.

0.3 captures the baselines, including 'make up-full' — the one the first
depth plan recorded as never captured (its D2). 22 containers on the full
profile; CORE passed 'make smoke' 10 of 10. The baseline host had nine
unrelated containers on it including a foreign Postgres on 5432, and
'make up-full' failed its first bind before the port resolver's overlay
landed. D2 records the sequence and, deliberately, does not claim a defect
from it: the preceding state is not replayable, so it carries a clean-host
reproduction as a follow-up instead.

0.4 is ADR-0015: AiSOC federates to the SIEM rather than replacing it. The
README's 'Not a drop-in SIEM replacement' is now a decided position with its
cost argument — compliance search needs raw-payload retention outside the
8 GB CORE budget and an availability promise this project has no measured
evidence it can keep. Proposed, and nothing in this plan builds from it.

* chore(depth2): claim Lane B migration 130-137 and ADR 0018 block

Signed-off-by: beenuar <beenu.a.arora@gmail.com>

* test(ingest): failing test for anonymizer and hosting classes at ingest

Depth plan wave 2 item 1.6. The reproduction, through the real Normalize
entry point rather than the classifier in isolation:

    internal/normalizer/ipclass_stamp_test.go:68:20:
      act.Location.IPClass undefined (type activity.Location has no field)

No class is stamped on any event today and no dataset exists to stamp it
from. The test drives Normalize so that a classifier package with passing
unit tests and no caller cannot satisfy it.

Also lands the downloader half of the dataset pair (the fidelity-corpus
rule: a loader without a downloader cannot be refreshed or audited) and the
pinned snapshot it produced: 21,726 records, 1,228 tor_exit from the Tor
Project bulk exit list (CC BY 3.0 US) and 20,498 hosting_provider from each
cloud's own published range endpoint. Per-source provenance, terms link and
upstream digest are in manifest.json.

vpn, public_proxy and residential_proxy ship with no records on purpose.
The widely cited community list for the first two carries no licence file
at all (its LICENSE path answers 404 on the default branch), so it cannot be
redistributed from an MIT repository. Those three classes are tenant-
supplied only.

Signed-off-by: beenuar <beenu.a.arora@gmail.com>

* feat(ingest): stamp anonymizer and hosting classes on public IPs at ingest

Depth plan wave 2, item 1.6.

Reproduced first: the Go test committed before this one failed to compile
because `activity.Location` had no `IPClass` field and nothing classified
anything. It now passes, and reverting the single `stampIPClass` call in
`Project` fails it again with

    ip 2.56.10.36: ip_class = "", want "tor_exit"
    ip 1.178.1.0:  ip_class = "", want "hosting_provider"

What runs where. One classifier, in Go, in `Project` rather than in the
normalizer's call site, so every caller gets it: a classifier wired into one
site is the built-but-unwired shape this tree keeps finding. The dataset is
embedded in the binary, so a CORE install classifies with no enrichment
service and no network call of any kind.

The trap the plan names, closed in two places. Live, the stamp lands nested
at `activity.location.ip_class`, where the matcher's plain `event.get`
cannot see it, so `DetectionEngine._raw_fields` now lifts it into the flat
namespace beside the `raw_event` merge that fixed the same shape one level
in. In replay, a committed fixture carries only a `src_ip`, so `enrich`
classifies it through the vendored loader. Without both halves a rule
matching `ip_class` would pass its fixtures and never fire live, or the
reverse. `check_ip_class_dataset.py` runs the Go classifier and the Python
one over 400 sampled addresses and requires identical answers.

Carried end to end: three ClickHouse columns (fresh-volume DDL and lake
migration 005 in lockstep, because a column added to one alone lands on new
deployments and silently not on old ones), two `alerts` columns (migration
130), the alert API response, and a rail section.

Absent is never false. Three of the five classes ship with no records, so an
unclassified address is the ordinary case: the column is NULL, the rail
renders nothing, and no surface says "not an anonymizer". The dataset
version travels with every stamp because the dataset is refreshed and a
class that cannot be dated cannot be re-read.

Signed-off-by: beenuar <beenu.a.arora@gmail.com>

* docs(depth2): ADR 0018, setup page and claim row for IP classification

Depth plan wave 2, item 1.6.

ADR 0018 records which classes ship and which are refused, and why the
refusal is on the licence rather than on the data: the community list the
obvious candidate would have come from carries no licence file at all, which
an MIT repository cannot redistribute.

The setup page leads with the table saying three of the five classes have no
records, so a reader learns that before they write a rule against one. Its
last section says tenant-supplied lists are not implemented rather than
implying a configuration step exists.

Claim matrix moves 334/329/5 to 335/330/5 across all three published
tallies. The row leads with the uncovered classes, because a row that read
"five anonymizer classes at ingest" would be true of the code and
misleading about the data.

Gate wired twice, deliberately: the cheap half in python-lint with
--skip-go, the Go/Python parity probe in the one job that has both
toolchains. The gate now fails rather than reporting 'not checked' when Go
is missing and --skip-go was not passed.

Signed-off-by: beenuar <beenu.a.arora@gmail.com>

* fix(1.6): regenerate the OpenAPI spec and close the semgrep finding at source

Two real CI failures on this branch, both from this change.

The spec was stale because AlertResponse gained src_ip_class and
src_ip_class_dataset_version and the committed document did not. Regenerated
with scripts/export_openapi.py; the diff is exactly those two optional
nullable fields on AlertResponse and AlertDetailResponse.

Semgrep went 112 to 113: dynamic-urllib-use-detected on the dataset
fetcher's urlopen. The ceiling is not the thing to move. The rule exists to
ask whether a caller can steer the URL, and urllib honours file://, so the
fix is to make that unrepresentable: _fetch now refuses any URL that is not
byte-identical to one declared in SOURCES. That is tighter than the scheme
allow-list the rule would settle for, because this script reaches a fixed,
reviewed set of endpoints and an address outside it is a bug rather than a
configuration choice.

The rule matches on the call shape and cannot see a guard, so the one-line
scoped suppression follows the precedent already in scripts/run_replay_eval.py:
it names the rule, it sits on the reported line, and any other urlopen added
to this file still fails the scan.

Measured locally with the pinned semgrep 1.86.0 against the vendored packs:
113 findings before, 112 after, which is the ceiling unchanged.

Signed-off-by: beenuar <beenu.a.arora@gmail.com>

* test(1.6): assert the source-address section on the rail's Details face

CI caught this and the local run could not: the rail opens on the story
view and every structured section lives behind the Details tab, so the
assertions were looking at a face the section is not on.

Unable to find an element with the text: Tor exit relay

Fixed by clicking through to Details first, following renderDetails in
InvestigationRail.test.tsx. Asserting without the click would have passed
only if the section were on the story face, which would be the wrong place
for it: the story face is the narrative, and this is a structured fact
about the source address.

Found because the web suite needs a pnpm install this machine does not
have, which is recorded in the pull request rather than implied as a pass.

Signed-off-by: beenuar <beenu.a.arora@gmail.com>
(cherry picked from commit f7e84c2094)

---------

Signed-off-by: beenuar <beenu.a.arora@gmail.com>
2026-11-01 04:13:01 -08:00

238 lines
8.2 KiB
Python

#!/usr/bin/env python3
"""Loader half of the anonymizer and hosting classification dataset.
Pairs with `scripts/fetch_ip_class_dataset.py` (the downloader) and is
compared against it by `scripts/check_ip_class_dataset.py`.
Who reads this, and who does not
--------------------------------
The classifier that runs in production is the Go one in
`services/ingest/internal/activity/ipclass`. It embeds the same committed
dataset and stamps every event at ingest. **This module is not a second
production classifier**, and adding one would be the drift this repository
has been bitten by before: two implementations of one security predicate
that agree until they quietly do not.
This module exists for fixture replay. A committed detection fixture carries
a `src_ip` and no activity projection, because fixtures are authored against
the rule rather than captured from a live pipeline. Without it, a rule Lane C
writes against `ip_class` would pass its fixtures and never fire live, or
fire live and fail its fixtures. `scripts/check_ip_class_dataset.py` asserts
the Go answer and the Python answer agree over a sample of the dataset, so
the two cannot diverge silently.
The dataset lives under the Go package because `go:embed` cannot reach above
its own package and the ingest image's build context is `services/ingest`.
One copy plus a gate beats two copies plus a sync, which is the arrangement
the event catalogue beside it already uses for the same reason.
"""
from __future__ import annotations
import bisect
import ipaddress
import json
from functools import lru_cache
from pathlib import Path
from typing import NamedTuple
#: Relative to the repository root, found by walking up from this file.
#:
#: An upward walk and not a fixed number of `.parent` hops, because this
#: module is vendored into `services/fusion/app/services/ip_class.py` and the
#: two copies must be byte-identical for the sync gate to hold them together.
#: A hop count would differ between them and would be the one line nobody
#: notices drifting.
#:
#: The walk failing is a supported outcome: the fusion runtime image ships
#: `app/` only, so the dataset is not on disk there. Every event in that
#: image already carries the class stamped by ingest, so nothing is lost; see
#: `load()`.
_DATASET_RELATIVE = Path("services") / "ingest" / "internal" / "activity" / "ipclass" / "data"
def _find_dataset_dir() -> Path | None:
for parent in Path(__file__).resolve().parents:
candidate = parent / _DATASET_RELATIVE
if (candidate / "ip_classes.tsv").is_file():
return candidate
return None
#: The closed set, in the order the plan names them. Mirrored by
#: `fetch_ip_class_dataset.ALL_CLASSES` and by the Go package; the gate
#: compares all three.
ALL_CLASSES = ("vpn", "tor_exit", "public_proxy", "residential_proxy", "hosting_provider")
class Classification(NamedTuple):
"""One answer. There is no "not an anonymizer" value on purpose."""
ip_class: str
source: str
version: str
class _Table(NamedTuple):
starts_v4: list[int]
entries_v4: list[tuple[int, int, str, str]]
starts_v6: list[int]
entries_v6: list[tuple[int, int, str, str]]
version: str
record_count: int
def _empty() -> _Table:
return _Table([], [], [], [], "", 0)
@lru_cache(maxsize=1)
def load(directory: str | None = None) -> _Table:
"""Parse the committed dataset once per process.
A missing dataset returns an empty table rather than raising. The fusion
runtime image ships `app/` only, so this file can be imported where the
dataset is not on disk; there, every event already carries the class
stamped by ingest and nothing is lost. A gate asserts the dataset is
present everywhere it is actually needed, so "empty" never passes
silently in CI.
"""
base = Path(directory) if directory else _find_dataset_dir()
if base is None:
return _empty()
records = base / "ip_classes.tsv"
if not records.is_file():
return _empty()
version = ""
manifest = base / "manifest.json"
if manifest.is_file():
try:
version = str(json.loads(manifest.read_text(encoding="utf-8")).get("version") or "")
except (ValueError, OSError):
version = ""
rows_v4: list[tuple[int, int, str, str]] = []
rows_v6: list[tuple[int, int, str, str]] = []
count = 0
for line in records.read_text(encoding="utf-8").splitlines():
if not line or line.startswith("#"):
continue
parts = line.split("\t")
if len(parts) < 3:
continue
try:
network = ipaddress.ip_network(parts[0], strict=False)
except ValueError:
continue
row = (
int(network.network_address),
int(network.broadcast_address),
parts[1],
parts[2],
)
(rows_v4 if network.version == 4 else rows_v6).append(row)
count += 1
# Sorted by start address, then by prefix length descending, so a nested
# /32 inside a /16 is found before its container. The walk below relies
# on that ordering rather than on the file's.
rows_v4.sort(key=lambda r: (r[0], -(r[1] - r[0])))
rows_v6.sort(key=lambda r: (r[0], -(r[1] - r[0])))
return _Table(
[r[0] for r in rows_v4],
rows_v4,
[r[0] for r in rows_v6],
rows_v6,
version,
count,
)
def classify(value: str, *, directory: str | None = None) -> Classification | None:
"""Classify one address, or None when the dataset has no entry.
None and not a default: three of the five classes ship with zero
records, so "no entry" is the normal case and must not read as "this
address is ordinary".
"""
if not isinstance(value, str) or not value.strip():
return None
try:
address = ipaddress.ip_address(value.strip())
except ValueError:
return None
if not is_public(address):
return None
table = load(directory)
starts, entries = (table.starts_v4, table.entries_v4) if address.version == 4 else (table.starts_v6, table.entries_v6)
if not entries:
return None
numeric = int(address)
index = bisect.bisect_right(starts, numeric)
# Walk back over candidates whose start is at or below the query. Bounded
# for the same reason as the Go side: a /8 with many siblings would make
# an unbounded walk linear in the sibling count.
for i in range(index - 1, max(-1, index - 1 - _MAX_NESTING_PROBE), -1):
start, end, cls, provider = entries[i]
if start <= numeric <= end:
return Classification(cls, provider, table.version)
return None
_MAX_NESTING_PROBE = 64
#: Mirrors `activity.IsPublicIP` in the Go tree. Listed explicitly rather
#: than using `ipaddress.is_global`, whose membership has moved between
#: Python minors: a security predicate must not answer differently under two
#: interpreter builds of the same commit.
_NON_PUBLIC = tuple(
ipaddress.ip_network(net)
for net in (
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"127.0.0.0/8",
"169.254.0.0/16",
"100.64.0.0/10",
"192.0.0.0/24",
"192.0.2.0/24",
"198.51.100.0/24",
"203.0.113.0/24",
"198.18.0.0/15",
"224.0.0.0/4",
"0.0.0.0/8",
"fc00::/7",
"fe80::/10",
"::1/128",
"::/128",
"ff00::/8",
"2001:db8::/32",
)
)
def is_public(address: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
return not any(address in network for network in _NON_PUBLIC)
def dataset_version(*, directory: str | None = None) -> str:
return load(directory).version
def record_count(*, directory: str | None = None) -> int:
return load(directory).record_count
def sample_address(ip_class: str, *, directory: str | None = None) -> str | None:
"""One address the dataset classifies as `ip_class`, for tests."""
table = load(directory)
for entries in (table.entries_v4, table.entries_v6):
for start, _end, cls, _provider in entries:
if cls == ip_class:
family = ipaddress.IPv4Address if entries is table.entries_v4 else ipaddress.IPv6Address
return str(family(start))
return None