# SPDX-License-Identifier: MIT
"""Forward urlquery's webhook notifications to a SIEM: Splunk's HTTP Event
Collector, Elasticsearch, or Microsoft Sentinel.

    export URLQUERY_WEBHOOK_SECRET=whsec_...    # the webhook channel's secret
    # Splunk:
    export SPLUNK_HEC_URL=https://splunk.example.org:8088 SPLUNK_HEC_TOKEN=<HEC token>
    # or Elasticsearch:
    export ELASTIC_URL=https://elastic.example.org:9200 ELASTIC_API_KEY=<API key>
    # or Microsoft Sentinel, through a data collection rule's Logs Ingestion API:
    export SENTINEL_ENDPOINT=https://<dcr endpoint> SENTINEL_DCR_ID=dcr-<immutable id>
    export AZURE_TENANT_ID=<tenant> AZURE_CLIENT_ID=<app> AZURE_CLIENT_SECRET=<secret>
    python urlquery_siem_relay.py --port 8080

Put it behind your HTTPS reverse proxy and give its URL to a webhook channel
under Settings -> Notifications on urlquery.net. It checks each request's
signature, forwards the message, and only then answers: when the SIEM is down,
urlquery gets an error and retries. Elasticsearch uses the message's id as the
document ID, so a repeated message is stored once; in Splunk and Sentinel,
drop repeats by id in searches. Needs only Python's
standard library.
"""

from __future__ import annotations

import argparse
import base64
import calendar
import hashlib
import hmac
import json
import os
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any

MAX_BODY = 1 << 20  # urlquery's messages are a few kilobytes
TOLERANCE = 300  # seconds a signature stays valid


def verify(secret: str, header: str, body: bytes) -> bool:
    try:
        parts = dict(p.split("=", 1) for p in header.split(","))
        t = int(parts["t"])
    except (KeyError, ValueError):
        return False
    expected = hmac.new(secret.encode(), str(t).encode() + b"." + body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts.get("v1", "")) and abs(time.time() - t) <= TOLERANCE


def send(url: str, body: dict[str, Any], headers: dict[str, str], method: str = "POST") -> int:
    request = urllib.request.Request(url, data=json.dumps(body).encode(), method=method,
                                     headers={"Content-Type": "application/json", **headers})
    try:
        with urllib.request.urlopen(request, timeout=5) as response:
            return response.status
    except urllib.error.HTTPError as e:
        return e.code


def to_splunk(message: dict[str, Any]) -> bool:
    """One HEC event; search it with sourcetype="urlquery:notification"."""
    occurred = message.get("occurred_at", "")
    try:
        epoch = float(calendar.timegm(time.strptime(occurred, "%Y-%m-%dT%H:%M:%SZ")))
    except ValueError:
        epoch = time.time()
    event = {"time": epoch, "source": "urlquery", "sourcetype": "urlquery:notification", "event": message}
    index = os.environ.get("SPLUNK_INDEX")
    if index:
        event["index"] = index
    status = send(os.environ["SPLUNK_HEC_URL"].rstrip("/") + "/services/collector/event", event,
                  {"Authorization": "Splunk " + os.environ["SPLUNK_HEC_TOKEN"]})
    return status == 200


def to_elastic(message: dict[str, Any]) -> bool:
    """One document per message, its id the message's: a repeat is refused as
    a conflict, which counts as stored."""
    index = os.environ.get("ELASTIC_INDEX", "urlquery-notifications")
    doc_id = base64.urlsafe_b64encode(message["id"].encode()).decode().rstrip("=")
    headers = {}
    if os.environ.get("ELASTIC_API_KEY"):
        headers["Authorization"] = "ApiKey " + os.environ["ELASTIC_API_KEY"]
    status = send(f"{os.environ['ELASTIC_URL'].rstrip('/')}/{index}/_create/{doc_id}",
                  {"@timestamp": message.get("occurred_at"), **message}, headers, method="PUT")
    return status in (200, 201, 409)


_token: dict[str, Any] = {"value": "", "expires": 0.0}
_token_lock = threading.Lock()


def sentinel_token() -> str:
    """An Entra ID token for the Logs Ingestion API, renewed before it expires."""
    with _token_lock:
        if time.time() < _token["expires"] - 300:
            return str(_token["value"])
        form = urllib.parse.urlencode({
            "grant_type": "client_credentials",
            "client_id": os.environ["AZURE_CLIENT_ID"],
            "client_secret": os.environ["AZURE_CLIENT_SECRET"],
            "scope": os.environ.get("SENTINEL_SCOPE", "https://monitor.azure.com/.default"),
        }).encode()
        authority = os.environ.get("AZURE_AUTHORITY", "https://login.microsoftonline.com").rstrip("/")
        request = urllib.request.Request(f"{authority}/{os.environ['AZURE_TENANT_ID']}/oauth2/v2.0/token", data=form)
        with urllib.request.urlopen(request, timeout=5) as response:
            answer = json.load(response)
        _token.update(value=answer["access_token"], expires=time.time() + int(answer.get("expires_in", 3600)))
        return str(_token["value"])


def to_sentinel(message: dict[str, Any]) -> bool:
    """One row in the custom table the data collection rule writes to.
    Title and id are reserved column names there, so the row uses Heading
    and NotificationId."""
    row = {
        "TimeGenerated": message.get("occurred_at"),
        "NotificationId": message.get("id"),
        "Kind": message.get("kind"),
        "Heading": message.get("title"),
        "ReportUrl": message.get("url", ""),
        "Fields": message.get("fields", []),
        "Data": message.get("data", {}),
    }
    stream = os.environ.get("SENTINEL_STREAM", "Custom-UrlqueryNotifications_CL")
    url = (f"{os.environ['SENTINEL_ENDPOINT'].rstrip('/')}/dataCollectionRules/{os.environ['SENTINEL_DCR_ID']}"
           f"/streams/{stream}?api-version=2023-01-01")
    request = urllib.request.Request(url, data=json.dumps([row]).encode(), method="POST", headers={
        "Content-Type": "application/json", "Authorization": "Bearer " + sentinel_token()})
    try:
        with urllib.request.urlopen(request, timeout=5) as response:
            return response.status in (200, 204)
    except urllib.error.HTTPError as e:
        print(f"Sentinel answered {e.code}: {e.read()[:300]!r}", file=sys.stderr)
        return False


class Relay(BaseHTTPRequestHandler):
    forward = staticmethod(to_splunk)

    def do_POST(self) -> None:
        length = int(self.headers.get("Content-Length", 0))
        if length > MAX_BODY:
            return self.answer(413)
        body = self.rfile.read(length)
        if not verify(os.environ["URLQUERY_WEBHOOK_SECRET"], self.headers.get("X-Urlquery-Signature", ""), body):
            return self.answer(401)
        try:
            message = json.loads(body)
        except json.JSONDecodeError:
            return self.answer(400)
        try:
            stored = self.forward(message)
        except (OSError, KeyError) as e:
            print(f"forwarding {message.get('id')} failed: {e}", file=sys.stderr)
            stored = False
        # A 502 makes urlquery retry the message.
        self.answer(204 if stored else 502)

    def answer(self, status: int) -> None:
        self.send_response(status)
        self.send_header("Content-Length", "0")
        self.end_headers()

    def log_message(self, format: str, *args: Any) -> None:
        print(f"{self.address_string()} {format % args}", file=sys.stderr)


def main() -> None:
    parser = argparse.ArgumentParser(description="Forward urlquery webhooks to Splunk, Elasticsearch or Sentinel.")
    parser.add_argument("--host", default="127.0.0.1", help="address to listen on (default 127.0.0.1)")
    parser.add_argument("--port", type=int, default=8080)
    args = parser.parse_args()
    if not os.environ.get("URLQUERY_WEBHOOK_SECRET"):
        parser.error("set URLQUERY_WEBHOOK_SECRET to the webhook channel's signing secret")
    if os.environ.get("SPLUNK_HEC_URL"):
        Relay.forward = staticmethod(to_splunk)
    elif os.environ.get("ELASTIC_URL"):
        Relay.forward = staticmethod(to_elastic)
    elif os.environ.get("SENTINEL_ENDPOINT"):
        Relay.forward = staticmethod(to_sentinel)
    else:
        parser.error("set SPLUNK_HEC_URL and SPLUNK_HEC_TOKEN, ELASTIC_URL, or SENTINEL_ENDPOINT")
    print(f"listening on {args.host}:{args.port}", file=sys.stderr)
    ThreadingHTTPServer((args.host, args.port), Relay).serve_forever()


if __name__ == "__main__":
    main()
