#!/usr/bin/python3
# blob:summary=Report live connections, per-app traffic, and firewall state, or change the firewall
# blob:args=<snapshot|geo-update|firewall on|off|outgoing allow|deny|incoming allow|deny|block <ip>|unblock <ip>>
# blob:group=network

from __future__ import annotations

import datetime as dt
import gzip
import ipaddress
import json
import os
import re
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import urllib.request
from pathlib import Path
from typing import Any

UFW_CONFIG = Path("/etc/ufw/ufw.conf")
UFW_DEFAULTS = Path("/etc/default/ufw")
UFW_USER_RULES = Path("/etc/ufw/user.rules")
UFW_USER6_RULES = Path("/etc/ufw/user6.rules")
SYSTEM_GEO_CITY = Path("/usr/share/GeoIP/GeoLite2-City.mmdb")
SYSTEM_GEO_ASN = Path("/usr/share/GeoIP/GeoLite2-ASN.mmdb")
GEO_CACHE = Path(os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))) / "blob" / "geoip"
CACHED_GEO_CITY = GEO_CACHE / "dbip-city-lite.mmdb"
CACHED_GEO_ASN = GEO_CACHE / "dbip-asn-lite.mmdb"
GEO_MAX_AGE_DAYS = 35
SHOWN_STATES = {"ESTAB", "SYN-SENT", "SYN-RECV"}
PROCESS_PATTERN = re.compile(r'\("([^"]+)",pid=(\d+)')
BYTES_PATTERN = re.compile(r"bytes_(sent|received):(\d+)")
KERNEL_FIELD_PATTERN = re.compile(r"\b(IN|OUT|SRC|DST|PROTO|DPT)=(\S*)")


def run(command: list[str]) -> str:
  try:
    return subprocess.run(command, capture_output=True, text=True, timeout=10).stdout
  except Exception:
    return ""


def read_text(path: Path) -> str:
  try:
    return path.read_text(encoding="utf-8", errors="replace")
  except Exception:
    return ""


def config_value(text: str, key: str) -> str:
  match = re.search(rf'^{key}="?([^"\n]*)"?', text, re.MULTILINE)
  return match.group(1).strip() if match else ""


def policy_word(value: str) -> str:
  return "allow" if value.upper() == "ACCEPT" else "deny"


def firewall_rules() -> list[dict[str, str]]:
  rules = []
  for path in (UFW_USER_RULES, UFW_USER6_RULES):
    for line in read_text(path).splitlines():
      if not line.startswith("### tuple ###"):
        continue
      parts = line.split()
      if len(parts) < 10:
        continue
      action, protocol, port, destination, _, source, direction = parts[3:10]
      rules.append({
        "action": action,
        "protocol": protocol,
        "port": port,
        "direction": direction,
        "address": destination if direction == "out" else source,
      })
  return rules


def firewall_state() -> dict[str, Any]:
  installed = UFW_CONFIG.exists()
  defaults = read_text(UFW_DEFAULTS)
  rules = firewall_rules()
  return {
    "installed": installed,
    "enabled": installed and config_value(read_text(UFW_CONFIG), "ENABLED").lower() == "yes",
    "incoming": policy_word(config_value(defaults, "DEFAULT_INPUT_POLICY")),
    "outgoing": policy_word(config_value(defaults, "DEFAULT_OUTPUT_POLICY")),
    "ruleCount": len(rules),
    "blockedAddresses": sorted({rule["address"] for rule in rules if rule["action"] in ("deny", "reject") and rule["direction"] == "out"}),
  }


def split_endpoint(endpoint: str) -> tuple[str, str]:
  if ":" not in endpoint:
    return endpoint, ""
  address, port = endpoint.rsplit(":", 1)
  address = address.strip("[]").split("%", 1)[0]
  return address, port


def is_public(address: str) -> bool:
  try:
    parsed = ipaddress.ip_address(address)
  except ValueError:
    return False
  return parsed.is_global


def is_loopback(address: str) -> bool:
  try:
    return ipaddress.ip_address(address).is_loopback
  except ValueError:
    return address in ("*", "")


def service_name(port: str, protocol: str) -> str:
  try:
    return socket.getservbyport(int(port), protocol)
  except Exception:
    return ""


def first_existing(*paths: Path) -> Path | None:
  for path in paths:
    if path.exists():
      return path
  return None


def download_database(kind: str, destination: Path) -> bool:
  today = dt.date.today()
  previous_month = (today.replace(day=1) - dt.timedelta(days=1))
  for month in (today, previous_month):
    url = f"https://download.db-ip.com/free/dbip-{kind}-lite-{month:%Y-%m}.mmdb.gz"
    handle, temporary_name = tempfile.mkstemp(dir=destination.parent, suffix=".mmdb")
    os.close(handle)
    try:
      request = urllib.request.Request(url, headers={"User-Agent": "blob-traffic"})
      with urllib.request.urlopen(request, timeout=60) as response, open(temporary_name, "wb") as output:
        with gzip.GzipFile(fileobj=response) as unpacked:
          shutil.copyfileobj(unpacked, output)
      os.replace(temporary_name, destination)
      return True
    except Exception:
      Path(temporary_name).unlink(missing_ok=True)
  return False


def database_is_fresh(path: Path) -> bool:
  return path.exists() and time.time() - path.stat().st_mtime < GEO_MAX_AGE_DAYS * 86400


def update_geo_databases() -> int:
  if SYSTEM_GEO_CITY.exists():
    print("Using the system GeoLite2 databases")
    return 0
  GEO_CACHE.mkdir(parents=True, exist_ok=True)
  failed = []
  for kind, path in (("city", CACHED_GEO_CITY), ("asn", CACHED_GEO_ASN)):
    if database_is_fresh(path):
      continue
    if not download_database(kind, path):
      failed.append(kind)
  if failed:
    print("Could not download the DB-IP " + " and ".join(failed) + " database", file=sys.stderr)
    return 1
  return 0


class GeoLookup:
  def __init__(self) -> None:
    self.city = None
    self.asn = None
    city_path = first_existing(SYSTEM_GEO_CITY, CACHED_GEO_CITY)
    asn_path = first_existing(SYSTEM_GEO_ASN, CACHED_GEO_ASN)
    try:
      import maxminddb
      if city_path:
        self.city = maxminddb.open_database(str(city_path))
      if asn_path:
        self.asn = maxminddb.open_database(str(asn_path))
    except Exception:
      self.city = None
      self.asn = None

  @property
  def available(self) -> bool:
    return self.city is not None

  def describe(self, address: str) -> dict[str, Any]:
    place: dict[str, Any] = {}
    if not is_public(address):
      return {"city": "", "country": "Local network", "latitude": None, "longitude": None, "organization": ""}
    try:
      record = self.city.get(address) if self.city else None
    except Exception:
      record = None
    if record:
      place["city"] = (record.get("city") or {}).get("names", {}).get("en", "")
      place["country"] = (record.get("country") or {}).get("names", {}).get("en", "")
      location = record.get("location") or {}
      place["latitude"] = location.get("latitude")
      place["longitude"] = location.get("longitude")
    try:
      owner = self.asn.get(address) if self.asn else None
    except Exception:
      owner = None
    place["organization"] = (owner or {}).get("autonomous_system_organization", "")
    return place


def connections(geo: GeoLookup) -> list[dict[str, Any]]:
  output = run(["ss", "-tunpiH"])
  found: list[dict[str, Any]] = []
  current: dict[str, Any] | None = None
  places: dict[str, dict[str, Any]] = {}

  for line in output.splitlines():
    if line[:1].isspace():
      if current is not None:
        for kind, value in BYTES_PATTERN.findall(line):
          current[kind] = int(value)
      continue

    current = None
    fields = line.split()
    if len(fields) < 6:
      continue
    protocol, state, _, _, local, peer = fields[:6]
    if state not in SHOWN_STATES:
      continue
    remote_address, remote_port = split_endpoint(peer)
    if is_loopback(remote_address):
      continue
    process = PROCESS_PATTERN.search(" ".join(fields[6:]))
    if remote_address not in places:
      places[remote_address] = geo.describe(remote_address)
    current = {
      "app": process.group(1) if process else "system",
      "pid": int(process.group(2)) if process else 0,
      "protocol": protocol,
      "state": state,
      "local": local,
      "remoteAddress": remote_address,
      "remotePort": remote_port,
      "service": service_name(remote_port, protocol),
      "sent": 0,
      "received": 0,
      **places[remote_address],
    }
    found.append(current)
  return found


def blocked_events() -> list[dict[str, Any]]:
  output = run(["journalctl", "-k", "--since", "-6h", "-g", "UFW BLOCK", "-o", "short-unix", "--no-pager", "-n", "500"])
  grouped: dict[tuple[str, str, str, str], dict[str, Any]] = {}
  for line in output.splitlines():
    fields = dict(KERNEL_FIELD_PATTERN.findall(line))
    if not fields.get("SRC"):
      continue
    outgoing = fields.get("OUT", "") != "" and fields.get("IN", "") == ""
    address = fields.get("DST", "") if outgoing else fields.get("SRC", "")
    port = fields.get("DPT", "")
    protocol = fields.get("PROTO", "").lower()
    key = ("out" if outgoing else "in", address, port, protocol)
    try:
      when = float(line.split(" ", 1)[0])
    except ValueError:
      when = 0.0
    entry = grouped.setdefault(key, {
      "direction": key[0], "address": address, "port": port, "protocol": protocol,
      "service": service_name(port, protocol) if port else "", "count": 0, "last": 0.0,
    })
    entry["count"] += 1
    entry["last"] = max(entry["last"], when)
  return sorted(grouped.values(), key=lambda entry: entry["last"], reverse=True)[:30]


def snapshot() -> dict[str, Any]:
  geo = GeoLookup()
  return {
    "firewall": firewall_state(),
    "geoAvailable": geo.available,
    "connections": connections(geo),
    "blocked": blocked_events(),
  }


def privileged(command: str) -> int:
  return subprocess.run(["pkexec", "sh", "-c", command]).returncode


def valid_address(value: str) -> str:
  try:
    return str(ipaddress.ip_network(value, strict=False)) if "/" in value else str(ipaddress.ip_address(value))
  except ValueError:
    print(f"Not an IP address: {value}", file=sys.stderr)
    raise SystemExit(2)


def main(arguments: list[str]) -> int:
  action = arguments[0] if arguments else "snapshot"
  value = arguments[1] if len(arguments) > 1 else ""

  if action == "snapshot":
    print(json.dumps(snapshot(), separators=(",", ":")))
    return 0
  if action == "geo-update":
    return update_geo_databases()
  if action == "firewall" and value in ("on", "off"):
    if value == "on":
      return privileged("systemctl enable --now ufw.service && ufw --force enable")
    return privileged("ufw disable")
  if action in ("outgoing", "incoming") and value in ("allow", "deny"):
    return privileged(f"ufw default {value} {action}")
  if action == "block" and value:
    return privileged(f"ufw prepend deny out to {valid_address(value)}")
  if action == "unblock" and value:
    return privileged(f"ufw delete deny out to {valid_address(value)}")

  print("Usage: blob-traffic <snapshot|geo-update|firewall on|off|outgoing allow|deny|incoming allow|deny|block <ip>|unblock <ip>>", file=sys.stderr)
  return 2


if __name__ == "__main__":
  raise SystemExit(main(sys.argv[1:]))
