# SPDX-License-Identifier: MIT
"""Investigate a phishing URL with urlquery: analyze it, collect the evidence
and find the kit's other deployments.

    pip install urlquery-api
    export URLQUERY_APIKEY=<API key>
    python investigate.py 'https://login.example.com/verify' --tag case_1234
    python investigate.py --report <report_id>    # an existing report

It prints what it found and writes evidence-<report_id>.json and
screenshot-<report_id>.png. New analyses are restricted. Captured content
comes from the phishing site: this script only reads it as text, never runs it.
"""

from __future__ import annotations

import argparse
import json
import re
import sys

from urlquery_api import Client, WaitError

RARE = 5  # content seen in at most this many reports is distinctive
ENDPOINT = re.compile(r"https?://[A-Za-z0-9.-]+\.[A-Za-z]{2,}")


def analyze(client: Client, url: str, tags: list[str]) -> str:
    try:
        s = client.submit(url, access="restricted", tags=tags or None, wait=True)
    except WaitError as e:
        # The URL is queued: don't submit it again, come back to the report.
        sys.exit(f"{e}; report {e.submission.report_id} (queue {e.submission.queue_id})")
    if s.status != "done":
        sys.exit(f"the analysis {s.status}; report {s.report_id}")
    return s.report_id


def count(client: Client, query: str) -> int:
    return client.search_reports(query, limit=1).page.total_hits


def investigate(client: Client, report_id: str) -> dict:
    r = client.report(report_id)
    evidence: dict = {
        "report_id": r.report_id,
        "date": r.date.isoformat(),
        "submitted": r.url.addr,
        "final": r.final.url.addr,
        "title": r.final.title,
        "ip": {"addr": r.ip.addr, "asn": r.ip.asn, "as": r.ip.as_, "country": r.ip.country_code},
        "tags": r.tags,
        "alerts": [{"severity": a.severity, "verdict": a.verdict, "alert": a.alert, "host": a.trigger}
                   for a in r.detection.urlquery],
        "verdict": client.lookup_reputation(r.url.schema_ + "://" + r.url.addr).verdict,
    }

    # Hosts: unranked, newly registered or never-seen hosts belong to the kit;
    # popular ones are usually the brand's own resources, loaded by the copy.
    evidence["hosts"] = [{"fqdn": h.fqdn, "ips": [ip.addr for ip in h.ips], "rank": h.domain_rank,
                          "registered": h.domain_registered, "first_seen": h.first_seen}
                         for h in r.hosts]

    # Scripts: the kit's own code is rare; the brand's library code is not.
    # Its endpoints show where stolen data would go.
    scripts = []
    for s in r.javascript.script:
        if s.times_seen > RARE:
            continue
        text = client.resource_content(report_id, s.sha256).decode("utf-8", "replace")
        scripts.append({"sha256": s.sha256, "url": s.url.addr if s.url else "", "inline": s.is_inline,
                        "times_seen": s.times_seen, "endpoints": sorted(set(ENDPOINT.findall(text))),
                        "other_reports": count(client, f"javascript.script.sha256:{s.sha256}") - 1})
    evidence["rare_scripts"] = scripts

    # What the page sent. The analysis has no password to enter, so this is
    # mostly telemetry; a kit that sends before the form does shows up here.
    evidence["posts"] = [{"url": t.url.addr, "status": t.response.status_code,
                          "size": t.request.post_data.size if t.request.post_data else 0}
                         for t in r.http if t.request.method == "POST"]

    # Telegram bots the kit would report to.
    evidence["telegram"] = [{"bot": t.bot.username if t.bot else "", "revoked": t.is_revoked}
                            for t in r.artifacts.telegram]

    # The same page elsewhere: the page's structure, and its title with a phishing tag.
    if r.final.dom and r.final.dom.dom_hash:
        evidence["same_page_structure"] = count(client, f"final.dom.dom_hash:{r.final.dom.dom_hash}") - 1

    with open(f"screenshot-{report_id}.png", "wb") as f:
        client.screenshot(report_id, f)
    return evidence


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("url", nargs="?", help="the URL to analyze")
    parser.add_argument("--report", help="investigate an existing report instead")
    parser.add_argument("--tag", action="append", default=[], help="a tag for the submission")
    args = parser.parse_args()
    if bool(args.url) == bool(args.report):
        parser.error("give a URL or --report")

    with Client(user_agent="investigate.py") as client:
        report_id = args.report or analyze(client, args.url, args.tag)
        evidence = investigate(client, report_id)

    with open(f"evidence-{report_id}.json", "w") as f:
        json.dump(evidence, f, indent=2, default=str)
    print(f"{evidence['final']}  {evidence['title']!r}  verdict {evidence['verdict']}")
    for a in evidence["alerts"]:
        print(f"  alert   {a['severity']:<8} {a['alert']}")
    for s in evidence["rare_scripts"]:
        print(f"  script  {s['sha256'][:16]}  in {s['other_reports']} other reports  {' '.join(s['endpoints'])}")
    for t in evidence["telegram"]:
        print(f"  telegram bot {t['bot'] or '?'}{' (revoked)' if t['revoked'] else ''}")
    if "same_page_structure" in evidence:
        print(f"  {evidence['same_page_structure']} other reports have the same page structure")
    print(f"evidence-{report_id}.json, screenshot-{report_id}.png")


if __name__ == "__main__":
    main()
