#!/usr/bin/env python3
"""freezeos-icewatch-report — send this machine's IceWatch state to the fleet
and apply the settings the fleet sends back. Runs every few minutes (timer).

  - a FreezeOS computer reports with its client certificate (node.json);
  - a fleet / build / AI server reports with its server certificate
    (fleet.env: FLEET_SERVER_ID, FLEET_PRIMARY_URL);
  - the fleet's primary server reports to itself (report.conf: SERVER_ID, URL).

Findings are only marked as sent after the fleet confirms them, so a failed
upload loses nothing. "Fleet not reachable right now" and "this machine is not
enrolled" are normal states: the tool exits quietly. Use -v to see what it did.

The fleet's answer may say IceWatch is enforced (make sure it runs), disabled
(make sure it does not) or optional (leave the machine's own choice alone).
Plan: docs/plans/icewatch.md.
"""
import json
import os
import subprocess
import sys

NODE_JSON = "/boot/freezeos/node.json"
NODE_CERT = "/boot/freezeos/client.crt"
NODE_KEY = "/boot/freezeos/client.key"
FLEET_ENV = "/etc/freezeos/fleet.env"
SRV_CERT = "/etc/freezeos/ca/server.crt"
SRV_KEY = "/etc/freezeos/ca/server.key"
CONF_DIR = "/etc/freezeos/icewatch"
POLICY = CONF_DIR + "/fleet-policy.json"
STATE_DIR = "/var/lib/icewatch"
INTEL_FILES = ("geo.bin", "bad-nets.txt", "bad-hashes.bin", "bad-hashes.names", 
               "bad-hashes-daily.bin", "bad-hashes-daily.names", "yara-rules.txt")
UNIT = "icewatch.service"
VERBOSE = "-v" in sys.argv[1:]


def say(msg):
    if VERBOSE:
        print(msg)


def envmap(path):
    d = {}
    try:
        with open(path) as f:
            for line in f:
                line = line.strip()
                if "=" in line and not line.startswith("#"):
                    k, v = line.split("=", 1)
                    d[k.strip()] = v.strip().strip('"').strip("'")
    except OSError:
        pass
    return d


def run(cmd, data=None, timeout=40):
    try:
        p = subprocess.run(cmd, input=data, capture_output=True, text=True, timeout=timeout)
        return p.returncode, p.stdout
    except (OSError, subprocess.SubprocessError):
        return 1, ""


def identity():
    """-> (url, body fields, curl auth arguments) or None when not enrolled."""
    test_url = os.environ.get("ICEWATCH_TEST_URL")          # test rig only
    if test_url:
        return (test_url, {"server_id": os.environ.get("ICEWATCH_TEST_SERVER_ID", "")},
                ["-H", "X-Admin-Api-Key: " + os.environ.get("ICEWATCH_TEST_KEY", "")])
    # The fleet's own primary server has no certificate to present to itself:
    # /etc/freezeos/icewatch/report.conf names its row and the local address,
    # and the admin key is read from fleet.env (root-only), never stored twice.
    conf = envmap(CONF_DIR + "/report.conf")
    if conf.get("SERVER_ID") and conf.get("URL"):
        key = envmap(FLEET_ENV).get("FLEET_ADMIN_API_KEY", "")
        if key:
            return (conf["URL"].rstrip("/"), {"server_id": conf["SERVER_ID"]}, ["-H", "X-Admin-Api-Key: " + key])
    try:
        with open(NODE_JSON) as f:
            node = json.load(f)
        url, nid = (node.get("fleet_url") or "").rstrip("/"), node.get("node_id") or ""
        if url and nid and os.path.exists(NODE_CERT) and os.path.exists(NODE_KEY):
            return url, {"node_id": nid}, ["--cert", NODE_CERT, "--key", NODE_KEY]
    except (OSError, ValueError):
        pass
    env = envmap(FLEET_ENV)
    sid = env.get("FLEET_SERVER_ID", "")
    url = (env.get("FLEET_PRIMARY_URL") or "").rstrip("/")
    if sid and "__" not in sid and url and os.path.exists(SRV_CERT) and os.path.exists(SRV_KEY):
        return url, {"server_id": sid}, ["--cert", SRV_CERT, "--key", SRV_KEY]
    return None


def unit_state():
    rc, out = run(["systemctl", "is-active", UNIT])
    active = out.strip() == "active"
    rc, out = run(["systemctl", "cat", UNIT])
    return active, rc == 0


def apply_policy(policy):
    """Write the fleet's settings for the service and follow enforced/disabled."""
    want = {
        "locked": policy.get("locked") or [],
        "rules": policy.get("rules") or {},
        "exceptions": policy.get("exceptions") or [],
        "blocked_hashes": [h for h in (policy.get("blocked_hashes") or []) if isinstance(h, str)],
        "blocked_addresses": [a for a in (policy.get("blocked_addresses") or []) if isinstance(a, str)][:5000],
    }
    if policy.get("level"):
        want["level"] = policy["level"]
    if policy.get("min_level"):
        want["min_level"] = policy["min_level"]
    text = json.dumps(want, indent=1, sort_keys=True) + "\n"
    try:
        with open(POLICY) as f:
            same = f.read() == text
    except OSError:
        same = False
    if not same:
        os.makedirs(CONF_DIR, mode=0o755, exist_ok=True)
        tmp = POLICY + ".new"
        with open(tmp, "w") as f:
            f.write(text)
        os.chmod(tmp, 0o644)
        os.replace(tmp, POLICY)
        say("fleet settings updated")
    active, installed = unit_state()
    mode = policy.get("mode")
    if not installed:
        return
    if mode == "enforced" and not active:
        run(["systemctl", "enable", "--now", UNIT])
        say("IceWatch is required by the fleet: started")
    elif mode == "disabled" and active:
        run(["systemctl", "disable", "--now", UNIT])
        say("IceWatch is switched off by the fleet: stopped")


def fetch_intel(url, manifest):
    """Definitions (country data, bad networks, malware hashes, rules).
    Download what changed plus the signed list, then let `icewatch defs-apply`
    decide: it installs nothing unless the list is signed with the IceWatch
    definitions key and every file matches it. This tool only fetches."""
    try:
        with open(STATE_DIR + "/defs.json") as f:
            have = (json.load(f) or {}).get("files") or {}
    except (OSError, ValueError):
        have = {}
    want = [n for n in INTEL_FILES
            if isinstance(manifest.get(n), dict) and manifest[n].get("sha256")
            and (have.get(n) != manifest[n]["sha256"] or not os.path.exists(os.path.join(STATE_DIR, n)))]
    if not want:
        return
    inc = STATE_DIR + "/incoming"
    os.makedirs(inc, mode=0o700, exist_ok=True)
    for name in want + ["manifest.json", "manifest.sig"]:
        rc, _ = run(["curl", "-sS", "--fail", "--max-time", "600", "-o", os.path.join(inc, name),
                     url + "/api/fleet/icewatch/intel/" + name], timeout=620)
        if rc != 0:
            say(name + " could not be fetched; keeping the definitions as they are")
            return
    rc, out = run(["icewatch", "defs-apply"], timeout=300)
    say(out.strip() or ("definitions are up to date" if rc == 0 else "the new definitions were refused; keeping the old ones"))
    for name in os.listdir(inc):          # anything not installed is not kept
        try:
            os.remove(os.path.join(inc, name))
        except OSError:
            pass


def main():
    if os.geteuid() != 0:
        print("freezeos-icewatch-report: must be run as root", file=sys.stderr)
        return 1
    ident = identity()
    if ident is None:
        say("this machine is not enrolled with a fleet; nothing to report")
        return 0
    url, body, auth = ident

    rc, out = run(["icewatch", "report-take"])
    try:
        taken = json.loads(out) if rc == 0 else {}
    except ValueError:
        taken = {}
    body["running"] = bool(taken.get("ok"))
    body["status"] = taken.get("status") or {}
    body["alerts"] = taken.get("alerts") or []
    body["attackers"] = taken.get("attackers") or []
    try:
        body["hostname"] = os.uname().nodename
    except OSError:
        pass

    rc, out = run(["curl", "-sS", "--fail", "--max-time", "30", *auth,
                   "-H", "Content-Type: application/json", "--data-binary", "@-",
                   url + "/api/fleet/icewatch/report"], data=json.dumps(body))
    try:
        reply = json.loads(out) if rc == 0 else {}
    except ValueError:
        reply = {}
    if not reply.get("ok"):
        say("the fleet could not be reached; will try again")
        return 0

    acked = reply.get("acked") or []
    if acked and body["running"]:
        run(["icewatch", "report-ack", json.dumps(acked)])
    say("reported %d finding(s)" % len(acked))
    if isinstance(reply.get("policy"), dict):
        apply_policy(reply["policy"])
    if os.path.isdir(STATE_DIR) and reply.get("intel"):
        fetch_intel(url, reply["intel"])
    return 0


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