#!/usr/bin/env python3
"""XplicitTrust event forwarder heartbeat check for Wazuh.

Wazuh rules fire on events that arrive, never on events that stop arriving.
This check closes that gap. rsyslog writes every forwarder heartbeat and every
forwarder change into EVENTS (see the Wazuh page of the documentation); this
script runs every five minutes, works out which forwarders have gone quiet,
and appends one line per change of state to OUTPUT, which the Wazuh manager
reads as a localfile:

  heartbeat_check.heartbeat_missing   a forwarder that sent heartbeats has
                                      been silent for four intervals
                                      (20 minutes by default)
  heartbeat_check.heartbeat_resumed   it is sending again

Each state change is reported once, not on every run. A forwarder that was
disabled or deleted is not reported as missing: its change event reaches
Wazuh before it stops and has rules of its own. A forwarder silent for
FORGET_AFTER is forgotten.

Python 3 standard library only. Usage:
  xplicittrust-heartbeat-check [--events FILE] [--output FILE] [--state FILE]
"""

import argparse
import datetime as dt
import json
import os
import socket
import sys
import tempfile

EVENTS = "/var/log/xplicittrust-forwarders.log"
OUTPUT = "/var/log/xplicittrust-heartbeat-check.log"
STATE = "/var/lib/xplicittrust-heartbeat/state.json"

DEFAULT_INTERVAL = 300  # seconds, for heartbeats without interval_seconds
MISSED_INTERVALS = 4  # silent for this many intervals = missing
MIN_SILENCE = dt.timedelta(minutes=20)
FORGET_AFTER = dt.timedelta(days=7)

EPOCH = "1970-01-01T00:00:00.000Z"

# The one key of the forwarder's JSON body that holds the event fields, so
# that Wazuh stores them as data.xplicittrust.*.
NAMESPACE = "xplicittrust"


def parse_time(value):
    """RFC 3339 as the forwarder writes it (UTC, milliseconds, Z)."""
    try:
        return dt.datetime.fromisoformat(str(value).replace("Z", "+00:00"))
    except ValueError:
        return None


def format_time(t):
    return t.astimezone(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.") + \
        f"{t.microsecond // 1000:03d}Z"


def read_events(path):
    """Yield (tenant, event) from the rotated file and the current one.

    Each line is "<tenant id> <JSON body>", the tenant id being the RFC 5424
    hostname of the forwarder's message. Lines that do not parse are skipped.
    """
    for name in (path + ".1", path):
        try:
            f = open(name, encoding="utf-8", errors="replace")
        except FileNotFoundError:
            continue
        with f:
            for line in f:
                tenant, _, body = line.strip().partition(" ")
                if not body.startswith("{"):
                    continue
                try:
                    event = json.loads(body)
                except ValueError:
                    continue
                # The fields sit under one "xplicittrust" key. A body without
                # it is from a forwarder release before that.
                if isinstance(event, dict) and isinstance(event.get(NAMESPACE), dict):
                    event = event[NAMESPACE]
                if isinstance(event, dict):
                    yield tenant, event


def load_state(path):
    try:
        with open(path, encoding="utf-8") as f:
            state = json.load(f)
        return state if isinstance(state, dict) else {}
    except (FileNotFoundError, ValueError):
        return {}


def save_state(path, state):
    directory = os.path.dirname(path)
    os.makedirs(directory, mode=0o750, exist_ok=True)
    fd, tmp = tempfile.mkstemp(dir=directory, prefix=".state-")
    with os.fdopen(fd, "w", encoding="utf-8") as f:
        json.dump(state, f, indent=1, sort_keys=True)
    os.replace(tmp, path)


def later(a, b):
    """The later of two RFC 3339 strings (all UTC with Z, so they sort)."""
    return a if a >= b else b


def update(state, events):
    """Fold the events into the per-forwarder state.

    The files are read whole on every run, so this must be idempotent: only
    the latest time of each kind of event is kept, never a counter.
    """
    for tenant, e in events:
        if e.get("object_type") != "event_forwarder":
            continue
        fid = str(e.get("object_id") or "")
        at = parse_time(e.get("created_at"))
        if not fid or at is None:
            continue
        at = format_time(at)
        f = state.setdefault(fid, {
            "tenant": tenant, "name": fid, "last_heartbeat": EPOCH,
            "last_stop": EPOCH, "last_start": EPOCH, "missing": False,
        })
        if e.get("object_name"):
            f["name"] = str(e["object_name"])
        if tenant:
            f["tenant"] = tenant
        kind = (e.get("event_class"), e.get("event_type"))
        if kind == ("event_forwarder", "heartbeat"):
            f["last_heartbeat"] = later(f["last_heartbeat"], at)
            interval = e.get("interval_seconds")
            if isinstance(interval, int) and interval > 0:
                f["interval_seconds"] = interval
        elif kind == ("configuration_change", "deleted"):
            f["last_stop"] = later(f["last_stop"], at)
        elif kind == ("configuration_change", "updated"):
            if e.get("enabled") is False:
                f["last_stop"] = later(f["last_stop"], at)
            elif e.get("enabled") is True:
                f["last_start"] = later(f["last_start"], at)


def check(state, now):
    """Return the findings to report and drop forwarders long gone."""
    findings = []
    for fid in sorted(state):
        f = state[fid]
        if f["last_heartbeat"] == EPOCH:
            # Only changes seen so far: a forwarder without heartbeats (mail,
            # or a release before heartbeats). Nothing to watch.
            if now - parse_time(later(f["last_stop"], f["last_start"])) > FORGET_AFTER:
                del state[fid]
            continue
        # Counted from a re-enable too, so the minutes before a re-enabled
        # forwarder's first heartbeat are not taken for silence.
        silent = now - parse_time(later(f["last_heartbeat"], f["last_start"]))
        interval = f.get("interval_seconds", DEFAULT_INTERVAL)
        limit = max(MIN_SILENCE, dt.timedelta(seconds=MISSED_INTERVALS * interval))
        stopped = f["last_stop"] > later(f["last_heartbeat"], f["last_start"])

        if stopped or silent > FORGET_AFTER:
            # Disabled or deleted on purpose, which the change rules report,
            # or gone for a week. A stopped forwarder that is enabled again
            # starts over without a "resumed".
            f["missing"] = False
            if silent > FORGET_AFTER:
                del state[fid]
            continue
        if silent >= limit and not f["missing"]:
            f["missing"] = True
            findings.append(("heartbeat_missing", fid, f, silent))
        elif silent < limit and f["missing"]:
            f["missing"] = False
            findings.append(("heartbeat_resumed", fid, f, silent))
    return findings


def message(kind, f, silent):
    minutes = int(silent.total_seconds() // 60)
    if kind == "heartbeat_missing":
        return f"event forwarder {f['name']} sent no heartbeat for {minutes} minutes"
    return f"event forwarder {f['name']} sends heartbeats again"


def report(path, findings, now):
    """Append the findings in the format the XplicitTrust decoder reads.

    The line is what rsyslog hands to Wazuh for a forwarded event: a syslog
    header, then "xplicittrust" and the JSON body, the fields under its
    "xplicittrust" key.
    """
    if not findings:
        return
    header = now.strftime("%b %e %H:%M:%S") + " " + socket.gethostname()
    with open(path, "a", encoding="utf-8") as out:
        for kind, fid, f, silent in findings:
            body = {
                "event_class": "heartbeat_check",
                "event_type": kind,
                "object_type": "event_forwarder",
                "object_id": fid,
                "object_name": f["name"],
                "tenant": f["tenant"],
                "last_heartbeat": f["last_heartbeat"],
                "silent_minutes": int(silent.total_seconds() // 60),
                "message": message(kind, f, silent),
                "created_at": format_time(now),
            }
            line = json.dumps({NAMESPACE: body}, separators=(',', ':'))
            out.write(f"{header} xplicittrust {line}\n")


def main():
    p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    p.add_argument("--events", default=EVENTS)
    p.add_argument("--output", default=OUTPUT)
    p.add_argument("--state", default=STATE)
    args = p.parse_args()

    now = dt.datetime.now(dt.timezone.utc)
    state = load_state(args.state)
    update(state, read_events(args.events))
    findings = check(state, now)
    # Report before saving: if the report fails, the next run reports again
    # instead of the finding being lost.
    report(args.output, findings, now)
    save_state(args.state, state)
    return 0


if __name__ == "__main__":
    sys.exit(main())
