# SPDX-License-Identifier: MIT
"""Enrich MISP events with urlquery: analyze each URL attribute, then add the
findings to the event as MISP objects.

    pip install urlquery-api pymisp
    export URLQUERY_APIKEY=<urlquery API key>
    export MISP_URL=https://misp.example.org MISP_KEY=<MISP automation key>
    python urlquery_misp.py --event 1234
    python urlquery_misp.py --tag urlquery:enrich     # every event with the tag

A URL analyzed in the last --max-age days is not analyzed again; its newest
report is used. New analyses are restricted and tagged with the event's ID.
Each enriched attribute is tagged urlquery:enriched and skipped next time.
The script adds nothing with to_ids set: review the findings before you
share them as IDS indicators.
"""

from __future__ import annotations

import argparse
import io
import os
import sys
from datetime import datetime, timezone

from pymisp import MISPEvent, MISPObject, PyMISP
from urlquery_api import APIError, Client, WaitError

REPORT_URL = "https://urlquery.net/report/{}"
ENRICHED = "urlquery:enriched"
RARE = 5  # content seen in at most this many reports is distinctive


def report_for(client: Client, url: str, event_id: str, max_age: int, access: str) -> str | None:
    """The newest report of url from the last max_age days, or a new one."""
    addr = url.split("://", 1)[-1]
    found = client.search_reports(f'url.addr:"{addr}" AND date:[now-{max_age}d TO now]', limit=1)
    if found.items:
        return found.items[0].report_id
    try:
        s = client.submit(url, access=access, tags=[f"misp_event_{event_id}"], wait=True)
    except WaitError as e:
        # The URL is queued; the next run finds its report.
        print(f"  {url}: {e}; report {e.submission.report_id} will be used next time", file=sys.stderr)
        return None
    if s.status != "done":
        print(f"  {url}: the analysis {s.status}", file=sys.stderr)
        return None
    return s.report_id


def report_objects(client: Client, report_id: str, url: str) -> tuple[list[MISPObject], list[str]]:
    """MISP objects with a report's findings, and the tags for the attribute:
    a sandbox-report always, a phishing object when urlquery calls the page
    phishing, and a telegram-bot for each bot the page reports to."""
    r = client.report(report_id)
    verdict = client.lookup_reputation(f"{r.url.schema_}://{r.url.addr}").verdict
    screenshot = client.screenshot(report_id)

    sandbox = MISPObject("sandbox-report", standalone=False)
    sandbox.add_attribute("sandbox-type", value="web")
    sandbox.add_attribute("web-sandbox", value="urlquery")
    sandbox.add_attribute("permalink", value=REPORT_URL.format(report_id))
    sandbox.add_attribute("score", value=verdict)
    for line in findings(r):
        sandbox.add_attribute("results", value=line)
    if screenshot:
        sandbox.add_attribute("sandbox-file", value=f"urlquery-{report_id}.png", data=io.BytesIO(screenshot))
    objects = [sandbox]

    targets = [a.alert.split(" - ", 1)[1] for a in r.detection.urlquery
               if a.verdict == "phishing" and " - " in a.alert]
    if targets:
        phishing = MISPObject("phishing", standalone=False)
        phishing.add_attribute("url", value=url)
        if r.final.url.addr != r.url.addr:
            phishing.add_attribute("url-redirect", value=f"{r.final.url.schema_}://{r.final.url.addr}")
        for host in sorted({r.url.fqdn, r.final.url.fqdn}):
            phishing.add_attribute("hostname", value=host)
        if r.ip.addr:
            phishing.add_attribute("ip", value=r.ip.addr, comment=f"AS{r.ip.asn} {r.ip.as_}, {r.ip.country_code}")
        for target in sorted(set(targets)):
            phishing.add_attribute("target", value=target)
        phishing.add_attribute("submission-time", value=r.date)
        phishing.add_attribute("online", value="Yes")  # when it was analyzed
        if screenshot:
            phishing.add_attribute("screenshot", value=f"urlquery-{report_id}.png", data=io.BytesIO(screenshot))
        phishing.add_reference(sandbox.uuid, "analysed-with")
        objects.append(phishing)

    for t in r.artifacts.telegram:
        if not t.bot:
            continue
        # The bot's token is left out: it gives control of the bot.
        bot = MISPObject("telegram-bot", standalone=False)
        bot.add_attribute("username", value=t.bot.username)
        bot.add_attribute("name", value=t.bot.first_name)
        bot.add_attribute("comment", value=f"found in urlquery report {report_id}"
                                           f"{'; revoked' if t.is_revoked else ''}")
        bot.add_reference(sandbox.uuid, "related-to")
        objects.append(bot)

    for obj in objects:
        for attribute in obj.attributes:
            attribute.to_ids = False
    tags = [ENRICHED, f'urlquery:verdict="{verdict}"'] + [f'urlquery:tag="{t}"' for t in r.tags]
    return objects, tags


def findings(r) -> list[str]:
    """One line per finding: the page, its alerts, and the kit's rare scripts."""
    lines = [f"Final URL: {r.final.url.schema_}://{r.final.url.addr}", f"Title: {r.final.title}"]
    lines += [f"Alert: {a.severity} {a.alert} ({a.trigger})" for a in r.detection.urlquery]
    lines += [f"Rare script: {s.sha256}, seen in {s.times_seen} reports"
              for s in r.javascript.script if s.times_seen <= RARE]
    return lines


def enrich(misp: PyMISP, client: Client, event: MISPEvent, max_age: int, access: str) -> int:
    added = 0
    for attribute in event.attributes:
        if attribute.type != "url" or any(t.name == ENRICHED for t in attribute.tags):
            continue
        print(f"event {event.id}: {attribute.value}")
        try:
            report_id = report_for(client, attribute.value, event.id, max_age, access)
            if not report_id:
                continue
            objects, tags = report_objects(client, report_id, attribute.value)
        except APIError as e:
            print(f"  {attribute.value}: {e}", file=sys.stderr)
            continue
        objects[0].add_reference(attribute.uuid, "related-to")
        for obj in objects:
            misp.add_object(event, obj, pythonify=True)
        for obj in objects:  # once both ends exist
            for reference in obj.ObjectReference:
                misp.add_object_reference(reference)
        for tag in tags:
            misp.tag(attribute, tag)
        added += 1
    return added


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    which = parser.add_mutually_exclusive_group(required=True)
    which.add_argument("--event", help="the ID or UUID of one event")
    which.add_argument("--tag", help="enrich every event with this tag")
    parser.add_argument("--max-age", type=int, default=7, help="reuse reports up to this many days old (default 7)")
    parser.add_argument("--access", default="restricted", choices=["restricted", "private", "public"],
                        help="visibility of new reports (default restricted)")
    parser.add_argument("--insecure", action="store_true", help="don't verify MISP's TLS certificate")
    args = parser.parse_args()

    misp = PyMISP(os.environ["MISP_URL"], os.environ["MISP_KEY"], ssl=not args.insecure)
    if args.event:
        events = [misp.get_event(args.event, pythonify=True)]
    else:
        events = misp.search(controller="events", tags=[args.tag], pythonify=True)

    started = datetime.now(timezone.utc)
    with Client(user_agent="urlquery-misp") as client:
        added = sum(enrich(misp, client, event, args.max_age, args.access) for event in events)
    print(f"{added} attributes enriched in {len(events)} events in {datetime.now(timezone.utc) - started}")


if __name__ == "__main__":
    main()
