"""Flow-store access and parsing. Three sources, one parser: * `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 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, Iterator, List, Optional, Tuple from . import config from .prom import SensorError _LOCAL_NETS = tuple(ipaddress.ip_network(n) for n in config.NON_EGRESS_NETS) # Documentation ranges are not routable, so nothing legitimate ever talks to # them — which makes them a fine destination for fixtures and for a synthetic # single-line demo. Python >= 3.13 classifies them `is_private`, so they are # whitelisted here explicitly rather than left to a version-dependent flag. _DOC_NETS = ( ipaddress.ip_network("192.0.2.0/24"), ipaddress.ip_network("198.51.100.0/24"), ipaddress.ip_network("203.0.113.0/24"), ipaddress.ip_network("2001:db8::/32"), ) # Peers carrying any of these prefixes are not workloads (nodes, world, the # gateway). `reserved:remote-node` / `reserved:host` egress is the node's own # software fetching things — attributing novelty to it produces CDN-IP churn, # not security signal. _RESERVED_PREFIX = "reserved:" def parse_ts(text: str) -> Optional[datetime]: if not text: return None try: return datetime.fromisoformat(text.replace("Z", "+00:00")) except ValueError: return None def is_external(ip: Optional[str]) -> bool: """True only for a globally routable unicast destination outside local space. Deliberately not `addr.is_global`: since Python 3.13 that returns False for documentation ranges (203.0.113.0/24 & co), which would make a synthetic beacon fixture invisible. Private/link-local/multicast/loopback/reserved are excluded explicitly, and NON_EGRESS_NETS covers the homelab's real address space (pod CIDR, mesh, LAN, CGNAT/tailnet). """ if not ip: return False try: addr = ipaddress.ip_address(ip) except ValueError: return False if any(addr in net for net in _LOCAL_NETS): return False if any(addr in net for net in _DOC_NETS): return True if (addr.is_private or addr.is_multicast or addr.is_link_local or addr.is_loopback or addr.is_unspecified or addr.is_reserved): return False return True def workload_name(peer: Optional[dict]) -> Optional[str]: """Stable workload identity (`namespace/name`) for a Cilium peer. Pod names change on every rollout, so a fingerprint built from `pod_name` would re-alert on every deploy. Prefer the workload object, then the app labels, and only fall back to a de-hashed pod name. """ if not isinstance(peer, dict): return None labels = peer.get("labels") or [] if any(str(lbl).startswith(_RESERVED_PREFIX) for lbl in labels): return None ns = peer.get("namespace") or "" for lbl in labels: if lbl.startswith("k8s:io.kubernetes.pod.namespace="): ns = ns or lbl.split("=", 1)[1] name = None for wl in peer.get("workloads") or []: if isinstance(wl, dict) and wl.get("name"): name = wl["name"] break if not name: for lbl in labels: for key in ("k8s:app=", "k8s:app.kubernetes.io/name="): if lbl.startswith(key): name = lbl[len(key):] break if name: break if not name: pod = peer.get("pod_name") if pod: # strip a Deployment/ReplicaSet suffix: name-hash1-hash2 parts = pod.split("-") if len(parts) >= 3 and len(parts[-1]) >= 5 and len(parts[-2]) >= 5: name = "-".join(parts[:-2]) else: name = pod if not name: return None return f"{ns}/{name}" if ns else name @dataclass class Flow: time: Optional[datetime] type: str verdict: str src_ip: Optional[str] dst_ip: Optional[str] proto: Optional[str] src_port: Optional[int] dst_port: Optional[int] src_workload: Optional[str] dst_workload: Optional[str] event_type: Optional[int] = None keys: Tuple[str, ...] = field(default_factory=tuple) def _peer_ports(l4: dict, proto: str) -> Tuple[Optional[int], Optional[int]]: body = l4.get(proto) if isinstance(l4, dict) else None if not isinstance(body, dict): return None, None sp, dp = body.get("source_port"), body.get("destination_port") return (int(sp) if isinstance(sp, int) else None, int(dp) if isinstance(dp, int) else None) def parse_flow(obj: dict) -> Optional[Flow]: flow = obj.get("flow") if isinstance(obj, dict) else None if not isinstance(flow, dict): return None ip = flow.get("IP") or {} src_ip, dst_ip = ip.get("source"), ip.get("destination") if not src_ip or not dst_ip: # ARP/non-IP trace events and any malformed line are unusable to every # rule here; counting them as parsed would inflate the flow counters. return None l4 = flow.get("l4") or {} proto = next(iter(l4), None) if isinstance(l4, dict) else None sp, dp = _peer_ports(l4, proto) if proto else (None, None) etype = (flow.get("event_type") or {}).get("type") return Flow( time=parse_ts(flow.get("time") or ""), type=str(flow.get("Type") or ""), verdict=str(flow.get("verdict") or ""), src_ip=src_ip, dst_ip=dst_ip, proto=proto, src_port=sp, dst_port=dp, src_workload=workload_name(flow.get("source")), dst_workload=workload_name(flow.get("destination")), event_type=etype if isinstance(etype, int) else None, ) def iter_lines(data: bytes) -> Tuple[List[str], bytes]: """Split a byte chunk into complete lines, returning the trailing partial.""" if not data: return [], b"" idx = data.rfind(b"\n") if idx < 0: return [], data complete = data[:idx].decode("utf-8", "replace") return complete.split("\n"), data[idx + 1:] # ------------------------------------------------------- archive names ---- # The collector's own naming contract (apps/base/netsec/collect.sh): # flows--.jsonl live, appended to # flows--.jsonl.gz closed, immutable # flows--.jsonl.gz.tmp. gzip in flight # 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.` 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]]: raise NotImplementedError def read_from(self, name: str, offset: int) -> bytes: raise NotImplementedError def _ssh_bin() -> str: for cand in config.SSH_CANDIDATES: if cand.startswith("/"): if os.path.exists(cand): return cand else: found = shutil.which(cand) if found: return found raise SensorError("no-ssh", "ssh client not found") class RemoteFlowStore(BaseStore): def __init__(self, host: str = None, key: str = None): self.host = host or config.SSH_HOST self.key = key or config.SSH_KEY def _run(self, remote_cmd: str) -> "subprocess.CompletedProcess": try: return subprocess.run( [ _ssh_bin(), "-i", self.key, "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=5", "-o", "ServerAliveCountMax=4", self.host, remote_cmd, ], capture_output=True, timeout=config.SSH_TIMEOUT, ) except subprocess.TimeoutExpired: raise SensorError("ssh-timeout", "ssh to %s exceeded %ss" % (self.host, config.SSH_TIMEOUT)) def list_files(self) -> List[Tuple[str, int]]: # `find -printf` rather than a shell glob: the glob must not be quoted # (quoted == literal, stat fails) and must not be unquoted (shell # injection surface). find needs neither. cmd = "sudo -n find %s -maxdepth 1 -type f -name %s -printf '%%f %%s\\n'" % ( shlex.quote(config.FLOW_DIR), shlex.quote(config.FLOW_PATTERN)) proc = self._run(cmd) out = proc.stdout.decode("utf-8", "replace") if proc.returncode != 0: err = proc.stderr.decode("utf-8", "replace").strip() if "No such file" in err or "cannot" in err and "stat" in err: raise SensorError("no-flows-file", "no JSONL under %s on %s" % (config.FLOW_DIR, self.host)) if "sudo" in err.lower() or "password" in err.lower(): raise SensorError("sudo-denied", err[:160]) raise SensorError("ssh-fail", err[:160]) files = [] for line in out.splitlines(): parts = line.rsplit(" ", 1) if len(parts) != 2 or not parts[1].isdigit(): continue 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 def read_from(self, name: str, offset: int) -> bytes: path = os.path.join(config.FLOW_DIR, os.path.basename(name)) # tail -c +N is 1-based: +1 is the first byte. cmd = "sudo -n tail -c +%d %s" % (offset + 1, shlex.quote(path)) proc = self._run(cmd) if proc.returncode != 0: err = proc.stderr.decode("utf-8", "replace").strip() raise SensorError("ssh-fail", err[:160] or "tail failed") return proc.stdout class LocalFlowStore(BaseStore): """For tests, fixtures and local re-runs against a copied collector dir.""" def __init__(self, directory: str): self.directory = Path(directory) def list_files(self) -> List[Tuple[str, int]]: files = [] 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 %s in %s" % (config.FLOW_PATTERN, self.directory)) return files def read_from(self, name: str, offset: int) -> bytes: data = (self.directory / name).read_bytes() return data[offset:] class SingleFileStore(BaseStore): """One fixture file, read whole; used by --fixture.""" def __init__(self, path: str): self.path = Path(path) def list_files(self) -> List[Tuple[str, int]]: if not self.path.is_file(): raise SensorError("no-flows-file", "fixture not found: %s" % self.path) return [(self.path.name, self.path.stat().st_size)] def read_from(self, name: str, offset: int) -> bytes: return self.path.read_bytes()[offset:] def fingerprint(kind: str, entity: str) -> str: """Stable id of (rule, entity). Never includes a timestamp or a count.""" return hashlib.sha256(f"{kind}|{entity}".encode("utf-8")).hexdigest()[:12]