#!/usr/bin/env python3
"""Monitum OT: check your products against Vulnerability watch on your own machine.

    python3 monitum_match.py inventory.csv watch.json
    python3 monitum_match.py inventory.csv watch.json --csv report.csv
    python3 monitum_match.py inventory.csv --fetch

It reads two files and prints the flaws that concern your products, each with its patch priority. Your list is
read from disk and is never sent anywhere. With --fetch the script first downloads the day's public data file
from brief.girder.in (one request that carries nothing about your list); without it, it makes no connection at
all, so it also runs on a machine with no network.

inventory.csv: one product a line, "vendor, product, version". A first line of column names is read in any
order (vendor, product, version, and optionally "reachable from outside" with yes or no, and "where it sits").
A list saved from the My products part of Vulnerability watch has this form.

watch.json: https://brief.girder.in/data/watch.json, rebuilt every day.

The rules are the ones the page runs in the browser (site/assets/watch.js): a product is matched to a flaw by
the flaw's list of affected products, then the version decides between Affected, Not affected and Check.
Anything unclear is Check, never Not affected. A flaw used in attacks is priority 1 and nothing lowers it.

Python 3.9 or later, standard library only. From Monitum OT, by Girder: https://brief.girder.in/watch/offline
"""

from __future__ import annotations

import argparse
import csv
import json
import re
import sys
import urllib.request
from pathlib import Path

DATA_URL = "https://brief.girder.in/data/watch.json"
MAX_ROWS = 500  # products read from a list, as on the page
MAX_BYTES = 20 * 1024 * 1024  # the data file is far smaller; anything larger is not it

STATUS = {"affected": "Affected", "check": "Check", "clear": "Not affected"}
ORDER = {"affected": 0, "check": 1, "clear": 2}
REACH = {"yes": "yes", "y": "yes", "true": "yes", "no": "no", "n": "no", "false": "no"}
WHERE = {
    "business": "Business network",
    "dmz": "DMZ and remote access",
    "ops": "Site operations",
    "control": "Control and safety",
}


# ---------- reading the list ----------


def text(value: object, limit: int) -> str:
    """A value as trimmed text of at most `limit` characters; nothing for a missing value or a list."""
    if value is None or isinstance(value, (dict, list)):
        return ""
    return str(value).strip()[:limit]


def cells(line: str) -> list[str]:
    """One line into cells: commas, tabs or semicolons; double quotes may wrap a cell."""
    out, cur, quoted, i = [], "", False, 0
    while i < len(line):
        ch = line[i]
        if quoted:
            if ch == '"' and line[i + 1 : i + 2] == '"':
                cur += '"'
                i += 1
            elif ch == '"':
                quoted = False
            else:
                cur += ch
        elif ch == '"':
            quoted = True
        elif ch in ",\t;":
            out.append(cur)
            cur = ""
        else:
            cur += ch
        i += 1
    out.append(cur)
    return [text(c, 80) for c in out]


VENDOR = re.compile(r"^(vendor|manufacturer|make)$", re.I)
PRODUCT = re.compile(r"^(product|model|asset|name)$", re.I)
VERSION = re.compile(r"^(version|firmware)$", re.I)
REACHES = re.compile(r"^(reachable from outside|reachable|reach)$", re.I)
SITS = re.compile(r"^(where it sits|where|zone)$", re.I)
PLAIN_VERSION = re.compile(r"^[vV]?[0-9]+\.[0-9]")


def column(name: str) -> str:
    for kind, pattern in (
        ("vendor", VENDOR),
        ("product", PRODUCT),
        ("version", VERSION),
        ("reach", REACHES),
        ("where", SITS),
    ):
        if pattern.match(name):
            return kind
    return ""


def where_key(value: str) -> str:
    v = norm(value)
    for key, label in WHERE.items():
        if v in (key, norm(label)):
            return key
    return ""


def parse_list(raw: str) -> list[dict[str, str]]:
    """The list: "vendor, product, version", "product, version" or "product" a line. A line of column names
    decides the columns and is not a product."""
    rows: list[dict[str, str]] = []
    cols: list[str] | None = None
    for line in re.split(r"\r?\n", raw):
        if not line.strip() or line.strip().startswith("#"):
            continue
        c = cells(line)
        if all(not x or column(x) for x in c):
            named = [column(x) for x in c]
            if "product" in named:
                cols = named
            continue
        got = {"vendor": "", "product": "", "version": "", "reach": "", "where": ""}
        if cols:
            for i, kind in enumerate(cols):
                if kind and i < len(c):
                    got[kind] = c[i]
        elif len(c) >= 3:
            got["vendor"], got["product"], got["version"] = c[0], c[1], c[2]
        elif len(c) == 2:
            # "product, version" only when the second cell is plainly a version number;
            # otherwise "vendor, product".
            if PLAIN_VERSION.match(c[1].strip()):
                got["product"], got["version"] = c
            else:
                got["vendor"], got["product"] = c
        else:
            got["product"] = c[0]
        if not got["product"] and got["vendor"]:
            got["product"], got["vendor"] = got["vendor"], ""
        if not got["product"]:
            continue
        rows.append(
            {
                "vendor": got["vendor"].strip(),
                "product": got["product"].strip(),
                "version": got["version"].strip(),
                "reach": REACH.get(got["reach"].strip().lower(), ""),
                "where": where_key(got["where"]),
            }
        )
        if len(rows) >= MAX_ROWS:
            break
    return rows


# ---------- names and versions ----------


def norm(s: object) -> str:
    return re.sub(r"[^0-9a-z]+", " ", str(s or "").lower()).strip()


def words(s: object) -> list[str]:
    return [w for w in norm(s).split(" ") if len(w) >= 2]


def names_match(a: str, b: str) -> bool:
    """Two names match when every word of the shorter appears in the longer (3 characters or more)."""
    wa, wb = words(a), words(b)
    if not wa or not wb:
        return False
    short, long = (wa, set(wb)) if len(wa) <= len(wb) else (wb, set(wa))
    return len("".join(short)) >= 3 and all(w in long for w in short)


PREFIX = re.compile(r"^(?:firmware|fw|version|ver|release|rel|sv|v|r)[._:-]*", re.I)
WORDS_ALLOWED = re.compile(r"update|build|patch|hotfix|feature|pack", re.I)
A_VERSION = re.compile(r"[0-9]+(?:[._+-]?[0-9A-Za-z]+){0,10}")


def version(v: object) -> str:
    """ "V3.1" is "3.1", "Firmware 6.62" is "6.62", "2.9 SP1" is "2.9SP1"; nothing for prose ("10.97.3 and
    prior"), families ("15x") or words."""
    t = re.sub(r"\s+", "", PREFIX.sub("", str(v or "").strip()))
    if len(t) > 31 or re.search(r"[A-Za-z]{5,}", WORDS_ALLOWED.sub("", t)) or re.search(r"[0-9][xX]\Z", t):
        return ""
    return t if A_VERSION.fullmatch(t) else ""


def cmp(a: str, b: str) -> int:
    """Compare two versions part by part: numbers as numbers, letters without regard to case."""

    def parts(v: str) -> list[int | str]:
        return [int(p) if p.isdigit() else p.lower() for p in re.findall(r"[0-9]+|[A-Za-z]+", v)]

    pa, pb = parts(a), parts(b)
    for i in range(max(len(pa), len(pb))):
        x = pa[i] if i < len(pa) else 0
        y = pb[i] if i < len(pb) else 0
        if isinstance(x, int) and isinstance(y, int):
            d = x - y
        else:
            sx, sy = str(x), str(y)
            d = -1 if sx < sy else 1 if sx > sy else 0
        if d:
            return -1 if d < 0 else 1
    return 0


COND = re.compile(r"(<=|>=|<|>|=)([0-9][0-9A-Za-z._+-]{0,30})")


def satisfies(v: str, alt: str) -> bool | None:
    """Does version v satisfy one alternative ("<=10.97.3", ">=3.0 <3.4", "*")? None when unreadable."""
    if alt == "*":
        return True
    for c in alt.split(" "):
        m = COND.fullmatch(c)
        if not m:
            return None
        d = cmp(v, m.group(2))
        ok = {"<=": d <= 0, ">=": d >= 0, "<": d < 0, ">": d > 0, "=": d == 0}[m.group(1)]
        if not ok:
            return False
    return True


def judge(a: dict[str, str], v: str, e: dict) -> tuple[str, str]:
    """One product against one affected entry: (status, why). Unclear is always Check, never Not affected."""
    if not e["versions"]:
        return "check", "The news item names this product but its versions could not be read exactly."
    if not v:
        if a["version"]:
            return "check", f'Your version "{a["version"]}" cannot be compared.'
        return "check", "Add your version to check it."
    results = [satisfies(v, alt) for alt in e["versions"]]
    ranges = " or ".join(e["versions"])
    if True in results:
        return "affected", f"{v} is in the affected range ({ranges})."
    if None in results:
        return "check", "A listed range cannot be read; compare with the source."
    return "clear", f"{v} is outside the affected range ({ranges})."


def mine_of(flaw: dict, assets: list[dict[str, str]]) -> list[dict]:
    """Your products that a flaw concerns, the most serious result first: [{a, status, why}]."""
    out = []
    names = f" {norm(flaw['names'])} "
    for a in assets:
        v = version(a["version"])
        hits = [
            e
            for e in flaw["affected"]
            if names_match(a["product"], e["product"])
            and (
                not a["vendor"]
                or not e["vendor"]
                or names_match(a["vendor"], e["vendor"])
                or names_match(f"{a['vendor']} {a['product']}", f"{e['vendor']} {e['product']}")
            )
        ]
        if hits:
            status, why = sorted((judge(a, v, e) for e in hits), key=lambda r: ORDER[r[0]])[0]
            out.append({"a": a, "status": status, "why": why})
        elif (
            len("".join(words(a["product"]))) >= 4
            and f" {norm(a['product'])} " in names
            and (not a["vendor"] or f" {norm(a['vendor'])} " in names)
        ):
            # By the flaw's own words: the product's name, and the vendor's too when you gave one, so a
            # product with an everyday name ("Control") is not matched to every flaw that uses the word.
            why = (
                "Named in the news item, but not in its list of affected products."
                if flaw["affected"]
                else "Named in the news item, which has no version data."
            )
            out.append({"a": a, "status": "check", "why": why})
    return sorted(out, key=lambda h: ORDER[h["status"]])


# ---------- the flaws ----------

DAY = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
CVE = re.compile(r"CVE-[0-9]{4}-[0-9]{4,7}")


def plain(s: str) -> str:
    """Without the ** marks the data uses for emphasis."""
    return s.replace("**", "")


def strs(value: object, count: int, limit: int) -> list[str]:
    return [t for t in (text(x, limit) for x in (value if isinstance(value, list) else [])[:count]) if t]


def http(value: object) -> str:
    return (
        value if isinstance(value, str) and len(value) <= 500 and re.match(r"https?://", value, re.I) else ""
    )


def clean(r: object) -> dict | None:
    """One flaw from the data file, with only what the report uses; None when it cannot be used."""
    if not isinstance(r, dict):
        return None
    ident, day, headline = text(r.get("id"), 40), text(r.get("day"), 10), plain(text(r.get("h"), 200))
    p = {1: 1, 2: 2, 3: 3, 4: 4, "1": 1, "2": 2, "3": 3, "4": 4}.get(
        r.get("p") if isinstance(r.get("p"), (int, str)) else 0
    )
    if not re.fullmatch(r"[a-z0-9]{1,40}", ident) or not DAY.fullmatch(day) or not headline or not p:
        return None
    affected = []
    for a in (r.get("affected") if isinstance(r.get("affected"), list) else [])[:40]:
        if not isinstance(a, dict) or not text(a.get("product"), 80):
            continue
        vs = [text(x, 40) for x in (a.get("versions") if isinstance(a.get("versions"), list) else [])]
        # A list that cannot be read in full is treated as no list (Check), never shortened.
        readable = len(vs) <= 8 and all(x == "*" or all(COND.fullmatch(c) for c in x.split(" ")) for x in vs)
        affected.append(
            {
                "vendor": text(a.get("vendor"), 80),
                "product": text(a.get("product"), 80),
                "versions": vs if readable else [],
            }
        )
    return {
        "id": ident,
        "day": day,
        "h": headline,
        "p": p,
        "why": text(r.get("why"), 200),
        "todo": plain(text(r.get("todo"), 400)),
        "source": text(r.get("source"), 80),
        "link": http(r.get("link")),
        "cves": [c for c in strs(r.get("cves"), 12, 20) if CVE.fullmatch(c)],
        "names": text(r.get("names"), 1300),
        "affected": affected,
    }


def load_flaws(data: object) -> list[dict]:
    flaws = data.get("flaws") if isinstance(data, dict) else None
    return [f for f in (clean(r) for r in (flaws if isinstance(flaws, list) else [])[:4000]) if f]


# ---------- your site ----------


def key_of(a: dict[str, str]) -> str:
    return f"{norm(a['vendor'])}|{norm(a['product'])}"


def yours(flaw: dict, hits: list[dict]) -> dict:
    """The flaw's priority for your site:
    - used in attacks (priority 1) is never lowered, and nothing else becomes priority 1;
    - a product that can be reached from outside lifts the flaw one priority (3 to 2, 4 to 3; a 2 stays 2);
    - a product that cannot be reached from outside lowers it one (2 to 3, 3 to 4);
    - several products: the one that gives the highest priority decides."""
    live = [h for h in hits if h["status"] != "clear"]
    if not live:
        return {"p": flaw["p"], "note": "", "reach": False}
    reach = any(h["a"]["reach"] == "yes" for h in live)
    closed = all(h["a"]["reach"] == "no" for h in live)
    p, note = flaw["p"], ""
    if flaw["p"] > 1 and reach:
        p = max(2, flaw["p"] - 1)
        note = (
            "your product can be reached from outside"
            if p == flaw["p"]
            else f"{flaw['p']} in general: your product can be reached from outside"
        )
    elif flaw["p"] > 1 and closed:
        p = min(4, flaw["p"] + 1)
        note = (
            "" if p == flaw["p"] else f"{flaw['p']} in general: your product cannot be reached from outside"
        )
    return {"p": p, "note": note, "reach": reach}


def one_answer_each(assets: list[dict[str, str]]) -> list[dict[str, str]]:
    """One answer for each product, as on the page: the page keeps the answers by vendor and product, so where
    a list names the same product twice, the last line for it decides for both (5 Dec 2026, found when two
    lines for one product with different answers gave the page and this script different orders)."""
    last = {f"{norm(a['vendor'])}|{norm(a['product'])}": a for a in assets}
    out = []
    for a in assets:
        said = last[f"{norm(a['vendor'])}|{norm(a['product'])}"]
        out.append({**a, "reach": said.get("reach", ""), "where": said.get("where", "")})
    return out


def match(flaws: list[dict], assets: list[dict[str, str]]) -> list[dict]:
    """The flaws to act on or check, as "Only my products" shows them on the page: in order of priority
    (yours), a reachable product first, affected before check, then the newest. News items about the same
    flaw in the same product are one row; the others are listed under "also"."""
    assets = one_answer_each(assets)
    rows = []
    for x in flaws:
        hits = mine_of(x, assets)
        if not any(h["status"] != "clear" for h in hits):
            continue
        mine = yours(x, hits)
        rows.append({"x": x, "hits": hits, "yours": mine, "p": mine["p"], "also": []})
    rows.sort(key=lambda r: r["x"]["day"], reverse=True)
    rows.sort(key=lambda r: (r["p"], 0 if r["yours"]["reach"] else 1, ORDER[r["hits"][0]["status"]]))
    owner: dict[str, dict] = {}
    out = []
    for r in rows:
        keys = [f"{c}|{key_of(h['a'])}" for h in r["hits"] if h["status"] != "clear" for c in r["x"]["cves"]]
        first = next((owner[k] for k in keys if k in owner), None)
        if first:
            first["also"].append(r["x"])
            continue
        for k in keys:
            owner[k] = r
        out.append(r)
    return out


# ---------- the report ----------

MONTHS = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()


def day_words(day: str) -> str:
    return f"{int(day[8:])} {MONTHS[int(day[5:7]) - 1]} {day[:4]}" if DAY.fullmatch(day) else day


def product_words(a: dict[str, str]) -> str:
    return " ".join(x for x in (a["vendor"], a["product"], a["version"]) if x)


def report_text(rows: list[dict], assets: list[dict[str, str]], data: dict) -> str:
    matched = {key_of(h["a"]) for r in rows for h in r["hits"] if h["status"] != "clear"}
    lines = [
        "Monitum OT, Vulnerability watch: your products",
        f"{len(rows)} {'flaw' if len(rows) == 1 else 'flaws'} to act on or check, in {len(matched)} of your "
        f"{len(assets)} {'product' if len(assets) == 1 else 'products'}.",
        f"Data: {day_words(text(data.get('from'), 10))} to {day_words(text(data.get('to'), 10))}. "
        "Checked on this machine; your list was not sent anywhere.",
    ]
    for r in rows:
        x, mine = r["x"], r["yours"]
        note = f" ({mine['note']})" if mine["note"] else ""
        lines += ["", f"Priority {mine['p']}{note}", f"  {x['h']}"]
        lines += [f"  {STATUS[h['status']]}: {product_words(h['a'])}. {h['why']}" for h in r["hits"]]
        about = "   ".join(p for p in (", ".join(x["cves"]), day_words(x["day"]), x["source"]) if p)
        lines += [f"  {about}"]
        if x["why"]:
            lines += [f"  Why this priority: {x['why']}"]
        if x["todo"]:
            lines += [f"  First step: {x['todo']}"]
        if x["link"]:
            lines += [f"  {x['link']}"]
        if r["also"]:
            lines += [f"  Also covered in: {'; '.join(o['h'] for o in r['also'])}"]
    return "\n".join(lines) + "\n"


def safe_cell(value: object) -> str:
    """A cell that a spreadsheet will not run as a formula."""
    s = str(value)
    return "'" + s if s[:1] in ("=", "+", "-", "@", "\t", "\r") else s


def report_csv(rows: list[dict], out) -> None:
    w = csv.writer(out)
    head = ["priority", "priority in general", "status", "your product", "why", "day", "CVEs", "news item"]
    w.writerow([*head, "first step", "link", "also covered in"])
    for r in rows:
        x = r["x"]
        for h in r["hits"]:
            if h["status"] == "clear":
                continue
            cells_out = [r["p"], x["p"], STATUS[h["status"]], product_words(h["a"]), h["why"], x["day"]]
            cells_out += [
                " ".join(x["cves"]),
                x["h"],
                x["todo"],
                x["link"],
                "; ".join(o["h"] for o in r["also"]),
            ]
            w.writerow([safe_cell(c) for c in cells_out])


def fetch() -> bytes:
    """The public data file. The request carries nothing about your list."""
    req = urllib.request.Request(DATA_URL, headers={"User-Agent": "monitum-match"})  # noqa: S310 (fixed https address)
    with urllib.request.urlopen(req, timeout=30) as r:  # noqa: S310
        return r.read(MAX_BYTES + 1)


def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser(
        description="Check your products against Monitum OT's Vulnerability watch, here."
    )
    ap.add_argument("inventory", help="your list: one product a line, vendor, product, version")
    ap.add_argument("data", nargs="?", help="watch.json, downloaded from brief.girder.in/data/watch.json")
    ap.add_argument("--fetch", action="store_true", help="download the day's watch.json first (one request)")
    ap.add_argument("--csv", metavar="FILE", help="also write the result as a CSV file")
    args = ap.parse_args(argv)
    if bool(args.data) == args.fetch:
        ap.error("give the data file, or --fetch to download it (one or the other)")
    try:
        raw = fetch() if args.fetch else Path(args.data).read_bytes()
        if len(raw) > MAX_BYTES:
            raise ValueError("the data file is too large to be watch.json")
        data = json.loads(raw.decode("utf-8"))
        assets = parse_list(Path(args.inventory).read_text("utf-8-sig"))
    except (OSError, ValueError) as ex:
        print(f"monitum_match: {ex}", file=sys.stderr)
        return 2
    flaws = load_flaws(data)
    if not flaws:
        print("monitum_match: no flaws could be read from the data file", file=sys.stderr)
        return 2
    if not assets:
        print("monitum_match: no products could be read from the list", file=sys.stderr)
        return 2
    rows = match(flaws, assets)
    sys.stdout.write(report_text(rows, assets, data if isinstance(data, dict) else {}))
    if args.csv:
        with Path(args.csv).open("w", newline="", encoding="utf-8") as out:
            report_csv(rows, out)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
