# SPDX-License-Identifier: MIT
"""Triage the URLs in a pile of reported emails or alerts: one decision per URL.

    pip install urlquery-api
    export URLQUERY_APIKEY=<API key>
    python triage_batch.py reported/*.eml alerts.txt --skip-domain example.com > triage.csv

It reads .eml files (headers, text and HTML parts) and plain text, finds every
http(s) URL, refangs defanged ones (hxxps://, [.]), and drops duplicates and
URLs on --skip-domain domains, such as your own. For each URL it reuses
urlquery's newest report from the last --max-age days, or analyzes the URL as
a restricted report, --parallel at a time, and writes a CSV row:

    url, decision, verdict, report_url, final_url, title, alerts, error

decision is block, review, no_evidence, pending (still being analyzed: run
again later, it will find the report) or error. no_evidence is not "safe".
"""

from __future__ import annotations

import argparse
import asyncio
import csv
import email
import email.policy
import html
import re
import sys
from pathlib import Path
from urllib.parse import urlsplit

from urlquery_api import APIError, AsyncClient, WaitError

URL = re.compile(r"h(?:tt|xx)ps?(?::|\[:\])//[^\s<>\"'()\[\]{}]+(?:\[\.\][^\s<>\"'()\[\]{}]+)*", re.I)
BLOCK_ALERTS = {"phishing", "malware"}
FIELDS = ["url", "decision", "verdict", "report_url", "final_url", "title", "alerts", "error"]


def texts(path: Path) -> list[str]:
    """The text of a file; for an email, its headers and every text part."""
    data = path.read_bytes()
    if path.suffix.lower() != ".eml":
        return [data.decode("utf-8", "replace")]
    message = email.message_from_bytes(data, policy=email.policy.default)
    out = [str(message.get("subject", ""))]
    for part in message.walk():
        if part.get_content_type() in ("text/plain", "text/html"):
            out.append(html.unescape(part.get_content()))
    return out


def refang(url: str) -> str:
    url = re.sub(r"^hxxp", "http", url, flags=re.I).replace("[.]", ".").replace("[:]", ":")
    return url.rstrip(".,;:!?")


def urls(paths: list[Path], skip: set[str]) -> list[str]:
    seen: dict[str, None] = {}
    for path in paths:
        for text in texts(path):
            for match in URL.findall(text):
                url = refang(match)
                host = (urlsplit(url).hostname or "").lower()
                if host and not any(host == d or host.endswith("." + d) for d in skip):
                    seen.setdefault(url, None)
    return list(seen)


async def triage(client: AsyncClient, limit: asyncio.Semaphore, url: str, max_age: int, tag: str | None) -> dict:
    row = dict.fromkeys(FIELDS, "")
    row["url"] = url
    async with limit:
        try:
            addr = url.split("://", 1)[-1]
            found = await client.search_reports(f'url.addr:"{addr}" AND date:[now-{max_age}d TO now]', limit=1)
            if found.items:
                report_id = found.items[0].report_id
            else:
                s = await client.submit(url, access="restricted", tags=[tag] if tag else None, wait=True)
                if s.status != "done":
                    return {**row, "decision": "error", "error": f"the analysis {s.status}"}
                report_id = s.report_id
            o = await client.report_overview(report_id)
            verdict = (await client.lookup_reputation(url)).verdict
        except WaitError as e:
            return {**row, "decision": "pending", "report_url": f"https://urlquery.net/report/{e.submission.report_id}"}
        except (APIError, ValueError) as e:
            return {**row, "decision": "error", "error": str(e)}
    alerts = [a for a in o.detection.urlquery]
    if verdict == "malicious" or any(a.verdict in BLOCK_ALERTS for a in alerts):
        decision = "block"
    elif verdict == "suspicious" or alerts:
        decision = "review"
    else:
        decision = "no_evidence"
    return {**row, "decision": decision, "verdict": verdict, "report_url": f"https://urlquery.net/report/{report_id}",
            "final_url": o.final.url.addr, "title": o.final.title, "alerts": "; ".join(a.alert for a in alerts)}


async def main() -> int:
    parser = argparse.ArgumentParser(description="Triage the URLs in reported emails or alerts.")
    parser.add_argument("files", nargs="+", type=Path, help=".eml or text files")
    parser.add_argument("--skip-domain", action="append", default=[], help="a domain to leave out, such as your own")
    parser.add_argument("--max-age", type=int, default=7, help="reuse reports up to this many days old (default 7)")
    parser.add_argument("--parallel", type=int, default=4, help="URLs handled at the same time (default 4)")
    parser.add_argument("--tag", help="a tag for new analyses, such as case_1234")
    args = parser.parse_args()

    todo = urls(args.files, {d.lower() for d in args.skip_domain})
    print(f"{len(todo)} URLs", file=sys.stderr)
    out = csv.DictWriter(sys.stdout, FIELDS)
    out.writeheader()
    limit = asyncio.Semaphore(args.parallel)
    async with AsyncClient(user_agent="urlquery-triage-batch") as client:
        for done in asyncio.as_completed([triage(client, limit, u, args.max_age, args.tag) for u in todo]):
            out.writerow(await done)
            sys.stdout.flush()
    return 0


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