Archived
1 parent
f5bdd7e21c
commit
affe28ad71
110 files changed
+52936
-14
No files matched your search
@@ -0,0 +1,452 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterator
|
||||
|
||||
from .settings import DATABASE_PATH
|
||||
|
||||
MAX_AUDIT_ROWS = 10000
|
||||
AUDIT_RETENTION_DAYS = 30
|
||||
AUDIT_RETENTION_SECONDS = AUDIT_RETENTION_DAYS * 24 * 60 * 60
|
||||
SECRET_KEYS = {
|
||||
"password",
|
||||
"new_password",
|
||||
"bot_token",
|
||||
"token",
|
||||
"private_key",
|
||||
"preshared_key",
|
||||
"psk",
|
||||
"control_token",
|
||||
"ssh_password",
|
||||
"ssh_private_key",
|
||||
"key_passphrase",
|
||||
"reset_code",
|
||||
"verification_code",
|
||||
"mfa_secret",
|
||||
"mfa_code",
|
||||
"totp_secret",
|
||||
"totp_code",
|
||||
"recovery_code",
|
||||
"recovery_codes",
|
||||
}
|
||||
|
||||
|
||||
SECRET_TEXT_PATTERNS = (
|
||||
re.compile(r"\b\d{6,12}:[A-Za-z0-9_-]{20,}\b"),
|
||||
re.compile(r"(?<![A-Za-z0-9+/])[A-Za-z0-9+/]{43}=(?![A-Za-z0-9+/=])"),
|
||||
re.compile(
|
||||
r"(?i)(password|bot[_ -]?token|private[_ -]?key|preshared[_ -]?key|psk|control[_ -]?token|ssh[_ -]?password|key[_ -]?passphrase|reset[_ -]?code|verification[_ -]?code|mfa[_ -]?(?:secret|code)|totp[_ -]?(?:secret|code)|recovery[_ -]?codes?)"
|
||||
r"(\s*[:=]\s*)([^\s,;]+)"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _redact_text(value: Any) -> str:
|
||||
text = str(value or "")
|
||||
text = SECRET_TEXT_PATTERNS[0].sub("[redacted]", text)
|
||||
text = SECRET_TEXT_PATTERNS[1].sub("[redacted]", text)
|
||||
text = SECRET_TEXT_PATTERNS[2].sub(lambda match: f"{match.group(1)}{match.group(2)}[redacted]", text)
|
||||
return text
|
||||
|
||||
|
||||
def _connect() -> sqlite3.Connection:
|
||||
Path(DATABASE_PATH).parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = sqlite3.connect(DATABASE_PATH, timeout=10)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
return conn
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _connection() -> Iterator[sqlite3.Connection]:
|
||||
conn = _connect()
|
||||
try:
|
||||
with conn:
|
||||
yield conn
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _prune_audit(conn: sqlite3.Connection, now: int | None = None) -> None:
|
||||
cutoff = int(now or time.time()) - AUDIT_RETENTION_SECONDS
|
||||
conn.execute("DELETE FROM audit_log WHERE created_at<?", (cutoff,))
|
||||
stale = conn.execute(
|
||||
"SELECT id FROM audit_log ORDER BY id DESC LIMIT 1 OFFSET ?",
|
||||
(MAX_AUDIT_ROWS,),
|
||||
).fetchone()
|
||||
if stale:
|
||||
conn.execute("DELETE FROM audit_log WHERE id<=?", (int(stale["id"]),))
|
||||
|
||||
|
||||
def init_audit_database() -> None:
|
||||
with _connection() as conn:
|
||||
conn.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS audit_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
created_at INTEGER NOT NULL,
|
||||
username TEXT NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
object TEXT NOT NULL DEFAULT '',
|
||||
result TEXT NOT NULL DEFAULT '',
|
||||
details TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_log_created_at ON audit_log(created_at DESC);
|
||||
CREATE TABLE IF NOT EXISTS audit_wg_connection_state (
|
||||
interface TEXT NOT NULL,
|
||||
public_key TEXT NOT NULL,
|
||||
latest_handshake INTEGER NOT NULL DEFAULT 0,
|
||||
endpoint TEXT NOT NULL DEFAULT '',
|
||||
PRIMARY KEY(interface, public_key)
|
||||
);
|
||||
"""
|
||||
)
|
||||
_prune_audit(conn)
|
||||
|
||||
|
||||
def _clean_text(value: Any, limit: int = 500) -> str:
|
||||
text = _redact_text(value).strip()
|
||||
text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f]+", " ", text)
|
||||
return text[:limit]
|
||||
|
||||
|
||||
def _scrub(value: Any, key: str = "") -> Any:
|
||||
key_l = key.lower()
|
||||
if any(secret in key_l for secret in SECRET_KEYS):
|
||||
return "[redacted]"
|
||||
if isinstance(value, dict):
|
||||
return {str(k): _scrub(v, str(k)) for k, v in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [_scrub(item, key) for item in value[:50]]
|
||||
if isinstance(value, str):
|
||||
return _redact_text(value)
|
||||
if isinstance(value, (int, float, bool)) or value is None:
|
||||
return value
|
||||
return str(value)
|
||||
|
||||
|
||||
def write_audit(
|
||||
username: str,
|
||||
action: str,
|
||||
*,
|
||||
object: str = "",
|
||||
result: str = "ok",
|
||||
details: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
init_audit_database()
|
||||
payload = ""
|
||||
if details:
|
||||
payload = json.dumps(_scrub(details), ensure_ascii=False, sort_keys=True)[:4000]
|
||||
with _connection() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO audit_log(created_at,username,action,object,result,details) VALUES(?,?,?,?,?,?)",
|
||||
(
|
||||
int(time.time()),
|
||||
_clean_text(username, 120) or "system",
|
||||
_clean_text(action, 160),
|
||||
_clean_text(object, 240),
|
||||
_clean_text(result, 240),
|
||||
payload,
|
||||
),
|
||||
)
|
||||
_prune_audit(conn)
|
||||
|
||||
|
||||
def list_audit(limit: int = 500) -> list[dict[str, Any]]:
|
||||
init_audit_database()
|
||||
limit = min(max(int(limit or 500), 1), 1000)
|
||||
with _connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT id,created_at,username,action,object,result,details
|
||||
FROM audit_log
|
||||
ORDER BY created_at DESC,id DESC
|
||||
LIMIT ?
|
||||
""",
|
||||
(limit,),
|
||||
).fetchall()
|
||||
return [dict(row) for row in rows]
|
||||
|
||||
|
||||
def list_audit_page(*, before_id: int = 0, after_id: int = 0, limit: int = 20) -> dict[str, Any]:
|
||||
"""Read-only, cursor-based history for Telegram. No unredacted details are returned."""
|
||||
init_audit_database()
|
||||
limit = min(max(int(limit), 1), 20)
|
||||
before_id = max(int(before_id or 0), 0)
|
||||
after_id = max(int(after_id or 0), 0)
|
||||
if before_id and after_id:
|
||||
raise ValueError("Choose one audit cursor")
|
||||
with _connection() as conn:
|
||||
if before_id:
|
||||
rows = conn.execute(
|
||||
"SELECT id,created_at,username,action,object,result FROM audit_log WHERE id < ? ORDER BY id DESC LIMIT ?",
|
||||
(before_id, limit),
|
||||
).fetchall()
|
||||
elif after_id:
|
||||
# Fetch the closest newer records, not the newest records overall.
|
||||
rows = list(reversed(conn.execute(
|
||||
"SELECT id,created_at,username,action,object,result FROM audit_log WHERE id > ? ORDER BY id ASC LIMIT ?",
|
||||
(after_id, limit),
|
||||
).fetchall()))
|
||||
else:
|
||||
rows = conn.execute(
|
||||
"SELECT id,created_at,username,action,object,result FROM audit_log ORDER BY id DESC LIMIT ?",
|
||||
(limit,),
|
||||
).fetchall()
|
||||
items = [dict(row) for row in rows]
|
||||
if not items:
|
||||
return {"items": [], "has_older": False, "has_newer": False}
|
||||
first, last = items[0]["id"], items[-1]["id"]
|
||||
has_older = conn.execute("SELECT 1 FROM audit_log WHERE id < ? LIMIT 1", (last,)).fetchone() is not None
|
||||
has_newer = conn.execute("SELECT 1 FROM audit_log WHERE id > ? LIMIT 1", (first,)).fetchone() is not None
|
||||
return {"items": items, "has_older": has_older, "has_newer": has_newer}
|
||||
|
||||
|
||||
def _endpoint_ip(endpoint: Any) -> str:
|
||||
text = str(endpoint or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
if text.startswith("[") and "]" in text:
|
||||
candidate = text[1:text.index("]")]
|
||||
else:
|
||||
candidate = text.rsplit(":", 1)[0] if ":" in text else text
|
||||
try:
|
||||
return str(ipaddress.ip_address(candidate))
|
||||
except ValueError:
|
||||
return candidate[:120]
|
||||
|
||||
|
||||
def record_wireguard_connections(
|
||||
interface: str,
|
||||
peers: list[dict[str, Any]],
|
||||
online_threshold_seconds: int = 180,
|
||||
) -> None:
|
||||
init_audit_database()
|
||||
now = int(time.time())
|
||||
fresh_window = max(180, int(online_threshold_seconds or 180))
|
||||
reconnect_gap = max(300, fresh_window * 2)
|
||||
seen_public_keys: set[str] = set()
|
||||
with _connection() as conn:
|
||||
for peer in peers:
|
||||
public_key = str(peer.get("public_key") or "").strip()
|
||||
if not public_key:
|
||||
continue
|
||||
# A configured peer must remain in the durable last-seen state even
|
||||
# when wg(8) currently reports handshake=0 after an interface or host
|
||||
# restart. Only remove state when the peer itself disappears.
|
||||
seen_public_keys.add(public_key)
|
||||
latest_handshake = int(peer.get("latest_handshake") or 0)
|
||||
endpoint = str(peer.get("endpoint") or "").strip()
|
||||
if latest_handshake <= 0 or not endpoint:
|
||||
continue
|
||||
previous = conn.execute(
|
||||
"""
|
||||
SELECT latest_handshake,endpoint
|
||||
FROM audit_wg_connection_state
|
||||
WHERE interface=? AND public_key=?
|
||||
""",
|
||||
(interface, public_key),
|
||||
).fetchone()
|
||||
previous_handshake = int(previous["latest_handshake"] or 0) if previous else 0
|
||||
previous_endpoint_ip = _endpoint_ip(previous["endpoint"]) if previous else ""
|
||||
endpoint_ip = _endpoint_ip(endpoint)
|
||||
if previous and latest_handshake <= previous_handshake and endpoint_ip == previous_endpoint_ip:
|
||||
continue
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO audit_wg_connection_state(interface,public_key,latest_handshake,endpoint)
|
||||
VALUES(?,?,?,?)
|
||||
ON CONFLICT(interface,public_key) DO UPDATE SET
|
||||
latest_handshake=excluded.latest_handshake,
|
||||
endpoint=excluded.endpoint
|
||||
""",
|
||||
(interface, public_key, latest_handshake, endpoint),
|
||||
)
|
||||
is_fresh = 0 <= now - latest_handshake <= fresh_window
|
||||
endpoint_changed = bool(previous and endpoint_ip and endpoint_ip != previous_endpoint_ip)
|
||||
reconnected = bool(previous and latest_handshake - previous_handshake > reconnect_gap)
|
||||
if not is_fresh or (previous and not endpoint_changed and not reconnected):
|
||||
continue
|
||||
name = _clean_text(peer.get("name") or "WireGuard client", 160)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO audit_log(created_at,username,action,object,result,details)
|
||||
VALUES(?,?,?,?,?,?)
|
||||
""",
|
||||
(
|
||||
now,
|
||||
"system",
|
||||
"wireguard.client_connected",
|
||||
f"{interface} · {name}",
|
||||
f"endpoint {endpoint_ip}" if endpoint_ip else "connected",
|
||||
json.dumps({"endpoint_ip": endpoint_ip, "handshake_at": latest_handshake}, ensure_ascii=False),
|
||||
),
|
||||
)
|
||||
state_rows = conn.execute(
|
||||
"SELECT public_key FROM audit_wg_connection_state WHERE interface=?",
|
||||
(interface,),
|
||||
).fetchall()
|
||||
for state in state_rows:
|
||||
if str(state["public_key"]) not in seen_public_keys:
|
||||
conn.execute(
|
||||
"DELETE FROM audit_wg_connection_state WHERE interface=? AND public_key=?",
|
||||
(interface, str(state["public_key"])),
|
||||
)
|
||||
_prune_audit(conn, now)
|
||||
|
||||
def wireguard_last_seen(interface: str, public_key: str, name: str = "") -> dict[str, Any] | None:
|
||||
"""Return durable last-seen state for a configured WireGuard peer.
|
||||
|
||||
audit_wg_connection_state is intentionally not subject to the 30-day audit
|
||||
retention window. For installations affected by the old state-pruning bug,
|
||||
a recent client_connected audit event is used once as a migration fallback
|
||||
and is then promoted back into the durable state table.
|
||||
"""
|
||||
init_audit_database()
|
||||
iface = str(interface or "").strip()
|
||||
key = str(public_key or "").strip()
|
||||
if not iface or not key:
|
||||
return None
|
||||
with _connection() as conn:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT latest_handshake,endpoint
|
||||
FROM audit_wg_connection_state
|
||||
WHERE interface=? AND public_key=?
|
||||
""",
|
||||
(iface, key),
|
||||
).fetchone()
|
||||
if row and int(row["latest_handshake"] or 0) > 0:
|
||||
return {
|
||||
"latest_handshake": int(row["latest_handshake"] or 0),
|
||||
"endpoint": str(row["endpoint"] or ""),
|
||||
"source": "state",
|
||||
}
|
||||
|
||||
peer_name = _clean_text(name, 160)
|
||||
if not peer_name:
|
||||
return None
|
||||
event = conn.execute(
|
||||
"""
|
||||
SELECT created_at,details
|
||||
FROM audit_log
|
||||
WHERE action='wireguard.client_connected' AND object=?
|
||||
ORDER BY created_at DESC,id DESC
|
||||
LIMIT 1
|
||||
""",
|
||||
(f"{iface} · {peer_name}",),
|
||||
).fetchone()
|
||||
if not event:
|
||||
return None
|
||||
handshake_at = int(event["created_at"] or 0)
|
||||
endpoint = ""
|
||||
try:
|
||||
details = json.loads(str(event["details"] or "{}"))
|
||||
handshake_at = int(details.get("handshake_at") or handshake_at)
|
||||
endpoint = str(details.get("endpoint_ip") or "")
|
||||
except (TypeError, ValueError, json.JSONDecodeError):
|
||||
pass
|
||||
if handshake_at <= 0:
|
||||
return None
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO audit_wg_connection_state(interface,public_key,latest_handshake,endpoint)
|
||||
VALUES(?,?,?,?)
|
||||
ON CONFLICT(interface,public_key) DO UPDATE SET
|
||||
latest_handshake=MAX(audit_wg_connection_state.latest_handshake, excluded.latest_handshake),
|
||||
endpoint=CASE
|
||||
WHEN excluded.latest_handshake>=audit_wg_connection_state.latest_handshake THEN excluded.endpoint
|
||||
ELSE audit_wg_connection_state.endpoint
|
||||
END
|
||||
""",
|
||||
(iface, key, handshake_at, endpoint),
|
||||
)
|
||||
return {"latest_handshake": handshake_at, "endpoint": endpoint, "source": "audit"}
|
||||
|
||||
|
||||
def merge_wireguard_last_seen(interface: str, peers: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Fill missing runtime handshakes from durable history in one DB session.
|
||||
|
||||
The previous implementation opened/initialized SQLite once for every
|
||||
offline peer. Clients and Dashboard call this on every refresh, so a
|
||||
handful of offline peers could make navigation feel much heavier than the
|
||||
actual WireGuard snapshot.
|
||||
"""
|
||||
missing = [
|
||||
peer for peer in peers
|
||||
if int(peer.get("latest_handshake") or 0) <= 0 and str(peer.get("public_key") or "").strip()
|
||||
]
|
||||
if not missing:
|
||||
return peers
|
||||
|
||||
init_audit_database()
|
||||
iface = str(interface or "").strip()
|
||||
if not iface:
|
||||
return peers
|
||||
|
||||
with _connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT public_key,latest_handshake,endpoint
|
||||
FROM audit_wg_connection_state
|
||||
WHERE interface=?
|
||||
""",
|
||||
(iface,),
|
||||
).fetchall()
|
||||
states = {str(row["public_key"]): row for row in rows}
|
||||
|
||||
for peer in missing:
|
||||
key = str(peer.get("public_key") or "").strip()
|
||||
row = states.get(key)
|
||||
handshake_at = int(row["latest_handshake"] or 0) if row else 0
|
||||
endpoint = str(row["endpoint"] or "") if row else ""
|
||||
|
||||
if handshake_at <= 0:
|
||||
peer_name = _clean_text(peer.get("name") or "", 160)
|
||||
if peer_name:
|
||||
event = conn.execute(
|
||||
"""
|
||||
SELECT created_at,details
|
||||
FROM audit_log
|
||||
WHERE action='wireguard.client_connected' AND object=?
|
||||
ORDER BY created_at DESC,id DESC
|
||||
LIMIT 1
|
||||
""",
|
||||
(f"{iface} · {peer_name}",),
|
||||
).fetchone()
|
||||
if event:
|
||||
handshake_at = int(event["created_at"] or 0)
|
||||
try:
|
||||
details = json.loads(str(event["details"] or "{}"))
|
||||
handshake_at = int(details.get("handshake_at") or handshake_at)
|
||||
endpoint = str(details.get("endpoint_ip") or "")
|
||||
except (TypeError, ValueError, json.JSONDecodeError):
|
||||
pass
|
||||
if handshake_at > 0:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO audit_wg_connection_state(interface,public_key,latest_handshake,endpoint)
|
||||
VALUES(?,?,?,?)
|
||||
ON CONFLICT(interface,public_key) DO UPDATE SET
|
||||
latest_handshake=MAX(audit_wg_connection_state.latest_handshake, excluded.latest_handshake),
|
||||
endpoint=CASE
|
||||
WHEN excluded.latest_handshake>=audit_wg_connection_state.latest_handshake THEN excluded.endpoint
|
||||
ELSE audit_wg_connection_state.endpoint
|
||||
END
|
||||
""",
|
||||
(iface, key, handshake_at, endpoint),
|
||||
)
|
||||
|
||||
if handshake_at <= 0:
|
||||
continue
|
||||
peer["latest_handshake"] = handshake_at
|
||||
peer["last_seen_historical"] = True
|
||||
if endpoint:
|
||||
peer["last_seen_endpoint"] = endpoint
|
||||
return peers
|
||||
Reference in new issue
Block a user