netsec-scan: read flows-*.jsonl.gz so a cold start baselines the retained window, not the live file
The collector gzips on rotation, so FLOW_PATTERN 'flows-*.jsonl' saw 1 of 5 files (measured: 1/72 of the retained window). Archives are immutable, so each is read once, whole, decrypted lazily and recorded in state['archives']. - archives are bounded (ARCHIVE_MAX_SECONDS/BYTES/FILES, newest first) and flows are consumed in batches; a partial pass leaves state seeded=false and reports the unread files as pending, so the next tick continues instead of alerting from a window it has not examined - the alert window comes from the coverage start in the consumed filenames (monotone), so 'no prior in ~Xh of observed flows' is now verifiable - the seed absorbs every egress tuple in the window, not just findings (a web-port tuple never becomes one on its first tick); a warm state meeting archives for the first time absorbs them the same way - a torn .gz keeps its readable prefix, is noted in state/seed.failed, and does not abort the tick; in-flight *.gz.tmp.* markers are never read - report.json carries window_h/covered_since/seed; 12 new tests
This commit is contained in:
parent
f4001d589e
commit
ba1bef3814
8 changed files with 690 additions and 98 deletions
|
|
@ -1,29 +1,36 @@
|
|||
"""Flow-store access and parsing.
|
||||
|
||||
Two sources, one parser:
|
||||
Three sources, one parser:
|
||||
|
||||
* `RemoteFlowStore` reads the collector's JSONL on siriussec over SSH with a
|
||||
per-file byte offset, so a 5-minute tick pulls only the new bytes (the whole
|
||||
retained window is <= 1 GiB, but 900 MiB every tick would be absurd).
|
||||
* `RemoteFlowStore` reads the collector's JSONL on siriussec over SSH. Plain
|
||||
`.jsonl` files are appended to by the collector, so they are read with a
|
||||
per-file byte offset and only new bytes are pulled each tick. `.jsonl.gz`
|
||||
archives are immutable once renamed into place (the collector gzips to a
|
||||
temp name and renames), so each one is read once, in full.
|
||||
* `LocalFlowStore` reads a directory (tests, fixtures, dev).
|
||||
* `SingleFileStore` reads one fixture file (the `--fixture` path).
|
||||
|
||||
Only complete lines are consumed; a trailing partial line is carried in state
|
||||
and re-parented to the next tick.
|
||||
Only complete lines are consumed; a trailing partial line in a live file is
|
||||
carried in state and re-parented to the next tick.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import hashlib
|
||||
import io
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import zlib
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Dict, Iterable, List, Optional, Tuple
|
||||
from typing import Dict, Iterable, Iterator, List, Optional, Tuple
|
||||
|
||||
from . import config
|
||||
from .prom import SensorError
|
||||
|
|
@ -188,6 +195,70 @@ def iter_lines(data: bytes) -> Tuple[List[str], bytes]:
|
|||
return complete.split("\n"), data[idx + 1:]
|
||||
|
||||
|
||||
# ------------------------------------------------------- archive names ----
|
||||
# The collector's own naming contract (apps/base/netsec/collect.sh):
|
||||
# flows-<UTCstamp>-<seq>.jsonl live, appended to
|
||||
# flows-<UTCstamp>-<seq>.jsonl.gz closed, immutable
|
||||
# flows-<UTCstamp>-<seq>.jsonl.gz.tmp.<pid> gzip in flight
|
||||
# <UTCstamp> is the moment the file was *opened*, so it is the start of that
|
||||
# file's coverage — min(stamps) is exactly "how far back these files go".
|
||||
_STAMP_RE = re.compile(r"^flows-(\d{8}T\d{6}Z)-\d+\.jsonl(?:\.gz)?$")
|
||||
|
||||
|
||||
def is_archive(name: str) -> bool:
|
||||
return name.endswith(".jsonl.gz")
|
||||
|
||||
|
||||
def is_plain(name: str) -> bool:
|
||||
return name.endswith(".jsonl")
|
||||
|
||||
|
||||
def is_usable(name: str) -> bool:
|
||||
"""A file the sensor may read: not in flight, not half-named.
|
||||
|
||||
`.jsonl*` also matches the collector's `…jsonl.gz.tmp.<pid>` marker, which
|
||||
is an in-progress gzip — reading it would be a torn stream every rotation.
|
||||
"""
|
||||
base = os.path.basename(name)
|
||||
if ".tmp" in base or not base.startswith("flows-"):
|
||||
return False
|
||||
return is_archive(base) or is_plain(base)
|
||||
|
||||
|
||||
def flow_stamp(name: str) -> Optional[datetime]:
|
||||
"""Coverage start of a collector file, from its name (UTC)."""
|
||||
match = _STAMP_RE.match(os.path.basename(name))
|
||||
if not match:
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(match.group(1), "%Y%m%dT%H%M%SZ").replace(tzinfo=timezone.utc)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
class ArchiveTruncated(Exception):
|
||||
"""A `.gz` that could not be decompressed to the end.
|
||||
|
||||
Raised *after* the readable prefix has been yielded, so a torn archive
|
||||
costs the tail of one file and never the tick.
|
||||
"""
|
||||
|
||||
|
||||
def iter_archive(store: "BaseStore", name: str) -> Iterator[str]:
|
||||
"""Yield decoded lines from an immutable archive, decompressing lazily.
|
||||
|
||||
Whole-file reads into a list are avoided on purpose: one live file is up to
|
||||
150 MB and a seed walks many of them.
|
||||
"""
|
||||
data = store.read_from(name, 0)
|
||||
try:
|
||||
with gzip.open(io.BytesIO(data), mode="rt", encoding="utf-8", errors="replace") as handle:
|
||||
for line in handle:
|
||||
yield line
|
||||
except (EOFError, gzip.BadGzipFile, zlib.error, OSError) as exc:
|
||||
raise ArchiveTruncated("%s: %s" % (type(exc).__name__, exc))
|
||||
|
||||
|
||||
# --------------------------------------------------------------- stores ----
|
||||
class BaseStore:
|
||||
def list_files(self) -> List[Tuple[str, int]]:
|
||||
|
|
@ -251,7 +322,10 @@ class RemoteFlowStore(BaseStore):
|
|||
parts = line.rsplit(" ", 1)
|
||||
if len(parts) != 2 or not parts[1].isdigit():
|
||||
continue
|
||||
files.append((os.path.basename(parts[0]), int(parts[1])))
|
||||
name = os.path.basename(parts[0])
|
||||
if not is_usable(name): # in-flight gzip and the like
|
||||
continue
|
||||
files.append((name, int(parts[1])))
|
||||
if not files:
|
||||
raise SensorError("no-flows-file", "collector directory is empty on %s" % self.host)
|
||||
return files
|
||||
|
|
@ -275,10 +349,12 @@ class LocalFlowStore(BaseStore):
|
|||
|
||||
def list_files(self) -> List[Tuple[str, int]]:
|
||||
files = []
|
||||
for path in sorted(self.directory.glob("flows-*.jsonl")):
|
||||
for path in sorted(self.directory.glob(config.FLOW_PATTERN.split("/")[-1])):
|
||||
if not is_usable(path.name):
|
||||
continue
|
||||
files.append((path.name, path.stat().st_size))
|
||||
if not files:
|
||||
raise SensorError("no-flows-file", "no flows-*.jsonl in %s" % self.directory)
|
||||
raise SensorError("no-flows-file", "no %s in %s" % (config.FLOW_PATTERN, self.directory))
|
||||
return files
|
||||
|
||||
def read_from(self, name: str, offset: int) -> bytes:
|
||||
|
|
|
|||
Loading…
Reference in a new issue