# SPDX-License-Identifier: MIT
"""An OpenCTI internal-enrichment connector for urlquery.

It enriches Url, Domain-Name and Hostname observables:

- a Url is analyzed, unless it was analyzed in the last URLQUERY_MAX_AGE days,
  in which case its newest report is used;
- a domain or host name gets its newest report from the last
  URLQUERY_MAX_AGE days, if there is one; it is not analyzed.

From the report it adds to the observable a score and labels from urlquery's
verdict and tags, an external reference to the report, the screenshot, and a
note with the alerts and the kit's rare scripts; it adds the server's IP
address and the final URL, when the page redirected, as related observables.

    pip install "pycti==<your OpenCTI version>" urlquery-api
    export OPENCTI_URL=http://localhost:8080 OPENCTI_TOKEN=<connector user's token>
    export CONNECTOR_ID=<a UUID of your own> URLQUERY_APIKEY=<urlquery API key>
    python urlquery_opencti.py

Optional: URLQUERY_ACCESS (visibility of new reports: restricted, the
default, private or public), URLQUERY_MAX_AGE (days, default 7),
URLQUERY_MAX_TLP (default TLP:AMBER; observables marked above it are not
sent to urlquery), and CONNECTOR_AUTO (true to enrich new observables
automatically).
"""

from __future__ import annotations

import base64
import os

import stix2
from pycti import (
    STIX_EXT_OCTI_SCO,
    Identity,
    OpenCTIConnectorHelper,
    OpenCTIStix2,
    StixCoreRelationship,
    get_config_variable,
)
from pycti.entities.opencti_note import Note
from urlquery_api import Client, WaitError

REPORT_URL = "https://urlquery.net/report/{}"
RARE = 5  # content seen in at most this many reports is distinctive
SCORES = {"malicious": 90, "suspicious": 50}  # benign and unknown leave the score alone


class UrlqueryConnector:
    def __init__(self) -> None:
        self.helper = OpenCTIConnectorHelper({
            "connector": {
                "type": "INTERNAL_ENRICHMENT",
                "name": "urlquery",
                "scope": "Url,Domain-Name,Hostname",
                "auto": False,
            },
        })
        self.access = os.environ.get("URLQUERY_ACCESS", "restricted")
        self.max_age = int(os.environ.get("URLQUERY_MAX_AGE", "7"))
        self.max_tlp = get_config_variable("URLQUERY_MAX_TLP", ["urlquery", "max_tlp"], {}, default="TLP:AMBER")
        self.client = Client(user_agent="urlquery-opencti")
        self.author = stix2.Identity(
            id=Identity.generate_id("urlquery", "organization"),
            name="urlquery", identity_class="organization",
            description="urlquery.net URL analysis", contact_information="https://urlquery.net",
        )

    # Finding the report

    def url_report(self, url: str) -> str | None:
        addr = url.split("://", 1)[-1]
        found = self.client.search_reports(f'url.addr:"{addr}" AND date:[now-{self.max_age}d TO now]', limit=1)
        if found.items:
            return found.items[0].report_id
        try:
            s = self.client.submit(url, access=self.access, tags=["opencti"], wait=True)
        except WaitError as e:
            # Still queued: enriching the observable again later finds the report.
            raise ValueError(f"{e}; report {e.submission.report_id} is still being analyzed") from e
        return s.report_id if s.status == "done" else None

    def host_report(self, field: str, value: str) -> str | None:
        found = self.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

    # Enrichment

    def process(self, data: dict) -> str:
        entity, objects = data["stix_entity"], data["stix_objects"]
        markings = [m["definition"] for m in data["enrichment_entity"].get("objectMarking", [])
                    if m["definition_type"] == "TLP"]
        if not all(OpenCTIConnectorHelper.check_max_tlp(tlp, self.max_tlp) for tlp in markings):
            return f"not sent to urlquery: marked above {self.max_tlp}"

        value = entity["value"]
        if entity["type"] == "url":
            report_id = self.url_report(value)
        elif entity["type"] == "domain-name":
            report_id = self.host_report("url.domain", value)
        else:
            report_id = self.host_report("url.fqdn", value)
        if not report_id:
            return f"no urlquery report of {value} in the last {self.max_age} days"

        r = self.client.report(report_id)
        verdict = self.client.lookup_reputation(f"{r.url.schema_}://{r.url.addr}").verdict
        link = REPORT_URL.format(report_id)
        reference = {"source_name": "urlquery", "url": link, "external_id": report_id,
                     "description": f"urlquery verdict: {verdict}; analyzed {r.date:%Y-%m-%d %H:%M} UTC"}

        put = OpenCTIStix2.put_attribute_in_extension
        put(entity, STIX_EXT_OCTI_SCO, "external_references", reference, True)
        if verdict in SCORES:
            put(entity, STIX_EXT_OCTI_SCO, "score", SCORES[verdict])
        for label in [f"urlquery:{verdict}"] + r.tags:
            put(entity, STIX_EXT_OCTI_SCO, "labels", label, True)
        screenshot = self.client.screenshot(report_id)
        if screenshot:
            put(entity, STIX_EXT_OCTI_SCO, "files", {
                "name": f"urlquery-{report_id}.png", "mime_type": "image/png",
                "data": base64.b64encode(screenshot).decode(), "no_trigger_import": True,
            }, True)

        new = [self.author, self.note(entity, r, verdict, link)]
        if r.ip.addr:
            ip = (stix2.IPv6Address if ":" in r.ip.addr else stix2.IPv4Address)(
                value=r.ip.addr, custom_properties={"x_opencti_created_by_ref": self.author.id})
            new += [ip, self.related(entity["id"], ip.id, f"served the analyzed page (AS{r.ip.asn} {r.ip.as_})")]
        if entity["type"] == "url" and r.final.url.addr != r.url.addr:
            final = stix2.URL(value=f"{r.final.url.schema_}://{r.final.url.addr}",
                              custom_properties={"x_opencti_created_by_ref": self.author.id})
            new += [final, self.related(entity["id"], final.id, "redirected to")]

        self.helper.send_stix2_bundle(self.helper.stix2_create_bundle(objects + new))
        return f"{value}: {verdict}, {link}"

    def note(self, entity: dict, r, verdict: str, link: str) -> stix2.Note:
        lines = [f"**Verdict:** {verdict}", f"**Final URL:** {r.final.url.schema_}://{r.final.url.addr}",
                 f"**Title:** {r.final.title}", "", "**Alerts**", ""]
        lines += [f"- {a.severity} {a.alert} ({a.trigger})" for a in r.detection.urlquery] or ["- none"]
        rare = [s for s in r.javascript.script if s.times_seen <= RARE]
        if rare:
            lines += ["", "**Rare scripts**", ""]
            lines += [f"- `{s.sha256}`, seen in {s.times_seen} reports" for s in rare]
        bots = [t.bot.username for t in r.artifacts.telegram if t.bot]
        if bots:
            lines += ["", "**Telegram bots:** " + ", ".join(bots)]
        lines += ["", f"[urlquery report]({link})"]
        content = "\n".join(lines)
        return stix2.Note(
            id=Note.generate_id(r.date, content), created=r.date, abstract=f"urlquery: {verdict}",
            content=content, object_refs=[entity["id"]], created_by_ref=self.author.id,
            allow_custom=True,
        )

    def related(self, source: str, target: str, description: str) -> stix2.Relationship:
        return stix2.Relationship(
            id=StixCoreRelationship.generate_id("related-to", source, target),
            relationship_type="related-to", source_ref=source, target_ref=target,
            description=description, created_by_ref=self.author.id,
        )

    def start(self) -> None:
        self.helper.listen(message_callback=self.process)


if __name__ == "__main__":
    UrlqueryConnector().start()
