#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""Cortex analyzers for urlquery: Urlquery_Analyze and Urlquery_Lookup.

Urlquery_Analyze takes a url observable: it reuses urlquery's newest report
of the URL from the last max_age days, or analyzes the URL as a restricted
report and waits for it. Urlquery_Lookup takes a url, domain or fqdn and only
finds the newest report; it never submits. Both report urlquery's verdict, the
alerts, the final URL and title, and the server's IP, and add the IP and the
final URL as new observables.

Report content comes from the analyzed sites: titles and URLs in the report
are data, not links to open.
"""

from __future__ import annotations

from cortexutils.analyzer import Analyzer
from urlquery_api import Client, URLQueryError, WaitError

REPORT_URL = "https://urlquery.net/report/{}"
LEVELS = {"malicious": "malicious", "suspicious": "suspicious", "benign": "safe", "unknown": "info"}


class UrlqueryAnalyzer(Analyzer):
    def __init__(self) -> None:
        Analyzer.__init__(self)
        self.service = self.get_param("config.service", None, "service is missing")
        self.key = self.get_param("config.key", None, "the urlquery API key is missing")
        self.access = self.get_param("config.access", "restricted")
        self.max_age = int(self.get_param("config.max_age", 7 if self.service == "analyze" else 30))
        self.wait_timeout = float(self.get_param("config.wait_timeout", 300))
        if self.access not in ("restricted", "private", "public"):
            self.error("access must be restricted, private or public")

    def find(self, client: Client) -> str | None:
        value = self.get_data()
        if self.data_type == "url":
            field, value = "url.addr", value.split("://", 1)[-1]
        elif self.data_type == "domain":
            field = "url.domain"
        else:
            field = "url.fqdn"
        found = client.search_reports(f'{field}:"{value}" AND date:[now-{self.max_age}d TO now]', limit=1)
        return found.items[0].report_id if found.items else None

    def run(self) -> None:
        if self.service == "analyze" and self.data_type != "url":
            self.error("Urlquery_Analyze takes url observables; use Urlquery_Lookup for domains and host names")
        if self.service not in ("analyze", "lookup") or self.data_type not in ("url", "domain", "fqdn"):
            self.error(f"unsupported service {self.service!r} or data type {self.data_type!r}")
        try:
            with Client(self.key, user_agent="urlquery-cortex") as client:
                report_id, analyzed = self.find(client), False
                if report_id is None and self.service == "analyze":
                    s = client.submit(self.get_data(), access=self.access, tags=["cortex"], wait=True,
                                      wait_timeout=self.wait_timeout)
                    if s.status != "done":
                        self.error(f"the analysis {s.status}; report {s.report_id}")
                    report_id, analyzed = s.report_id, True
                if report_id is None:
                    self.report({"found": False, "data": self.get_data(), "max_age": self.max_age})
                    return
                self.report(self.findings(client, report_id, analyzed))
        except WaitError as e:
            # Still queued: running the analyzer again later finds the report.
            self.error(f"{e}; report {e.submission.report_id} is still being analyzed, run again later")
        except URLQueryError as e:
            self.error(str(e))

    def findings(self, client: Client, report_id: str, analyzed: bool) -> dict:
        o = client.report_overview(report_id)
        verdict = client.lookup_reputation(f"{o.url.schema_}://{o.url.addr}").verdict
        return {
            "found": True,
            "analyzed": analyzed,
            "report_id": report_id,
            "report_url": REPORT_URL.format(report_id),
            "date": o.date.isoformat(),
            "verdict": verdict,
            "url": f"{o.url.schema_}://{o.url.addr}",
            "final_url": f"{o.final.url.schema_}://{o.final.url.addr}",
            "title": o.final.title,
            "ip": o.ip.addr,
            "asn": o.ip.asn,
            "as": o.ip.as_,
            "country": o.ip.country_code,
            "tags": o.tags,
            "alerts": [{"severity": a.severity, "verdict": a.verdict, "alert": a.alert, "host": a.trigger}
                       for a in o.detection.urlquery],
        }

    def summary(self, raw: dict) -> dict:
        if not raw.get("found"):
            return {"taxonomies": [self.build_taxonomy("info", "urlquery", "Report", "none")]}
        verdict = raw["verdict"]
        taxonomies = [self.build_taxonomy(LEVELS.get(verdict, "info"), "urlquery", "Verdict", verdict)]
        if raw["alerts"]:
            level = "malicious" if any(a["verdict"] in ("phishing", "malware") for a in raw["alerts"]) else "suspicious"
            taxonomies.append(self.build_taxonomy(level, "urlquery", "Alerts", len(raw["alerts"])))
        return {"taxonomies": taxonomies}

    def artifacts(self, raw: dict) -> list:
        if not raw.get("found"):
            return []
        out = []
        if raw["ip"]:
            out.append(self.build_artifact("ip", raw["ip"], message="served the analyzed page", tags=["urlquery"]))
        if raw["final_url"] != raw["url"]:
            out.append(self.build_artifact("url", raw["final_url"], message="redirect target", tags=["urlquery"]))
        return out


if __name__ == "__main__":
    UrlqueryAnalyzer().run()
