247 lines
9.2 KiB
Python
247 lines
9.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Build the most complete Buryans Hub audit packet possible."""
|
|
import json
|
|
import re
|
|
import subprocess
|
|
import time
|
|
import urllib.request
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
import psycopg2
|
|
|
|
PASS = Path("/root/.pg-superuser-pass").read_text().strip()
|
|
OUT = Path("/root/buryan-infra/ops/audit/AUDIT-360-FULL.json")
|
|
|
|
|
|
def sh(cmd, timeout=20):
|
|
try:
|
|
p = subprocess.run(cmd, shell=True, text=True, capture_output=True, timeout=timeout)
|
|
return p.stdout.strip()
|
|
except Exception:
|
|
return ""
|
|
|
|
|
|
def containers():
|
|
out = []
|
|
for line in sh("pct list").splitlines()[1:]:
|
|
parts = line.split()
|
|
if len(parts) < 3:
|
|
continue
|
|
vmid, status = parts[0], parts[1]
|
|
name = " ".join(parts[2:])
|
|
if status != "running":
|
|
continue
|
|
raw = sh("pct exec %s -- docker ps --format '{{json .}}'" % vmid, timeout=15)
|
|
for ln in raw.splitlines():
|
|
try:
|
|
d = json.loads(ln)
|
|
except Exception:
|
|
continue
|
|
out.append({"ct": vmid, "ct_name": name, "name": d.get("Names"), "image": d.get("Image"),
|
|
"state": d.get("State"), "status": d.get("Status"), "ports": d.get("Ports")})
|
|
return out
|
|
|
|
|
|
def cts():
|
|
out = []
|
|
for line in sh("pct list").splitlines()[1:]:
|
|
p = line.split()
|
|
if len(p) >= 3:
|
|
out.append({"vmid": p[0], "status": p[1], "name": " ".join(p[2:])})
|
|
return out
|
|
|
|
|
|
def vms():
|
|
out = []
|
|
for line in sh("qm list").splitlines()[1:]:
|
|
p = line.split()
|
|
if p:
|
|
out.append({"vmid": p[0], "name": " ".join(p[1:-2]) if len(p) > 3 else "", "raw": line})
|
|
return out
|
|
|
|
|
|
def systemd_services():
|
|
out = []
|
|
for line in sh("systemctl list-units --type=service --state=running --no-legend --plain").splitlines():
|
|
p = line.split(None, 4)
|
|
if p:
|
|
out.append({"unit": p[0], "load": p[1] if len(p) > 1 else "", "active": p[2] if len(p) > 2 else "",
|
|
"sub": p[3] if len(p) > 3 else "", "description": p[4] if len(p) > 4 else ""})
|
|
return out
|
|
|
|
|
|
def domains():
|
|
raw = sh("grep -RhoE 'server_name[^;]+' /etc/nginx/conf.d/*.conf 2>/dev/null")
|
|
vals = set()
|
|
for ln in raw.splitlines():
|
|
for x in ln.replace("server_name", "").split():
|
|
if x and x != "_":
|
|
vals.add(x)
|
|
return sorted(vals)
|
|
|
|
|
|
def routes():
|
|
out = []
|
|
for p in Path("/etc/nginx/conf.d").glob("*.conf"):
|
|
try:
|
|
lines = p.read_text(errors="ignore").splitlines()
|
|
except OSError:
|
|
continue
|
|
cur = None
|
|
depth = 0
|
|
for ln in lines:
|
|
if cur is None and re.search(r"\bserver\s*\{", ln):
|
|
cur = {"file": p.name, "names": [], "upstreams": []}
|
|
depth = ln.count("{") - ln.count("}")
|
|
continue
|
|
if cur is None:
|
|
continue
|
|
m = re.search(r"\bserver_name\s+([^;]+);", ln)
|
|
if m:
|
|
cur["names"].extend(x for x in m.group(1).split() if x != "_")
|
|
m = re.search(r"\bproxy_pass\s+([^;]+);", ln)
|
|
if m:
|
|
cur["upstreams"].append(m.group(1).strip())
|
|
depth += ln.count("{") - ln.count("}")
|
|
if depth <= 0:
|
|
if cur["names"] or cur["upstreams"]:
|
|
cur["names"] = sorted(set(cur["names"]))
|
|
cur["upstreams"] = sorted(set(cur["upstreams"]))
|
|
out.append(cur)
|
|
cur = None
|
|
return out
|
|
|
|
|
|
def owners():
|
|
try:
|
|
with urllib.request.urlopen("http://127.0.0.1:9160/api/audit", timeout=15) as r:
|
|
return json.load(r).get("owners") or []
|
|
except Exception:
|
|
return []
|
|
|
|
|
|
def arena_items(rid):
|
|
conn = psycopg2.connect(host="192.168.1.151", dbname="rag", user="postgres", password=PASS, client_encoding="UTF8")
|
|
cur = conn.cursor()
|
|
cur.execute("select id from audit.arena_runs order by id desc limit 1")
|
|
row = cur.fetchone()
|
|
if not row:
|
|
cur.close(); conn.close(); return []
|
|
cur.execute("select row_to_json(t) from audit.arena_items t where arena_run_id=%s order by score desc", (row[0],))
|
|
out = [r[0] for r in cur.fetchall()]
|
|
cur.close(); conn.close(); return out
|
|
|
|
|
|
def kuma():
|
|
raw = sh("curl -sS --max-time 8 http://192.168.1.107:3010/metrics")
|
|
out = []
|
|
for ln in raw.splitlines():
|
|
if ln.startswith("kuma_monitor_up{"):
|
|
m = re.search(r'id="([^"]+)".*name="([^"]+)".* (0|1)$', ln)
|
|
if m:
|
|
out.append({"id": m.group(1), "name": m.group(2), "up": m.group(3) == "1"})
|
|
return sorted(out, key=lambda x: x["name"])
|
|
|
|
|
|
def db_rows():
|
|
env = {"PGPASSWORD": PASS}
|
|
cmd = ("psql -h 192.168.1.151 -U postgres -d rag -X -A -F'|' -c "
|
|
"\"select datname,pg_size_pretty(pg_database_size(datname)) from pg_database where datistemplate=false order by pg_database_size(datname) desc\"")
|
|
p = subprocess.run(cmd, shell=True, text=True, capture_output=True, env={**__import__('os').environ, **env})
|
|
out = []
|
|
for ln in p.stdout.splitlines():
|
|
if "|" in ln and not ln.startswith("datname"):
|
|
d, s = ln.split("|", 1)
|
|
out.append({"name": d, "size": s})
|
|
return out
|
|
|
|
|
|
def backup_files():
|
|
out = []
|
|
for pattern in ("/mnt/archive/backups/db/*", "/mnt/backups/postgresql/*", "/mnt/backups/n8n/*",
|
|
"/mnt/archive/backups/audit/*"):
|
|
for p in Path("/").glob(pattern.lstrip("/")):
|
|
try:
|
|
if p.is_file():
|
|
out.append({"path": str(p), "size": p.stat().st_size, "mtime": p.stat().st_mtime})
|
|
except OSError:
|
|
pass
|
|
out.sort(key=lambda x: x["mtime"], reverse=True)
|
|
for x in out:
|
|
x["age_days"] = round((time.time() - x["mtime"]) / 86400, 2)
|
|
x.pop("mtime", None)
|
|
return out[:80]
|
|
|
|
|
|
def audit_rows():
|
|
conn = psycopg2.connect(host="192.168.1.151", dbname="rag", user="postgres", password=PASS, client_encoding="UTF8")
|
|
cur = conn.cursor()
|
|
cur.execute("select id from audit.runs order by id desc limit 1")
|
|
rid = cur.fetchone()[0]
|
|
cur.execute("select summary,started_at from audit.runs where id=%s", (rid,))
|
|
summary, started = cur.fetchone()
|
|
data = {"run_id": rid, "started_at": str(started), "summary": summary or {}}
|
|
for table, key in [("findings", "findings"), ("entities", "entities"), ("links", "links"),
|
|
("capabilities", "capabilities"), ("opportunities", "opportunities"),
|
|
("decisions", "decisions"), ("experiments", "experiments")]:
|
|
cur.execute("select row_to_json(t) from audit.%s t where run_id=%s" % (table, "%s") if table not in ("decisions", "experiments") else "select row_to_json(t) from audit.%s t" % table, (rid,))
|
|
data[key] = [r[0] for r in cur.fetchall()]
|
|
cur.execute("select row_to_json(t) from audit.arena_runs t order by id desc limit 1")
|
|
r = cur.fetchone()
|
|
data["arena_run"] = r[0] if r else None
|
|
cur.close(); conn.close()
|
|
try:
|
|
with urllib.request.urlopen("http://127.0.0.1:9160/api/graph", timeout=20) as r:
|
|
data["graph"] = json.load(r)
|
|
except Exception:
|
|
data["graph"] = {}
|
|
return data
|
|
|
|
|
|
def main():
|
|
a = audit_rows()
|
|
packet = {
|
|
"schema": "audit360/full/v1",
|
|
"generated_at": datetime.now(timezone.utc).isoformat(),
|
|
"host": {"name": "pve", "ip": "192.168.1.10", "audit_run_id": a["run_id"]},
|
|
"summary": {
|
|
"cts": 0, "containers": 0, "vms": 0, "systemd": 0, "domains": 0, "routes": 0,
|
|
"kuma": 0, "databases": 0, "owners": 0, "integrations": 0, "arena_items": 0,
|
|
"findings": len(a["findings"]), "capabilities": len(a["capabilities"]),
|
|
"decisions": len(a["decisions"]), "experiments": len(a["experiments"]),
|
|
"graph_nodes": len((a.get("graph") or {}).get("nodes") or []),
|
|
"graph_links": len((a.get("graph") or {}).get("links") or []),
|
|
},
|
|
"cts": cts(),
|
|
"vms": vms(),
|
|
"containers": containers(),
|
|
"systemd": systemd_services(),
|
|
"nginx_domains": domains(),
|
|
"routes": routes(),
|
|
"owners": owners(),
|
|
"integrations": a["links"],
|
|
"kuma": kuma(),
|
|
"databases": db_rows(),
|
|
"backups": backup_files(),
|
|
"arena_items": arena_items(a["run_id"]),
|
|
"audit": a,
|
|
}
|
|
packet["summary"]["cts"] = len(packet["cts"])
|
|
packet["summary"]["vms"] = len(packet["vms"])
|
|
packet["summary"]["containers"] = len(packet["containers"])
|
|
packet["summary"]["systemd"] = len(packet["systemd"])
|
|
packet["summary"]["domains"] = len(packet["nginx_domains"])
|
|
packet["summary"]["routes"] = len(packet["routes"])
|
|
packet["summary"]["kuma"] = len(packet["kuma"])
|
|
packet["summary"]["databases"] = len(packet["databases"])
|
|
packet["summary"]["owners"] = len(packet["owners"])
|
|
packet["summary"]["integrations"] = len(packet["integrations"])
|
|
packet["summary"]["arena_items"] = len(packet["arena_items"])
|
|
OUT.write_text(json.dumps(packet, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
print(json.dumps(packet["summary"], ensure_ascii=False))
|
|
print("bytes", OUT.stat().st_size)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|