#!/usr/bin/env python3 from __future__ import annotations import fcntl import hashlib import ipaddress import json import os import re import secrets import shutil import shlex import socket import sqlite3 import subprocess import sys import tarfile import tempfile import time import urllib.error import urllib.parse import urllib.request import unicodedata from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime, timezone from pathlib import Path from typing import Any ALLOWED_ACTIONS = {"snapshot", "interfaces_list", "interface_meta_set", "interface_delete", "metrics_sample", "metrics_history", "diagnostics", "network_trace", "wireguard_start", "wireguard_stop", "wireguard_restart", "install_wireguard", "create_server", "create_client", "update_client", "delete_client", "rotate_client_credentials", "expire_clients", "client_config", "group_create", "group_update", "group_delete", "raw_config_get", "raw_config_apply", "server_settings_apply", "route_create", "route_update", "route_delete", "access_rule_create", "access_rule_update", "access_rule_delete", "migration_backup_create", "migration_restore", "update_check", "update_notice", "update_status", "update_schedule", "update_apply", "traffic_reset", "https_status", "https_ports", "https_issue", "https_enable", "https_disable", "https_switch_commit"} ALLOWED_ACTIONS.update({"extended_snat_get", "extended_snat_apply"}) ALLOWED_ACTIONS.add("extended_host_ips") ALLOWED_ACTIONS.update({"extended_listen_get", "extended_listen_apply"}) ALLOWED_ACTIONS.update({"extended_ip_groups_get", "extended_ip_groups_set", "extended_forward_get", "extended_forward_add", "extended_forward_delete"}) ALLOWED_ACTIONS.add("extended_forward_update") ALLOWED_ACTIONS.update({"update_file_schedule", "update_file_apply"}) ALLOWED_IFACE_RE = re.compile(r"^[A-Za-z0-9_.-]{1,15}$") INTERNAL_INTERFACE_PREFIXES = ("wgrly", "wgnode") LOCK_PATH = Path("/run/wgtools.lock") WG_DIR = Path("/etc/wireguard") DATA_DIR = Path("/var/lib/wgtools") CLIENT_DIR = DATA_DIR / "clients" GROUPS_PATH = DATA_DIR / "groups.json" BACKUP_DIR = DATA_DIR / "backups" DATABASE_PATH = DATA_DIR / "wgtools.db" METRICS_CACHE = Path("/run/wgtools-metrics.json") METRICS_HISTORY_PATH = DATA_DIR / "metrics-history.json" METRICS_HISTORY_STAMP = Path("/run/wgtools-metrics-history.stamp") METRICS_HISTORY_LOCK = Path("/run/wgtools-metrics-history.lock") METRICS_HISTORY_SECONDS = 24 * 60 * 60 METRICS_HISTORY_SAMPLE_SECONDS = 60 TRACE_GEO_CACHE_PATH = Path("/run/wgtools-trace-geo.json") TRACE_GEO_CACHE_TTL = 24 * 60 * 60 EXPORT_DIR = DATA_DIR / "exports" MIGRATION_SAFETY_DIR = DATA_DIR / "migration-backups" SYSCTL_FILE = Path("/etc/sysctl.d/99-wgtools-wireguard.conf") MIGRATION_FORMAT_VERSION = 4 MIGRATION_MAX_BYTES = 64 * 1024 * 1024 APP_DIR = Path("/opt/wgtools") ENV_FILE = Path("/etc/wgtools/wgtools.env") HELPER_INSTALL_PATH = Path("/usr/local/libexec/wgtools-helper") SYSTEMD_DIR = Path("/etc/systemd/system") UPDATE_STATUS_PATH = DATA_DIR / "update-status.json" UPDATE_NOTICE_PATH = DATA_DIR / "update-notice.json" UPDATE_NOTICE_MAX_AGE = 15 * 60 UPDATE_LOCK_PATH = Path("/run/wgtools-update.lock") UPDATE_BACKUP_DIR = DATA_DIR / "update-backups" INTERFACES_META_PATH = DATA_DIR / "interfaces.json" EXT_IP_GROUPS_PATH = DATA_DIR / "extended-ip-groups.json" HTTPS_ENV_FILE = Path("/etc/wgtools/https.env") HTTPS_STATE_FILE = Path("/etc/wgtools/https.json") HTTPS_CERT_NAME = "wgtools" HTTPS_CERT_DIR = Path("/etc/letsencrypt/live") / HTTPS_CERT_NAME HTTPS_CERT_FILE = HTTPS_CERT_DIR / "fullchain.pem" HTTPS_KEY_FILE = HTTPS_CERT_DIR / "privkey.pem" HTTPS_RENEW_TIMER = "wgtools-certbot-renew.timer" CERTBOT_PATH = APP_DIR / ".venv" / "bin" / "certbot" def run(cmd: list[str], timeout: int = 8, input_text: str | None = None) -> tuple[int, str, str]: try: p = subprocess.run( cmd, input=input_text, capture_output=True, text=True, timeout=timeout, check=False, env={**os.environ, "LC_ALL": "C"}, ) return p.returncode, p.stdout.strip(), p.stderr.strip() except FileNotFoundError as exc: return 127, "", str(exc) except subprocess.TimeoutExpired: return 124, "", f"Command timed out after {timeout}s: {' '.join(cmd)}" except Exception as exc: return 127, "", str(exc) def read_app_setting(key: str, default: int) -> int: try: if not DATABASE_PATH.exists(): return default conn = sqlite3.connect(DATABASE_PATH) try: row = conn.execute("SELECT value FROM app_settings WHERE key=?", (key,)).fetchone() finally: conn.close() return int(row[0]) if row else default except Exception: return default def backup_retention() -> int: return max(1, min(read_app_setting("backup_retention", 20), 200)) def _audit_safe_text(value: Any, limit: int = 1200) -> str: text = str(value or "") text = re.sub(r"\b\d{6,12}:[A-Za-z0-9_-]{20,}\b", "[redacted]", text) text = re.sub(r"(? None: """Best-effort audit writer for privileged/background helper jobs. Update installation continues while the web service restarts, so lifecycle events cannot depend on the FastAPI process being alive. """ try: DATA_DIR.mkdir(parents=True, exist_ok=True) conn = sqlite3.connect(DATABASE_PATH, timeout=10) try: with conn: conn.execute( """ 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 '' ) """ ) payload = "" if details: cleaned = {str(k): _audit_safe_text(v, 1000) for k, v in details.items()} payload = json.dumps(cleaned, ensure_ascii=False, sort_keys=True)[:4000] conn.execute( "INSERT INTO audit_log(created_at,username,action,object,result,details) VALUES(?,?,?,?,?,?)", ( int(time.time()), "system", _audit_safe_text(action, 160), _audit_safe_text(object, 240), _audit_safe_text(result, 1200), payload, ), ) finally: conn.close() except Exception: # Audit must never make an update fail. pass def _traffic_connect() -> sqlite3.Connection: DATA_DIR.mkdir(parents=True, exist_ok=True) conn = sqlite3.connect(DATABASE_PATH, timeout=10) conn.row_factory = sqlite3.Row conn.execute("PRAGMA journal_mode=WAL") conn.execute( """ CREATE TABLE IF NOT EXISTS wg_traffic_counters ( interface TEXT NOT NULL, public_key TEXT NOT NULL, runtime_rx INTEGER NOT NULL DEFAULT 0, runtime_tx INTEGER NOT NULL DEFAULT 0, total_rx INTEGER NOT NULL DEFAULT 0, total_tx INTEGER NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(interface, public_key) ) """ ) return conn def _traffic_runtime_peers(iface: str) -> list[dict[str, Any]]: dump = wg_dump(iface) if not dump.get("running"): return [] return list((dump.get("peers") or {}).values()) def persist_wireguard_traffic(iface: str, peers: list[dict[str, Any]]) -> dict[str, int]: """Merge WireGuard's resettable runtime counters into durable totals. WireGuard transfer counters return to zero after an interface/peer reset. We retain the previous runtime sample and only add the positive delta. If the runtime value goes backwards, the counter was reset and the new value is the first delta of the new runtime session. """ now = int(time.time()) conn = _traffic_connect() try: # Snapshot requests can arrive from the UI and background sampler at # the same time. Take the write lock before reading baselines so an # older concurrent sample can never overwrite a newer lifetime total. conn.execute("BEGIN IMMEDIATE") try: for peer in peers: public_key = str(peer.get("public_key") or "").strip() # Config-only peers do not contain runtime counters. Treating # that as zero would double count the next time wg comes up. if not public_key or "rx_bytes" not in peer or "tx_bytes" not in peer: continue runtime_rx = max(0, int(peer.get("rx_bytes") or 0)) runtime_tx = max(0, int(peer.get("tx_bytes") or 0)) row = conn.execute( "SELECT runtime_rx,runtime_tx,total_rx,total_tx FROM wg_traffic_counters WHERE interface=? AND public_key=?", (iface, public_key), ).fetchone() if row is None: total_rx, total_tx = runtime_rx, runtime_tx else: old_rx = max(0, int(row["runtime_rx"] or 0)) old_tx = max(0, int(row["runtime_tx"] or 0)) total_rx = max(0, int(row["total_rx"] or 0)) + (runtime_rx - old_rx if runtime_rx >= old_rx else runtime_rx) total_tx = max(0, int(row["total_tx"] or 0)) + (runtime_tx - old_tx if runtime_tx >= old_tx else runtime_tx) conn.execute( """ INSERT INTO wg_traffic_counters(interface,public_key,runtime_rx,runtime_tx,total_rx,total_tx,updated_at) VALUES(?,?,?,?,?,?,?) ON CONFLICT(interface,public_key) DO UPDATE SET runtime_rx=excluded.runtime_rx, runtime_tx=excluded.runtime_tx, total_rx=excluded.total_rx, total_tx=excluded.total_tx, updated_at=excluded.updated_at """, (iface, public_key, runtime_rx, runtime_tx, total_rx, total_tx, now), ) totals = conn.execute( "SELECT COALESCE(SUM(total_rx),0) AS rx, COALESCE(SUM(total_tx),0) AS tx FROM wg_traffic_counters WHERE interface=?", (iface,), ).fetchone() conn.commit() return {"rx_bytes": int(totals["rx"] or 0), "tx_bytes": int(totals["tx"] or 0)} except Exception: conn.rollback() raise finally: conn.close() def merge_wireguard_traffic(iface: str, peers: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], dict[str, int]]: totals = persist_wireguard_traffic(iface, peers) conn = _traffic_connect() try: rows = { str(row["public_key"]): row for row in conn.execute( "SELECT public_key,total_rx,total_tx FROM wg_traffic_counters WHERE interface=?", (iface,), ).fetchall() } finally: conn.close() merged: list[dict[str, Any]] = [] for peer in peers: item = dict(peer) row = rows.get(str(item.get("public_key") or "")) if row is not None: item["rx_bytes"] = int(row["total_rx"] or 0) item["tx_bytes"] = int(row["total_tx"] or 0) else: item["rx_bytes"] = int(item.get("rx_bytes") or 0) item["tx_bytes"] = int(item.get("tx_bytes") or 0) merged.append(item) return merged, totals def capture_wireguard_traffic(iface: str) -> dict[str, int]: return persist_wireguard_traffic(iface, _traffic_runtime_peers(iface)) def reset_wireguard_traffic(iface: str) -> dict[str, Any]: require_valid_iface(iface) runtime_peers = _traffic_runtime_peers(iface) now = int(time.time()) conn = _traffic_connect() try: conn.execute("BEGIN IMMEDIATE") try: # This intentionally removes rows for deleted clients too: the # Dashboard counter represents all traffic since the last reset. conn.execute("DELETE FROM wg_traffic_counters WHERE interface=?", (iface,)) for peer in runtime_peers: public_key = str(peer.get("public_key") or "").strip() if not public_key: continue runtime_rx = max(0, int(peer.get("rx_bytes") or 0)) runtime_tx = max(0, int(peer.get("tx_bytes") or 0)) conn.execute( "INSERT INTO wg_traffic_counters(interface,public_key,runtime_rx,runtime_tx,total_rx,total_tx,updated_at) VALUES(?,?,?,?,0,0,?)", (iface, public_key, runtime_rx, runtime_tx, now), ) conn.commit() except Exception: conn.rollback() raise finally: conn.close() return {"ok": True, "interface": iface, "rx_bytes": 0, "tx_bytes": 0} def delete_wireguard_traffic(iface: str) -> None: try: conn = _traffic_connect() try: with conn: conn.execute("DELETE FROM wg_traffic_counters WHERE interface=?", (iface,)) finally: conn.close() except Exception: pass def installed_relay_for_interface(vps_id: str, iface: str) -> dict[str, Any] | None: wanted = str(vps_id or "").strip() if not wanted or not DATABASE_PATH.exists(): return None try: conn = sqlite3.connect(DATABASE_PATH) conn.row_factory = sqlite3.Row try: row = conn.execute( """SELECT id,name,host,endpoint_domain,relay_port,status,published_interface FROM vps_relays WHERE id=?""", (wanted,), ).fetchone() finally: conn.close() except sqlite3.Error: return None if not row: return None item = dict(row) if str(item.get("status") or "") != "installed": return None if str(item.get("published_interface") or "") != iface: return None return item def relay_client_endpoint(item: dict[str, Any]) -> str: host = str(item.get("endpoint_domain") or item.get("host") or "").strip() try: port = int(item.get("relay_port") or 0) except (TypeError, ValueError): port = 0 if not host or not (1 <= port <= 65535): raise ValueError("Selected VPS Relay does not have a valid public endpoint") return f"{host}:{port}" def _read_proc_cpu() -> tuple[int, int]: line = Path("/proc/stat").read_text(encoding="utf-8", errors="replace").splitlines()[0] parts = line.split()[1:] values = [int(x) for x in parts if x.isdigit()] total = sum(values) idle = (values[3] if len(values) > 3 else 0) + (values[4] if len(values) > 4 else 0) return total, idle def _read_meminfo() -> dict[str, int]: result: dict[str, int] = {} for line in Path("/proc/meminfo").read_text(encoding="utf-8", errors="replace").splitlines(): if ":" not in line: continue key, value = line.split(":", 1) token = value.strip().split()[0] if value.strip() else "0" if token.isdigit(): result[key] = int(token) * 1024 return result def _read_net_bytes(interface: str | None) -> tuple[int, int]: if not interface: return 0, 0 base = Path("/sys/class/net") / interface / "statistics" try: return int((base / "rx_bytes").read_text().strip()), int((base / "tx_bytes").read_text().strip()) except Exception: return 0, 0 def system_metrics(uplink: str | None) -> dict[str, Any]: now = time.time() cpu_total, cpu_idle = _read_proc_cpu() rx_bytes, tx_bytes = _read_net_bytes(uplink) previous: dict[str, Any] = {} try: previous = json.loads(METRICS_CACHE.read_text(encoding="utf-8")) if METRICS_CACHE.exists() else {} except Exception: previous = {} cpu_percent = previous.get("cpu_percent") rx_rate = float(previous.get("rx_rate") or 0.0) tx_rate = float(previous.get("tx_rate") or 0.0) dt = now - float(previous.get("timestamp") or 0.0) if not previous: time.sleep(0.08) total2, idle2 = _read_proc_cpu() delta_total = total2 - cpu_total delta_idle = idle2 - cpu_idle if delta_total > 0: cpu_percent = max(0.0, min(100.0, 100.0 * (1.0 - delta_idle / delta_total))) cpu_total, cpu_idle = total2, idle2 now = time.time() elif dt >= 0.5: delta_total = cpu_total - int(previous.get("cpu_total") or cpu_total) delta_idle = cpu_idle - int(previous.get("cpu_idle") or cpu_idle) if delta_total > 0: cpu_percent = max(0.0, min(100.0, 100.0 * (1.0 - delta_idle / delta_total))) if str(previous.get("uplink") or "") == str(uplink or ""): rx_rate = max(0.0, (rx_bytes - int(previous.get("rx_bytes") or rx_bytes)) / dt) tx_rate = max(0.0, (tx_bytes - int(previous.get("tx_bytes") or tx_bytes)) / dt) cache = { "timestamp": now, "cpu_total": cpu_total, "cpu_idle": cpu_idle, "cpu_percent": cpu_percent, "uplink": uplink or "", "rx_bytes": rx_bytes, "tx_bytes": tx_bytes, "rx_rate": rx_rate, "tx_rate": tx_rate, } try: METRICS_CACHE.write_text(json.dumps(cache), encoding="utf-8") os.chmod(METRICS_CACHE, 0o600) except Exception: pass mem = _read_meminfo() total_mem = int(mem.get("MemTotal") or 0) available_mem = int(mem.get("MemAvailable") or mem.get("MemFree") or 0) used_mem = max(0, total_mem - available_mem) mem_percent = (100.0 * used_mem / total_mem) if total_mem else 0.0 load1, load5, load15 = os.getloadavg() if hasattr(os, "getloadavg") else (0.0, 0.0, 0.0) try: uptime_seconds = int(float(Path("/proc/uptime").read_text().split()[0])) except Exception: uptime_seconds = 0 disk = shutil.disk_usage("/") return { "cpu": { "percent": round(float(cpu_percent), 1) if cpu_percent is not None else None, "cores": int(os.cpu_count() or 1), "load1": round(load1, 2), "load5": round(load5, 2), "load15": round(load15, 2), }, "memory": { "total_bytes": total_mem, "used_bytes": used_mem, "available_bytes": available_mem, "percent": round(mem_percent, 1), }, "network": { "interface": uplink, "rx_bytes": rx_bytes, "tx_bytes": tx_bytes, "rx_bytes_per_second": round(rx_rate, 1), "tx_bytes_per_second": round(tx_rate, 1), }, "disk": { "total_bytes": disk.total, "used_bytes": disk.used, "free_bytes": disk.free, "percent": round(100.0 * disk.used / disk.total, 1) if disk.total else 0.0, }, "uptime_seconds": uptime_seconds, } def _load_metrics_history() -> list[dict[str, Any]]: try: raw = json.loads(METRICS_HISTORY_PATH.read_text(encoding="utf-8")) if METRICS_HISTORY_PATH.exists() else [] except Exception: raw = [] if not isinstance(raw, list): return [] now = int(time.time()) cutoff = now - METRICS_HISTORY_SECONDS result: list[dict[str, Any]] = [] for item in raw: if not isinstance(item, dict): continue try: ts = int(item.get("timestamp") or 0) except (TypeError, ValueError): continue if ts < cutoff or ts > now + 300: continue try: result.append({ "timestamp": ts, "cpu": round(float(item.get("cpu") or 0.0), 1), "memory": round(float(item.get("memory") or 0.0), 1), "rx": round(max(0.0, float(item.get("rx") or 0.0)), 1), "tx": round(max(0.0, float(item.get("tx") or 0.0)), 1), }) except (TypeError, ValueError): continue result.sort(key=lambda item: item["timestamp"]) return result[-1600:] def _record_metrics_history(metrics: dict[str, Any], *, force: bool = False) -> None: METRICS_HISTORY_LOCK.parent.mkdir(parents=True, exist_ok=True) with METRICS_HISTORY_LOCK.open("w") as lock: fcntl.flock(lock.fileno(), fcntl.LOCK_EX) now = int(time.time()) if not force: try: last = int(METRICS_HISTORY_STAMP.read_text(encoding="utf-8").strip() or 0) except Exception: last = 0 if now - last < METRICS_HISTORY_SAMPLE_SECONDS: return cpu = metrics.get("cpu") or {} memory = metrics.get("memory") or {} network = metrics.get("network") or {} point = { "timestamp": now, "cpu": round(float(cpu.get("percent") or 0.0), 1), "memory": round(float(memory.get("percent") or 0.0), 1), "rx": round(max(0.0, float(network.get("rx_bytes_per_second") or 0.0)), 1), "tx": round(max(0.0, float(network.get("tx_bytes_per_second") or 0.0)), 1), } history = _load_metrics_history() if history and now - int(history[-1].get("timestamp") or 0) < METRICS_HISTORY_SAMPLE_SECONDS: return history.append(point) cutoff = now - METRICS_HISTORY_SECONDS history = [item for item in history if int(item.get("timestamp") or 0) >= cutoff][-1600:] tmp: Path | None = None try: DATA_DIR.mkdir(parents=True, exist_ok=True) tmp = METRICS_HISTORY_PATH.with_name(f".{METRICS_HISTORY_PATH.name}.{os.getpid()}.tmp") tmp.write_text(json.dumps(history, ensure_ascii=False, separators=(",", ":")), encoding="utf-8") os.chmod(tmp, 0o600) os.replace(tmp, METRICS_HISTORY_PATH) os.chmod(METRICS_HISTORY_PATH, 0o600) METRICS_HISTORY_STAMP.write_text(str(now), encoding="utf-8") os.chmod(METRICS_HISTORY_STAMP, 0o600) except Exception: if tmp is not None: try: tmp.unlink() except Exception: pass def metrics_sample(iface: str) -> dict[str, Any]: require_valid_iface(iface) # CPU, memory and Network on Dashboard are host metrics, not metrics of the # selected WireGuard interface. Always sample the host default uplink so # switching wg0/wg1 cannot mix different NICs in the same 24-hour graph. route_info = default_route_info() metrics = system_metrics(route_info.get("default_uplink")) _record_metrics_history(metrics) return {"ok": True, "timestamp": int(time.time()), "metrics": metrics} def metrics_history() -> dict[str, Any]: return {"ok": True, "window_seconds": METRICS_HISTORY_SECONDS, "sample_seconds": METRICS_HISTORY_SAMPLE_SECONDS, "history": _load_metrics_history()} def _load_interface_meta() -> dict[str, dict[str, Any]]: try: raw = json.loads(INTERFACES_META_PATH.read_text(encoding="utf-8")) if INTERFACES_META_PATH.exists() else {} except Exception: raw = {} if not isinstance(raw, dict): return {} result: dict[str, dict[str, Any]] = {} for name, value in raw.items(): if ALLOWED_IFACE_RE.fullmatch(str(name)) and isinstance(value, dict): result[str(name)] = dict(value) return result def _save_interface_meta(data: dict[str, dict[str, Any]]) -> None: DATA_DIR.mkdir(parents=True, exist_ok=True) os.chmod(DATA_DIR, 0o755) temp = INTERFACES_META_PATH.with_suffix(".tmp") temp.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") os.chmod(temp, 0o600) os.replace(temp, INTERFACES_META_PATH) os.chmod(INTERFACES_META_PATH, 0o600) def interface_meta_set(iface: str, payload: dict[str, Any]) -> dict[str, Any]: require_valid_iface(iface) display_name = str(payload.get("display_name") or "").strip() if len(display_name) > 64: raise ValueError("Interface display name must be 64 characters or fewer") if any(ord(ch) < 32 for ch in display_name): raise ValueError("Interface display name contains unsupported control characters") data = _load_interface_meta() current = dict(data.get(iface) or {}) current["display_name"] = display_name or iface current["updated_at"] = int(time.time()) data[iface] = current _save_interface_meta(data) return {"ok": True, "interface": iface, "display_name": current["display_name"]} def interface_delete(iface: str) -> dict[str, Any]: require_valid_iface(iface) if any(iface in group.get("interfaces", []) for group in _extended_groups().values()): raise ValueError("Najpierw usuń tę sieć z grup adresów IP") # Preserve every byte reported by the live interface before it disappears. capture_wireguard_traffic(iface) config_path = WG_DIR / f"{iface}.conf" if not config_path.exists(): raise ValueError(f"WireGuard interface configuration {iface}.conf was not found") configured = sorted( path.stem for path in WG_DIR.glob("*.conf") if path.is_file() and ALLOWED_IFACE_RE.fullmatch(path.stem) ) if len(configured) <= 1: raise ValueError("The last configured WireGuard interface cannot be deleted") # Keep the exact server configuration before any destructive action. backup = make_backup(iface, config_path) systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" rc, out, err = run([systemctl, "disable", "--now", f"wg-quick@{iface}.service"], timeout=30) if rc != 0: raise RuntimeError(f"Could not stop WireGuard interface {iface}: {(err or out)[-1200:]}") # A manually-created/runtime-only interface can survive a service stop. # Try wg-quick down using the still-present config before deleting the file. if wg_dump(iface).get("running"): wg_quick = shutil.which("wg-quick") or "/usr/bin/wg-quick" run([wg_quick, "down", str(config_path)], timeout=20) if wg_dump(iface).get("running"): raise RuntimeError(f"WireGuard interface {iface} is still running; configuration was not deleted") # Remove WGTools-managed private metadata belonging only to this interface. removed_clients = 0 for meta in iter_client_metas(): if str(meta.get("interface") or "").strip() != iface: continue public_key = str(meta.get("public_key") or "").strip() if public_key: delete_client_meta(public_key) removed_clients += 1 groups_doc = _load_groups_document() groups_doc["groups"] = [ item for item in groups_doc.get("groups", []) if str(item.get("interface") or "") != iface ] _save_groups_document(groups_doc) config_path.unlink() meta = _load_interface_meta() if iface in meta: meta.pop(iface, None) _save_interface_meta(meta) remaining = [name for name in configured if name != iface] def _sort_key(name: str) -> tuple[int, int | str]: match = re.fullmatch(r"wg(\d+)", name) return (0, int(match.group(1))) if match else (1, name) remaining.sort(key=_sort_key) next_interface = remaining[0] if remaining else "" delete_wireguard_traffic(iface) return { "ok": True, "message": f"WireGuard interface {iface} deleted", "interface": iface, "next_interface": next_interface, "removed_managed_clients": removed_clients, "backup": str(backup), } def _configured_interface_names() -> set[str]: result: set[str] = set() if WG_DIR.exists(): for path in WG_DIR.glob("*.conf"): if path.is_file() and ALLOWED_IFACE_RE.fullmatch(path.stem) and not is_internal_interface(path.stem): result.add(path.stem) wg = shutil.which("wg") if wg: rc, out, _ = run([wg, "show", "interfaces"]) if rc == 0: for token in out.split(): if ALLOWED_IFACE_RE.fullmatch(token) and not is_internal_interface(token): result.add(token) return result def _suggest_next_interface_name(used: set[str]) -> str: for idx in range(0, 1000): candidate = f"wg{idx}" if candidate not in used: return candidate return "wg-new" def _suggest_next_port(used_ports: set[int]) -> int: for port in range(51820, 65536): if port not in used_ports: return port for port in range(1024, 51820): if port not in used_ports: return port raise RuntimeError("No free UDP listen port could be suggested") def _suggest_next_policy_table(used_tables: set[int]) -> int: for table in range(200, 32766): if table not in used_tables: return table raise RuntimeError("No free policy routing table number could be suggested") def _suggest_next_vpn_network(networks: list[ipaddress.IPv4Network]) -> ipaddress.IPv4Network: # Prefer continuing the first configured private /24. This keeps the # common wg0=10.0.0.0/24, wg1=10.0.1.0/24 layout predictable. seeds = [net for net in networks if net.version == 4 and net.is_private and net.prefixlen <= 30] if seeds: seed = seeds[0] step = seed.num_addresses value = int(seed.network_address) + step limit = (1 << 32) - step while value <= limit: try: candidate = ipaddress.ip_network((value, seed.prefixlen), strict=True) except ValueError: break if candidate.is_private and not any(candidate.overlaps(existing) for existing in networks): return candidate value += step for raw in ("10.0.0.0/24", "10.1.0.0/24", "10.2.0.0/24", "172.31.0.0/24", "192.168.177.0/24"): candidate = ipaddress.ip_network(raw) if not any(candidate.overlaps(existing) for existing in networks): return candidate raise RuntimeError("No non-overlapping private IPv4 network could be suggested") def interfaces_list(active_iface: str) -> dict[str, Any]: require_valid_iface(active_iface) names = _configured_interface_names() # Keep the configured default visible during first-run provisioning even # before its .conf exists. if not names: names.add(active_iface) meta = _load_interface_meta() items: list[dict[str, Any]] = [] used_ports: set[int] = set() used_tables: set[int] = set() networks: list[ipaddress.IPv4Network] = [] preferred_uplink = "" preferred_gateway = "" preferred_local = "" def sort_key(name: str) -> tuple[int, int | str]: match = re.fullmatch(r"wg(\d+)", name) return (0, int(match.group(1))) if match else (1, name) for name in sorted(names, key=sort_key): config_path = WG_DIR / f"{name}.conf" cfg = None parse_error = "" if config_path.exists(): try: cfg = parse_config(read_config_text(name), name) except Exception as exc: parse_error = str(exc) dump = wg_dump(name) if wg_installed() else {"running": False, "listen_port": None, "peers": {}} interface_cfg = (cfg or {}).get("interface") or {} detected = (cfg or {}).get("detected") or {} address = interface_cfg.get("address") port_raw = dump.get("listen_port") or interface_cfg.get("listen_port") try: port = int(port_raw) if port_raw not in (None, "") else None except (TypeError, ValueError): port = None if port: used_ports.add(port) table_raw = detected.get("policy_table") try: table_num = int(table_raw) if table_raw not in (None, "") else None except (TypeError, ValueError): table_num = None if table_num: used_tables.add(table_num) vpn_network = str(detected.get("vpn_network") or "") if vpn_network: try: networks.append(ipaddress.ip_network(vpn_network, strict=False)) except ValueError: pass preferred_uplink = preferred_uplink or str(detected.get("uplink_interface") or "") preferred_gateway = preferred_gateway or str(detected.get("gateway") or "") preferred_local = preferred_local or str(detected.get("local_network") or "") peer_count = len((cfg or {}).get("peers") or dump.get("peers") or {}) remote_networks: list[str] = [] for peer in (cfg or {}).get("peers") or []: for raw in peer.get("remote_networks") or []: text = str(raw or "").strip() if text and text not in remote_networks: remote_networks.append(text) display_name = str((meta.get(name) or {}).get("display_name") or name) items.append({ "name": name, "display_name": display_name, "configured": config_path.exists(), "running": bool(dump.get("running")), "address": address, "listen_port": port, "vpn_network": vpn_network or None, "remote_networks": remote_networks, "policy_table": table_num, "uplink_interface": detected.get("uplink_interface"), "peer_count": peer_count, "config_error": parse_error or None, "active": name == active_iface, }) route = default_route_info() suggestion_network = _suggest_next_vpn_network(networks) first_host = next(suggestion_network.hosts()) suggested_name = _suggest_next_interface_name(names) suggestion = { "interface": suggested_name, "display_name": "", "vpn_network": str(suggestion_network), "server_address": str(ipaddress.ip_interface(f"{first_host}/{suggestion_network.prefixlen}")), "listen_port": _suggest_next_port(used_ports), "uplink_interface": preferred_uplink or route.get("default_uplink") or "", "gateway": preferred_gateway or route.get("default_gateway") or "", "local_network": preferred_local or route.get("local_network") or "", "policy_table": str(_suggest_next_policy_table(used_tables)) if used_tables else "", "nat_enabled": True, "ip_forwarding": True, } return {"ok": True, "active_interface": active_iface, "interfaces": items, "suggested": suggestion} def _validate_cross_interface_server_settings(iface: str, network: ipaddress.IPv4Network, listen_port: int, policy_table: int | None) -> None: for path in WG_DIR.glob("*.conf") if WG_DIR.exists() else []: other = path.stem if other == iface or not ALLOWED_IFACE_RE.fullmatch(other): continue try: cfg = parse_config(path.read_text(encoding="utf-8", errors="replace"), other) except Exception: continue detected = cfg.get("detected") or {} other_network_raw = str(detected.get("vpn_network") or "").strip() if other_network_raw: try: other_network = ipaddress.ip_network(other_network_raw, strict=False) if network.overlaps(other_network): raise ValueError(f"VPN network {network} overlaps with {other} ({other_network})") except ValueError as exc: if "overlaps with" in str(exc): raise other_port = (cfg.get("interface") or {}).get("listen_port") try: if other_port not in (None, "") and int(other_port) == listen_port: raise ValueError(f"UDP listen port {listen_port} is already used by {other}") except (TypeError, ValueError) as exc: if isinstance(exc, ValueError) and "already used" in str(exc): raise other_table = detected.get("policy_table") try: if policy_table is not None and other_table not in (None, "") and int(other_table) == policy_table: raise ValueError(f"Policy routing table {policy_table} is already used by {other}; use a separate table for each WGTools interface") except (TypeError, ValueError) as exc: if isinstance(exc, ValueError) and "already used" in str(exc): raise def backup_info(iface: str) -> dict[str, Any]: files = sorted(BACKUP_DIR.glob(f"{iface}-*.conf"), key=lambda x: x.stat().st_mtime, reverse=True) if BACKUP_DIR.exists() else [] latest = files[0] if files else None return { "count": len(files), "retention": backup_retention(), "latest_name": latest.name if latest else None, "latest_modified_at": int(latest.stat().st_mtime) if latest else None, } def wireguard_service_action(iface: str, action: str) -> dict[str, Any]: require_valid_iface(iface) if action not in {"start", "stop", "restart"}: raise ValueError("Unsupported WireGuard service action") if not wg_installed(): raise RuntimeError("WireGuard is not installed") config_path = WG_DIR / f"{iface}.conf" if not config_path.exists(): raise RuntimeError(f"{config_path} does not exist") systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" service = f"wg-quick@{iface}.service" if action in {"stop", "restart"}: capture_wireguard_traffic(iface) rc, out, err = run([systemctl, action, service], timeout=40) if rc != 0: raise RuntimeError(f"Could not {action} {service}: {err or out}") running = bool(wg_dump(iface).get("running")) expected = action != "stop" if running != expected: raise RuntimeError(f"systemd completed {action}, but {iface} is {'running' if running else 'stopped'} unexpectedly") return {"ok": True, "action": action, "running": running, "message": f"WireGuard {action} completed"} def read_json_stdin() -> dict[str, Any]: raw = sys.stdin.read() if not raw.strip(): return {} data = json.loads(raw) if not isinstance(data, dict): raise ValueError("JSON payload must be an object") return data def read_config_text(iface: str) -> str: path = WG_DIR / f"{iface}.conf" if not path.exists(): raise FileNotFoundError(str(path)) return path.read_text(encoding="utf-8", errors="replace") def parse_comment_name(line: str) -> str | None: s = line.strip() if not s.startswith("#"): return None s = s.lstrip("#").strip() m = re.fullmatch(r"-+\s*(.*?)\s*-+", s) if m and m.group(1).strip(): return m.group(1).strip().replace("\\_", "_") return None def parse_config(text: str, iface_hint: str | None = None) -> dict[str, Any]: interface: dict[str, Any] = { "address": None, "listen_port": None, "mtu": None, "private_key_set": False, "save_config": None, "post_up": [], "post_down": [], } peers: list[dict[str, Any]] = [] current_section: str | None = None current_peer: dict[str, Any] | None = None pending_name: str | None = None for raw in text.splitlines(): line = raw.strip() if not line: continue name = parse_comment_name(line) if name: pending_name = name continue if line.startswith("#") or line.startswith(";"): continue if line.startswith("[") and line.endswith("]"): current_section = line[1:-1].strip().lower() if current_section == "peer": current_peer = { "name": pending_name or "Unnamed peer", "public_key": None, "allowed_ips": [], "persistent_keepalive": None, "preshared_key_set": False, } peers.append(current_peer) pending_name = None continue if "=" not in line: continue key, value = [x.strip() for x in line.split("=", 1)] lk = key.lower() if current_section == "interface": if lk == "address": interface["address"] = value elif lk == "listenport": interface["listen_port"] = int(value) if value.isdigit() else value elif lk == "mtu": interface["mtu"] = int(value) if value.isdigit() else value elif lk == "privatekey": interface["private_key_set"] = bool(value) elif lk == "saveconfig": interface["save_config"] = value elif lk == "postup": interface["post_up"].append(value) elif lk == "postdown": interface["post_down"].append(value) elif current_section == "peer" and current_peer is not None: if lk == "publickey": current_peer["public_key"] = value elif lk == "allowedips": current_peer["allowed_ips"] = [v.strip() for v in value.split(",") if v.strip()] elif lk == "persistentkeepalive": current_peer["persistent_keepalive"] = int(value) if value.isdigit() else value elif lk == "presharedkey": current_peer["preshared_key_set"] = bool(value) vpn_network = None if interface["address"]: first_address = str(interface["address"]).split(",")[0].strip() try: vpn_network = str(ipaddress.ip_interface(first_address).network) except ValueError: pass routes: list[dict[str, Any]] = [] firewall: list[dict[str, Any]] = [] policy_table = None gateway = None uplink_interface = None local_network = None nat_enabled = False forward_from_vpn = False forward_to_vpn = False def parse_hook(hook: str, commands: list[str]) -> None: nonlocal policy_table, gateway, uplink_interface, local_network, nat_enabled, forward_from_vpn, forward_to_vpn for cmd in commands: if re.search(r"\biptables\b", cmd): kind = "Firewall" if "-t nat" in cmd or "MASQUERADE" in cmd: kind = "NAT" nat_enabled = True elif "REJECT" in cmd or "DROP" in cmd: kind = "Access rule" if hook == "PostUp" and iface_hint: if re.search(r"(?:^|\s)-(?:A|I)\s+FORWARD\b.*\s-i\s+" + re.escape(iface_hint) + r"(?:\s|$)", cmd): forward_from_vpn = True if re.search(r"(?:^|\s)-(?:A|I)\s+FORWARD\b.*\s-o\s+" + re.escape(iface_hint) + r"(?:\s|$)", cmd): forward_to_vpn = True firewall.append({"hook": hook, "kind": kind, "command": cmd}) continue if re.search(r"\bip\s+rule\s+(add|del)\b", cmd): m = re.search(r"\btable\s+(\d+)\b", cmd) if m and hook == "PostUp": policy_table = m.group(1) continue if re.search(r"\bip\s+route\s+(add|replace|del)\b", cmd): network = None mnet = re.search(r"\broute\s+(?:add|replace|del)\s+([^\s]+)", cmd) if mnet: network = mnet.group(1) mtable = re.search(r"\btable\s+(\d+)\b", cmd) mvia = re.search(r"\bvia\s+([^\s]+)", cmd) mdev = re.search(r"\bdev\s+([^\s]+)", cmd) if hook == "PostUp": routes.append({ "hook": hook, "network": network, "table": mtable.group(1) if mtable else "main", "via": mvia.group(1) if mvia else None, "device": mdev.group(1) if mdev else None, "command": cmd, }) if network == "default" and mvia: gateway = mvia.group(1) if mdev: uplink_interface = mdev.group(1) parse_hook("PostUp", interface["post_up"]) parse_hook("PostDown", interface["post_down"]) if uplink_interface: for route in routes: if route.get("device") == uplink_interface and route.get("network") != "default": local_network = route.get("network") break vpn_network_obj = None if vpn_network: try: vpn_network_obj = ipaddress.ip_network(vpn_network, strict=False) except ValueError: vpn_network_obj = None for peer in peers: vpn_address = None remote_networks: list[str] = [] for allowed in peer["allowed_ips"]: try: net = ipaddress.ip_network(allowed, strict=False) # A valid WireGuard peer may contain both IPv4 and IPv6 AllowedIPs # (for example 0.0.0.0/0, ::/0). Never compare networks of # different IP versions: ipaddress raises TypeError and that used # to break the entire WGTools snapshot/provisioning page. is_peer_vpn_address = ( vpn_network_obj is not None and net.version == vpn_network_obj.version and net.subnet_of(vpn_network_obj) and net.prefixlen == vpn_network_obj.max_prefixlen and vpn_address is None ) if is_peer_vpn_address: vpn_address = allowed else: remote_networks.append(allowed) except (ValueError, TypeError): remote_networks.append(allowed) peer["vpn_address"] = vpn_address peer["remote_networks"] = remote_networks return { "interface": interface, "peers": peers, "routes": routes, "firewall": firewall, "detected": { "vpn_network": vpn_network, "policy_table": policy_table, "gateway": gateway, "uplink_interface": uplink_interface, "local_network": local_network, "nat_enabled": nat_enabled, "forward_from_vpn": forward_from_vpn, "forward_to_vpn": forward_to_vpn, }, } def wg_installed() -> bool: return shutil.which("wg") is not None and shutil.which("wg-quick") is not None def wg_dump(iface: str) -> dict[str, Any]: wg = shutil.which("wg") if not wg: return {"running": False, "listen_port": None, "public_key": None, "peers": {}, "error": "WireGuard tools are not installed"} rc, out, err = run([wg, "show", iface, "dump"]) if rc != 0: return {"running": False, "listen_port": None, "public_key": None, "peers": {}, "error": err or out or "Interface is not running"} lines = out.splitlines() if not lines: return {"running": False, "listen_port": None, "public_key": None, "peers": {}} first = lines[0].split("\t") public_key = first[1] if len(first) > 1 else None listen_port = int(first[2]) if len(first) > 2 and first[2].isdigit() else (first[2] if len(first) > 2 else None) peers: dict[str, Any] = {} for line in lines[1:]: cols = line.split("\t") if len(cols) < 8: continue pub = cols[0] peers[pub] = { "public_key": pub, "preshared_key_set": bool(cols[1] and set(cols[1]) != {"0", "="}), "endpoint": cols[2] or None, "allowed_ips_runtime": [x.strip() for x in cols[3].split(",") if x.strip()], "latest_handshake": int(cols[4] or 0), "rx_bytes": int(cols[5] or 0), "tx_bytes": int(cols[6] or 0), "persistent_keepalive_runtime": int(cols[7]) if cols[7].isdigit() else 0, } return {"running": True, "listen_port": listen_port, "public_key": public_key, "peers": peers} def default_route_info() -> dict[str, Any]: ip = shutil.which("ip") or "/usr/sbin/ip" rc, out, _ = run([ip, "-4", "route", "show", "default"]) gateway = None uplink = None if rc == 0 and out: line = out.splitlines()[0] mgw = re.search(r"\bvia\s+(\S+)", line) mdev = re.search(r"\bdev\s+(\S+)", line) gateway = mgw.group(1) if mgw else None uplink = mdev.group(1) if mdev else None local_network = None if uplink: rc, out, _ = run([ip, "-4", "route", "show", "dev", uplink, "scope", "link"]) if rc == 0: for line in out.splitlines(): first = line.split()[0] if line.split() else "" try: net = ipaddress.ip_network(first, strict=False) if not net.is_loopback and not net.is_link_local: local_network = str(net) break except ValueError: continue return {"default_gateway": gateway, "default_uplink": uplink, "local_network": local_network} def diagnostics(iface: str, cfg: dict[str, Any] | None = None, dump: dict[str, Any] | None = None) -> list[dict[str, Any]]: installed = wg_installed() config_exists = (WG_DIR / f"{iface}.conf").exists() checks: list[dict[str, Any]] = [ {"label": "WireGuard installed", "ok": installed, "detail": "wg and wg-quick are available" if installed else "WireGuard tools are not installed"}, {"label": f"Configuration {iface}.conf", "ok": config_exists, "detail": str(WG_DIR / f"{iface}.conf") if config_exists else "Server has not been configured yet"}, ] if not installed or not config_exists: return checks if cfg is None: cfg = parse_config(read_config_text(iface), iface) if dump is None: dump = wg_dump(iface) checks.append({ "label": f"WireGuard interface {iface}", "ok": bool(dump.get("running")), "detail": "Interface is available via wg show" if dump.get("running") else dump.get("error", "Interface is not running"), }) systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" rc, out, err = run([systemctl, "is-active", f"wg-quick@{iface}.service"]) checks.append({"label": f"wg-quick@{iface}", "ok": rc == 0 and out == "active", "detail": out or err or "unknown"}) sysctl = shutil.which("sysctl") or "/usr/sbin/sysctl" rc, out, err = run([sysctl, "-n", "net.ipv4.ip_forward"]) ipf = rc == 0 and out.strip() == "1" checks.append({"label": "IPv4 forwarding", "ok": ipf, "detail": f"net.ipv4.ip_forward={out.strip() if out else '?'}"}) listen_port = dump.get("listen_port") or cfg.get("interface", {}).get("listen_port") if listen_port: ss = shutil.which("ss") or "/usr/bin/ss" rc, out, err = run([ss, "-lun"]) present = rc == 0 and re.search(rf":{re.escape(str(listen_port))}\b", out) is not None checks.append({"label": f"UDP {listen_port} listening", "ok": present, "detail": "UDP socket found" if present else "UDP socket not found in ss -lun"}) table = cfg.get("detected", {}).get("policy_table") if table: ip = shutil.which("ip") or "/usr/sbin/ip" rc, out, err = run([ip, "route", "show", "table", str(table)]) checks.append({"label": f"Routing table {table}", "ok": rc == 0 and bool(out.strip()), "detail": out.splitlines()[0] if out else (err or "Table is empty")}) nat_expected = bool(cfg.get("detected", {}).get("nat_enabled")) if nat_expected: iptables = shutil.which("iptables") if not iptables: checks.append({"label": "NAT / Masquerade", "ok": False, "detail": "iptables is not installed"}) else: rc, out, err = run([iptables, "-t", "nat", "-S", "POSTROUTING"]) vpn_net = cfg.get("detected", {}).get("vpn_network") or "" uplink = cfg.get("detected", {}).get("uplink_interface") or "" found = rc == 0 and "MASQUERADE" in out and (not vpn_net or vpn_net in out) and (not uplink or uplink in out) checks.append({"label": "NAT / Masquerade", "ok": found, "detail": "Matching POSTROUTING rule found" if found else (err or "Expected MASQUERADE rule was not found")}) ip = shutil.which("ip") or "/usr/sbin/ip" rc, out, err = run([ip, "address", "show", "dev", iface]) address = cfg.get("interface", {}).get("address") addr_ip = str(address).split("/")[0] if address else "" has_addr = rc == 0 and (not addr_ip or addr_ip in out) checks.append({"label": f"{iface} address", "ok": has_addr, "detail": address or (err or "No configured address")}) return checks def _route_remote_networks(cfg: dict[str, Any]) -> set[str]: return { str(net).strip() for peer in cfg.get("peers", []) for net in (peer.get("remote_networks") or []) if str(net).strip() } def _route_category(route: dict[str, Any], cfg: dict[str, Any], iface: str) -> tuple[str, bool]: target = str(route.get("network") or "") table = str(route.get("table") or "main") device = str(route.get("device") or "") via = str(route.get("via") or "") detected = cfg.get("detected", {}) vpn_network = str(detected.get("vpn_network") or "") local_network = str(detected.get("local_network") or "") policy_table = str(detected.get("policy_table") or "") uplink = str(detected.get("uplink_interface") or "") gateway = str(detected.get("gateway") or "") remotes = _route_remote_networks(cfg) if target in remotes and device == iface: return "site_to_site", False if policy_table and table == policy_table: if target == "default" and (not gateway or via == gateway): return "server", False if target == vpn_network and device == iface: return "server", False if local_network and target == local_network and (not uplink or device == uplink): return "server", False return "custom", True def _parse_access_rule(command: str) -> dict[str, Any] | None: compact = " ".join(str(command).split()) if not re.search(r"\biptables\b", compact) or not re.search(r"\bFORWARD\b", compact): return None action_match = re.search(r"\s-j\s+(ACCEPT|REJECT|DROP)(?:\s|$)", compact) if not action_match: return None # The simple editor intentionally supports only the common FORWARD rule shape. # Interface-specific, stateful, multiport, mark and other advanced rules stay read-only # and are still editable from the raw wg0.conf editor. if re.search(r"\s(?:-i|-o|--sport|--sports|--dports|--sports|-m\s+(?!iprange\b|comment\b)|--state|--ctstate|--mark|--uid-owner)\b", compact): return None def grab(pattern: str) -> str: m = re.search(pattern, compact) return m.group(1) if m else "" src_range = grab(r"--src-range\s+([^\s]+)") dst_range = grab(r"--dst-range\s+([^\s]+)") source = src_range or grab(r"(?:^|\s)-s\s+([^\s]+)") destination = dst_range or grab(r"(?:^|\s)-d\s+([^\s]+)") protocol = grab(r"(?:^|\s)-p\s+(tcp|udp)(?:\s|$)") dport = grab(r"--dport\s+(\d+(?::\d+)?)") managed_tag = grab(r"--comment\s+(wgtools-protect-[A-Za-z0-9_-]+)") # Reject any tokens we do not know how to recreate faithfully. test = compact test = re.sub(r"^.*?iptables\s+(?:-[AI])\s+FORWARD\b", "", test).strip() patterns = [ r"(?:^|\s)-m\s+iprange(?=\s|$)", r"(?:^|\s)-m\s+comment(?=\s|$)", r"(?:^|\s)--comment\s+wgtools-protect-[A-Za-z0-9_-]+", r"(?:^|\s)--src-range\s+[^\s]+", r"(?:^|\s)--dst-range\s+[^\s]+", r"(?:^|\s)-s\s+[^\s]+", r"(?:^|\s)-d\s+[^\s]+", r"(?:^|\s)-p\s+(?:tcp|udp)(?=\s|$)", r"(?:^|\s)--dport\s+\d+(?::\d+)?", r"(?:^|\s)-j\s+(?:ACCEPT|REJECT|DROP)(?=\s|$)", ] for pattern in patterns: test = re.sub(pattern, " ", test) if test.strip(): return None return { "source": source, "destination": destination, "action": action_match.group(1), "protocol": protocol or "any", "destination_port": dport, "managed_tag": managed_tag, } def _is_peer_isolation_access_rule(access: dict[str, Any], meta: dict[str, Any] | None, cfg: dict[str, Any]) -> bool: if not meta or not bool(meta.get("peer_isolation")) or str(access.get("action") or "") != "REJECT": return False try: source = str(ipaddress.ip_network(str(access.get("source") or ""), strict=False)) destination = str(ipaddress.ip_network(str(access.get("destination") or ""), strict=False)) client = str(ipaddress.ip_network(str(meta.get("vpn_address") or ""), strict=False)) vpn_network = str(ipaddress.ip_network(str(cfg.get("detected", {}).get("vpn_network") or ""), strict=False)) except ValueError: return False return (source == client and destination == vpn_network) or (source == vpn_network and destination == client) def describe_server_items(cfg: dict[str, Any], iface: str) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: route_items: list[dict[str, Any]] = [] for route in cfg.get("routes", []): item = dict(route) category, editable = _route_category(item, cfg, iface) item["category"] = category item["editable"] = editable item["id"] = hashlib.sha256(str(item.get("command") or "").encode("utf-8")).hexdigest()[:16] route_items.append(item) firewall_items: list[dict[str, Any]] = [] old_cfg = cfg remote_set = _route_remote_networks(cfg) # Resolve WGTools-managed policy tags once. Looking up every firewall row # by rescanning all client metadata becomes noticeably expensive on large # group deployments. policy_meta_by_tag = { client_policy_tag(str(meta.get("public_key") or "")): meta for meta in iter_client_metas() if meta.get("public_key") } seen_up: set[str] = set() for row in cfg.get("firewall", []): if row.get("hook") != "PostUp": continue cmd = str(row.get("command") or "") if not cmd or cmd in seen_up: continue seen_up.add(cmd) managed_kind = _managed_hook_kind(cmd, iface, old_cfg, remote_set) access = _parse_access_rule(cmd) if managed_kind in {"forward_from", "forward_to", "nat"}: category = "server" editable = False elif access is not None: category = "access" # Managed ACCEPT rows are client-local exceptions. They are edited # from the client form so their ordering relative to the broader # managed REJECT policy stays deterministic. managed_meta = policy_meta_by_tag.get(str(access.get("managed_tag") or "")) if access.get("managed_tag") else None managed_group = bool(managed_meta and managed_meta.get("group_id")) managed_isolation = _is_peer_isolation_access_rule(access, managed_meta, cfg) editable = not managed_group and not managed_isolation and not (access.get("managed_tag") and access.get("action") == "ACCEPT") else: category = "advanced" editable = False item = { "id": hashlib.sha256(cmd.encode("utf-8")).hexdigest()[:16], "hook": "PostUp", "kind": row.get("kind") or "Firewall", "command": cmd, "category": category, "editable": editable, "access": access, } firewall_items.append(item) return route_items, firewall_items def _proc_default_uplink() -> str | None: """Return the host default IPv4 interface without spawning `ip`. Dashboard snapshots run every few seconds. Reading /proc avoids paying for route helper subprocesses merely to select the NIC used for host metrics. """ try: lines = Path("/proc/net/route").read_text(encoding="utf-8", errors="replace").splitlines()[1:] for line in lines: cols = line.split() if len(cols) >= 4 and cols[1] == "00000000" and int(cols[3], 16) & 0x2: return cols[0] except Exception: pass return None def _ip_forwarding_enabled() -> bool: try: return Path("/proc/sys/net/ipv4/ip_forward").read_text(encoding="utf-8", errors="replace").strip() == "1" except Exception: return False def build_snapshot(iface: str, view: str = "full") -> dict[str, Any]: """Build a UI snapshot, doing only the work required by the current page. `full` preserves the server/settings payload. `clients` skips host metrics, diagnostics, firewall/route descriptions and backup scans. `dashboard` skips client-editor/group expansion and server-management data; diagnostics are fetched independently so they never block first paint. """ view = str(view or "full").strip().lower() if view not in {"full", "clients", "dashboard", "peers", "server"}: view = "full" full_view = view == "full" clients_view = view == "clients" dashboard_view = view == "dashboard" peers_view = view == "peers" server_view = view == "server" detailed_clients = full_view or clients_view installed = wg_installed() config_path = WG_DIR / f"{iface}.conf" config_exists = config_path.exists() cfg: dict[str, Any] = { "interface": {"address": None, "listen_port": None, "mtu": None, "private_key_set": False, "save_config": None, "post_up": [], "post_down": []}, "peers": [], "routes": [], "firewall": [], "detected": {"vpn_network": None, "policy_table": None, "gateway": None, "uplink_interface": None, "local_network": None, "nat_enabled": False, "forward_from_vpn": False, "forward_to_vpn": False}, } config_parse_error = None if config_exists: try: cfg = parse_config(read_config_text(iface), iface) except Exception as exc: config_parse_error = str(exc) dump = wg_dump(iface) if installed else {"running": False, "listen_port": None, "public_key": None, "peers": {}} runtime = dump.get("peers", {}) # Read client metadata once. The old path opened the same files repeatedly # per peer and again for group counts, which became very visible when merely # switching to Clients/Dashboard. all_client_metas = [] if (peers_view or server_view) else iter_client_metas() meta_by_public_key = { str(meta.get("public_key") or ""): meta for meta in all_client_metas if str(meta.get("public_key") or "") and (not meta.get("interface") or str(meta.get("interface")) == iface) } groups = iter_groups(iface) if detailed_clients else [] groups_by_id = {str(group.get("id") or ""): group for group in groups if group.get("id")} peers: list[dict[str, Any]] = [] for peer in cfg.get("peers", []): if server_view: continue merged = dict(peer) live = runtime.get(peer.get("public_key"), {}) merged.update(live) pub = str(peer.get("public_key") or "") meta = meta_by_public_key.get(pub) if dashboard_view or peers_view: # Dashboard only needs policy state that affects the status badge; # background peer summaries need no client metadata at all. if dashboard_view and meta: merged["expired_disabled"] = bool(meta.get("expired_disabled")) merged["schedule_disabled"] = bool(meta.get("schedule_disabled")) peers.append(merged) continue merged["managed"] = bool(meta and meta.get("private_key")) if meta: merged["client_endpoint"] = meta.get("endpoint") merged["client_allowed_ips"] = meta.get("client_allowed_ips", []) merged["client_route_preset"] = meta.get("client_route_preset") or _infer_route_preset(cfg, list(meta.get("client_allowed_ips") or []), bool(meta.get("protect_local_networks"))) merged["protect_local_networks"] = bool(meta.get("protect_local_networks")) merged["local_access_exceptions"] = meta.get("local_access_exceptions", []) merged["client_dns"] = meta.get("dns", []) merged["group_id"] = str(meta.get("group_id") or "") merged["policy_mode"] = str(meta.get("policy_mode") or "inherit") if meta.get("group_id") else "" merged["internet_access"] = str(meta.get("internet_access") or "inherit") if meta.get("group_id") else "" merged["local_access"] = str(meta.get("local_access") or "inherit") if meta.get("group_id") else "" merged["policy_allow"] = meta.get("policy_allow", []) merged["policy_deny"] = meta.get("policy_deny", []) merged["config_mode"] = str(meta.get("config_mode") or "") if meta.get("group_id") else "" merged["preshared_key_enabled"] = bool(meta.get("preshared_key")) merged["peer_isolation"] = bool(meta.get("peer_isolation")) merged["expires_at"] = int(meta.get("expires_at") or 0) merged["expiration_action"] = str(meta.get("expiration_action") or "delete") merged["expired_disabled"] = bool(meta.get("expired_disabled")) merged["expired_at"] = int(meta.get("expired_at") or 0) merged["access_schedule_enabled"] = bool(meta.get("access_schedule_enabled")) merged["access_schedule_days"] = list(meta.get("access_schedule_days") or []) merged["access_schedule_start"] = str(meta.get("access_schedule_start") or "08:00") merged["access_schedule_end"] = str(meta.get("access_schedule_end") or "19:00") merged["schedule_disabled"] = bool(meta.get("schedule_disabled")) merged["connection_mode"] = str(meta.get("connection_mode") or "direct") merged["relay_vps_id"] = str(meta.get("relay_vps_id") or "") try: merged["schedule_allowed_now"] = client_schedule_allows(meta) if meta.get("access_schedule_enabled") else True except Exception: merged["schedule_allowed_now"] = False merged.update(_client_group_snapshot(meta, cfg, iface, groups_by_id)) peers.append(merged) # Dashboard and Clients both display lifetime peer counters; keep this one # durable merge, but avoid all unrelated management work around it. if peers_view or server_view: traffic_totals = {"rx_bytes": 0, "tx_bytes": 0} else: peers, traffic_totals = merge_wireguard_traffic(iface, peers) next_free = next_free_address(cfg) if config_exists and detailed_clients else None detected = cfg.get("detected") or {} if full_view or server_view: route_info = default_route_info() system = {"ip_forwarding": _ip_forwarding_enabled(), **route_info} if full_view: metrics = system_metrics(route_info.get("default_uplink")) _record_metrics_history(metrics) else: metrics = None elif dashboard_view: uplink = str(detected.get("uplink_interface") or "").strip() or _proc_default_uplink() system = { "ip_forwarding": _ip_forwarding_enabled(), "default_gateway": detected.get("gateway"), "default_uplink": uplink, "local_network": detected.get("local_network"), } metrics = system_metrics(uplink) else: system = { "ip_forwarding": None, "default_gateway": detected.get("gateway"), "default_uplink": detected.get("uplink_interface"), "local_network": detected.get("local_network"), } metrics = None if not installed: server_state = "not_installed" elif not config_exists: server_state = "not_configured" elif dump.get("running"): server_state = "running" else: server_state = "stopped" route_items, firewall_items = describe_server_items(cfg, iface) if (full_view or server_view) and config_exists and not config_parse_error else ([], []) diagnostic_items = diagnostics(iface, cfg if config_exists else None, dump if installed else None) if full_view else None if config_parse_error and diagnostic_items is not None: diagnostic_items.insert(2, { "label": "Configuration parse", "ok": False, "detail": config_parse_error, }) group_rows: list[dict[str, Any]] = [] if detailed_clients: member_counts: dict[str, int] = {} for meta in all_client_metas: if str(meta.get("interface") or "") != iface: continue group_id = str(meta.get("group_id") or "") if group_id: member_counts[group_id] = member_counts.get(group_id, 0) + 1 for group in groups: row = dict(group) row["member_count"] = member_counts.get(str(group.get("id") or ""), 0) row["resolved_defaults"] = _group_defaults_for_config(group, cfg) if config_exists and not config_parse_error else group.get("defaults", {}) group_rows.append(row) result: dict[str, Any] = { "ok": True, "timestamp": int(time.time()), "interface": iface, "running": bool(dump.get("running")), "listen_port": dump.get("listen_port"), "public_key": dump.get("public_key"), "config": cfg, "peers": peers, "traffic_totals": traffic_totals, "system": system, "wireguard": { "installed": installed, "config_exists": config_exists, "config_path": str(config_path), "config_error": config_parse_error, "state": server_state, }, } if detailed_clients: result["client_groups"] = group_rows result["next_free_address"] = next_free if metrics is not None: result["metrics"] = metrics if full_view: result.update({ "route_items": route_items, "firewall_items": firewall_items, "backups": backup_info(iface), "diagnostics": diagnostic_items or [], }) elif server_view: result.update({ "route_items": route_items, "firewall_items": firewall_items, }) return result def build_diagnostics(iface: str) -> dict[str, Any]: """Run only diagnostics, without constructing a full UI snapshot first.""" installed = wg_installed() config_path = WG_DIR / f"{iface}.conf" cfg: dict[str, Any] | None = None parse_error = "" if config_path.exists(): try: cfg = parse_config(read_config_text(iface), iface) except Exception as exc: parse_error = str(exc) dump = wg_dump(iface) if installed else {"running": False, "listen_port": None, "public_key": None, "peers": {}} items = diagnostics(iface, cfg if cfg is not None else None, dump if installed else None) if parse_error: items.insert(2, {"label": "Configuration parse", "ok": False, "detail": parse_error}) return {"ok": True, "interface": iface, "diagnostics": items} def _trace_target_host(raw: Any) -> str: value = str(raw or "").strip() if not value or len(value) > 320: raise ValueError("Enter an IPv4 address or hostname") # Accept a pasted URL as a convenience, but trace only its host. try: parsed = urllib.parse.urlsplit(value if "://" in value else f"//{value}") host = (parsed.hostname or "").strip().rstrip(".") except Exception: host = "" if not host: host = value.strip("[]").rstrip(".") if len(host) > 253 or any(ch.isspace() for ch in host): raise ValueError("Invalid trace target") return host def _resolve_trace_ipv4(host: str) -> str: try: literal = ipaddress.ip_address(host) if literal.version != 4: raise ValueError("IPv6 traceroute is not enabled yet") return str(literal) except ValueError as exc: if "IPv6 traceroute" in str(exc): raise try: infos = socket.getaddrinfo(host, None, socket.AF_INET, socket.SOCK_STREAM) except socket.gaierror as exc: raise ValueError(f"Could not resolve {host}") from exc addresses = [] for info in infos: address = str(info[4][0]) if address not in addresses: addresses.append(address) if not addresses: raise ValueError(f"No IPv4 address found for {host}") return addresses[0] def _parse_ping_output(text: str) -> dict[str, Any]: result: dict[str, Any] = {"sent": 0, "received": 0, "loss_percent": 100.0, "min_ms": None, "avg_ms": None, "max_ms": None} summary = re.search(r"(\d+) packets transmitted, (\d+) received,.*?([0-9.]+)% packet loss", text) if summary: result["sent"] = int(summary.group(1)) result["received"] = int(summary.group(2)) result["loss_percent"] = float(summary.group(3)) rtt = re.search(r"(?:rtt|round-trip) min/avg/max/(?:mdev|stddev) = ([0-9.]+)/([0-9.]+)/([0-9.]+)/", text) if rtt: result["min_ms"] = round(float(rtt.group(1)), 2) result["avg_ms"] = round(float(rtt.group(2)), 2) result["max_ms"] = round(float(rtt.group(3)), 2) return result def _parse_traceroute_output(text: str, target_ip: str) -> list[dict[str, Any]]: hops: list[dict[str, Any]] = [] previous_avg: float | None = None ip_re = re.compile(r"(? dict[str, Any]: try: data = json.loads(TRACE_GEO_CACHE_PATH.read_text(encoding="utf-8")) return data if isinstance(data, dict) else {} except Exception: return {} def _save_trace_geo_cache(cache: dict[str, Any]) -> None: try: now = int(time.time()) cleaned = { ip: item for ip, item in cache.items() if isinstance(item, dict) and now - int(item.get("cached_at") or 0) <= TRACE_GEO_CACHE_TTL } if len(cleaned) > 500: cleaned = dict(sorted(cleaned.items(), key=lambda pair: int(pair[1].get("cached_at") or 0), reverse=True)[:500]) TRACE_GEO_CACHE_PATH.write_text(json.dumps(cleaned, ensure_ascii=False), encoding="utf-8") TRACE_GEO_CACHE_PATH.chmod(0o600) except Exception: pass def _trace_geo_lookup(ip: str, language: str = "en") -> dict[str, Any] | None: try: address = ipaddress.ip_address(ip) if not address.is_global: return None except ValueError: return None lang = "ru" if str(language).lower() == "ru" else "en" fields = "success,ip,continent,country,country_code,region,city,latitude,longitude,connection" url = f"https://ipwho.is/{urllib.parse.quote(ip, safe='')}?fields={urllib.parse.quote(fields)}&lang={lang}" req = urllib.request.Request(url, headers={"User-Agent": "WGTools/0.40.0 network-trace"}) try: with urllib.request.urlopen(req, timeout=3.5) as response: payload = json.loads(response.read().decode("utf-8", errors="replace")) except Exception: return None if not isinstance(payload, dict) or not payload.get("success", False): return None try: latitude = float(payload.get("latitude")) longitude = float(payload.get("longitude")) except (TypeError, ValueError): return None connection = payload.get("connection") if isinstance(payload.get("connection"), dict) else {} return { "latitude": latitude, "longitude": longitude, "city": str(payload.get("city") or ""), "region": str(payload.get("region") or ""), "country": str(payload.get("country") or ""), "country_code": str(payload.get("country_code") or ""), "asn": str(connection.get("asn") or ""), "org": str(connection.get("org") or connection.get("isp") or ""), } def _trace_geolocate(hops: list[dict[str, Any]], language: str, extra_ips: list[str] | None = None) -> tuple[dict[str, dict[str, Any]], bool]: ips = [] for hop in hops: ip = str(hop.get("ip") or "") try: if ip and ipaddress.ip_address(ip).is_global and ip not in ips: ips.append(ip) except ValueError: pass for candidate in extra_ips or []: try: if ipaddress.ip_address(candidate).is_global and candidate not in ips: ips.append(candidate) except ValueError: pass if not ips: return {}, False cache = _load_trace_geo_cache() now = int(time.time()) result: dict[str, dict[str, Any]] = {} missing = [] for ip in ips: cached = cache.get(ip) if isinstance(cached, dict) and now - int(cached.get("cached_at") or 0) <= TRACE_GEO_CACHE_TTL: result[ip] = {k: v for k, v in cached.items() if k != "cached_at"} else: missing.append(ip) lookup_failed = False if missing: with ThreadPoolExecutor(max_workers=min(6, len(missing))) as pool: futures = {pool.submit(_trace_geo_lookup, ip, language): ip for ip in missing} for future in as_completed(futures): ip = futures[future] try: geo = future.result() except Exception: geo = None if geo: result[ip] = geo cache[ip] = {**geo, "cached_at": now} else: lookup_failed = True _save_trace_geo_cache(cache) return result, lookup_failed def network_trace(payload: dict[str, Any]) -> dict[str, Any]: host = _trace_target_host(payload.get("target")) target_ip = _resolve_trace_ipv4(host) ping_path = shutil.which("ping") trace_path = shutil.which("traceroute") if not ping_path: raise RuntimeError("ping is not installed (install iputils-ping)") if not trace_path: raise RuntimeError("traceroute is not installed") ping_rc, ping_out, ping_err = run([ping_path, "-n", "-c", "4", "-W", "2", target_ip], timeout=12) ping = _parse_ping_output("\n".join(part for part in (ping_out, ping_err) if part)) ping["reachable"] = bool(ping.get("received", 0)) ping["return_code"] = ping_rc started = time.monotonic() trace_rc, trace_out, trace_err = run([trace_path, "-n", "-q", "2", "-w", "1", "-m", "30", target_ip], timeout=68) trace_seconds = round(time.monotonic() - started, 2) hops = _parse_traceroute_output("\n".join(part for part in (trace_out, trace_err) if part), target_ip) if not hops and trace_rc not in (0, 1): raise RuntimeError(trace_err or trace_out or "Traceroute failed") geo: dict[str, dict[str, Any]] = {} geo_partial = False if bool(payload.get("geolocate", True)): geo, geo_partial = _trace_geolocate(hops, str(payload.get("language") or "en"), [target_ip]) for hop in hops: ip = str(hop.get("ip") or "") hop["geo"] = geo.get(ip) reached = any(bool(hop.get("reached")) for hop in hops) return { "ok": True, "target": host, "target_ip": target_ip, "ping": ping, "hops": hops, "hop_count": len(hops), "reached": reached, "trace_seconds": trace_seconds, "geolocate": bool(payload.get("geolocate", True)), "geo_partial": geo_partial, "target_geo": geo.get(target_ip), } def is_internal_interface(iface: str) -> bool: value = str(iface or "").strip().lower() return any(value.startswith(prefix) for prefix in INTERNAL_INTERFACE_PREFIXES) def require_valid_iface(iface: str) -> None: if not ALLOWED_IFACE_RE.fullmatch(iface): raise ValueError("Invalid WireGuard interface name") if is_internal_interface(iface): raise ValueError("This WireGuard interface name is reserved for WGTools internal transport") def install_wireguard() -> dict[str, Any]: if wg_installed(): return {"ok": True, "changed": False, "message": "WireGuard is already installed"} apt = shutil.which("apt-get") if not apt: raise RuntimeError("apt-get was not found; automatic installation is supported on Debian/Ubuntu systems") rc, out, err = run([apt, "update"], timeout=180) if rc != 0: raise RuntimeError(f"apt-get update failed: {(err or out)[-1600:]}") rc, out, err = run([apt, "install", "-y", "wireguard", "iptables", "iproute2"], timeout=240) if rc != 0: raise RuntimeError(f"WireGuard installation failed: {(err or out)[-2000:]}") if not wg_installed(): raise RuntimeError("Package installation completed, but wg/wg-quick are still unavailable") return {"ok": True, "changed": True, "message": "WireGuard installed successfully"} def validate_server_payload(iface: str, payload: dict[str, Any]) -> dict[str, Any]: require_valid_iface(iface) network_raw = str(payload.get("vpn_network", "")).strip() try: network = ipaddress.ip_network(network_raw, strict=True) except ValueError as exc: raise ValueError("VPN network must be a valid IPv4 network such as 10.77.0.0/24") from exc if network.version != 4: raise ValueError("Only IPv4 VPN networks are supported in this version") if network.prefixlen > 30: raise ValueError("VPN network must contain at least two usable addresses") address_raw = str(payload.get("server_address", "")).strip() if not address_raw: try: first_host = next(network.hosts()) except StopIteration as exc: raise ValueError("VPN network has no usable host addresses") from exc server_iface = ipaddress.ip_interface(f"{first_host}/{network.prefixlen}") else: try: server_iface = ipaddress.ip_interface(address_raw) except ValueError as exc: raise ValueError("Server address must include a prefix, for example 10.77.0.1/24") from exc if server_iface.version != 4 or server_iface.ip not in network or server_iface.network != network: raise ValueError("Server address must belong to the selected VPN network and use the same prefix") if server_iface.ip == network.network_address or server_iface.ip == network.broadcast_address: raise ValueError("Server address cannot be the network or broadcast address") try: listen_port = int(payload.get("listen_port", 51820)) except (TypeError, ValueError) as exc: raise ValueError("Listen port must be a number") from exc if not 1 <= listen_port <= 65535: raise ValueError("Listen port must be between 1 and 65535") try: mtu = int(payload.get("mtu") or 0) except (TypeError, ValueError) as exc: raise ValueError("MTU must be a number") from exc if mtu and not 576 <= mtu <= 65535: raise ValueError("MTU must be empty/0 for automatic mode or between 576 and 65535") uplink = str(payload.get("uplink_interface", "")).strip() if not uplink or not ALLOWED_IFACE_RE.fullmatch(uplink): raise ValueError("A valid uplink interface is required") if not (Path("/sys/class/net") / uplink).exists(): raise ValueError(f"Network interface {uplink} does not exist") nat_enabled = bool(payload.get("nat_enabled", True)) ip_forwarding = bool(payload.get("ip_forwarding", True)) table_raw = str(payload.get("policy_table", "")).strip() policy_table: int | None = None if table_raw: try: policy_table = int(table_raw) except ValueError as exc: raise ValueError("Policy routing table must be a number") from exc if not 1 <= policy_table <= 32765: raise ValueError("Policy routing table must be between 1 and 32765") gateway_raw = str(payload.get("gateway", "")).strip() gateway = None if gateway_raw: try: gateway = str(ipaddress.ip_address(gateway_raw)) except ValueError as exc: raise ValueError("Gateway must be a valid IPv4 address") from exc if policy_table is not None and not gateway: raise ValueError("Gateway is required when policy routing is enabled") local_raw = str(payload.get("local_network", "")).strip() local_network = None if local_raw: try: local = ipaddress.ip_network(local_raw, strict=True) except ValueError as exc: raise ValueError("Local network must be a valid IPv4 network") from exc if local.version != 4: raise ValueError("Only IPv4 local networks are supported") local_network = str(local) _validate_cross_interface_server_settings(iface, network, listen_port, policy_table) return { "network": str(network), "server_address": str(server_iface), "listen_port": listen_port, "mtu": mtu, "uplink_interface": uplink, "nat_enabled": nat_enabled, "ip_forwarding": ip_forwarding, "policy_table": policy_table, "gateway": gateway, "local_network": local_network, } def generate_private_key() -> str: wg = shutil.which("wg") if not wg: raise RuntimeError("WireGuard is not installed") rc, out, err = run([wg, "genkey"]) if rc != 0 or not out: raise RuntimeError(err or "Failed to generate WireGuard private key") return out.strip() def private_to_public(private_key: str) -> str | None: wg = shutil.which("wg") if not wg: return None rc, out, _ = run([wg, "pubkey"], input_text=private_key + "\n") return out.strip() if rc == 0 and out else None def generate_preshared_key() -> str: wg = shutil.which("wg") if not wg: raise RuntimeError("WireGuard is not installed") rc, out, err = run([wg, "genpsk"]) if rc != 0 or not out: raise RuntimeError(err or "Failed to generate WireGuard preshared key") return out.strip() def create_server(iface: str, payload: dict[str, Any]) -> dict[str, Any]: if not wg_installed(): raise RuntimeError("WireGuard is not installed") config_path = WG_DIR / f"{iface}.conf" if config_path.exists(): raise RuntimeError(f"{config_path} already exists; WGTools will not overwrite an existing server configuration") settings = validate_server_payload(iface, payload) source_groups = _prepare_network_sources(iface, str(payload.get("forward_sources") or "")) if payload.get("forward_sources") else None private_key = generate_private_key() public_key = private_to_public(private_key) network = settings["network"] uplink = settings["uplink_interface"] table = settings["policy_table"] gateway = settings["gateway"] local_network = settings["local_network"] post_up: list[str] = [] post_down: list[str] = [] if settings["ip_forwarding"]: post_up.append("sysctl -w net.ipv4.ip_forward=1") if table is not None: post_up.append(f"ip rule add from {network} table {table}") post_down.append(f"ip rule del from {network} table {table} 2>/dev/null || true") post_up.append(f"ip route add default via {gateway} dev {uplink} table {table}") post_down.append(f"ip route del default via {gateway} dev {uplink} table {table} 2>/dev/null || true") if local_network: post_up.append(f"ip route add {local_network} dev {uplink} table {table}") post_down.append(f"ip route del {local_network} dev {uplink} table {table} 2>/dev/null || true") post_up.append(f"ip route replace {network} dev {iface} table {table}") post_down.append(f"ip route del {network} dev {iface} table {table} 2>/dev/null || true") post_up.append(f"iptables -A FORWARD -i {iface} -j ACCEPT") post_down.append(f"iptables -D FORWARD -i {iface} -j ACCEPT 2>/dev/null || true") post_up.append(f"iptables -A FORWARD -o {iface} -j ACCEPT") post_down.append(f"iptables -D FORWARD -o {iface} -j ACCEPT 2>/dev/null || true") if settings["nat_enabled"]: post_up.append(f"iptables -t nat -A POSTROUTING -s {network} -o {uplink} -j MASQUERADE") post_down.append(f"iptables -t nat -D POSTROUTING -s {network} -o {uplink} -j MASQUERADE 2>/dev/null || true") lines = [ "[Interface]", f"Address = {settings['server_address']}", f"ListenPort = {settings['listen_port']}", ] if settings.get("mtu"): lines.append(f"MTU = {settings['mtu']}") lines.extend([ f"PrivateKey = {private_key}", "SaveConfig = false", "", ]) lines.extend(f"PostUp = {cmd}" for cmd in post_up) if post_down: lines.append("") lines.extend(f"PostDown = {cmd}" for cmd in post_down) lines.append("") config_text = "\n".join(lines) if payload.get("listen_address") or payload.get("listen_interface"): config_text = extended_listen_apply(iface, {"address": payload.get("listen_address"), "interface": payload.get("listen_interface")}, text_override=config_text, prepare_only=True)["content"] if payload.get("snat_address"): config_text = extended_snat_apply(iface, {"address": payload.get("snat_address"), "uplink": uplink}, text_override=config_text, prepare_only=True)["content"] WG_DIR.mkdir(parents=True, exist_ok=True) os.chmod(WG_DIR, 0o700) tmp = WG_DIR / f".{iface}.conf.tmp" tmp.write_text(config_text, encoding="utf-8") os.chmod(tmp, 0o600) os.replace(tmp, config_path) os.chmod(config_path, 0o600) if settings["ip_forwarding"]: sysctl_file = Path("/etc/sysctl.d/99-wgtools-wireguard.conf") sysctl_file.write_text("net.ipv4.ip_forward=1\n", encoding="utf-8") os.chmod(sysctl_file, 0o644) sysctl = shutil.which("sysctl") or "/usr/sbin/sysctl" run([sysctl, "-w", "net.ipv4.ip_forward=1"]) systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" rc, out, err = run([systemctl, "enable", "--now", f"wg-quick@{iface}.service"], timeout=30) if rc != 0: run([systemctl, "disable", "--now", f"wg-quick@{iface}.service"], timeout=15) failed_path = WG_DIR / f"{iface}.failed-{time.strftime('%Y%m%d-%H%M%S')}.conf" try: os.replace(config_path, failed_path) except OSError: failed_path = config_path raise RuntimeError(f"wg-quick failed to start. Generated configuration was preserved as {failed_path}. Detail: {(err or out)[-1200:]}") dump = wg_dump(iface) if not dump.get("running"): raise RuntimeError("wg-quick started without an error, but the WireGuard interface is not visible in wg show") if source_groups is not None: try: _save_extended_groups(source_groups) except Exception as exc: run([systemctl, "disable", "--now", f"wg-quick@{iface}.service"], timeout=30) failed_path = WG_DIR / f"{iface}.failed-{time.strftime('%Y%m%d-%H%M%S')}.conf" os.replace(config_path, failed_path) raise RuntimeError(f"Nie zapisano adresów do przekierowań; interfejs zatrzymano, konfigurację zachowano w {failed_path}: {exc}") from exc interface_meta_set(iface, {"display_name": str(payload.get("display_name") or iface)}) return { "ok": True, "message": "WireGuard server created and started", "interface": iface, "config_path": str(config_path), "public_key": public_key, "server": settings, } def client_meta_path(public_key: str) -> Path: digest = hashlib.sha256(public_key.encode("utf-8")).hexdigest() return CLIENT_DIR / f"{digest}.json" def load_client_meta(public_key: str) -> dict[str, Any] | None: if not public_key: return None path = client_meta_path(public_key) if not path.exists(): return None try: data = json.loads(path.read_text(encoding="utf-8")) return data if isinstance(data, dict) and data.get("public_key") == public_key else None except Exception: return None def save_client_meta(meta: dict[str, Any]) -> None: CLIENT_DIR.mkdir(parents=True, exist_ok=True) os.chmod(CLIENT_DIR, 0o700) path = client_meta_path(str(meta["public_key"])) tmp = path.with_suffix(".tmp") tmp.write_text(json.dumps(meta, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") os.chmod(tmp, 0o600) os.replace(tmp, path) os.chmod(path, 0o600) def delete_client_meta(public_key: str) -> None: path = client_meta_path(public_key) try: path.unlink() except FileNotFoundError: pass def iter_client_metas() -> list[dict[str, Any]]: result: list[dict[str, Any]] = [] if not CLIENT_DIR.exists(): return result for path in sorted(CLIENT_DIR.glob("*.json")): try: data = json.loads(path.read_text(encoding="utf-8")) if isinstance(data, dict) and data.get("public_key"): result.append(data) except Exception: continue return result def _load_groups_document() -> dict[str, Any]: if not GROUPS_PATH.exists(): return {"version": 1, "groups": []} try: data = json.loads(GROUPS_PATH.read_text(encoding="utf-8")) except Exception: return {"version": 1, "groups": []} if not isinstance(data, dict): return {"version": 1, "groups": []} raw_groups = data.get("groups") if isinstance(data.get("groups"), list) else [] groups = [item for item in raw_groups if isinstance(item, dict) and item.get("id") and item.get("interface")] return {"version": 1, "groups": groups} def _save_groups_document(data: dict[str, Any]) -> None: DATA_DIR.mkdir(parents=True, exist_ok=True) GROUPS_PATH.parent.mkdir(parents=True, exist_ok=True) tmp = GROUPS_PATH.with_suffix(".tmp") payload = {"version": 1, "groups": list(data.get("groups") or [])} tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") os.chmod(tmp, 0o600) os.replace(tmp, GROUPS_PATH) os.chmod(GROUPS_PATH, 0o600) def iter_groups(interface: str | None = None) -> list[dict[str, Any]]: groups = [dict(item) for item in _load_groups_document().get("groups", [])] if interface is not None: groups = [item for item in groups if str(item.get("interface") or "") == interface] groups.sort(key=lambda item: (str(item.get("name") or "").casefold(), str(item.get("id") or ""))) return groups def load_group(group_id: str, interface: str | None = None) -> dict[str, Any] | None: wanted = str(group_id or "").strip() if not wanted: return None for item in iter_groups(interface): if str(item.get("id") or "") == wanted: return item return None def _group_member_metas(group_id: str, interface: str) -> list[dict[str, Any]]: return [ meta for meta in iter_client_metas() if str(meta.get("interface") or "") == interface and str(meta.get("group_id") or "") == group_id ] def _validate_policy_access(value: Any, label: str, *, allow_inherit: bool) -> str: text = str(value or ("inherit" if allow_inherit else "allow")).strip().lower() allowed = {"allow", "block"} | ({"inherit"} if allow_inherit else set()) if text not in allowed: options = ", ".join(sorted(allowed)) raise ValueError(f"{label} must be one of: {options}") return text def _validate_policy_lists(allow_values: Any, deny_values: Any) -> tuple[list[str], list[str]]: allow = normalize_networks(allow_values, "Allowed policy addresses", allow_empty=True) deny = normalize_networks(deny_values, "Blocked policy addresses", allow_empty=True) for left in allow: a = ipaddress.ip_network(left, strict=False) for right in deny: b = ipaddress.ip_network(right, strict=False) if a.overlaps(b): raise ValueError(f"Allowed policy network {a} overlaps blocked policy network {b}") return allow, deny def _route_preset_values(cfg: dict[str, Any], preset: str, custom_routes: list[str] | None = None) -> list[str]: preset = str(preset or "full").strip().lower() if preset not in {"full", "full_except_local", "vpn_lan", "vpn", "custom"}: raise ValueError("Client route preset is invalid") vpn = str(cfg.get("detected", {}).get("vpn_network") or "").strip() local = str(cfg.get("detected", {}).get("local_network") or "").strip() sites = sorted(_route_remote_networks(cfg)) if preset in {"full", "full_except_local"}: return ["0.0.0.0/0"] if preset == "vpn": return [vpn] if vpn else [] if preset == "vpn_lan": out: list[str] = [] for raw in [vpn, local, *sites]: if raw and raw not in out: out.append(raw) return out return list(custom_routes or []) def _infer_route_preset(cfg: dict[str, Any], routes: list[str], protect_local: bool = False) -> str: if protect_local and "0.0.0.0/0" in routes: return "full_except_local" if routes == ["0.0.0.0/0"]: return "full" vpn = str(cfg.get("detected", {}).get("vpn_network") or "").strip() if vpn and routes == [vpn]: return "vpn" expected = _route_preset_values(cfg, "vpn_lan") if sorted(routes) == sorted(expected) and routes: return "vpn_lan" return "custom" def validate_group_payload(iface: str, payload: dict[str, Any], existing_id: str | None = None) -> dict[str, Any]: require_valid_iface(iface) cfg = parse_config(read_config_text(iface), iface) name = str(payload.get("name") or "").strip() if not name or len(name) > 64 or any(ord(ch) < 32 for ch in name): raise ValueError("Group name must be between 1 and 64 printable characters") description = str(payload.get("description") or "").strip() if len(description) > 240: raise ValueError("Group description cannot exceed 240 characters") for group in iter_groups(iface): if existing_id and str(group.get("id") or "") == existing_id: continue if str(group.get("name") or "").casefold() == name.casefold(): raise ValueError(f"A group named {name!r} already exists on {iface}") internet_access = _validate_policy_access(payload.get("internet_access", "allow"), "Internet access", allow_inherit=False) local_access = _validate_policy_access(payload.get("local_access", "allow"), "Local network access", allow_inherit=False) policy_allow, policy_deny = _validate_policy_lists(payload.get("policy_allow", []), payload.get("policy_deny", [])) route_preset = str(payload.get("route_preset") or "full").strip().lower() custom_routes = normalize_networks(payload.get("client_allowed_ips", []), "Group client routes", allow_empty=route_preset != "custom") routes = _route_preset_values(cfg, route_preset, custom_routes) if not routes: raise ValueError("Group client routes cannot be empty") dns = normalize_dns(payload.get("dns", [])) try: keepalive = int(payload.get("persistent_keepalive", 25)) except (TypeError, ValueError) as exc: raise ValueError("Persistent keepalive must be a number") from exc if not 0 <= keepalive <= 65535: raise ValueError("Persistent keepalive must be between 0 and 65535") return { "name": name, "description": description, "policy": { "internet_access": internet_access, "local_access": local_access, "allow": policy_allow, "deny": policy_deny, }, "defaults": { "route_preset": route_preset, "client_allowed_ips": routes, "dns": dns, "persistent_keepalive": keepalive, }, } def _save_group_record(group: dict[str, Any]) -> None: data = _load_groups_document() groups = list(data.get("groups") or []) replaced = False for idx, current in enumerate(groups): if str(current.get("id") or "") == str(group.get("id") or ""): groups[idx] = group replaced = True break if not replaced: groups.append(group) data["groups"] = groups _save_groups_document(data) def _sync_group_policy_transaction(iface: str) -> Path: old_text = read_config_text(iface) cfg = parse_config(old_text, iface) new_text = sync_managed_client_policies(old_text, iface) return write_config_transaction(iface, new_text, [], [], cfg.get("detected", {}).get("policy_table")) def group_create(iface: str, payload: dict[str, Any]) -> dict[str, Any]: values = validate_group_payload(iface, payload) now = int(time.time()) group = { "id": "g_" + secrets.token_hex(8), "interface": iface, **values, "created_at": now, "updated_at": now, } _save_group_record(group) return {"ok": True, "message": f"Group {group['name']} created", "group": group} def group_update(iface: str, payload: dict[str, Any]) -> dict[str, Any]: group_id = str(payload.get("group_id") or "").strip() old_group = load_group(group_id, iface) if not old_group: raise ValueError("Client group was not found") values = validate_group_payload(iface, payload, existing_id=group_id) new_group = {**old_group, **values, "updated_at": int(time.time())} old_doc = _load_groups_document() _save_group_record(new_group) backup = None policy_changed = old_group.get("policy") != new_group.get("policy") try: # Name/description/default-template edits do not alter live firewall # policy and therefore must not rewrite the WireGuard config. if policy_changed and _group_member_metas(group_id, iface): backup = _sync_group_policy_transaction(iface) except Exception: _save_groups_document(old_doc) raise return {"ok": True, "message": f"Group {new_group['name']} updated", "group": new_group, "backup": str(backup) if backup else ""} def group_delete(iface: str, payload: dict[str, Any]) -> dict[str, Any]: group_id = str(payload.get("group_id") or "").strip() group = load_group(group_id, iface) if not group: raise ValueError("Client group was not found") move_to = str(payload.get("move_to_group_id") or "").strip() if move_to == group_id: raise ValueError("Clients cannot be moved to the group being deleted") target = load_group(move_to, iface) if move_to else None if move_to and not target: raise ValueError("Destination client group was not found") old_doc = _load_groups_document() members = _group_member_metas(group_id, iface) old_metas = {str(meta.get("public_key") or ""): dict(meta) for meta in members} try: for meta in members: meta["group_id"] = move_to meta["policy_mode"] = "inherit" if move_to else "" meta["config_mode"] = "inherit" if move_to else "" meta["internet_access"] = "inherit" meta["local_access"] = "inherit" meta["policy_allow"] = [] meta["policy_deny"] = [] meta["updated_at"] = int(time.time()) save_client_meta(meta) data = _load_groups_document() data["groups"] = [item for item in data.get("groups", []) if str(item.get("id") or "") != group_id] _save_groups_document(data) backup = _sync_group_policy_transaction(iface) if members else None except Exception: _save_groups_document(old_doc) for old_meta in old_metas.values(): save_client_meta(old_meta) raise return { "ok": True, "message": f"Group {group.get('name') or group_id} deleted", "moved_clients": len(members), "backup": str(backup) if backup else "", } def _client_group_policy(meta: dict[str, Any], iface: str, group: dict[str, Any] | None = None) -> dict[str, Any] | None: group_id = str(meta.get("group_id") or "").strip() if not group_id: return None if group is None: group = load_group(group_id, iface) if not group: return None mode = str(meta.get("policy_mode") or "inherit").strip().lower() if mode not in {"inherit", "custom"}: mode = "inherit" group_policy = group.get("policy") if isinstance(group.get("policy"), dict) else {} base_internet = str(group_policy.get("internet_access") or "allow") base_local = str(group_policy.get("local_access") or "allow") group_allow = normalize_networks(group_policy.get("allow", []), "Group allowed addresses", allow_empty=True) group_deny = normalize_networks(group_policy.get("deny", []), "Group blocked addresses", allow_empty=True) client_allow = normalize_networks(meta.get("policy_allow", []), "Client allowed addresses", allow_empty=True) client_deny = normalize_networks(meta.get("policy_deny", []), "Client blocked addresses", allow_empty=True) if mode == "custom": internet = _validate_policy_access(meta.get("internet_access", "allow"), "Internet access", allow_inherit=False) local = _validate_policy_access(meta.get("local_access", "allow"), "Local network access", allow_inherit=False) group_allow = [] group_deny = [] else: internet_override = _validate_policy_access(meta.get("internet_access", "inherit"), "Internet access", allow_inherit=True) local_override = _validate_policy_access(meta.get("local_access", "inherit"), "Local network access", allow_inherit=True) internet = base_internet if internet_override == "inherit" else internet_override local = base_local if local_override == "inherit" else local_override return { "group": group, "mode": mode, "internet_access": internet, "local_access": local, "group_allow": group_allow, "group_deny": group_deny, "client_allow": client_allow, "client_deny": client_deny, } def _policy_logical_rules(meta: dict[str, Any], cfg: dict[str, Any], iface: str) -> list[tuple[str, str]]: group_policy = _client_group_policy(meta, iface) if not group_policy: if not meta.get("protect_local_networks"): return [] exclusions = _policy_exclusions(meta) effective_networks = [network for network in protected_networks(cfg) if network not in exclusions] effective_objs = [ipaddress.ip_network(network, strict=False) for network in effective_networks] allow_exceptions = [] for raw in _local_access_exceptions(meta): exc = ipaddress.ip_network(raw, strict=False) if any(exc.subnet_of(parent) for parent in effective_objs): allow_exceptions.append(str(exc)) return [(dest, "ACCEPT") for dest in allow_exceptions] + [(dest, "REJECT") for dest in effective_networks] rules: list[tuple[str, str]] = [] # Client-specific exceptions intentionally outrank group exceptions. rules.extend((dest, "REJECT") for dest in group_policy["client_deny"]) rules.extend((dest, "ACCEPT") for dest in group_policy["client_allow"]) rules.extend((dest, "REJECT") for dest in group_policy["group_deny"]) rules.extend((dest, "ACCEPT") for dest in group_policy["group_allow"]) local_networks = protected_networks(cfg) vpn_network = str(cfg.get("detected", {}).get("vpn_network") or "").strip() if group_policy["internet_access"] == "block": # Internet policy must stay independent from future peer-isolation # controls, so the VPN pool itself remains reachable. if vpn_network: rules.append((vpn_network, "ACCEPT")) if group_policy["local_access"] == "allow": rules.extend((dest, "ACCEPT") for dest in local_networks) rules.append(("0.0.0.0/0", "REJECT")) elif group_policy["local_access"] == "block": rules.extend((dest, "REJECT") for dest in local_networks) # Remove exact duplicate rules while preserving priority/order. out: list[tuple[str, str]] = [] seen: set[tuple[str, str]] = set() for destination, action in rules: item = (destination, action) if item not in seen: seen.add(item) out.append(item) return out def _group_defaults_for_config(group: dict[str, Any], cfg: dict[str, Any]) -> dict[str, Any]: defaults = group.get("defaults") if isinstance(group.get("defaults"), dict) else {} preset = str(defaults.get("route_preset") or "full").strip().lower() stored_routes = normalize_networks(defaults.get("client_allowed_ips", []), "Group client routes", allow_empty=True) routes = _route_preset_values(cfg, preset, stored_routes) return { "route_preset": preset, "client_allowed_ips": routes, "dns": normalize_dns(defaults.get("dns", [])), "persistent_keepalive": int(defaults.get("persistent_keepalive", 25) or 0), } def _client_group_snapshot( meta: dict[str, Any], cfg: dict[str, Any], iface: str, groups_by_id: dict[str, dict[str, Any]] | None = None, ) -> dict[str, Any]: group_id = str(meta.get("group_id") or "").strip() group = (groups_by_id or {}).get(group_id) if groups_by_id is not None else (load_group(group_id, iface) if group_id else None) if not group: return { "group_id": "", "group_name": "", "group_policy_mode": "", "group_config_differs": False, "effective_policy": None, } policy = _client_group_policy(meta, iface, group) defaults = _group_defaults_for_config(group, cfg) current_routes = normalize_networks(meta.get("client_allowed_ips", []), "Client routes", allow_empty=True) current_preset = str(meta.get("client_route_preset") or "").strip().lower() if not current_preset: current_preset = _infer_route_preset(cfg, current_routes, bool(meta.get("protect_local_networks"))) config_mode = str(meta.get("config_mode") or "inherit").strip().lower() if config_mode not in {"inherit", "custom"}: config_mode = "inherit" differs = config_mode == "inherit" and ( current_preset != defaults["route_preset"] or sorted(current_routes) != sorted(defaults["client_allowed_ips"]) or normalize_dns(meta.get("dns", [])) != defaults["dns"] or int(meta.get("persistent_keepalive", 25) or 0) != defaults["persistent_keepalive"] ) return { "group_id": group_id, "group_name": str(group.get("name") or ""), "group_policy_mode": str(meta.get("policy_mode") or "inherit"), "group_config_mode": config_mode, "group_config_differs": differs, "effective_policy": { "internet_access": policy.get("internet_access") if policy else "allow", "local_access": policy.get("local_access") if policy else "allow", "allow": [*(policy.get("group_allow") or []), *(policy.get("client_allow") or [])] if policy else [], "deny": [*(policy.get("group_deny") or []), *(policy.get("client_deny") or [])] if policy else [], }, } def client_policy_tag(public_key: str) -> str: return "wgtools-protect-" + hashlib.sha256(public_key.encode("utf-8")).hexdigest()[:12] def protected_networks(cfg: dict[str, Any]) -> list[str]: values: list[str] = [] local = str(cfg.get("detected", {}).get("local_network") or default_route_info().get("local_network") or "").strip() if local: values.append(local) values.extend(sorted(_route_remote_networks(cfg))) result: list[str] = [] seen: set[str] = set() for raw in values: try: net = ipaddress.ip_network(raw, strict=False) except ValueError: continue if net.version != 4: continue value = str(net) if value not in seen: seen.add(value) result.append(value) return result def _policy_exclusions(meta: dict[str, Any]) -> set[str]: result: set[str] = set() for raw in meta.get("protect_local_exclusions") or []: try: net = ipaddress.ip_network(str(raw).strip(), strict=False) except ValueError: continue if net.version == 4: result.add(str(net)) return result def _local_access_exceptions(meta: dict[str, Any]) -> list[str]: result: list[str] = [] for raw in meta.get("local_access_exceptions") or []: try: net = ipaddress.ip_network(str(raw).strip(), strict=False) except ValueError: continue if net.version != 4: continue value = str(net) if value not in result: result.append(value) return result def _set_policy_exclusion_by_tag(tag: str, destination: str) -> dict[str, Any] | None: meta = find_policy_meta_by_tag(tag) if not meta: return None old_meta = dict(meta) try: network = ipaddress.ip_network(str(destination).strip(), strict=False) except ValueError as exc: raise ValueError("Managed policy destination is not a valid IPv4 network") from exc exclusions = _policy_exclusions(meta) exclusions.add(str(network)) meta["protect_local_exclusions"] = sorted(exclusions) meta["updated_at"] = int(time.time()) save_client_meta(meta) return old_meta def managed_policy_commands( public_key: str, vpn_address: str, logical_rules: list[tuple[str, str]], ) -> tuple[list[str], list[str]]: tag = client_policy_tag(public_key) source = vpn_address up: list[str] = [] down: list[str] = [] # logical_rules is highest priority first. PostUp uses iptables -I, so write # the commands in reverse order to reproduce that priority after boot. for destination, action in reversed(logical_rules): cmd = f"iptables -I FORWARD -s {source} -d {destination} -m comment --comment {tag} -j {action}" up.append(cmd) down.append(cmd.replace("iptables -I FORWARD", "iptables -D FORWARD", 1) + " 2>/dev/null || true") return up, down def _managed_policy_hook_commands(text: str) -> tuple[list[str], list[str]]: up: list[str] = [] down: list[str] = [] for raw in text.replace("\r\n", "\n").replace("\r", "\n").splitlines(): if "=" not in raw: continue key, value = [x.strip() for x in raw.split("=", 1)] if "--comment wgtools-protect-" not in value: continue if key.lower() == "postup": up.append(value) elif key.lower() == "postdown": down.append(value) return up, down def _peer_isolation_commands(public_key: str, vpn_address: str, vpn_network: str) -> tuple[list[str], list[str]]: """Build symmetric FORWARD rules that isolate one VPN client from peers. The rules intentionally target only the WireGuard address pool. They do not affect INPUT traffic to the WGTools server itself and do not block Internet, local-LAN or Site-to-site destinations controlled by the other client/group policy settings. """ if not vpn_network: return [], [] tag = client_policy_tag(public_key) source = str(ipaddress.ip_network(vpn_address, strict=False)) destination = source specs = [ (source, vpn_network, "REJECT"), (vpn_network, destination, "REJECT"), ] up: list[str] = [] down: list[str] = [] for src, dst, action in specs: cmd = f"iptables -I FORWARD -s {src} -d {dst} -m comment --comment {tag} -j {action}" up.append(cmd) down.append(cmd.replace("iptables -I FORWARD", "iptables -D FORWARD", 1) + " 2>/dev/null || true") return up, down def sync_managed_client_policies(text: str, iface: str) -> str: old_up, old_down = _managed_policy_hook_commands(text) if old_up or old_down: text = _edit_interface_hooks(text, old_up, old_down, [], []) cfg = parse_config(text, iface) peers = {str(p.get("public_key") or ""): p for p in cfg.get("peers", [])} add_up: list[str] = [] add_down: list[str] = [] isolation_up: list[str] = [] isolation_down: list[str] = [] vpn_network = str(cfg.get("detected", {}).get("vpn_network") or "").strip() for meta in iter_client_metas(): if meta.get("interface") and str(meta.get("interface")) != iface: continue public_key = str(meta.get("public_key") or "") peer = peers.get(public_key) if not peer: continue vpn_address = str(peer.get("vpn_address") or meta.get("vpn_address") or "").strip() if not vpn_address: continue logical_rules = _policy_logical_rules(meta, cfg, iface) if logical_rules: up, down = managed_policy_commands(public_key, vpn_address, logical_rules) add_up.extend(up) add_down.extend(down) if bool(meta.get("peer_isolation")) and not list(peer.get("remote_networks") or []): up, down = _peer_isolation_commands(public_key, vpn_address, vpn_network) isolation_up.extend(up) isolation_down.extend(down) # Isolation commands are emitted after normal policy commands because all # of them use iptables -I. Executing them last places isolation at the top # of FORWARD, so a group/client ACCEPT rule cannot accidentally bypass it. add_up.extend(isolation_up) add_down.extend(isolation_down) if add_up or add_down: text = _edit_interface_hooks(text, [], [], add_up, add_down) return text def detach_managed_policy(text: str, tag: str) -> str: if not tag: return text lines = [] marker = f"--comment {tag}" for raw in text.splitlines(): if marker in raw: raw = raw.replace(f" -m comment --comment {tag}", "") lines.append(raw) return "\n".join(lines).rstrip() + "\n" def find_policy_meta_by_tag(tag: str) -> dict[str, Any] | None: if not tag: return None for meta in iter_client_metas(): if client_policy_tag(str(meta.get("public_key") or "")) == tag: return meta return None def disable_policy_by_tag(tag: str) -> dict[str, Any] | None: meta = find_policy_meta_by_tag(tag) if not meta: return None old_meta = dict(meta) meta["protect_local_networks"] = False meta["updated_at"] = int(time.time()) save_client_meta(meta) return old_meta def next_free_address(cfg: dict[str, Any]) -> str | None: vpn_network = cfg.get("detected", {}).get("vpn_network") if not vpn_network: return None try: network = ipaddress.ip_network(vpn_network, strict=True) except ValueError: return None if network.version != 4: return None used: set[ipaddress.IPv4Address] = set() address = cfg.get("interface", {}).get("address") if address: for raw in str(address).split(","): try: used.add(ipaddress.ip_interface(raw.strip()).ip) except ValueError: pass for peer in cfg.get("peers", []): raw = peer.get("vpn_address") if raw: try: used.add(ipaddress.ip_interface(raw).ip) except ValueError: pass # Keep this bounded even if somebody configured a very large VPN network. for idx, host in enumerate(network.hosts()): if idx > 65535: break if host not in used: return f"{host}/32" return None def normalize_name(value: Any) -> str: name = str(value or "").strip() if not name or len(name) > 64: raise ValueError("Client name must be between 1 and 64 characters") if any(ord(ch) < 32 for ch in name) or "\n" in name or "\r" in name: raise ValueError("Client name contains unsupported control characters") return name def normalize_networks(value: Any, label: str, allow_empty: bool = True) -> list[str]: if value is None: items: list[Any] = [] elif isinstance(value, str): items = [x.strip() for x in re.split(r"[,\n]+", value) if x.strip()] elif isinstance(value, list): items = value else: raise ValueError(f"{label} must be a list of networks") result: list[str] = [] for raw in items: try: net = ipaddress.ip_network(str(raw).strip(), strict=False) except ValueError as exc: raise ValueError(f"Invalid network in {label}: {raw}") from exc if net.version != 4: raise ValueError(f"Only IPv4 networks are supported in {label}") canonical = str(net) if canonical not in result: result.append(canonical) if not allow_empty and not result: raise ValueError(f"{label} cannot be empty") return result def normalize_dns(value: Any) -> list[str]: if value is None: return [] if isinstance(value, str): items = [x.strip() for x in value.split(",") if x.strip()] elif isinstance(value, list): items = [str(x).strip() for x in value if str(x).strip()] else: raise ValueError("DNS must be a comma-separated list of IP addresses") result: list[str] = [] for raw in items: try: ip = ipaddress.ip_address(raw) except ValueError as exc: raise ValueError(f"Invalid DNS address: {raw}") from exc if ip.version != 4: raise ValueError("Only IPv4 DNS addresses are supported in this version") text = str(ip) if text not in result: result.append(text) return result def _normalize_schedule_time(value: Any, label: str) -> str: text = str(value or "").strip() if not re.fullmatch(r"(?:[01]\d|2[0-3]):[0-5]\d", text): raise ValueError(f"{label} must use HH:MM in 24-hour format") return text def _normalize_schedule_days(value: Any) -> list[int]: if value is None: return [] if not isinstance(value, list): raise ValueError("Access schedule days must be a list") result: list[int] = [] for raw in value: try: day = int(raw) except (TypeError, ValueError) as exc: raise ValueError("Access schedule days must be integers from 0 to 6") from exc if day < 0 or day > 6: raise ValueError("Access schedule days must be integers from 0 to 6") if day not in result: result.append(day) return sorted(result) def _schedule_minutes(value: str) -> int: hour, minute = value.split(":", 1) return int(hour) * 60 + int(minute) def client_schedule_allows(meta: dict[str, Any], now: int | None = None) -> bool: if not bool(meta.get("access_schedule_enabled")): return True days = _normalize_schedule_days(meta.get("access_schedule_days") or []) if not days: return False start = _normalize_schedule_time(meta.get("access_schedule_start") or "08:00", "Access schedule start") end = _normalize_schedule_time(meta.get("access_schedule_end") or "19:00", "Access schedule end") current = datetime.fromtimestamp(int(now if now is not None else time.time())).astimezone() current_minute = current.hour * 60 + current.minute start_minute = _schedule_minutes(start) end_minute = _schedule_minutes(end) weekday = current.weekday() if start_minute == end_minute: return weekday in days if start_minute < end_minute: return weekday in days and start_minute <= current_minute < end_minute previous_weekday = (weekday - 1) % 7 return (weekday in days and current_minute >= start_minute) or (previous_weekday in days and current_minute < end_minute) def schedule_settings_disabled(settings: dict[str, Any], now: int | None = None) -> bool: if not bool(settings.get("access_schedule_enabled")): return False meta = { "access_schedule_enabled": True, "access_schedule_days": list(settings.get("access_schedule_days") or []), "access_schedule_start": str(settings.get("access_schedule_start") or "08:00"), "access_schedule_end": str(settings.get("access_schedule_end") or "19:00"), } return not client_schedule_allows(meta, now) def validate_client_payload(iface: str, payload: dict[str, Any], existing_public_key: str | None = None) -> dict[str, Any]: require_valid_iface(iface) config_path = WG_DIR / f"{iface}.conf" if not config_path.exists(): raise RuntimeError("WireGuard server is not configured") cfg = parse_config(read_config_text(iface), iface) vpn_raw = cfg.get("detected", {}).get("vpn_network") if not vpn_raw: raise RuntimeError("WGTools could not determine the VPN network from the server configuration") vpn_network = ipaddress.ip_network(vpn_raw, strict=True) name = normalize_name(payload.get("name")) client_type = str(payload.get("type", "client")).strip().lower() if client_type not in {"client", "site_to_site"}: raise ValueError("Client type must be client or site_to_site") group_id = str(payload.get("group_id") or "").strip() group = load_group(group_id, iface) if group_id else None if group_id and not group: raise ValueError("Selected client group does not exist on this WireGuard interface") if group_id and client_type != "client": raise ValueError("Client groups are available only for normal clients, not Site-to-site peers") address_raw = str(payload.get("vpn_address", "")).strip() if not address_raw: address_raw = next_free_address(cfg) or "" try: addr_iface = ipaddress.ip_interface(address_raw) except ValueError as exc: raise ValueError("VPN address must be a valid IPv4 address such as 10.77.0.10/32") from exc if addr_iface.version != 4 or addr_iface.ip not in vpn_network: raise ValueError("VPN address must belong to the configured VPN network") if addr_iface.ip in {vpn_network.network_address, vpn_network.broadcast_address}: raise ValueError("VPN address cannot be the network or broadcast address") vpn_address = f"{addr_iface.ip}/32" server_address = cfg.get("interface", {}).get("address") if server_address: try: server_ip = ipaddress.ip_interface(str(server_address).split(",")[0].strip()).ip if addr_iface.ip == server_ip: raise ValueError("VPN address is already used by the WireGuard server") except ValueError as exc: if str(exc).startswith("VPN address"): raise remote_networks = normalize_networks(payload.get("remote_networks", []), "Remote networks", allow_empty=True) if client_type == "client" and remote_networks: client_type = "site_to_site" if client_type == "site_to_site" and not remote_networks: raise ValueError("At least one remote network is required for a Site-to-site peer") try: keepalive = int(payload.get("persistent_keepalive", 25)) except (TypeError, ValueError) as exc: raise ValueError("Persistent keepalive must be a number") from exc if not 0 <= keepalive <= 65535: raise ValueError("Persistent keepalive must be between 0 and 65535") connection_mode = str(payload.get("connection_mode") or "direct").strip().lower() if connection_mode not in {"direct", "relay"}: raise ValueError("Client connection mode must be direct or relay") relay_vps_id = str(payload.get("relay_vps_id") or "").strip() if connection_mode == "relay": relay = installed_relay_for_interface(relay_vps_id, iface) if not relay: raise ValueError("Selected VPS Relay is not installed for this WireGuard interface") endpoint = relay_client_endpoint(relay) else: relay_vps_id = "" endpoint = str(payload.get("endpoint", "")).strip() if endpoint and (len(endpoint) > 255 or any(ch.isspace() for ch in endpoint)): raise ValueError("Endpoint must be a host or IP with optional port and no spaces") if endpoint and ":" not in endpoint: port = cfg.get("interface", {}).get("listen_port") or 51820 endpoint = f"{endpoint}:{port}" client_allowed_ips = normalize_networks(payload.get("client_allowed_ips", []), "Client routes", allow_empty=existing_public_key is not None) if client_allowed_ips and not endpoint: raise ValueError("Server address/domain is required for a generated client configuration") route_preset = str(payload.get("route_preset") or "").strip().lower() if route_preset and route_preset not in {"full", "full_except_local", "vpn_lan", "vpn", "custom"}: raise ValueError("Client route preset is invalid") if not route_preset: route_preset = _infer_route_preset(cfg, client_allowed_ips, bool(payload.get("protect_local_networks"))) protect_local_networks = bool(payload.get("protect_local_networks")) and client_type == "client" and not group_id local_access_exceptions = normalize_networks(payload.get("local_access_exceptions", []), "Local access exceptions", allow_empty=True) if protect_local_networks: # The client remains a plain full tunnel. Local/Site-to-site blocking is # a server-side WGTools policy and must not clutter AllowedIPs. client_allowed_ips = ["0.0.0.0/0"] protected_objs = [ipaddress.ip_network(raw, strict=False) for raw in protected_networks(cfg)] validated_exceptions: list[str] = [] for raw in local_access_exceptions: exc = ipaddress.ip_network(raw, strict=False) parents = [parent for parent in protected_objs if exc.subnet_of(parent)] if not parents: raise ValueError(f"Local access exception {exc} is outside the protected local/Site-to-site networks") if any(exc == parent for parent in parents): raise ValueError(f"Local access exception {exc} opens an entire protected network; remove that network restriction instead") value = str(exc) if value not in validated_exceptions: validated_exceptions.append(value) local_access_exceptions = validated_exceptions else: local_access_exceptions = [] dns = normalize_dns(payload.get("dns", [])) config_mode = "" if group_id: config_mode = str(payload.get("config_mode") or "inherit").strip().lower() if config_mode not in {"inherit", "custom"}: raise ValueError("Group client configuration mode must be inherit or custom") if config_mode == "inherit" and existing_public_key is None: defaults = _group_defaults_for_config(group, cfg) route_preset = defaults["route_preset"] client_allowed_ips = list(defaults["client_allowed_ips"]) dns = list(defaults["dns"]) keepalive = int(defaults["persistent_keepalive"] or 0) use_preshared_key = bool(payload.get("use_preshared_key", True)) peer_isolation = bool(payload.get("peer_isolation")) and client_type == "client" try: expires_at = int(payload.get("expires_at") or 0) except (TypeError, ValueError) as exc: raise ValueError("Expiration time must be a Unix timestamp") from exc if expires_at < 0 or expires_at > 4102444800: raise ValueError("Expiration time is outside the supported range") if expires_at and expires_at <= int(time.time()): raise ValueError("Expiration time must be in the future") expiration_action = str(payload.get("expiration_action") or "delete").strip().lower() if expiration_action not in {"delete", "disable"}: raise ValueError("Expiration action must be delete or disable") if not expires_at: expiration_action = "delete" if client_type == "site_to_site": expiration_action = "delete" access_schedule_enabled = bool(payload.get("access_schedule_enabled")) and client_type != "site_to_site" access_schedule_days = _normalize_schedule_days(payload.get("access_schedule_days") or []) if access_schedule_enabled else [] access_schedule_start = _normalize_schedule_time(payload.get("access_schedule_start") or "08:00", "Access schedule start") access_schedule_end = _normalize_schedule_time(payload.get("access_schedule_end") or "19:00", "Access schedule end") if access_schedule_enabled and not access_schedule_days: raise ValueError("Choose at least one day for the access schedule") policy_mode = "" internet_access = "" local_access = "" policy_allow: list[str] = [] policy_deny: list[str] = [] if group_id: policy_mode = str(payload.get("policy_mode") or "inherit").strip().lower() if policy_mode not in {"inherit", "custom"}: raise ValueError("Group policy mode must be inherit or custom") internet_access = _validate_policy_access( payload.get("internet_access", "inherit" if policy_mode == "inherit" else "allow"), "Internet access", allow_inherit=policy_mode == "inherit", ) local_access = _validate_policy_access( payload.get("local_access", "inherit" if policy_mode == "inherit" else "allow"), "Local network access", allow_inherit=policy_mode == "inherit", ) policy_allow, policy_deny = _validate_policy_lists(payload.get("policy_allow", []), payload.get("policy_deny", [])) candidate_server_allowed = [vpn_address] + remote_networks for peer in cfg.get("peers", []): pub = peer.get("public_key") if existing_public_key and pub == existing_public_key: continue peer_name = str(peer.get("name") or "").strip() if peer_name and peer_name.casefold() == name.casefold(): raise ValueError(f"A peer named {name!r} already exists") for used_raw in peer.get("allowed_ips", []): try: used = ipaddress.ip_network(used_raw, strict=False) except ValueError: continue for candidate_raw in candidate_server_allowed: candidate = ipaddress.ip_network(candidate_raw, strict=False) if candidate.overlaps(used): raise ValueError(f"Address/network {candidate} overlaps with peer {peer.get('name') or pub}") return { "name": name, "type": client_type, "vpn_address": vpn_address, "remote_networks": remote_networks, "persistent_keepalive": keepalive, "endpoint": endpoint, "client_allowed_ips": client_allowed_ips, "client_route_preset": route_preset, "protect_local_networks": protect_local_networks, "local_access_exceptions": local_access_exceptions, "dns": dns, "group_id": group_id, "policy_mode": policy_mode, "internet_access": internet_access, "local_access": local_access, "policy_allow": policy_allow, "policy_deny": policy_deny, "config_mode": config_mode, "use_preshared_key": use_preshared_key, "peer_isolation": peer_isolation, "expires_at": expires_at, "expiration_action": expiration_action, "access_schedule_enabled": access_schedule_enabled, "access_schedule_days": access_schedule_days, "access_schedule_start": access_schedule_start, "access_schedule_end": access_schedule_end, "connection_mode": connection_mode, "relay_vps_id": relay_vps_id, "cfg": cfg, } def peer_block(name: str, public_key: str, allowed_ips: list[str], keepalive: int, preshared_key: str = "") -> str: lines = [ f"# ---{name}---", "", "[Peer]", f"PublicKey = {public_key}", ] if preshared_key: lines.append(f"PresharedKey = {preshared_key}") lines.append(f"AllowedIPs = {','.join(allowed_ips)}") if keepalive: lines.append(f"PersistentKeepalive = {keepalive}") return "\n".join(lines) def peer_block_spans(text: str) -> list[dict[str, Any]]: lines = text.splitlines() section_starts = [i for i, line in enumerate(lines) if line.strip().lower() == "[peer]"] block_starts: list[int] = [] for section_start in section_starts: block_start = section_start j = section_start - 1 while j >= 0 and not lines[j].strip(): j -= 1 if j >= 0 and parse_comment_name(lines[j]) is not None: block_start = j block_starts.append(block_start) spans: list[dict[str, Any]] = [] for pos, section_start in enumerate(section_starts): block_start = block_starts[pos] block_end = block_starts[pos + 1] if pos + 1 < len(block_starts) else len(lines) public_key = None for line in lines[section_start + 1:block_end]: if "=" not in line: continue key, value = [x.strip() for x in line.split("=", 1)] if key.lower() == "publickey": public_key = value break spans.append({"start": block_start, "end": block_end, "section_start": section_start, "public_key": public_key}) return spans def find_peer_span(text: str, public_key: str) -> tuple[int, int] | None: for span in peer_block_spans(text): if span.get("public_key") == public_key: return int(span["start"]), int(span["end"]) return None def peer_preshared_key(text: str, public_key: str) -> str: span = find_peer_span(text, public_key) if not span: return "" start, end = span lines = text.splitlines() for raw in lines[start:end]: if "=" not in raw: continue key, value = [part.strip() for part in raw.split("=", 1)] if key.lower() == "presharedkey": return value return "" def replace_peer_block(text: str, public_key: str, replacement: str | None) -> str: span = find_peer_span(text, public_key) if span is None: raise ValueError("Peer was not found in the server configuration") lines = text.splitlines() start, end = span new_lines = lines[:start] if replacement: if new_lines and new_lines[-1].strip(): new_lines.append("") new_lines.extend(replacement.splitlines()) new_lines.append("") new_lines.extend(lines[end:]) result = "\n".join(new_lines).strip() + "\n" result = re.sub(r"\n{3,}", "\n\n", result) return result def append_peer_block(text: str, block: str) -> str: return text.rstrip() + "\n\n" + block.strip() + "\n" def update_route_hooks(text: str, iface: str, remove_networks: list[str], add_networks: list[str], policy_table: str | int | None) -> str: remove = set(remove_networks) lines = text.splitlines() spans = peer_block_spans(text) first_peer = int(spans[0]["start"]) if spans else len(lines) interface_lines = lines[:first_peer] peer_lines = lines[first_peer:] def route_network_from_hook(line: str) -> str | None: if "=" not in line: return None key, cmd = [x.strip() for x in line.split("=", 1)] if key.lower() not in {"postup", "postdown"}: return None m = re.search(r"\bip\s+route\s+(?:add|replace|del)\s+(\S+)\s+dev\s+" + re.escape(iface) + r"(?:\s+table\s+\d+)?\b", cmd) return m.group(1) if m else None cleaned: list[str] = [] for line in interface_lines: net = route_network_from_hook(line) if net and net in remove: continue cleaned.append(line) existing = set() for line in cleaned: net = route_network_from_hook(line) if net: existing.add((line.split("=", 1)[0].strip().lower(), net, "table" in line)) additions: list[str] = [] for net in add_networks: if policy_table: if ("postup", net, True) not in existing: additions.append(f"PostUp = ip route add {net} dev {iface} table {policy_table}") if ("postdown", net, True) not in existing: additions.append(f"PostDown = ip route del {net} dev {iface} table {policy_table} 2>/dev/null || true") if ("postup", net, False) not in existing: additions.append(f"PostUp = ip route replace {net} dev {iface}") if ("postdown", net, False) not in existing: additions.append(f"PostDown = ip route del {net} dev {iface} 2>/dev/null || true") while cleaned and not cleaned[-1].strip(): cleaned.pop() if additions: cleaned.append("") cleaned.extend(additions) if peer_lines: cleaned.append("") cleaned.extend(peer_lines) return re.sub(r"\n{3,}", "\n\n", "\n".join(cleaned).strip() + "\n") def make_backup(iface: str, config_path: Path) -> Path: BACKUP_DIR.mkdir(parents=True, exist_ok=True) os.chmod(BACKUP_DIR, 0o700) stamp = time.strftime("%Y%m%d-%H%M%S") path = BACKUP_DIR / f"{iface}-{stamp}-{time.time_ns() % 1000000:06d}.conf" shutil.copy2(config_path, path) os.chmod(path, 0o600) files = sorted(BACKUP_DIR.glob(f"{iface}-*.conf"), key=lambda x: x.stat().st_mtime, reverse=True) for stale in files[backup_retention():]: try: stale.unlink() except OSError: pass return path def validate_config_file(path: Path) -> str: wg_quick = shutil.which("wg-quick") if not wg_quick: raise RuntimeError("wg-quick is not installed") rc, out, err = run([wg_quick, "strip", str(path)], timeout=12) if rc != 0 or not out.strip(): raise RuntimeError(f"WireGuard configuration validation failed: {err or out}") return out + "\n" def sync_runtime(iface: str, config_path: Path) -> None: dump = wg_dump(iface) if not dump.get("running"): return stripped = validate_config_file(config_path) sync_path = Path(f"/run/wgtools-{iface}.sync.conf") sync_path.write_text(stripped, encoding="utf-8") os.chmod(sync_path, 0o600) wg = shutil.which("wg") if not wg: raise RuntimeError("wg is not installed") rc, out, err = run([wg, "syncconf", iface, str(sync_path)], timeout=12) try: sync_path.unlink() except FileNotFoundError: pass if rc != 0: raise RuntimeError(f"wg syncconf failed: {err or out}") def apply_remote_routes(iface: str, remove_networks: list[str], add_networks: list[str], policy_table: str | int | None) -> None: if not wg_dump(iface).get("running"): return ip = shutil.which("ip") or "/usr/sbin/ip" for net in remove_networks: run([ip, "route", "del", net, "dev", iface], timeout=5) if policy_table: run([ip, "route", "del", net, "dev", iface, "table", str(policy_table)], timeout=5) for net in add_networks: rc, out, err = run([ip, "route", "replace", net, "dev", iface], timeout=5) if rc != 0: raise RuntimeError(f"Failed to install route {net}: {err or out}") if policy_table: rc, out, err = run([ip, "route", "replace", net, "dev", iface, "table", str(policy_table)], timeout=5) if rc != 0: raise RuntimeError(f"Failed to install route {net} in table {policy_table}: {err or out}") def _managed_runtime_rule(command: str) -> tuple[str, str, str, str] | None: compact = " ".join(str(command).split()) match = re.fullmatch( r"iptables -I FORWARD -s ([^\s]+) -d ([^\s]+) -m comment --comment (wgtools-protect-[A-Za-z0-9_-]+) -j (REJECT|DROP|ACCEPT)", compact, ) if not match: return None return match.group(1), match.group(2), match.group(3), match.group(4) def _parse_live_managed_policy_rule(raw: str) -> tuple[tuple[str, str, str, str], list[str]]: """Parse one ``iptables -S FORWARD`` rule owned by WGTools. iptables normalises rules when printing them. In particular, an explicit ``-d 0.0.0.0/0`` is omitted and ``-j REJECT`` is printed with its default ``--reject-with icmp-port-unreachable`` option. Treat those canonical forms as equivalent to the commands stored in wg0.conf, while still rejecting any unexpected WGTools-tagged rule shape. """ tokens = shlex.split(raw) if len(tokens) < 4 or tokens[0:2] != ["-A", "FORWARD"]: raise ValueError("not a FORWARD rule") source = "" destination = "0.0.0.0/0" tag = "" action = "" reject_with = "" seen_comment_match = False i = 2 while i < len(tokens): token = tokens[i] if token == "-s" and i + 1 < len(tokens): source = tokens[i + 1] i += 2 elif token == "-d" and i + 1 < len(tokens): destination = tokens[i + 1] i += 2 elif token == "-m" and i + 1 < len(tokens) and tokens[i + 1] == "comment": seen_comment_match = True i += 2 elif token == "--comment" and i + 1 < len(tokens): tag = tokens[i + 1] i += 2 elif token == "-j" and i + 1 < len(tokens): action = tokens[i + 1] i += 2 elif token == "--reject-with" and i + 1 < len(tokens): reject_with = tokens[i + 1] i += 2 else: raise ValueError(f"unexpected token {token}") if not source or not seen_comment_match or not tag.startswith("wgtools-protect-"): raise ValueError("unexpected WGTools rule shape") if action not in {"REJECT", "DROP", "ACCEPT"}: raise ValueError("unexpected WGTools rule action") if reject_with and action != "REJECT": raise ValueError("reject option on a non-REJECT rule") return (source, destination, tag, action), tokens def _apply_managed_policy_runtime_diff(old_text: str, new_text: str) -> None: # Rebuild every WGTools-tagged rule in a deterministic order. This heals # stale/duplicate rules left by older releases and, importantly, preserves # the precedence of client overrides over group rules and broad defaults. new_up, _ = _managed_policy_hook_commands(new_text) desired_specs: list[tuple[str, str, str, str]] = [] for command in new_up: parsed = _managed_runtime_rule(command) if not parsed: raise RuntimeError(f"Unsupported WGTools-managed firewall rule: {command}") desired_specs.append(parsed) iptables = shutil.which("iptables") or "/usr/sbin/iptables" def args_for_spec(spec: tuple[str, str, str, str], operation: str) -> list[str]: source, destination, tag, action = spec return [iptables, operation, "FORWARD", "-s", source, "-d", destination, "-m", "comment", "--comment", tag, "-j", action] rc, out, err = run([iptables, "-S", "FORWARD"], timeout=8) if rc != 0: raise RuntimeError(f"Failed to inspect live firewall rules: {err or out}") current_rules: list[tuple[tuple[str, str, str, str], list[str], str]] = [] for raw in out.splitlines(): if "wgtools-protect-" not in raw: continue try: spec, tokens = _parse_live_managed_policy_rule(raw) current_rules.append((spec, tokens, raw)) except (ValueError, IndexError) as exc: raise RuntimeError(f"Unsupported live WGTools firewall rule: {' '.join(raw.split())}") from exc # Only reconcile tags that belong to the interface/configuration being # changed. WGTools can manage multiple WireGuard interfaces at once; # removing every wgtools-protect-* rule globally would otherwise erase # policy rules belonging to the other interfaces. managed_tags = {spec[2] for spec in desired_specs} for command in [*_managed_policy_hook_commands(old_text)[0], *_managed_policy_hook_commands(new_text)[0]]: parsed = _managed_runtime_rule(command) if parsed: managed_tags.add(parsed[2]) # Delete the exact canonical rules returned by ``iptables -S``. Using the # printed token shape is important for REJECT rules because iptables adds # ``--reject-with`` automatically and may omit ``-d 0.0.0.0/0``. for spec, tokens, raw in current_rules: if spec[2] not in managed_tags: continue delete_args = [iptables, "-D", "FORWARD", *tokens[2:]] rc, out, err = run(delete_args, timeout=8) if rc != 0: raise RuntimeError(f"Failed to remove stale WGTools client firewall policy: {err or out or raw}") added: list[tuple[str, str, str, str]] = [] try: # new_up is deliberately stored in reverse logical priority because # wg-quick executes PostUp commands with iptables -I. Replaying in that # same order yields the exact same final chain as a clean boot. for spec in desired_specs: rc, out, err = run(args_for_spec(spec, "-I"), timeout=8) if rc != 0: raise RuntimeError(f"Failed to apply WGTools client firewall policy: {err or out}") added.append(spec) except Exception: for spec in reversed(added): run(args_for_spec(spec, "-D"), timeout=8) raise def write_config_transaction(iface: str, new_text: str, remove_routes: list[str], add_routes: list[str], policy_table: str | int | None) -> Path: # syncconf may remove/recreate peers. Snapshot the runtime counters first # so no accumulated traffic disappears during a managed configuration edit. capture_wireguard_traffic(iface) config_path = WG_DIR / f"{iface}.conf" old_text = config_path.read_text(encoding="utf-8", errors="strict") backup = make_backup(iface, config_path) validate_dir = Path("/run/wgtools-validate") validate_dir.mkdir(parents=True, exist_ok=True) validate_path = validate_dir / f"{iface}.conf" validate_path.write_text(new_text, encoding="utf-8") os.chmod(validate_path, 0o600) try: validate_config_file(validate_path) tmp = WG_DIR / f".{iface}.conf.wgtools.tmp" tmp.write_text(new_text, encoding="utf-8") os.chmod(tmp, 0o600) os.replace(tmp, config_path) os.chmod(config_path, 0o600) try: sync_runtime(iface, config_path) apply_remote_routes(iface, remove_routes, add_routes, policy_table) _apply_managed_policy_runtime_diff(old_text, new_text) except Exception: shutil.copy2(backup, config_path) os.chmod(config_path, 0o600) try: sync_runtime(iface, config_path) apply_remote_routes(iface, add_routes, remove_routes, policy_table) _apply_managed_policy_runtime_diff(new_text, old_text) except Exception: pass raise finally: try: validate_path.unlink() except FileNotFoundError: pass return backup def server_public_key_from_config(iface: str) -> str: text = read_config_text(iface) current = None private = None for raw in text.splitlines(): line = raw.strip() if line.startswith("[") and line.endswith("]"): current = line[1:-1].strip().lower() continue if current == "interface" and "=" in line: key, value = [x.strip() for x in line.split("=", 1)] if key.lower() == "privatekey": private = value break if not private: raise RuntimeError("Server private key is missing from the WireGuard configuration") public = private_to_public(private) if not public: raise RuntimeError("Failed to derive the server public key") return public def create_client(iface: str, payload: dict[str, Any]) -> dict[str, Any]: if not wg_installed(): raise RuntimeError("WireGuard is not installed") settings = validate_client_payload(iface, payload) new_ip = str(ipaddress.ip_interface(settings["vpn_address"]).ip) if any(row["target_ip"] == new_ip for row in _extended_forwards(iface)): raise ValueError("Adres klienta jest używany przez istniejące przekierowanie") cfg = settings.pop("cfg") private_key = generate_private_key() public_key = private_to_public(private_key) if not public_key: raise RuntimeError("Failed to generate the client public key") preshared_key = generate_preshared_key() if settings["use_preshared_key"] else "" schedule_disabled = schedule_settings_disabled(settings) server_preshared_key = generate_preshared_key() if schedule_disabled else preshared_key allowed = [settings["vpn_address"]] + settings["remote_networks"] block = peer_block(settings["name"], public_key, allowed, settings["persistent_keepalive"], server_preshared_key) text = read_config_text(iface) new_text = append_peer_block(text, block) policy_table = cfg.get("detected", {}).get("policy_table") new_text = update_route_hooks(new_text, iface, [], settings["remote_networks"], policy_table) meta = { "public_key": public_key, "interface": iface, "private_key": private_key, "name": settings["name"], "vpn_address": settings["vpn_address"], "endpoint": settings["endpoint"], "client_allowed_ips": settings["client_allowed_ips"], "client_route_preset": settings["client_route_preset"], "protect_local_networks": settings["protect_local_networks"], "protect_local_exclusions": [], "local_access_exceptions": settings["local_access_exceptions"], "dns": settings["dns"], "persistent_keepalive": settings["persistent_keepalive"], "group_id": settings["group_id"], "policy_mode": settings["policy_mode"], "internet_access": settings["internet_access"], "local_access": settings["local_access"], "policy_allow": settings["policy_allow"], "policy_deny": settings["policy_deny"], "config_mode": settings["config_mode"], "preshared_key": preshared_key, "peer_isolation": settings["peer_isolation"], "expires_at": settings["expires_at"], "expiration_action": settings["expiration_action"], "expired_disabled": False, "expired_at": 0, "access_schedule_enabled": settings["access_schedule_enabled"], "access_schedule_days": settings["access_schedule_days"], "access_schedule_start": settings["access_schedule_start"], "access_schedule_end": settings["access_schedule_end"], "schedule_disabled": schedule_disabled, "schedule_changed_at": int(time.time()) if schedule_disabled else 0, "connection_mode": settings["connection_mode"], "relay_vps_id": settings["relay_vps_id"], "created_at": int(time.time()), } save_client_meta(meta) try: new_text = sync_managed_client_policies(new_text, iface) backup = write_config_transaction(iface, new_text, [], settings["remote_networks"], policy_table) except Exception: delete_client_meta(public_key) raise return { "ok": True, "message": "Client created and applied without restarting WireGuard", "public_key": public_key, "vpn_address": settings["vpn_address"], "backup": str(backup), "managed": True, } def update_client(iface: str, payload: dict[str, Any]) -> dict[str, Any]: public_key = str(payload.get("public_key", "")).strip() if not public_key: raise ValueError("Public key is required") settings = validate_client_payload(iface, payload, existing_public_key=public_key) cfg = settings.pop("cfg") peer = next((p for p in cfg.get("peers", []) if p.get("public_key") == public_key), None) if not peer: raise ValueError("Peer was not found") old_ip = str(ipaddress.ip_interface(peer["vpn_address"]).ip) if peer.get("vpn_address") else "" new_ip = str(ipaddress.ip_interface(settings["vpn_address"]).ip) if old_ip != new_ip and any(row["target_ip"] in {old_ip, new_ip} for row in _extended_forwards(iface)): raise ValueError("Najpierw usuń przekierowania powiązane z adresem klienta") old_remote = list(peer.get("remote_networks", [])) meta = load_client_meta(public_key) old_meta = dict(meta) if meta else None text = read_config_text(iface) if meta: preshared_key = str(meta.get("preshared_key") or "").strip() if settings["use_preshared_key"] else "" if settings["use_preshared_key"] and not preshared_key: preshared_key = generate_preshared_key() else: # Existing/unmanaged peers may already use a PSK. The visual editor # cannot regenerate their client configuration, so preserve that secret # instead of silently removing it when other peer fields are edited. preshared_key = peer_preshared_key(text, public_key) schedule_disabled = schedule_settings_disabled(settings) if meta else False server_preshared_key = generate_preshared_key() if schedule_disabled else preshared_key allowed = [settings["vpn_address"]] + settings["remote_networks"] block = peer_block(settings["name"], public_key, allowed, settings["persistent_keepalive"], server_preshared_key) new_text = replace_peer_block(text, public_key, block) policy_table = cfg.get("detected", {}).get("policy_table") new_text = update_route_hooks(new_text, iface, old_remote, settings["remote_networks"], policy_table) if meta: old_protect_local = bool(meta.get("protect_local_networks")) if not settings["protect_local_networks"] or not old_protect_local: meta["protect_local_exclusions"] = [] else: meta["protect_local_exclusions"] = sorted(_policy_exclusions(meta)) if not settings["protect_local_networks"]: meta["local_access_exceptions"] = [] meta.update({ "interface": iface, "name": settings["name"], "vpn_address": settings["vpn_address"], "endpoint": settings["endpoint"], "client_allowed_ips": settings["client_allowed_ips"], "client_route_preset": settings["client_route_preset"], "protect_local_networks": settings["protect_local_networks"], "local_access_exceptions": settings["local_access_exceptions"], "dns": settings["dns"], "persistent_keepalive": settings["persistent_keepalive"], "group_id": settings["group_id"], "policy_mode": settings["policy_mode"], "internet_access": settings["internet_access"], "local_access": settings["local_access"], "policy_allow": settings["policy_allow"], "policy_deny": settings["policy_deny"], "config_mode": settings["config_mode"], "preshared_key": preshared_key, "peer_isolation": settings["peer_isolation"], "expires_at": settings["expires_at"], "expiration_action": settings["expiration_action"], "expired_disabled": False, "expired_at": 0, "access_schedule_enabled": settings["access_schedule_enabled"], "access_schedule_days": settings["access_schedule_days"], "access_schedule_start": settings["access_schedule_start"], "access_schedule_end": settings["access_schedule_end"], "schedule_disabled": schedule_disabled, "schedule_changed_at": int(time.time()) if bool(old_meta and old_meta.get("schedule_disabled")) != schedule_disabled else int((old_meta or {}).get("schedule_changed_at") or 0), "connection_mode": settings["connection_mode"], "relay_vps_id": settings["relay_vps_id"], "updated_at": int(time.time()), }) save_client_meta(meta) try: new_text = sync_managed_client_policies(new_text, iface) backup = write_config_transaction(iface, new_text, old_remote, settings["remote_networks"], policy_table) except Exception: if old_meta: save_client_meta(old_meta) raise return {"ok": True, "message": "Client updated", "backup": str(backup), "managed": bool(meta)} def delete_client(iface: str, payload: dict[str, Any]) -> dict[str, Any]: public_key = str(payload.get("public_key", "")).strip() if not public_key: raise ValueError("Public key is required") cfg = parse_config(read_config_text(iface), iface) peer = next((p for p in cfg.get("peers", []) if p.get("public_key") == public_key), None) if not peer: raise ValueError("Peer was not found") peer_ip = str(ipaddress.ip_interface(peer["vpn_address"]).ip) if peer.get("vpn_address") else "" forwards = _extended_forwards(iface) remaining_forwards = [row for row in forwards if row["target_ip"] != peer_ip] if len(remaining_forwards) != len(forwards): _extended_write_forwards(iface, remaining_forwards) old_remote = list(peer.get("remote_networks", [])) text = read_config_text(iface) new_text = replace_peer_block(text, public_key, None) policy_table = cfg.get("detected", {}).get("policy_table") new_text = update_route_hooks(new_text, iface, old_remote, [], policy_table) old_meta = load_client_meta(public_key) delete_client_meta(public_key) try: new_text = sync_managed_client_policies(new_text, iface) backup = write_config_transaction(iface, new_text, old_remote, [], policy_table) except Exception: if old_meta: save_client_meta(old_meta) raise return {"ok": True, "message": f"Client {peer.get('name') or public_key} deleted", "name": str(peer.get("name") or public_key[:16]), "backup": str(backup)} def _migrate_client_public_key_state(iface: str, old_public_key: str, new_public_key: str) -> None: """Move durable traffic/last-seen state to a rotated client public key.""" try: conn = _traffic_connect() try: with conn: # A freshly generated key cannot normally collide, but keep the # operation deterministic if stale state somehow exists. conn.execute( "DELETE FROM wg_traffic_counters WHERE interface=? AND public_key=?", (iface, new_public_key), ) conn.execute( "UPDATE wg_traffic_counters SET public_key=? WHERE interface=? AND public_key=?", (new_public_key, iface, old_public_key), ) state_table = conn.execute( "SELECT 1 FROM sqlite_master WHERE type='table' AND name='audit_wg_connection_state'" ).fetchone() if state_table: conn.execute( "DELETE FROM audit_wg_connection_state WHERE interface=? AND public_key=?", (iface, new_public_key), ) conn.execute( "UPDATE audit_wg_connection_state SET public_key=? WHERE interface=? AND public_key=?", (new_public_key, iface, old_public_key), ) finally: conn.close() except Exception: # The key rotation itself must not be made unsafe by auxiliary history # migration. The interface lifetime total still retains old-key bytes. pass def rotate_client_credentials(iface: str, payload: dict[str, Any]) -> dict[str, Any]: old_public_key = str(payload.get("public_key", "")).strip() if not old_public_key: raise ValueError("Public key is required") meta = load_client_meta(old_public_key) if not meta or str(meta.get("interface") or "") != iface or not meta.get("private_key"): raise ValueError("Key rotation is available only for WGTools-managed clients") if bool(meta.get("expired_disabled")): raise ValueError("Restore this client's access before rotating its keys") cfg = parse_config(read_config_text(iface), iface) peer = next((p for p in cfg.get("peers", []) if p.get("public_key") == old_public_key), None) if not peer: raise ValueError("Peer was not found") # Capture resettable counters while the old public key still exists. capture_wireguard_traffic(iface) new_private_key = generate_private_key() new_public_key = private_to_public(new_private_key) if not new_public_key: raise RuntimeError("Failed to derive the new client public key") old_meta = dict(meta) new_meta = dict(meta) new_meta["public_key"] = new_public_key new_meta["private_key"] = new_private_key # One user action rotates every active client secret. Respect the PSK # checkbox: an enabled PSK is regenerated, while a deliberately disabled # PSK stays disabled. psk_enabled = bool(str(meta.get("preshared_key") or "").strip()) new_client_psk = generate_preshared_key() if psk_enabled else "" new_meta["preshared_key"] = new_client_psk new_meta["credentials_rotated_at"] = int(time.time()) new_meta["updated_at"] = int(time.time()) schedule_disabled = bool(meta.get("access_schedule_enabled")) and not client_schedule_allows(meta) server_psk = generate_preshared_key() if schedule_disabled else new_client_psk block = peer_block( str(peer.get("name") or meta.get("name") or "Client"), new_public_key, list(peer.get("allowed_ips") or []), int(peer.get("persistent_keepalive") or meta.get("persistent_keepalive") or 0), server_psk, ) old_text = read_config_text(iface) new_text = replace_peer_block(old_text, old_public_key, block) new_meta["schedule_disabled"] = schedule_disabled new_meta["schedule_changed_at"] = int(time.time()) if bool(old_meta.get("schedule_disabled")) != schedule_disabled else int(old_meta.get("schedule_changed_at") or 0) save_client_meta(new_meta) delete_client_meta(old_public_key) try: new_text = sync_managed_client_policies(new_text, iface) backup = write_config_transaction(iface, new_text, [], [], cfg.get("detected", {}).get("policy_table")) except Exception: delete_client_meta(new_public_key) save_client_meta(old_meta) raise _migrate_client_public_key_state(iface, old_public_key, new_public_key) return { "ok": True, "message": "Client keys rotated. Issue a new client config or QR before reconnecting.", "name": str(peer.get("name") or meta.get("name") or "Client"), "public_key": new_public_key, "psk_enabled": psk_enabled, "psk_rotated": psk_enabled, "backup": str(backup), "requires_client_config_update": True, } def _apply_schedule_state(meta: dict[str, Any], *, disable: bool, now: int) -> dict[str, Any] | None: public_key = str(meta.get("public_key") or "").strip() interface = str(meta.get("interface") or "").strip() name = str(meta.get("name") or public_key) if not public_key or not ALLOWED_IFACE_RE.fullmatch(interface): raise ValueError("Invalid client metadata for access schedule") if bool(meta.get("expired_disabled")): return None currently_disabled = bool(meta.get("schedule_disabled")) if currently_disabled == disable: return None cfg = parse_config(read_config_text(interface), interface) peer = next((p for p in cfg.get("peers", []) if p.get("public_key") == public_key), None) if not peer: raise ValueError("Peer was not found while applying access schedule") old_meta = dict(meta) old_text = read_config_text(interface) target_psk = generate_preshared_key() if disable else str(meta.get("preshared_key") or "").strip() block = peer_block( str(peer.get("name") or name), public_key, list(peer.get("allowed_ips") or []), int(peer.get("persistent_keepalive") or meta.get("persistent_keepalive") or 0), target_psk, ) new_text = replace_peer_block(old_text, public_key, block) meta["schedule_disabled"] = disable meta["schedule_changed_at"] = now meta["updated_at"] = now save_client_meta(meta) try: new_text = sync_managed_client_policies(new_text, interface) backup = write_config_transaction(interface, new_text, [], [], cfg.get("detected", {}).get("policy_table")) except Exception: save_client_meta(old_meta) raise return { "name": name, "interface": interface, "disabled": disable, "backup": str(backup), } def enforce_client_schedule(public_key: str, now: int | None = None) -> dict[str, Any] | None: meta = load_client_meta(public_key) if not meta: return None current = int(now if now is not None else time.time()) if bool(meta.get("expired_disabled")): return None try: expires_at = int(meta.get("expires_at") or 0) except (TypeError, ValueError): expires_at = 0 if expires_at and expires_at <= current: return None enabled = bool(meta.get("access_schedule_enabled")) if not enabled: if bool(meta.get("schedule_disabled")): return _apply_schedule_state(meta, disable=False, now=current) return None allowed = client_schedule_allows(meta, current) return _apply_schedule_state(meta, disable=not allowed, now=current) def expire_clients() -> dict[str, Any]: now = int(time.time()) due = [] for meta in iter_client_metas(): try: expires_at = int(meta.get("expires_at") or 0) except (TypeError, ValueError): expires_at = 0 if expires_at and expires_at <= now and not bool(meta.get("expired_disabled")): due.append(meta) due.sort(key=lambda item: (int(item.get("expires_at") or 0), str(item.get("interface") or ""), str(item.get("name") or ""))) deleted: list[dict[str, Any]] = [] disabled: list[dict[str, Any]] = [] errors: list[dict[str, str]] = [] for meta in due: public_key = str(meta.get("public_key") or "").strip() interface = str(meta.get("interface") or "").strip() name = str(meta.get("name") or public_key) if not public_key or not ALLOWED_IFACE_RE.fullmatch(interface): errors.append({"name": name, "error": "invalid client metadata"}) continue config_path = WG_DIR / f"{interface}.conf" if not config_path.exists(): errors.append({"name": name, "error": f"WireGuard interface config {interface}.conf is missing"}) continue try: cfg = parse_config(read_config_text(interface), interface) peer = next((p for p in cfg.get("peers", []) if p.get("public_key") == public_key), None) if not peer: if str(meta.get("expiration_action") or "delete").lower() == "disable": errors.append({"name": name, "interface": interface, "error": "peer is already absent; cannot preserve it as disabled"}) else: delete_client_meta(public_key) deleted.append({"name": name, "interface": interface, "already_absent": True}) continue action = str(meta.get("expiration_action") or "delete").strip().lower() if action == "disable": old_meta = dict(meta) old_text = read_config_text(interface) disabled_psk = generate_preshared_key() block = peer_block( str(peer.get("name") or name), public_key, list(peer.get("allowed_ips") or []), int(peer.get("persistent_keepalive") or 0), disabled_psk, ) new_text = replace_peer_block(old_text, public_key, block) meta["expired_disabled"] = True meta["expired_at"] = now meta["schedule_disabled"] = False meta["updated_at"] = now save_client_meta(meta) try: new_text = sync_managed_client_policies(new_text, interface) backup = write_config_transaction(interface, new_text, [], [], cfg.get("detected", {}).get("policy_table")) except Exception: save_client_meta(old_meta) raise disabled.append({"name": name, "interface": interface, "backup": str(backup)}) else: result = delete_client(interface, {"public_key": public_key}) deleted.append({"name": name, "interface": interface, "backup": str(result.get("backup") or "")}) except Exception as exc: errors.append({"name": name, "interface": interface, "error": str(exc)}) schedule_disabled: list[dict[str, Any]] = [] schedule_restored: list[dict[str, Any]] = [] for meta in list(iter_client_metas()): public_key = str(meta.get("public_key") or "").strip() if not public_key: continue try: change = enforce_client_schedule(public_key, now) if not change: continue if change.get("disabled"): schedule_disabled.append(change) else: schedule_restored.append(change) except Exception as exc: errors.append({ "name": str(meta.get("name") or public_key), "interface": str(meta.get("interface") or ""), "error": f"schedule: {exc}", }) return { "ok": True, "checked_at": now, "expired": len(due), "deleted": deleted, "disabled": disabled, "schedule_disabled": schedule_disabled, "schedule_restored": schedule_restored, "errors": errors, } CYRILLIC_FILENAME_TRANSLIT = str.maketrans({ "А": "A", "Б": "B", "В": "V", "Г": "G", "Д": "D", "Е": "E", "Ё": "Yo", "Ж": "Zh", "З": "Z", "И": "I", "Й": "Y", "К": "K", "Л": "L", "М": "M", "Н": "N", "О": "O", "П": "P", "Р": "R", "С": "S", "Т": "T", "У": "U", "Ф": "F", "Х": "Kh", "Ц": "Ts", "Ч": "Ch", "Ш": "Sh", "Щ": "Sch", "Ъ": "", "Ы": "Y", "Ь": "", "Э": "E", "Ю": "Yu", "Я": "Ya", "а": "a", "б": "b", "в": "v", "г": "g", "д": "d", "е": "e", "ё": "yo", "ж": "zh", "з": "z", "и": "i", "й": "y", "к": "k", "л": "l", "м": "m", "н": "n", "о": "o", "п": "p", "р": "r", "с": "s", "т": "t", "у": "u", "ф": "f", "х": "kh", "ц": "ts", "ч": "ch", "ш": "sh", "щ": "sch", "ъ": "", "ы": "y", "ь": "", "э": "e", "ю": "yu", "я": "ya", }) def safe_client_filename_stem(value: Any) -> str: """Return a portable ASCII filename stem while keeping Cyrillic client names recognizable.""" raw = str(value or "").strip() if not raw: return "wireguard-client" transliterated = raw.translate(CYRILLIC_FILENAME_TRANSLIT) ascii_text = unicodedata.normalize("NFKD", transliterated).encode("ascii", "ignore").decode("ascii") stem = re.sub(r"[^A-Za-z0-9._-]+", "_", ascii_text).strip("._-") return stem[:96] or "wireguard-client" def build_client_config(iface: str, public_key: str) -> dict[str, Any]: meta = load_client_meta(public_key) if meta and meta.get("interface") and meta.get("interface") != iface: meta = None if not meta or not meta.get("private_key"): raise RuntimeError("Client configuration is unavailable for this existing peer because WGTools does not have its private key") cfg = parse_config(read_config_text(iface), iface) peer = next((p for p in cfg.get("peers", []) if p.get("public_key") == public_key), None) if not peer: raise RuntimeError("Peer no longer exists in the WireGuard configuration") connection_mode = str(meta.get("connection_mode") or "direct") if connection_mode == "relay": relay = installed_relay_for_interface(str(meta.get("relay_vps_id") or ""), iface) if not relay: raise RuntimeError("The VPS Relay selected for this client is no longer available") endpoint = relay_client_endpoint(relay) else: endpoint = str(meta.get("endpoint") or "").strip() if not endpoint: raise RuntimeError("Client endpoint is not configured. Edit the client and set the server IP/domain used by this client") server_public = server_public_key_from_config(iface) lines = [ "[Interface]", f"PrivateKey = {meta['private_key']}", f"Address = {peer.get('vpn_address') or meta.get('vpn_address')}", ] dns = meta.get("dns") or [] if dns: lines.append(f"DNS = {', '.join(dns)}") lines.extend([ "", "[Peer]", f"PublicKey = {server_public}", ]) preshared_key = str(meta.get("preshared_key") or "").strip() if preshared_key: lines.append(f"PresharedKey = {preshared_key}") lines.extend([ f"Endpoint = {endpoint}", f"AllowedIPs = {', '.join(meta.get('client_allowed_ips') or [])}", ]) keepalive = peer.get("persistent_keepalive") or meta.get("persistent_keepalive") or 0 if keepalive: lines.append(f"PersistentKeepalive = {keepalive}") config = "\n".join(lines) + "\n" filename = safe_client_filename_stem(peer.get("name")) return {"ok": True, "config": config, "filename": f"{filename}.conf", "name": peer.get("name")} def _interface_section_parts(text: str) -> tuple[list[str], list[str], list[str]]: lines = text.replace("\r\n", "\n").replace("\r", "\n").splitlines() start = None end = len(lines) for idx, line in enumerate(lines): if re.fullmatch(r"\s*\[Interface\]\s*", line, flags=re.IGNORECASE): start = idx break if start is None: raise ValueError("WireGuard configuration does not contain an [Interface] section") for idx in range(start + 1, len(lines)): if re.fullmatch(r"\s*\[[^\]]+\]\s*", lines[idx]): end = idx break # Peer labels are commonly written as comments immediately before [Peer]. # Keep those comments with the peer section instead of absorbing them into [Interface]. suffix_start = end if end < len(lines): while suffix_start > start + 1: prev = lines[suffix_start - 1].strip() if not prev or prev.startswith("#") or prev.startswith(";"): suffix_start -= 1 continue break return lines[:start], lines[start:suffix_start], lines[suffix_start:] def _extract_interface_values(section: list[str]) -> tuple[str, str, list[str], list[str], list[str]]: private_key = "" save_config = "false" preserved: list[str] = [] post_up: list[str] = [] post_down: list[str] = [] for idx, raw in enumerate(section): if idx == 0: continue stripped = raw.strip() if not stripped or stripped.startswith("#") or stripped.startswith(";"): preserved.append(raw) continue if "=" not in raw: preserved.append(raw) continue key, value = [x.strip() for x in raw.split("=", 1)] lk = key.lower() if lk == "privatekey": private_key = value elif lk == "saveconfig": save_config = value or "false" elif lk == "postup": post_up.append(value) elif lk == "postdown": post_down.append(value) elif lk in {"address", "listenport", "mtu"}: continue else: preserved.append(raw) if not private_key: raise ValueError("The existing [Interface] section does not contain PrivateKey") return private_key, save_config, preserved, post_up, post_down def _managed_hook_kind(cmd: str, iface: str, old_cfg: dict[str, Any], remote_networks: set[str]) -> str | None: # Extended rules own their entire compound hook and must not be rewritten # by the original server-settings classifier. if f"--comment wgext-forward-{iface}-" in cmd or f"--comment wgext-listen-{iface}-" in cmd or f"--comment wgext-snat-{iface}" in cmd: return None old = old_cfg.get("detected", {}) old_network = str(old.get("vpn_network") or "") old_table = str(old.get("policy_table") or "") old_uplink = str(old.get("uplink_interface") or "") old_gateway = str(old.get("gateway") or "") old_local = str(old.get("local_network") or "") compact = " ".join(cmd.split()) if re.search(r"\bsysctl\s+-w\s+net\.ipv4\.ip_forward=1\b", compact): return "forwarding" if re.search(rf"\biptables\b.*\bFORWARD\b.*\s-i\s+{re.escape(iface)}(?:\s|$)", compact) and "-j ACCEPT" in compact: return "forward_from" if re.search(rf"\biptables\b.*\bFORWARD\b.*\s-o\s+{re.escape(iface)}(?:\s|$)", compact) and "-j ACCEPT" in compact: return "forward_to" if "iptables" in compact and "POSTROUTING" in compact and "MASQUERADE" in compact: if (not old_network or old_network in compact) and (not old_uplink or old_uplink in compact): return "nat" if old_table and re.search(r"\bip\s+rule\s+(?:add|del)\b", compact) and f"table {old_table}" in compact: if not old_network or old_network in compact: return "policy_rule" if old_table and re.search(r"\bip\s+route\s+(?:add|replace|del)\b", compact) and f"table {old_table}" in compact: m = re.search(r"\broute\s+(?:add|replace|del)\s+([^\s]+)", compact) target = m.group(1) if m else "" if target in {"default", old_network, old_local}: return "policy_base_route" if target in remote_networks and re.search(rf"\bdev\s+{re.escape(iface)}\b", compact): return "policy_remote_route" if target == "default" and old_gateway and old_gateway in compact: return "policy_base_route" return None def _canonical_hook_lines(iface: str, settings: dict[str, Any], remote_networks: list[str]) -> tuple[list[str], list[str]]: network = settings["network"] uplink = settings["uplink_interface"] table = settings["policy_table"] gateway = settings["gateway"] local_network = settings["local_network"] up: list[str] = [] down: list[str] = [] if settings["ip_forwarding"]: up.append("sysctl -w net.ipv4.ip_forward=1") if table is not None: up.append(f"ip rule add from {network} table {table}") down.append(f"ip rule del from {network} table {table} 2>/dev/null || true") up.append(f"ip route add default via {gateway} dev {uplink} table {table}") down.append(f"ip route del default via {gateway} dev {uplink} table {table} 2>/dev/null || true") if local_network: up.append(f"ip route add {local_network} dev {uplink} table {table}") down.append(f"ip route del {local_network} dev {uplink} table {table} 2>/dev/null || true") up.append(f"ip route replace {network} dev {iface} table {table}") down.append(f"ip route del {network} dev {iface} table {table} 2>/dev/null || true") for remote in remote_networks: up.append(f"ip route add {remote} dev {iface} table {table}") down.append(f"ip route del {remote} dev {iface} table {table} 2>/dev/null || true") if settings.get("forward_from_vpn", True): up.append(f"iptables -A FORWARD -i {iface} -j ACCEPT") down.append(f"iptables -D FORWARD -i {iface} -j ACCEPT 2>/dev/null || true") if settings.get("forward_to_vpn", True): up.append(f"iptables -A FORWARD -o {iface} -j ACCEPT") down.append(f"iptables -D FORWARD -o {iface} -j ACCEPT 2>/dev/null || true") if settings["nat_enabled"]: up.append(f"iptables -t nat -A POSTROUTING -s {network} -o {uplink} -j MASQUERADE") down.append(f"iptables -t nat -D POSTROUTING -s {network} -o {uplink} -j MASQUERADE 2>/dev/null || true") return up, down def _extended_groups() -> dict[str, dict[str, Any]]: if not EXT_IP_GROUPS_PATH.exists(): return {} data = json.loads(EXT_IP_GROUPS_PATH.read_text(encoding="utf-8")) if not isinstance(data, dict): raise ValueError("Nieprawidłowa konfiguracja grup adresów") return data def _extended_configured() -> set[str]: return {iface for iface in _configured_interface_names() if (WG_DIR / f"{iface}.conf").is_file()} def _extended_allowed(groups: dict[str, Any], iface: str) -> set[str]: allowed: set[str] = set() host_ips = None for group in groups.values(): if iface not in group.get("interfaces", []): continue if "sources" in group: if host_ips is None: host_ips = _extended_host_ips() allowed.update(ip for ip, dev in host_ips.items() if ip in group["sources"] or dev in group["sources"]) else: allowed.update(group.get("addresses", [])) return allowed def _network_sources_name(iface: str) -> str: return f"_wgext_network_{iface}" def _prepare_network_sources(iface: str, text: str) -> dict[str, Any]: sources = list(dict.fromkeys(item.strip() for item in text.split(',') if item.strip())) if len(sources) > 256: raise ValueError("Zbyt wiele adresów lub interfejsów") host = _extended_host_ips() for source in sources: if source not in host and source not in host.values(): raise ValueError(f"Adres lub interfejs {source} nie ma przypisanego IPv4 na serwerze") groups = _extended_groups() key = _network_sources_name(iface) if sources: groups[key] = {"addresses": sorted(ip for ip, dev in host.items() if ip in sources or dev in sources), "interfaces": [iface], "sources": sources} else: groups.pop(key, None) if (WG_DIR / f"{iface}.conf").is_file(): for row in _extended_forwards(iface): if row["public_ip"] not in _extended_allowed(groups, iface): raise ValueError("Najpierw usuń przekierowania korzystające z odbieranego adresu") return groups def _save_extended_groups(groups: dict[str, Any]) -> None: EXT_IP_GROUPS_PATH.parent.mkdir(parents=True, exist_ok=True) temp = EXT_IP_GROUPS_PATH.with_name(f".{EXT_IP_GROUPS_PATH.name}.{os.getpid()}.tmp") try: temp.write_text(json.dumps(groups, ensure_ascii=False), encoding="utf-8") os.chmod(temp, 0o600) os.replace(temp, EXT_IP_GROUPS_PATH) finally: temp.unlink(missing_ok=True) def _extended_host_ips() -> dict[str, str]: rc, out, err = run(["ip", "-j", "-4", "addr", "show"]) if rc: raise ValueError(f"Nie można odczytać adresów serwera: {err}") result: dict[str, str] = {} for dev in json.loads(out): name = str(dev.get("ifname") or "") if not ALLOWED_IFACE_RE.fullmatch(name) or name.startswith('-'): continue for item in dev.get("addr_info", []): if item.get("family") == "inet" and item.get("local"): result[str(item["local"])] = name return result def _extended_listener_conflict(public_ip: str, port: int, protocols: set[str]) -> bool: rc, out, err = run(["ss", "-H", "-lntu"]) if rc: raise ValueError(f"Nie można sprawdzić zajętych portów: {err}") for line in out.splitlines(): parts = line.split() if len(parts) < 5 or parts[0].lower() not in protocols: continue local = parts[4] host, separator, raw_port = local.rpartition(':') if separator and raw_port.isdigit() and int(raw_port) == port: host = host.strip('[]') if host in {'*', '0.0.0.0', '::', public_ip}: return True return False def _extended_forwards(iface: str) -> list[dict[str, Any]]: _, section, _ = _interface_section_parts(read_config_text(iface)) result = [] for line in section: if line.strip().startswith("# WGEXT-FORWARD "): try: row = json.loads(line.strip()[len("# WGEXT-FORWARD "):]) if not re.fullmatch(r"[0-9a-f]{16}", str(row["id"])): raise ValueError() row["public_ip"] = str(ipaddress.IPv4Address(row["public_ip"])) row["target_ip"] = str(ipaddress.IPv4Address(row["target_ip"])) row["public_port"] = int(row["public_port"]) row["target_port"] = int(row["target_port"]) if not (1 <= row["public_port"] <= 65535 and 1 <= row["target_port"] <= 65535): raise ValueError() if row["protocol"] not in {"tcp", "udp", "both"} or not ALLOWED_IFACE_RE.fullmatch(row["device"]) or row["device"].startswith('-'): raise ValueError() sources = row.get("allowed_sources", []) if not isinstance(sources, list) or len(sources) > 32: raise ValueError() row["allowed_sources"] = sorted({str(ipaddress.IPv4Address(value)) for value in sources}) except (KeyError, ValueError, TypeError) as exc: raise ValueError(f"Nieprawidłowy wpis przekierowania w {iface}") from exc result.append(row) return result def extended_ip_groups_get() -> dict[str, Any]: return {"ok": True, "groups": _extended_groups(), "forwards": [{**row, "interface": iface} for iface in sorted(_extended_configured()) for row in _extended_forwards(iface)]} def extended_ip_groups_set(payload: dict[str, Any]) -> dict[str, Any]: name = str(payload.get("name") or "").strip() if not re.fullmatch(r"[A-Za-z0-9_. -]{1,64}", name): raise ValueError("Nieprawidłowa nazwa grupy") if name.startswith('_wgext_network_'): raise ValueError("Tą grupą zarządza formularz sieci") groups = _extended_groups() if payload.get("delete"): if name not in groups: raise ValueError("Nie znaleziono grupy") del groups[name] else: addresses = payload.get("addresses") or [] interfaces = payload.get("interfaces") or [] if not isinstance(addresses, list) or not isinstance(interfaces, list) or len(addresses) > 256 or len(interfaces) > 100: raise ValueError("Nieprawidłowa lista adresów lub sieci") try: addresses = sorted({str(ipaddress.IPv4Address(addr)) for addr in addresses}) except (ValueError, TypeError) as exc: raise ValueError("Nieprawidłowy adres IPv4") from exc configured = _extended_configured() if any(not isinstance(item, str) or item not in configured for item in interfaces): raise ValueError("Grupa zawiera nieistniejącą sieć WireGuard") host_ips = _extended_host_ips() if any(addr not in host_ips for addr in addresses): raise ValueError("Adres grupy nie jest przypisany do serwera") groups[name] = {"addresses": addresses, "interfaces": sorted(set(interfaces))} for iface in _extended_configured(): for row in _extended_forwards(iface): if row["public_ip"] not in _extended_allowed(groups, iface): raise ValueError(f"Zmiana odebrałaby adres używany przez przekierowanie w {iface}; usuń najpierw przekierowanie") _save_extended_groups(groups) return {"ok": True, "groups": groups} def extended_forward_get(iface: str) -> dict[str, Any]: require_valid_iface(iface) return {"ok": True, "addresses": sorted(_extended_allowed(_extended_groups(), iface)), "forwards": _extended_forwards(iface)} def _extended_write_forwards(iface: str, rows: list[dict[str, Any]]) -> dict[str, Any]: complexity = sum((len(row.get('allowed_sources', [])) or 1) * (2 if row['protocol'] == 'both' else 1) for row in rows) if complexity > 100: raise ValueError("Zbyt wiele adresów źródłowych w przekierowaniach tej sieci") prefix, section, suffix = _interface_section_parts(read_config_text(iface)) marker = f"wgext-forward-{iface}" section = [line for line in section if not (line.strip().startswith("# WGEXT-FORWARD ") or (re.match(r"\s*Post(?:Up|Down)\s*=", line, re.I) and f"--comment {marker}-" in line))] up: list[str] = [] down: list[str] = [] for row in rows: section.append('# WGEXT-FORWARD ' + json.dumps(row, separators=(',', ':'), sort_keys=True)) for proto in (["tcp", "udp"] if row["protocol"] == "both" else [row["protocol"]]): tag = f"{marker}-{row['id']}-{proto}" nat = f"-i {row['device']} -d {row['public_ip']} -p {proto} --dport {row['public_port']} -m comment --comment {tag}-nat -j DNAT --to-destination {row['target_ip']}:{row['target_port']}" forward_match = f"-i {row['device']} -o {iface} -d {row['target_ip']} -p {proto} --dport {row['target_port']} -m conntrack --ctorigdst {row['public_ip']} --ctorigdstport {row['public_port']}" reply = f"-i {iface} -o {row['device']} -s {row['target_ip']} -p {proto} --sport {row['target_port']} -m conntrack --ctstate ESTABLISHED,RELATED -m comment --comment {tag}-out -j ACCEPT" rules = [(' -t nat', 'PREROUTING', nat), ('', 'FORWARD', reply)] sources = row.get('allowed_sources', []) if sources: # Match the original public tuple even for connections created # before an edit changed the destination client. deny_match = f"-i {row['device']} -o {iface} -p {proto} -m conntrack --ctorigdst {row['public_ip']} --ctorigdstport {row['public_port']}" rules.append(('', 'FORWARD', f"{deny_match} -m comment --comment {tag}-deny -j DROP")) for index, source in enumerate(sources or ['']): source_match = f" -s {source}" if source else '' rules.append(('', 'FORWARD', f"{forward_match}{source_match} -m comment --comment {tag}-in{index} -j ACCEPT")) for table, chain, rule in rules: up.append(f"iptables -w{table} -I {chain} 1 {rule}") down.append(f"iptables -w{table} -D {chain} {rule} 2>/dev/null || true") if up: cleanup = '; '.join(down) section.extend([f"PostUp = {' && '.join(up)} || {{ {cleanup}; false; }}", f"PostDown = {cleanup}"]) return raw_config_apply(iface, {"content": "\n".join([*prefix, *section, *suffix]).rstrip() + "\n"}) def extended_forward_add(iface: str, payload: dict[str, Any], *, update_id: str = '') -> dict[str, Any]: require_valid_iface(iface) try: public_ip = str(ipaddress.IPv4Address(payload.get("public_ip"))) target_ip = str(ipaddress.IPv4Address(payload.get("target_ip"))) public_port, target_port = int(payload.get("public_port")), int(payload.get("target_port")) except (ValueError, TypeError) as exc: raise ValueError("Nieprawidłowy adres lub port") from exc protocol = str(payload.get("protocol") or "") sources = payload.get('allowed_sources') or [] if not isinstance(sources, list) or len(sources) > 32: raise ValueError("Można podać maksymalnie 32 adresy źródłowe") try: sources = sorted({str(ipaddress.IPv4Address(value)) for value in sources}) except (ValueError, TypeError) as exc: raise ValueError("Podaj poprawne adresy źródłowe IPv4") from exc if bool(payload.get('restrict_sources')) != bool(sources): raise ValueError("Podaj co najmniej jeden adres IPv4 albo wyłącz ograniczenie") if protocol not in {"tcp", "udp", "both"} or not (1 <= public_port <= 65535 and 1 <= target_port <= 65535): raise ValueError("Nieprawidłowy protokół lub port") if public_ip not in _extended_allowed(_extended_groups(), iface): raise ValueError("Ten publiczny adres IPv4 nie jest przypisany do tej sieci") device = _extended_host_ips().get(public_ip) if not device: raise ValueError("Adres IPv4 nie jest obecnie przypisany do serwera") cfg = parse_config(read_config_text(iface), iface) peers = {str(ipaddress.ip_interface(p['vpn_address']).ip) for p in cfg.get('peers', []) if p.get('vpn_address')} if target_ip not in peers: raise ValueError("Adres docelowy nie należy do klienta tej sieci") protocols = {"tcp", "udp"} if protocol == "both" else {protocol} if _extended_listener_conflict(public_ip, public_port, protocols): raise ValueError("Ten port jest już używany przez usługę na serwerze") for other in _extended_configured(): other_cfg = parse_config(read_config_text(other), other) if "udp" in protocols and (other_cfg.get("interface") or {}).get("listen_port") == public_port: raise ValueError("Ten port UDP jest używany przez WireGuard") for row in _extended_forwards(other): if other == iface and row['id'] == update_id: continue existing = {"tcp", "udp"} if row["protocol"] == "both" else {row["protocol"]} if row["public_ip"] == public_ip and row["public_port"] == public_port and protocols & existing: raise ValueError("Ten adres, port i protokół są już używane przez inne przekierowanie") rows = _extended_forwards(iface) if update_id and not any(row['id'] == update_id for row in rows): raise ValueError("Nie znaleziono przekierowania") if not update_id and len(rows) >= 20: raise ValueError("Osiągnięto limit przekierowań w tej sieci") row = {"id": update_id or secrets.token_hex(8), "public_ip": public_ip, "public_port": public_port, "target_ip": target_ip, "target_port": target_port, "protocol": protocol, "device": device, "allowed_sources": sources} if payload.get('service') and isinstance(payload.get('responsibility'), dict): row['service'] = str(payload['service'])[:120] row['responsibility'] = payload['responsibility'] elif update_id: previous = next(item for item in rows if item['id'] == update_id) for key in ('service', 'responsibility'): if key in previous: row[key] = previous[key] result = _extended_write_forwards(iface, [*(item for item in rows if item['id'] != update_id), row]) return {**result, "forward": row} def extended_forward_delete(iface: str, payload: dict[str, Any]) -> dict[str, Any]: require_valid_iface(iface) identifier = str(payload.get("id") or "") rows = _extended_forwards(iface) remaining = [row for row in rows if row['id'] != identifier] if len(remaining) == len(rows): raise ValueError("Nie znaleziono przekierowania") return _extended_write_forwards(iface, remaining) def extended_snat_get(iface: str) -> dict[str, Any]: require_valid_iface(iface) text = read_config_text(iface) marker = f"wgext-snat-{iface}" prefix, section, suffix = _interface_section_parts(text) found = [line for line in section if marker in line and re.match(r"\s*PostUp\s*=", line, re.I)] if len(found) > 1: raise ValueError("Wykryto więcej niż jedną regułę SNAT; sprawdź konfigurację") if not found: return {"ok": True, "address": "", "uplink": ""} match = re.search(r"\s-o\s+([A-Za-z0-9_.-]{1,15})\s+.*?--to-source\s+(\d+\.\d+\.\d+\.\d+)", found[0]) if not match: raise ValueError("Nie można odczytać zapisanej reguły SNAT") return {"ok": True, "address": match.group(2), "uplink": match.group(1)} def extended_listen_get(iface: str) -> dict[str, Any]: require_valid_iface(iface) _, section, _ = _interface_section_parts(read_config_text(iface)) marker = f"# WGEXT-LISTEN-{iface} " entries = [line.strip()[len(marker):] for line in section if line.strip().startswith(marker)] if not entries: return {"ok": True, "address": "", "interface": ""} if len(entries) != 1: raise ValueError("Nieprawidłowa konfiguracja ograniczenia nasłuchiwania") match = re.fullmatch(r"address=([0-9.]*) interface=([A-Za-z0-9_.-]*)", entries[0]) if not match: raise ValueError("Nieprawidłowa konfiguracja ograniczenia nasłuchiwania") return {"ok": True, "address": match.group(1), "interface": match.group(2)} def extended_listen_apply(iface: str, payload: dict[str, Any], *, text_override: str | None = None, prepare_only: bool = False) -> dict[str, Any]: require_valid_iface(iface) text = text_override if text_override is not None else read_config_text(iface) cfg = parse_config(text, iface) address = str(payload.get("address") or "").strip() device = str(payload.get("interface") or "").strip() marker = f"wgext-listen-{iface}" metadata = f"# WGEXT-LISTEN-{iface} " prefix, section, suffix = _interface_section_parts(text) section = [line for line in section if not (line.strip().startswith(metadata) or (re.match(r"\s*Post(?:Up|Down)\s*=", line, re.I) and f"--comment {marker}-" in line))] if address or device: port = (cfg.get("interface") or {}).get("listen_port") if not isinstance(port, int) or not 1 <= port <= 65535: raise ValueError("Nie można ustalić portu WireGuard") if device: if not ALLOWED_IFACE_RE.fullmatch(device) or device.startswith('-'): raise ValueError("Nieprawidłowy interfejs") rc, _, _ = run(["ip", "link", "show", "dev", device]) if rc: raise ValueError("Interfejs nie istnieje") if address: try: address = str(ipaddress.IPv4Address(address)) except ValueError as exc: raise ValueError("Podaj poprawny adres IPv4") from exc cmd = ["ip", "-j", "-4", "addr", "show"] + (["dev", device] if device else []) rc, out, _ = run(cmd) try: assigned = {item.get("local") for dev in json.loads(out) for item in dev.get("addr_info", []) if item.get("family") == "inet"} if not rc else set() except (ValueError, TypeError) as exc: raise ValueError("Nie można odczytać adresów interfejsu") from exc if address not in assigned: raise ValueError("Adres IPv4 nie jest przypisany do wskazanego interfejsu") common = f"-p udp --dport {port}" selected = (f" -i {device}" if device else "") + (f" -d {address}" if address else "") drop4 = f"{common} -m comment --comment {marker}-drop -j DROP" allow4 = f"{common}{selected} -m comment --comment {marker}-allow -j ACCEPT" drop6 = f"{common} -m comment --comment {marker}-v6 -j DROP" cleanup = f"iptables -w -D INPUT {allow4} 2>/dev/null || true; iptables -w -D INPUT {drop4} 2>/dev/null || true; ip6tables -w -D INPUT {drop6} 2>/dev/null || true" section.extend([metadata + f"address={address} interface={device}", f"PostUp = iptables -w -I INPUT 1 {drop4} && ip6tables -w -I INPUT 1 {drop6} && iptables -w -I INPUT 1 {allow4} || {{ {cleanup}; false; }}", f"PostDown = {cleanup}"]) new_text = "\n".join([*prefix, *section, *suffix]).rstrip() + "\n" result = {"ok": True, "content": new_text} if prepare_only else raw_config_apply(iface, {"content": new_text}) result.update({"address": address, "interface": device}) return result def extended_snat_apply(iface: str, payload: dict[str, Any], *, text_override: str | None = None, prepare_only: bool = False) -> dict[str, Any]: require_valid_iface(iface) text = text_override if text_override is not None else read_config_text(iface) cfg = parse_config(text, iface) address = str(payload.get("address") or "").strip() uplink = str(payload.get("uplink") or "").strip() marker = f"wgext-snat-{iface}" prefix, section, suffix = _interface_section_parts(text) section = [line for line in section if not (marker in line and re.match(r"\s*Post(?:Up|Down)\s*=", line, re.I))] if address: try: address = str(ipaddress.IPv4Address(address)) except ValueError as exc: raise ValueError("Podaj poprawny adres IPv4") from exc if not ALLOWED_IFACE_RE.fullmatch(uplink) or uplink.startswith('-'): raise ValueError("Nieprawidłowy interfejs wyjściowy") rc, out, err = run(["ip", "-j", "-4", "addr", "show", "dev", uplink]) if rc: raise ValueError(f"Nie można odczytać adresów interfejsu {uplink}: {err}") try: assigned = {item.get("local") for dev in json.loads(out) for item in dev.get("addr_info", []) if item.get("family") == "inet"} except (ValueError, TypeError) as exc: raise ValueError("Nie można odczytać adresów interfejsu") from exc if address not in assigned: raise ValueError("Adres IPv4 nie jest przypisany do wskazanego interfejsu") detected = cfg.get("detected") or {} try: network = str(ipaddress.IPv4Network(str(detected.get("vpn_network") or ""), strict=False)) except ValueError as exc: raise ValueError("Nie można ustalić sieci IPv4 WireGuard") from exc if detected.get("uplink_interface") and uplink != str(detected["uplink_interface"]): raise ValueError("Interfejs wyjściowy musi odpowiadać ustawieniom sieci") rule = f"-s {network} -o {uplink} -m comment --comment {marker} -j SNAT --to-source {address}" section.extend([f"PostUp = iptables -t nat -I POSTROUTING 1 {rule}", f"PostDown = iptables -t nat -D POSTROUTING {rule}"]) new_text = "\n".join([*prefix, *section, *suffix]).rstrip() + "\n" result = {"ok": True, "content": new_text} if prepare_only else raw_config_apply(iface, {"content": new_text}) result.update({"address": address, "uplink": uplink if address else ""}) return result def server_settings_apply(iface: str, payload: dict[str, Any]) -> dict[str, Any]: require_valid_iface(iface) if not wg_installed(): raise RuntimeError("WireGuard is not installed") config_path = WG_DIR / f"{iface}.conf" if not config_path.exists(): raise RuntimeError(f"{config_path} does not exist") old_text = read_config_text(iface) old_cfg = parse_config(old_text, iface) source_groups = _prepare_network_sources(iface, str(payload.get("forward_sources") or "")) if "forward_sources" in payload else None normalized = dict(payload) normalized["forward_from_vpn"] = bool(payload.get("forward_from_vpn", True)) normalized["forward_to_vpn"] = bool(payload.get("forward_to_vpn", True)) settings = validate_server_payload(iface, normalized) listen = extended_listen_get(iface) if "listen_address" not in payload and (listen["address"] or listen["interface"]) and settings["listen_port"] != (old_cfg.get("interface") or {}).get("listen_port"): raise ValueError("Przed zmianą portu wyłącz ograniczenie nasłuchiwania i ustaw je ponownie") snat = extended_snat_get(iface) if "snat_address" not in payload and snat["address"] and (settings["network"] != str((old_cfg.get("detected") or {}).get("vpn_network") or "") or settings["uplink_interface"] != snat["uplink"]): raise ValueError("Przed zmianą sieci VPN lub interfejsu wyjściowego usuń podstawowy adres SNAT i ustaw go ponownie po zapisaniu zmian") settings["forward_from_vpn"] = normalized["forward_from_vpn"] settings["forward_to_vpn"] = normalized["forward_to_vpn"] network = ipaddress.ip_network(settings["network"], strict=True) for peer in old_cfg.get("peers", []): vpn_address = peer.get("vpn_address") if not vpn_address: continue try: peer_ip = ipaddress.ip_interface(vpn_address).ip except ValueError: continue if peer_ip not in network: raise ValueError( f"VPN pool {network} does not contain existing peer {peer.get('name') or 'Unnamed peer'} ({vpn_address}). " "Move or remove that peer before changing the VPN pool." ) remote_networks = sorted({ str(net) for peer in old_cfg.get("peers", []) for net in (peer.get("remote_networks") or []) if str(net).strip() }) remote_set = set(remote_networks) prefix, section, suffix = _interface_section_parts(old_text) private_key, save_config, preserved_lines, old_up, old_down = _extract_interface_values(section) extra_up = [cmd for cmd in old_up if _managed_hook_kind(cmd, iface, old_cfg, remote_set) is None] extra_down = [cmd for cmd in old_down if _managed_hook_kind(cmd, iface, old_cfg, remote_set) is None] managed_up, managed_down = _canonical_hook_lines(iface, settings, remote_networks) # Preserve unknown interface directives and comments, but normalize the common WGTools-managed fields. new_section = [ "[Interface]", f"Address = {settings['server_address']}", f"ListenPort = {settings['listen_port']}", ] if settings.get("mtu"): new_section.append(f"MTU = {settings['mtu']}") new_section.extend([ f"PrivateKey = {private_key}", f"SaveConfig = {save_config}", ]) nonempty_preserved = [line for line in preserved_lines if line.strip()] if nonempty_preserved: new_section.append("") new_section.extend(nonempty_preserved) if managed_up or extra_up: new_section.append("") new_section.extend(f"PostUp = {cmd}" for cmd in [*managed_up, *extra_up]) if managed_down or extra_down: new_section.append("") new_section.extend(f"PostDown = {cmd}" for cmd in [*managed_down, *extra_down]) new_section.append("") new_lines = [*prefix, *new_section, *suffix] new_text = "\n".join(new_lines).rstrip() + "\n" new_text = sync_managed_client_policies(new_text, iface) if "listen_address" in payload: new_text = extended_listen_apply(iface, {"address": payload.get("listen_address"), "interface": payload.get("listen_interface")}, text_override=new_text, prepare_only=True)["content"] if "snat_address" in payload: new_text = extended_snat_apply(iface, {"address": payload.get("snat_address"), "uplink": settings["uplink_interface"]}, text_override=new_text, prepare_only=True)["content"] result = raw_config_apply(iface, {"content": new_text}) if source_groups is not None: try: _save_extended_groups(source_groups) except Exception as exc: try: raw_config_apply(iface, {"content": old_text}) except Exception as rollback: raise RuntimeError(f"Nie zapisano adresów do przekierowań i nie udało się przywrócić konfiguracji: {rollback}") from exc raise RuntimeError(f"Nie zapisano adresów do przekierowań; przywrócono poprzednią konfigurację: {exc}") from exc sysctl_file = Path("/etc/sysctl.d/99-wgtools-wireguard.conf") sysctl_value = "1" if settings["ip_forwarding"] else "0" sysctl_file.write_text(f"net.ipv4.ip_forward={sysctl_value}\n", encoding="utf-8") os.chmod(sysctl_file, 0o644) sysctl = shutil.which("sysctl") or "/usr/sbin/sysctl" rc, out, err = run([sysctl, "-w", f"net.ipv4.ip_forward={sysctl_value}"]) if rc != 0: result["warning"] = f"Configuration was applied, but sysctl could not set net.ipv4.ip_forward={sysctl_value}: {err or out}" result["server"] = settings result["message"] = "Server settings saved and applied" return result def _normalize_route_target(value: Any) -> str: text = str(value or "").strip() if text.lower() == "default": return "default" try: return str(ipaddress.ip_network(text, strict=False)) except ValueError as exc: raise ValueError("Route network must be a valid IPv4 network or 'default'") from exc def _normalize_ipv4(value: Any, label: str, allow_empty: bool = True) -> str: text = str(value or "").strip() if not text and allow_empty: return "" try: return str(ipaddress.ip_address(text)) except ValueError as exc: raise ValueError(f"{label} must be a valid IP address") from exc def _normalize_route_table(value: Any) -> str: text = str(value or "").strip().lower() if not text or text == "main": return "main" if not text.isdigit() or not (1 <= int(text) <= 4294967295): raise ValueError("Routing table must be 'main' or a positive numeric table ID") return str(int(text)) def _build_route_commands(payload: dict[str, Any]) -> tuple[str, str, dict[str, str]]: network = _normalize_route_target(payload.get("network")) gateway = _normalize_ipv4(payload.get("gateway"), "Gateway") device = str(payload.get("device") or "").strip() if device and not ALLOWED_IFACE_RE.fullmatch(device): raise ValueError("Invalid route interface name") if not gateway and not device: raise ValueError("Specify at least a gateway or an interface for the route") table = _normalize_route_table(payload.get("table")) parts = ["ip", "route", "add", network] if gateway: parts += ["via", gateway] if device: parts += ["dev", device] if table != "main": parts += ["table", table] up = " ".join(parts) down_parts = ["ip", "route", "del", network] if gateway: down_parts += ["via", gateway] if device: down_parts += ["dev", device] if table != "main": down_parts += ["table", table] down = " ".join(down_parts) + " 2>/dev/null || true" return up, down, {"network": network, "gateway": gateway, "device": device, "table": table} def _normalize_rule_endpoint(value: Any, label: str) -> tuple[str, str]: text = str(value or "").strip() if not text or text.lower() in {"any", "all", "*"}: return "", "any" if "-" in text: left, right = [x.strip() for x in text.split("-", 1)] try: a = ipaddress.ip_address(left) b = ipaddress.ip_address(right) except ValueError as exc: raise ValueError(f"{label} range must contain valid IP addresses") from exc if a.version != 4 or b.version != 4 or int(a) > int(b): raise ValueError(f"{label} range is invalid") return f"{a}-{b}", "range" try: if "/" in text: return str(ipaddress.ip_network(text, strict=False)), "cidr" return str(ipaddress.ip_address(text)), "ip" except ValueError as exc: raise ValueError(f"{label} must be an IP, CIDR, IP range, or empty") from exc def _normalize_port(value: Any) -> str: text = str(value or "").strip() if not text: return "" if ":" in text: a, b = text.split(":", 1) if not a.isdigit() or not b.isdigit() or not (1 <= int(a) <= int(b) <= 65535): raise ValueError("Destination port range must be in the form 1000:2000") return f"{int(a)}:{int(b)}" if not text.isdigit() or not (1 <= int(text) <= 65535): raise ValueError("Destination port must be between 1 and 65535") return str(int(text)) def _normalize_rule_destinations(value: Any) -> list[tuple[str, str]]: text = str(value or "").strip() if not text or text.lower() in {"any", "all", "*"}: return [("", "any")] raw_items = [x.strip() for x in re.split(r"[,\n]+", text) if x.strip()] if not raw_items: return [("", "any")] if len(raw_items) > 32: raise ValueError("Destination may contain at most 32 IPs/networks") result: list[tuple[str, str]] = [] seen: set[str] = set() for raw in raw_items: endpoint = _normalize_rule_endpoint(raw, "Destination") if endpoint[0] not in seen: seen.add(endpoint[0]) result.append(endpoint) return result def _build_access_rule_commands(payload: dict[str, Any]) -> tuple[list[str], list[str], dict[str, str]]: source, source_kind = _normalize_rule_endpoint(payload.get("source"), "Source") destinations = _normalize_rule_destinations(payload.get("destination")) action = str(payload.get("action") or "REJECT").strip().upper() if action not in {"ACCEPT", "REJECT", "DROP"}: raise ValueError("Action must be ACCEPT, REJECT or DROP") protocol = str(payload.get("protocol") or "any").strip().lower() if protocol not in {"any", "tcp", "udp"}: raise ValueError("Protocol must be any, tcp or udp") dport = _normalize_port(payload.get("destination_port")) if dport and protocol == "any": raise ValueError("Select TCP or UDP when a destination port is specified") ups: list[str] = [] downs: list[str] = [] for destination, destination_kind in destinations: tokens = ["iptables", "-I", "FORWARD"] if source_kind == "range" or destination_kind == "range": tokens += ["-m", "iprange"] if source: if source_kind == "range": tokens += ["--src-range", source] else: tokens += ["-s", source] if destination: if destination_kind == "range": tokens += ["--dst-range", destination] else: tokens += ["-d", destination] if protocol != "any": tokens += ["-p", protocol] if dport: tokens += ["--dport", dport] tokens += ["-j", action] up = " ".join(tokens) ups.append(up) downs.append(up.replace("iptables -I FORWARD", "iptables -D FORWARD", 1) + " 2>/dev/null || true") return ups, downs, { "source": source, "destination": ", ".join(destination for destination, _ in destinations if destination), "action": action, "protocol": protocol, "destination_port": dport, } def _edit_interface_hooks(text: str, remove_up: list[str], remove_down: list[str], add_up: list[str], add_down: list[str]) -> str: lines = text.splitlines() start = None end = len(lines) for i, raw in enumerate(lines): stripped = raw.strip().lower() if stripped == "[interface]": start = i continue if start is not None and i > start and stripped.startswith("[") and stripped.endswith("]"): end = i break if start is None: raise ValueError("[Interface] section was not found") # Keep comments/blank lines immediately preceding the first peer together # with that peer. Otherwise adding a route/firewall hook can separate a # human-readable peer label from its [Peer] section. suffix_start = end if end < len(lines): while suffix_start > start + 1: prev = lines[suffix_start - 1].strip() if not prev or prev.startswith("#") or prev.startswith(";"): suffix_start -= 1 continue break end = suffix_start def hook_compare(value: str) -> str: compact = " ".join(value.split()) compact = re.sub(r"\s+2>/dev/null\s+\|\|\s+true$", "", compact) return compact remove_up_set = {hook_compare(x) for x in remove_up if x} remove_down_set = {hook_compare(x) for x in remove_down if x} new_section: list[str] = [] for raw in lines[start:end]: stripped = raw.strip() if "=" in raw: key, value = [x.strip() for x in raw.split("=", 1)] compact = hook_compare(value) if key.lower() == "postup" and compact in remove_up_set: continue if key.lower() == "postdown" and compact in remove_down_set: continue new_section.append(raw) while len(new_section) > 1 and not new_section[-1].strip(): new_section.pop() if add_up or add_down: new_section.append("") new_section.extend(f"PostUp = {cmd}" for cmd in add_up) new_section.extend(f"PostDown = {cmd}" for cmd in add_down) new_section.append("") return "\n".join([*lines[:start], *new_section, *lines[end:]]).rstrip() + "\n" def _find_route_item(cfg: dict[str, Any], iface: str, command: str) -> dict[str, Any]: for item in describe_server_items(cfg, iface)[0]: if " ".join(str(item.get("command") or "").split()) == " ".join(command.split()): if not item.get("editable"): raise ValueError("This route is managed automatically by WGTools and cannot be edited here") return item raise ValueError("The route no longer exists in the selected WireGuard configuration; refresh the page and try again") def _find_access_item(cfg: dict[str, Any], iface: str, command: str) -> dict[str, Any]: for item in describe_server_items(cfg, iface)[1]: if " ".join(str(item.get("command") or "").split()) == " ".join(command.split()): if not item.get("editable") or item.get("category") != "access": raise ValueError("This firewall rule is not supported by the simple editor; use the raw configuration editor") return item raise ValueError("The firewall rule no longer exists in the selected WireGuard configuration; refresh the page and try again") def _expected_route_down(command: str) -> str: compact = " ".join(command.split()) return re.sub(r"\bip\s+route\s+(?:add|replace)\b", "ip route del", compact, count=1) + " 2>/dev/null || true" def _expected_access_down(command: str) -> str: compact = " ".join(command.split()) compact = re.sub(r"\biptables\s+(?:-I|-A)\s+FORWARD\b", "iptables -D FORWARD", compact, count=1) return compact + " 2>/dev/null || true" def route_create(iface: str, payload: dict[str, Any]) -> dict[str, Any]: old_text = read_config_text(iface) cfg = parse_config(old_text, iface) up, down, values = _build_route_commands(payload) if any(" ".join(str(r.get("command") or "").split()) == up for r in cfg.get("routes", [])): raise ValueError("An identical route already exists") new_text = _edit_interface_hooks(old_text, [], [], [up], [down]) result = raw_config_apply(iface, {"content": new_text}) result.update({"route": values, "message": "Route added and applied"}) return result def route_update(iface: str, payload: dict[str, Any]) -> dict[str, Any]: old_command = " ".join(str(payload.get("original_command") or "").split()) if not old_command: raise ValueError("original_command is required") old_text = read_config_text(iface) cfg = parse_config(old_text, iface) _find_route_item(cfg, iface, old_command) up, down, values = _build_route_commands(payload) old_down = _expected_route_down(old_command) new_text = _edit_interface_hooks(old_text, [old_command], [old_down], [up], [down]) result = raw_config_apply(iface, {"content": new_text}) result.update({"route": values, "message": "Route updated and applied"}) return result def route_delete(iface: str, payload: dict[str, Any]) -> dict[str, Any]: old_command = " ".join(str(payload.get("original_command") or "").split()) if not old_command: raise ValueError("original_command is required") old_text = read_config_text(iface) cfg = parse_config(old_text, iface) _find_route_item(cfg, iface, old_command) old_down = _expected_route_down(old_command) new_text = _edit_interface_hooks(old_text, [old_command], [old_down], [], []) result = raw_config_apply(iface, {"content": new_text}) result["message"] = "Route removed and applied" return result def access_rule_create(iface: str, payload: dict[str, Any]) -> dict[str, Any]: old_text = read_config_text(iface) cfg = parse_config(old_text, iface) ups, downs, values = _build_access_rule_commands(payload) existing = {" ".join(str(r.get("command") or "").split()) for r in cfg.get("firewall", [])} duplicates = [up for up in ups if " ".join(up.split()) in existing] if duplicates: raise ValueError("One or more identical firewall rules already exist") new_text = _edit_interface_hooks(old_text, [], [], ups, downs) result = raw_config_apply(iface, {"content": new_text}) result.update({"access_rule": values, "message": "Access rule added and applied"}) return result def access_rule_update(iface: str, payload: dict[str, Any]) -> dict[str, Any]: old_command = " ".join(str(payload.get("original_command") or "").split()) if not old_command: raise ValueError("original_command is required") old_text = read_config_text(iface) cfg = parse_config(old_text, iface) item = _find_access_item(cfg, iface, old_command) ups, downs, values = _build_access_rule_commands(payload) managed_tag = str((item.get("access") or {}).get("managed_tag") or "") old_meta = None if managed_tag: # Editing one automatically generated restriction turns only that # destination into an explicit exception. The client's remaining # local-network restrictions keep following Site-to-site changes. old_destination = str((item.get("access") or {}).get("destination") or "").strip() if not old_destination: raise ValueError("Managed client policy destination is missing") old_meta = _set_policy_exclusion_by_tag(managed_tag, old_destination) if not old_meta: raise ValueError("The managed client policy metadata no longer exists") working_text = sync_managed_client_policies(old_text, iface) try: new_text = _edit_interface_hooks(working_text, [], [], ups, downs) result = raw_config_apply(iface, {"content": new_text}) except Exception: save_client_meta(old_meta) raise else: old_down = _expected_access_down(old_command) new_text = _edit_interface_hooks(old_text, [old_command], [old_down], ups, downs) result = raw_config_apply(iface, {"content": new_text}) result.update({"access_rule": values, "message": "Access rule updated and applied"}) return result def access_rule_delete(iface: str, payload: dict[str, Any]) -> dict[str, Any]: old_command = " ".join(str(payload.get("original_command") or "").split()) if not old_command: raise ValueError("original_command is required") old_text = read_config_text(iface) cfg = parse_config(old_text, iface) item = _find_access_item(cfg, iface, old_command) managed_tag = str((item.get("access") or {}).get("managed_tag") or "") if managed_tag: destination = str((item.get("access") or {}).get("destination") or "").strip() if not destination: raise ValueError("Managed client policy destination is missing") old_meta = _set_policy_exclusion_by_tag(managed_tag, destination) if not old_meta: raise ValueError("The managed client policy metadata no longer exists") try: new_text = sync_managed_client_policies(old_text, iface) backup = write_config_transaction(iface, new_text, [], [], cfg.get("detected", {}).get("policy_table")) except Exception: save_client_meta(old_meta) raise return { "ok": True, "message": "Managed client restriction removed; the destination is now an explicit exception for this client", "backup": str(backup), "restarted": False, } command_to_remove = old_command old_down = _expected_access_down(command_to_remove) new_text = _edit_interface_hooks(old_text, [command_to_remove], [old_down], [], []) result = raw_config_apply(iface, {"content": new_text}) result["message"] = "Access rule removed and applied" return result def raw_config_get(iface: str) -> dict[str, Any]: require_valid_iface(iface) config_path = WG_DIR / f"{iface}.conf" if not config_path.exists(): raise RuntimeError(f"{config_path} does not exist") text = config_path.read_text(encoding="utf-8", errors="strict") stat = config_path.stat() return { "ok": True, "interface": iface, "path": str(config_path), "content": text, "sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(), "modified_at": int(stat.st_mtime), "running": bool(wg_dump(iface).get("running")), } def normalize_raw_config_text(value: Any) -> str: if not isinstance(value, str): raise ValueError("Configuration content must be text") if not value.strip(): raise ValueError("Configuration cannot be empty") if len(value.encode("utf-8")) > 1024 * 1024: raise ValueError("Configuration is too large") if "\x00" in value: raise ValueError("Configuration contains a NUL byte") text = value.replace("\r\n", "\n").replace("\r", "\n") if not text.endswith("\n"): text += "\n" if not re.search(r"(?mi)^\s*\[Interface\]\s*$", text): raise ValueError("WireGuard configuration must contain an [Interface] section") return text def raw_config_apply(iface: str, payload: dict[str, Any]) -> dict[str, Any]: require_valid_iface(iface) if not wg_installed(): raise RuntimeError("WireGuard is not installed") config_path = WG_DIR / f"{iface}.conf" if not config_path.exists(): raise RuntimeError(f"{config_path} does not exist") new_text = normalize_raw_config_text(payload.get("content")) new_cfg = parse_config(new_text, iface) if ('# WGEXT-FORWARD ' in new_text or f'# WGEXT-LISTEN-{iface} ' in new_text) and str((new_cfg.get('interface') or {}).get('save_config') or '').lower() == 'true': raise ValueError("Przekierowania i ograniczenie nasłuchiwania wymagają SaveConfig = false") validate_dir = Path("/run/wgtools-validate") validate_dir.mkdir(parents=True, exist_ok=True) validate_path = validate_dir / f"{iface}.conf" validate_path.write_text(new_text, encoding="utf-8") os.chmod(validate_path, 0o600) try: # wg-quick strip parses the file without executing PostUp/PostDown commands. validate_config_file(validate_path) finally: try: validate_path.unlink() except FileNotFoundError: pass backup = make_backup(iface, config_path) was_running = bool(wg_dump(iface).get("running")) systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" service = f"wg-quick@{iface}.service" if was_running: rc, out, err = run([systemctl, "stop", service], timeout=30) if rc != 0: raise RuntimeError(f"Could not stop {service} before applying the raw configuration: {err or out}") if wg_dump(iface).get("running"): raise RuntimeError(f"{iface} is still running after systemd reported that it was stopped; configuration was not changed") tmp = WG_DIR / f".{iface}.conf.wgtools-raw.tmp" try: tmp.write_text(new_text, encoding="utf-8") os.chmod(tmp, 0o600) os.replace(tmp, config_path) os.chmod(config_path, 0o600) if was_running: rc, out, err = run([systemctl, "start", service], timeout=35) if rc != 0 or not wg_dump(iface).get("running"): failure = (err or out or f"{iface} did not return to the running state")[-1800:] shutil.copy2(backup, config_path) os.chmod(config_path, 0o600) rollback_rc, rollback_out, rollback_err = run([systemctl, "start", service], timeout=35) rollback_ok = rollback_rc == 0 and bool(wg_dump(iface).get("running")) if rollback_ok: raise RuntimeError(f"New configuration failed to start and was rolled back automatically. Detail: {failure}") raise RuntimeError( "New configuration failed and automatic rollback could not restore the WireGuard interface. " f"New config error: {failure}. Rollback error: {(rollback_err or rollback_out)[-1200:]}" ) # A restart executes PostDown/PostUp once, but older releases could # have left duplicate/stale tagged rules in RAM. Reconcile against # the config that is now active so one restart cannot preserve them. _apply_managed_policy_runtime_diff("", new_text) except Exception: try: tmp.unlink() except FileNotFoundError: pass raise return { "ok": True, "message": "Configuration saved and applied" if was_running else "Configuration saved. The WireGuard interface was already stopped, so it was left stopped.", "backup": str(backup), "running": bool(wg_dump(iface).get("running")), "restarted": was_running, } def _wgtools_version() -> str: for candidate in (Path("/opt/wgtools/VERSION"), Path(__file__).resolve().parents[1] / "VERSION"): try: value = candidate.read_text(encoding="utf-8").strip() if value: return value except Exception: pass return "unknown" def _copy_sqlite_database(source: Path, destination: Path) -> None: destination.parent.mkdir(parents=True, exist_ok=True) src = sqlite3.connect(source, timeout=10) dst = sqlite3.connect(destination, timeout=10) try: src.backup(dst) finally: dst.close() src.close() os.chmod(destination, 0o600) def _migration_manifest(iface: str, *, interfaces: list[dict[str, Any]], has_database: bool, managed_clients: int, vps_relays: int, has_sysctl: bool, has_interface_meta: bool, has_groups: bool) -> dict[str, Any]: return { "product": "WGTools", "format_version": MIGRATION_FORMAT_VERSION, "created_at": int(time.time()), "wgtools_version": _wgtools_version(), # Kept for compatibility and as the preferred/default interface. "interface": iface, "interfaces": interfaces, "source_hostname": os.uname().nodename, "components": { "wireguard_config": bool(interfaces), "wireguard_configs": len(interfaces), "database": has_database, "managed_clients": managed_clients, "vps_relay_records": vps_relays, "client_groups": has_groups, "interface_metadata": has_interface_meta, "sysctl_forwarding": has_sysctl, "automatic_config_history": False, }, "contains_secrets": True, } def _build_migration_archive(iface: str, destination_dir: Path, *, prefix: str = "WGTools-backup") -> Path: require_valid_iface(iface) destination_dir.mkdir(parents=True, exist_ok=True) os.chmod(destination_dir, 0o700) staging = Path(tempfile.mkdtemp(prefix="wgtools-export-", dir="/run")) try: has_database = DATABASE_PATH.exists() managed_clients = 0 vps_relays = 0 has_sysctl = SYSCTL_FILE.exists() has_interface_meta = INTERFACES_META_PATH.exists() has_groups = GROUPS_PATH.exists() interface_entries: list[dict[str, Any]] = [] (staging / "data" / "clients").mkdir(parents=True, exist_ok=True) if has_database: _copy_sqlite_database(DATABASE_PATH, staging / "data" / "wgtools.db") try: conn = sqlite3.connect(DATABASE_PATH, timeout=10) try: row = conn.execute("SELECT COUNT(*) FROM vps_relays WHERE status IN ('installed','detached')").fetchone() vps_relays = int(row[0] or 0) if row else 0 finally: conn.close() except sqlite3.Error: vps_relays = 0 if CLIENT_DIR.exists(): for source in sorted(CLIENT_DIR.glob("*.json")): if not source.is_file(): continue target = staging / "data" / "clients" / source.name shutil.copy2(source, target) os.chmod(target, 0o600) managed_clients += 1 if has_interface_meta: target = staging / "data" / "interfaces.json" shutil.copy2(INTERFACES_META_PATH, target) os.chmod(target, 0o600) if has_groups: target = staging / "data" / "groups.json" shutil.copy2(GROUPS_PATH, target) os.chmod(target, 0o600) if EXT_IP_GROUPS_PATH.exists(): target = staging / "data" / "extended-ip-groups.json" shutil.copy2(EXT_IP_GROUPS_PATH, target) os.chmod(target, 0o600) names = sorted({p.stem for p in WG_DIR.glob("*.conf") if p.is_file() and ALLOWED_IFACE_RE.fullmatch(p.stem)}) if WG_DIR.exists() else [] for name in names: config_path = WG_DIR / f"{name}.conf" target = staging / "wireguard" / f"{name}.conf" target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(config_path, target) os.chmod(target, 0o600) interface_entries.append({"name": name, "running": bool(wg_dump(name).get("running")) if wg_installed() else False}) if has_sysctl: target = staging / "system" / SYSCTL_FILE.name target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(SYSCTL_FILE, target) manifest = _migration_manifest( iface, interfaces=interface_entries, has_database=has_database, managed_clients=managed_clients, vps_relays=vps_relays, has_sysctl=has_sysctl, has_interface_meta=has_interface_meta, has_groups=has_groups, ) (staging / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") stamp = time.strftime("%Y%m%d-%H%M%S") filename = f"{prefix}-{stamp}.wgtbackup" archive = destination_dir / filename counter = 1 while archive.exists(): archive = destination_dir / f"{prefix}-{stamp}-{counter}.wgtbackup" counter += 1 with tarfile.open(archive, "w:gz", compresslevel=6) as tf: for rel in ("manifest.json", "wireguard", "data", "system"): item = staging / rel if item.exists(): tf.add(item, arcname=rel, recursive=True) os.chmod(archive, 0o600) return archive finally: shutil.rmtree(staging, ignore_errors=True) def migration_backup_create(iface: str) -> dict[str, Any]: archive = _build_migration_archive(iface, EXPORT_DIR) return { "ok": True, "path": str(archive), "filename": archive.name, "size": archive.stat().st_size, "message": "Full migration backup created", } def _safe_extract_migration_archive(archive: Path, destination: Path) -> dict[str, Any]: if not archive.exists() or not archive.is_file(): raise RuntimeError("Backup file does not exist") if archive.stat().st_size <= 0 or archive.stat().st_size > MIGRATION_MAX_BYTES: raise RuntimeError("Backup file is empty or exceeds the 64 MB safety limit") total = 0 allowed_roots = {"manifest.json", "wireguard", "data", "system"} try: tf = tarfile.open(archive, "r:gz") except (tarfile.TarError, OSError) as exc: raise RuntimeError("The selected file is not a valid WGTools backup archive") from exc with tf: for member in tf.getmembers(): name = member.name.replace("\\", "/") while name.startswith("./"): name = name[2:] parts = [part for part in name.split("/") if part not in ("", ".")] if name.startswith("/") or not parts or ".." in parts or parts[0] not in allowed_roots: raise RuntimeError(f"Unsafe or unsupported path in backup: {member.name}") if member.issym() or member.islnk() or not (member.isdir() or member.isfile()): raise RuntimeError(f"Unsupported archive entry: {member.name}") if member.isfile(): total += max(0, int(member.size)) if total > MIGRATION_MAX_BYTES: raise RuntimeError("Unpacked backup exceeds the 64 MB safety limit") target = destination.joinpath(*parts) target.parent.mkdir(parents=True, exist_ok=True) source = tf.extractfile(member) if source is None: raise RuntimeError(f"Could not read backup entry: {member.name}") with target.open("wb") as out: shutil.copyfileobj(source, out) else: destination.joinpath(*parts).mkdir(parents=True, exist_ok=True) manifest_path = destination / "manifest.json" if not manifest_path.exists(): raise RuntimeError("Backup manifest is missing") try: manifest = json.loads(manifest_path.read_text(encoding="utf-8")) except Exception as exc: raise RuntimeError("Backup manifest is invalid") from exc version = int(manifest.get("format_version", 0)) if manifest.get("product") != "WGTools" or version not in {1, 2, 3, MIGRATION_FORMAT_VERSION}: raise RuntimeError("Unsupported WGTools backup format") return manifest def _validate_restored_database(path: Path) -> None: if not path.exists(): raise RuntimeError("WGTools database is missing from the backup") conn = sqlite3.connect(path, timeout=10) try: row = conn.execute("PRAGMA integrity_check").fetchone() if not row or str(row[0]).lower() != "ok": raise RuntimeError("WGTools database failed SQLite integrity_check") tables = {str(row[0]) for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()} if "users" not in tables: raise RuntimeError("WGTools database does not contain the users table") finally: conn.close() def _replace_file(source: Path | None, target: Path, mode: int) -> None: target.parent.mkdir(parents=True, exist_ok=True) if source is None or not source.exists(): try: target.unlink() except FileNotFoundError: pass return temp = target.parent / f".{target.name}.wgtools-restore-{os.getpid()}" shutil.copy2(source, temp) os.chmod(temp, mode) os.replace(temp, target) os.chmod(target, mode) def _replace_clients(source_dir: Path | None) -> None: CLIENT_DIR.parent.mkdir(parents=True, exist_ok=True) temp = DATA_DIR / f".clients-restore-{os.getpid()}" shutil.rmtree(temp, ignore_errors=True) temp.mkdir(parents=True, exist_ok=True) os.chmod(temp, 0o700) if source_dir is not None and source_dir.exists(): for source in source_dir.glob("*.json"): if source.is_file(): target = temp / source.name shutil.copy2(source, target) os.chmod(target, 0o600) old = DATA_DIR / f".clients-old-{os.getpid()}" shutil.rmtree(old, ignore_errors=True) if CLIENT_DIR.exists(): os.replace(CLIENT_DIR, old) os.replace(temp, CLIENT_DIR) shutil.rmtree(old, ignore_errors=True) def _manifest_interfaces(iface: str, tree: Path, manifest: dict[str, Any]) -> list[dict[str, Any]]: version = int(manifest.get("format_version", 0)) if version == 1: backup_iface = str(manifest.get("interface") or "") if backup_iface != iface: raise RuntimeError(f"Backup belongs to interface {backup_iface or 'unknown'}, but this WGTools instance manages {iface}") config = tree / "wireguard" / f"{iface}.conf" return [{"name": iface, "running": True}] if config.exists() else [] result: list[dict[str, Any]] = [] raw = manifest.get("interfaces") if isinstance(manifest.get("interfaces"), list) else [] for item in raw: if not isinstance(item, dict): continue name = str(item.get("name") or "").strip() if ALLOWED_IFACE_RE.fullmatch(name) and (tree / "wireguard" / f"{name}.conf").exists(): result.append({"name": name, "running": bool(item.get("running"))}) if not result: for path in sorted((tree / "wireguard").glob("*.conf")) if (tree / "wireguard").exists() else []: if ALLOWED_IFACE_RE.fullmatch(path.stem): result.append({"name": path.stem, "running": True}) return result def _apply_migration_tree(iface: str, tree: Path, manifest: dict[str, Any], *, start_configured_wireguard: bool) -> None: components = manifest.get("components") if isinstance(manifest.get("components"), dict) else {} interface_entries = _manifest_interfaces(iface, tree, manifest) db_source = tree / "data" / "wgtools.db" _validate_restored_database(db_source) if interface_entries and not wg_installed(): install_wireguard() for entry in interface_entries: validate_config_file(tree / "wireguard" / f"{entry['name']}.conf") systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" run([systemctl, "stop", "wgtools-telegram.service"], timeout=20) if wg_installed(): for entry in interface_entries: run([systemctl, "stop", f"wg-quick@{entry['name']}.service"], timeout=40) db_temp = DATA_DIR / f".wgtools.db.restore-{os.getpid()}" shutil.copy2(db_source, db_temp) os.chmod(db_temp, 0o600) os.replace(db_temp, DATABASE_PATH) os.chmod(DATABASE_PATH, 0o600) for suffix in ("-wal", "-shm"): try: Path(str(DATABASE_PATH) + suffix).unlink() except FileNotFoundError: pass _replace_clients(tree / "data" / "clients") meta_source = tree / "data" / "interfaces.json" if int(manifest.get("format_version", 0)) >= 2: _replace_file(meta_source if meta_source.exists() else None, INTERFACES_META_PATH, 0o600) groups_source = tree / "data" / "groups.json" if int(manifest.get("format_version", 0)) >= 3: _replace_file(groups_source if groups_source.exists() else None, GROUPS_PATH, 0o600) else: _replace_file(None, GROUPS_PATH, 0o600) extended_groups_source = tree / "data" / "extended-ip-groups.json" _replace_file(extended_groups_source if int(manifest.get("format_version", 0)) >= 4 and extended_groups_source.exists() else None, EXT_IP_GROUPS_PATH, 0o600) for entry in interface_entries: name = entry["name"] _replace_file(tree / "wireguard" / f"{name}.conf", WG_DIR / f"{name}.conf", 0o600) sysctl_source = tree / "system" / SYSCTL_FILE.name _replace_file(sysctl_source if bool(components.get("sysctl_forwarding")) and sysctl_source.exists() else None, SYSCTL_FILE, 0o644) for entry in interface_entries: name = entry["name"] run([systemctl, "enable", f"wg-quick@{name}.service"], timeout=20) should_run = bool(entry.get("running")) if int(manifest.get("format_version", 0)) >= 2 else start_configured_wireguard if start_configured_wireguard and should_run: rc, out, err = run([systemctl, "restart", f"wg-quick@{name}.service"], timeout=45) if rc != 0 or not wg_dump(name).get("running"): raise RuntimeError(f"Restored WireGuard configuration {name} could not be started: {(err or out)[-1600:]}") else: run([systemctl, "stop", f"wg-quick@{name}.service"], timeout=30) run([systemctl, "restart", "wgtools-telegram.service"], timeout=20) def _prune_migration_safety_backups() -> None: if not MIGRATION_SAFETY_DIR.exists(): return files = sorted(MIGRATION_SAFETY_DIR.glob("*.wgtbackup"), key=lambda p: p.stat().st_mtime, reverse=True) for stale in files[5:]: try: stale.unlink() except OSError: pass def migration_restore(iface: str, payload: dict[str, Any]) -> dict[str, Any]: raw_path = str(payload.get("path") or "").strip() if not raw_path: raise ValueError("Backup path is required") archive = Path(raw_path) import_root = DATA_DIR / "imports" try: archive.resolve().relative_to(import_root.resolve()) except Exception as exc: raise RuntimeError("Restore file is outside the WGTools import directory") from exc restore_tree = Path(tempfile.mkdtemp(prefix="wgtools-restore-", dir="/run")) rollback_tree = Path(tempfile.mkdtemp(prefix="wgtools-rollback-", dir="/run")) safety_archive: Path | None = None try: manifest = _safe_extract_migration_archive(archive, restore_tree) _validate_restored_database(restore_tree / "data" / "wgtools.db") restore_entries = _manifest_interfaces(iface, restore_tree, manifest) if restore_entries and not wg_installed(): install_wireguard() for entry in restore_entries: validate_config_file(restore_tree / "wireguard" / f"{entry['name']}.conf") safety_archive = _build_migration_archive(iface, MIGRATION_SAFETY_DIR, prefix="WGTools-pre-restore") _prune_migration_safety_backups() rollback_manifest = _safe_extract_migration_archive(safety_archive, rollback_tree) try: _apply_migration_tree(iface, restore_tree, manifest, start_configured_wireguard=True) except Exception as exc: try: _apply_migration_tree(iface, rollback_tree, rollback_manifest, start_configured_wireguard=True) except Exception as rollback_exc: raise RuntimeError(f"Restore failed: {exc}. Automatic rollback also failed: {rollback_exc}") from exc raise RuntimeError(f"Restore failed and the previous WGTools state was restored automatically: {exc}") from exc return { "ok": True, "message": "Full WGTools backup restored successfully", "backup_version": str(manifest.get("wgtools_version") or "unknown"), "created_at": int(manifest.get("created_at") or 0), "interfaces_restored": [entry["name"] for entry in restore_entries], "safety_backup": str(safety_archive) if safety_archive else None, "running": bool(wg_dump(iface).get("running")) if wg_installed() else False, "relogin_required": True, } finally: shutil.rmtree(restore_tree, ignore_errors=True) shutil.rmtree(rollback_tree, ignore_errors=True) def _current_wgtools_version() -> str: try: value = (APP_DIR / "VERSION").read_text(encoding="utf-8").strip() return value or "unknown" except Exception: return "unknown" def _version_tuple(value: str) -> tuple[int, int, int] | None: text = str(value or "").strip() if text.startswith("v"): text = text[1:] match = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)", text) if not match: return None return tuple(int(match.group(i)) for i in range(1, 4)) def update_check() -> dict[str, Any]: raise RuntimeError("Aktualizacje online są wyłączone. Wgraj pakiet .bin w ustawieniach.") def update_notice() -> dict[str, Any]: return {"ok": True, "update_available": False, "latest_version": ""} def _write_update_status(data: dict[str, Any]) -> None: DATA_DIR.mkdir(parents=True, exist_ok=True) try: DATA_DIR.chmod(0o700) except OSError: pass payload = dict(data) payload["updated_at"] = int(time.time()) temp = UPDATE_STATUS_PATH.with_name(f".{UPDATE_STATUS_PATH.name}.{os.getpid()}.tmp") temp.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8") temp.chmod(0o600) os.replace(temp, UPDATE_STATUS_PATH) def update_status() -> dict[str, Any]: if not UPDATE_STATUS_PATH.exists(): return {"ok": True, "state": "idle", "current_version": _current_wgtools_version()} try: data = json.loads(UPDATE_STATUS_PATH.read_text(encoding="utf-8")) if not isinstance(data, dict): raise ValueError("invalid status") except Exception: return {"ok": True, "state": "idle", "current_version": _current_wgtools_version()} data["ok"] = True data["current_version"] = _current_wgtools_version() return data def _current_web_port() -> int: service = SYSTEMD_DIR / "wgtools.service" try: text = service.read_text(encoding="utf-8", errors="replace") match = re.search(r"--port\s+(\d{1,5})", text) if match: port = int(match.group(1)) if 1 <= port <= 65535: return port except Exception: pass return 8341 def _validate_update_source(source_root: Path, expected_version: str) -> None: required = [ "VERSION", "app/main.py", "app/locales/pl.json", "scripts/install.sh", "scripts/uninstall.sh", "scripts/wgtools-helper", "systemd/wgtools.service", "systemd/wgtools-telegram.service", "systemd/wgtools-certbot-renew.service", "systemd/wgtools-certbot-renew.timer", "scripts/wgtools-web", "scripts/wgtools-certbot-reload", "scripts/wgtools-cli", "requirements.txt", ] for relative in required: if not (source_root / relative).is_file(): raise RuntimeError(f"Update archive is missing required file: {relative}") actual_version = (source_root / "VERSION").read_text(encoding="utf-8").strip() if actual_version != expected_version: raise RuntimeError(f"Update archive version mismatch: expected {expected_version}, got {actual_version or 'empty'}") for locale in (source_root / "app/locales/pl.json",): json.loads(locale.read_text(encoding="utf-8")) for script_name in ("scripts/install.sh", "scripts/wgtools-cli"): rc, out, err = run(["bash", "-n", str(source_root / script_name)], timeout=15) if rc != 0: raise RuntimeError(f"Update script syntax check failed ({script_name}): {err or out}") rc, out, err = run(["python3", "-m", "py_compile", str(source_root / "app/main.py"), str(source_root / "scripts/wgtools-helper")], timeout=30) if rc != 0: raise RuntimeError(f"Update Python syntax check failed: {err or out}") def _create_app_rollback_archive(current_version: str) -> Path: UPDATE_BACKUP_DIR.mkdir(parents=True, exist_ok=True) UPDATE_BACKUP_DIR.chmod(0o700) stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime()) path = UPDATE_BACKUP_DIR / f"WGTools-app-pre-update-v{current_version}-{stamp}.tar.gz" with tarfile.open(path, "w:gz") as tar: if APP_DIR.exists(): tar.add(APP_DIR, arcname="opt/wgtools", recursive=True) files = [ (ENV_FILE, "etc/wgtools/wgtools.env"), (HTTPS_ENV_FILE, "etc/wgtools/https.env"), (HTTPS_STATE_FILE, "etc/wgtools/https.json"), (HELPER_INSTALL_PATH, "usr/local/libexec/wgtools-helper"), (Path("/usr/local/libexec/wgtools-certbot-reload"), "usr/local/libexec/wgtools-certbot-reload"), (Path("/usr/local/bin/wgtools"), "usr/local/bin/wgtools"), (SYSTEMD_DIR / "wgtools.service", "etc/systemd/system/wgtools.service"), (SYSTEMD_DIR / "wgtools-telegram.service", "etc/systemd/system/wgtools-telegram.service"), (SYSTEMD_DIR / "wgtools-certbot-renew.service", "etc/systemd/system/wgtools-certbot-renew.service"), (SYSTEMD_DIR / "wgtools-certbot-renew.timer", "etc/systemd/system/wgtools-certbot-renew.timer"), ] for source, arcname in files: if source.exists(): tar.add(source, arcname=arcname, recursive=False) path.chmod(0o600) return path def _restore_app_rollback_archive(archive: Path) -> None: restore_root = Path(tempfile.mkdtemp(prefix="wgtools-update-rollback-", dir="/run")) try: with tarfile.open(archive, "r:gz") as tar: root = restore_root.resolve() for member in tar.getmembers(): target = (restore_root / member.name).resolve() try: target.relative_to(root) except Exception as exc: raise RuntimeError("Rollback archive contains an unsafe path") from exc tar.extractall(restore_root) systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" run([systemctl, "stop", "wgtools.service"], timeout=30) run([systemctl, "stop", "wgtools-telegram.service"], timeout=30) restored_app = restore_root / "opt/wgtools" if not restored_app.is_dir(): raise RuntimeError("Rollback archive does not contain the previous application") shutil.rmtree(APP_DIR, ignore_errors=True) shutil.copytree(restored_app, APP_DIR, symlinks=True) cli_backup = restore_root / "usr/local/bin/wgtools" if not cli_backup.exists(): try: Path("/usr/local/bin/wgtools").unlink() except FileNotFoundError: pass replacements = [ (restore_root / "etc/wgtools/wgtools.env", ENV_FILE, 0o644), (restore_root / "etc/wgtools/https.env", HTTPS_ENV_FILE, 0o600), (restore_root / "etc/wgtools/https.json", HTTPS_STATE_FILE, 0o600), (restore_root / "usr/local/libexec/wgtools-helper", HELPER_INSTALL_PATH, 0o755), (restore_root / "usr/local/libexec/wgtools-certbot-reload", Path("/usr/local/libexec/wgtools-certbot-reload"), 0o755), (restore_root / "usr/local/bin/wgtools", Path("/usr/local/bin/wgtools"), 0o755), (restore_root / "etc/systemd/system/wgtools.service", SYSTEMD_DIR / "wgtools.service", 0o644), (restore_root / "etc/systemd/system/wgtools-telegram.service", SYSTEMD_DIR / "wgtools-telegram.service", 0o644), (restore_root / "etc/systemd/system/wgtools-certbot-renew.service", SYSTEMD_DIR / "wgtools-certbot-renew.service", 0o644), (restore_root / "etc/systemd/system/wgtools-certbot-renew.timer", SYSTEMD_DIR / "wgtools-certbot-renew.timer", 0o644), ] for source, destination, mode in replacements: if source.exists(): destination.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source, destination) destination.chmod(mode) run([systemctl, "daemon-reload"], timeout=30) if _https_enabled_from_env() and (SYSTEMD_DIR / "wgtools-certbot-renew.timer").exists(): run([systemctl, "enable", "--now", HTTPS_RENEW_TIMER], timeout=20) rc, out, err = run([systemctl, "restart", "wgtools.service"], timeout=45) if rc != 0: raise RuntimeError(f"Could not restart the previous WGTools web service: {err or out}") run([systemctl, "restart", "wgtools-telegram.service"], timeout=30) finally: shutil.rmtree(restore_root, ignore_errors=True) def _prune_update_backups() -> None: if not UPDATE_BACKUP_DIR.exists(): return groups = ["WGTools-app-pre-update-*.tar.gz", "WGTools-pre-update-*.wgtbackup"] for pattern in groups: files = sorted(UPDATE_BACKUP_DIR.glob(pattern), key=lambda p: p.stat().st_mtime, reverse=True) for stale in files[3:]: try: stale.unlink() except OSError: pass def _uploaded_update_path(value: str) -> Path: root = (DATA_DIR / "imports").resolve() path = Path(value) if not re.fullmatch(r"upload-[0-9a-f]{24}\.bin", path.name) or path.resolve().parent != root or not path.is_file() or path.is_symlink(): raise ValueError("Nieprawidłowa ścieżka pakietu aktualizacji") if not 0 < path.stat().st_size <= 64 * 1024 * 1024: raise ValueError("Pakiet aktualizacji musi mieć rozmiar do 64 MB") return path def _extract_uploaded_update(archive: Path, destination: Path) -> Path: destination.mkdir(parents=True, exist_ok=True) root = destination.resolve() total = 0 seen: set[str] = set() with tarfile.open(archive, "r:gz") as tar: for count, member in enumerate(tar, 1): if count > 10000: raise ValueError("Pakiet zawiera za dużo plików") name = member.name.replace('\\', '/') parts = [part for part in name.split('/') if part not in ('', '.')] if name.startswith('/') or not parts or '..' in parts or not (member.isfile() or member.isdir()): raise ValueError("Pakiet zawiera niedozwolony wpis") normalized = '/'.join(parts) if normalized in seen: raise ValueError("Pakiet zawiera powtórzoną ścieżkę") seen.add(normalized) target = destination.joinpath(*parts) target.resolve().relative_to(root) if member.isdir(): target.mkdir(parents=True, exist_ok=True) else: total += member.size if total > 256 * 1024 * 1024: raise ValueError("Rozpakowany pakiet jest za duży") target.parent.mkdir(parents=True, exist_ok=True) source = tar.extractfile(member) if source is None: raise ValueError("Nie można odczytać pakietu") with target.open('wb') as out: shutil.copyfileobj(source, out) os.chmod(target, member.mode & 0o755) return destination def _uploaded_update_validate(path: Path, work: Path) -> tuple[Path, str]: source = _extract_uploaded_update(path, work) version_file = source / 'VERSION' if not version_file.is_file(): raise ValueError("Pakiet nie zawiera pliku VERSION") version = version_file.read_text(encoding='utf-8').strip() if not re.fullmatch(r'\d+\.\d+\.\d+', version): raise ValueError("Nieprawidłowa wersja pakietu") _validate_update_source(source, version) current = _current_wgtools_version() if not _version_tuple(current) or _version_tuple(version) <= _version_tuple(current): raise ValueError("Wersja pakietu musi być nowsza od zainstalowanej") return source, version def update_file_schedule(iface: str, payload: dict[str, Any]) -> dict[str, Any]: if str(update_status().get('state') or '') in {'queued', 'running', 'rolling_back'}: raise ValueError("Aktualizacja jest już uruchomiona") path = _uploaded_update_path(str(payload.get('path') or '')) with tempfile.TemporaryDirectory(prefix='wgext-update-check-', dir=DATA_DIR) as work: _, version = _uploaded_update_validate(path, Path(work) / 'source') digest = hashlib.sha256(path.read_bytes()).hexdigest() unit = f"wgtools-update-{int(time.time())}-{os.getpid()}" _write_update_status({'state':'queued', 'target_version':version, 'current_version':_current_wgtools_version(), 'message':'Aktualizacja oczekuje na uruchomienie', 'unit':unit}) rc, out, err = run([shutil.which('systemd-run') or '/usr/bin/systemd-run', '--quiet', '--collect', '--no-block', f'--unit={unit}', '--property=Type=oneshot', f'--setenv=WGEXT_UPDATE_PATH={path}', f'--setenv=WGEXT_UPDATE_SHA256={digest}', str(HELPER_INSTALL_PATH), 'update_file_apply', iface], timeout=20) if rc: _write_update_status({'state':'error', 'message':'Nie udało się uruchomić aktualizacji', 'error':err or out}) raise RuntimeError(f"Nie udało się uruchomić aktualizacji: {err or out}") return {'ok':True, 'scheduled':True, 'target_version':version, 'unit':unit} def update_file_apply(iface: str) -> dict[str, Any]: path = _uploaded_update_path(str(os.environ.get('WGEXT_UPDATE_PATH') or '')) expected = str(os.environ.get('WGEXT_UPDATE_SHA256') or '') rollback = None backup = None current = _current_wgtools_version() try: if not re.fullmatch(r'[0-9a-f]{64}', expected) or not secrets.compare_digest(hashlib.sha256(path.read_bytes()).hexdigest(), expected): raise ValueError("Pakiet zmienił się po zatwierdzeniu") with tempfile.TemporaryDirectory(prefix='wgext-update-', dir=DATA_DIR) as work: source, version = _uploaded_update_validate(path, Path(work) / 'source') _write_update_status({'state':'running', 'phase':'backup', 'target_version':version, 'current_version':current, 'message':'Tworzenie kopii zapasowej'}) backup = locked_call(lambda: _build_migration_archive(iface, UPDATE_BACKUP_DIR, prefix='WGTools-pre-update')) rollback = _create_app_rollback_archive(current) _prune_update_backups() _write_update_status({'state':'running', 'phase':'install', 'target_version':version, 'current_version':current, 'message':'Instalowanie aktualizacji', 'state_backup':backup.name, 'app_backup':rollback.name}) proc = subprocess.run(['bash', str(source / 'scripts/install.sh')], cwd=str(source), capture_output=True, text=True, timeout=900, check=False, env={**os.environ, 'WG_INTERFACE':iface, 'WGTOOLS_PORT':str(_current_web_port())}) if proc.returncode: raise RuntimeError(f"Instalator zakończył się błędem: {(proc.stderr or proc.stdout)[-5000:]}") rc, out, err = run([shutil.which('systemctl') or '/usr/bin/systemctl', 'is-active', 'wgtools.service'], timeout=15) if _current_wgtools_version() != version or rc or out.strip() != 'active': raise RuntimeError(f"Nie udało się uruchomić zaktualizowanego programu: {err or out}") _write_update_status({'state':'success', 'phase':'done', 'target_version':version, 'current_version':version, 'message':f'Zainstalowano WGTools-Extended {version}', 'state_backup':backup.name, 'app_backup':rollback.name}) _write_system_audit('update.completed', object=version, result='updated') return {'ok':True, 'version':version} except Exception as exc: rollback_ok = False rollback_error = '' if rollback and rollback.exists(): _write_update_status({'state':'rolling_back', 'message':'Przywracanie poprzedniej wersji', 'error':str(exc)}) try: _restore_app_rollback_archive(rollback) rollback_ok = True except Exception as rollback_exc: rollback_error = str(rollback_exc) _write_update_status({'state':'error', 'message':'Aktualizacja nie powiodła się', 'error':str(exc), 'rollback_ok':rollback_ok, 'rollback_error':rollback_error, 'state_backup':backup.name if backup else None}) _write_system_audit('update.failed', object='upload', result=f'error: {_audit_safe_text(exc)}') raise finally: path.unlink(missing_ok=True) def update_schedule(iface: str, payload: dict[str, Any]) -> dict[str, Any]: raise RuntimeError("Aktualizacje online są wyłączone. Wgraj pakiet .bin w ustawieniach.") def update_apply(iface: str) -> dict[str, Any]: raise RuntimeError("Aktualizacje online są wyłączone. Wgraj pakiet .bin w ustawieniach.") def _https_read_state() -> dict[str, Any]: try: data = json.loads(HTTPS_STATE_FILE.read_text(encoding="utf-8")) return data if isinstance(data, dict) else {} except Exception: return {} def _https_write_state(data: dict[str, Any]) -> None: HTTPS_STATE_FILE.parent.mkdir(parents=True, exist_ok=True) temp = HTTPS_STATE_FILE.parent / f".{HTTPS_STATE_FILE.name}.tmp-{os.getpid()}" temp.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") os.chmod(temp, 0o600) os.replace(temp, HTTPS_STATE_FILE) os.chmod(HTTPS_STATE_FILE, 0o600) def _https_env_settings() -> dict[str, Any]: result: dict[str, Any] = { "enabled": False, "port": 443, "access_path": "", } try: for raw in HTTPS_ENV_FILE.read_text(encoding="utf-8").splitlines(): line = raw.strip() if not line or "=" not in line: continue key, value = line.split("=", 1) value = value.strip().strip('"').strip("'") if key == "WGTOOLS_HTTPS_ENABLED": result["enabled"] = value == "1" elif key == "WGTOOLS_HTTPS_PORT": try: result["port"] = int(value) except Exception: pass elif key == "WGTOOLS_ACCESS_PATH": result["access_path"] = value except Exception: pass return result def _https_enabled_from_env() -> bool: return bool(_https_env_settings().get("enabled")) def _https_normalize_port(value: Any) -> int: try: port = int(value or 443) except Exception as exc: raise ValueError("HTTPS port must be a number") from exc if port < 1 or port > 65535: raise ValueError("HTTPS port must be between 1 and 65535") if port == 80: raise ValueError("TCP port 80 is reserved for Let's Encrypt HTTP-01 validation") return port def _https_normalize_access_path(value: Any, *, required: bool = False) -> str: raw = str(value or "").strip() if not raw: if required: raise ValueError("Panel access path is required when built-in HTTPS is enabled") return "" raw = raw.strip("/") if not re.fullmatch(r"[A-Za-z0-9_-]{8,96}", raw): raise ValueError("Panel access path must contain 8-96 letters, digits, '_' or '-' characters") return f"/{raw}/" def _https_write_env( enabled: bool, *, https_port: int | None = None, access_path: str | None = None, ) -> None: current = _https_env_settings() port = _https_normalize_port(https_port if https_port is not None else current.get("port") or 443) path = _https_normalize_access_path(access_path if access_path is not None else current.get("access_path") or "", required=False) HTTPS_ENV_FILE.parent.mkdir(parents=True, exist_ok=True) content = "\n".join([ f"WGTOOLS_HTTPS_ENABLED={'1' if enabled else '0'}", f"WGTOOLS_HTTPS_PORT={port}", f"WGTOOLS_ACCESS_PATH={path}", f"WGTOOLS_SSL_CERTFILE={HTTPS_CERT_FILE}", f"WGTOOLS_SSL_KEYFILE={HTTPS_KEY_FILE}", "", ]) temp = HTTPS_ENV_FILE.parent / f".{HTTPS_ENV_FILE.name}.tmp-{os.getpid()}" temp.write_text(content, encoding="utf-8") os.chmod(temp, 0o600) os.replace(temp, HTTPS_ENV_FILE) os.chmod(HTTPS_ENV_FILE, 0o600) def _https_normalize_target(target_type: str, target: str) -> tuple[str, str]: kind = str(target_type or "").strip().lower() value = str(target or "").strip() if kind not in {"domain", "ip"}: raise ValueError("Certificate type must be domain or ip") if not value: raise ValueError("Domain or public IP is required") if any(part in value for part in ("://", "/", "?", "#")): raise ValueError("Enter only a domain name or IP address, without URL or port") if kind == "ip": try: addr = ipaddress.ip_address(value.strip("[]")) except ValueError as exc: raise ValueError("Public IP address is invalid") from exc if not addr.is_global: raise ValueError("Let's Encrypt IP certificates require a public IP address") return kind, str(addr) try: ascii_name = value.rstrip(".").encode("idna").decode("ascii").lower() except Exception as exc: raise ValueError("Domain name is invalid") from exc if len(ascii_name) > 253 or not re.fullmatch(r"(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", ascii_name): raise ValueError("Enter a fully qualified domain name, for example wg.example.com") return kind, ascii_name def _https_validate_email(value: str) -> str: email = str(value or "").strip() if not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", email) or len(email) > 254: raise ValueError("A valid Let's Encrypt account email is required") return email def _https_container_port_listener(port: int) -> dict[str, Any] | None: """Detect container-published TCP ports that may not have a host LISTEN socket. Docker with userland-proxy disabled publishes ports using netfilter DNAT, so ``ss -ltnp`` can report the host port as free even though inbound traffic is already claimed by a container (a common Nginx Proxy Manager setup). """ wanted = int(port) for runtime in ("docker", "podman"): binary = shutil.which(runtime) if not binary: continue rc, out, _ = run([binary, "ps", "--format", "{{.ID}}\t{{.Names}}\t{{.Ports}}"], timeout=8) if rc != 0: continue for raw in out.splitlines(): parts = raw.split("\t", 2) if len(parts) < 3: continue container_id, name, ports = (part.strip() for part in parts) # Examples: 0.0.0.0:443->443/tcp, [::]:443->443/tcp, # 127.0.0.1:8443->443/tcp. We care about the published host port. if not re.search(rf"(?:^|[,\s])(?:[^,\s]*:)?{wanted}->\d+/tcp(?:$|[,\s])", ports, re.I): continue owner = name or container_id[:12] or runtime return { "port": wanted, "free": False, "owner": owner, "detail": f"{runtime}: {raw}"[:700], "source": runtime, } return None def _https_nat_port_listener(port: int) -> dict[str, Any] | None: """Best-effort fallback for TCP DNAT/redirect rules outside container metadata.""" wanted = int(port) # Native nftables ruleset. nft = shutil.which("nft") if nft: rc, out, _ = run([nft, "-a", "list", "ruleset"], timeout=8) if rc == 0: for raw in out.splitlines(): line = raw.strip() if not re.search(rf"\btcp\s+dport\s+(?:\{{[^}}]*\b{wanted}\b[^}}]*\}}|{wanted})\b", line): continue if not re.search(r"\b(?:dnat|redirect)\b", line): continue return { "port": wanted, "free": False, "owner": "NAT", "detail": line[:700], "source": "nft", } # Docker/NPM installations may still expose their NAT through the legacy # iptables compatibility layer even when no process owns a LISTEN socket. for tool_name in ("iptables-save", "ip6tables-save"): tool = shutil.which(tool_name) if not tool: continue rc, out, _ = run([tool, "-t", "nat"], timeout=8) if rc != 0: continue for raw in out.splitlines(): line = raw.strip() if not re.search(rf"(?:--dport|--dports)\s+(?:[^\s]*,)?{wanted}(?:,|\s|$)", line): continue if not re.search(r"\s-j\s+(?:DNAT|REDIRECT)\b", line, re.I): continue return { "port": wanted, "free": False, "owner": "NAT", "detail": line[:700], "source": "iptables", } return None def _https_connectable_port_listener(port: int) -> dict[str, Any] | None: """Last-resort local reachability test for NAT-published services. A container/NAT service can accept traffic on a host address while neither ``ss`` nor container metadata exposes a local listener to WGTools. Probe loopback plus the host's own addresses; a successful TCP handshake means the port is not safe for WGTools to claim. """ wanted = int(port) targets: list[str] = ["127.0.0.1"] ip_cmd = shutil.which("ip") or "/usr/sbin/ip" rc, out, _ = run([ip_cmd, "-j", "addr", "show"], timeout=8) if rc == 0: try: for iface in json.loads(out or "[]"): for info in iface.get("addr_info") or []: local = str(info.get("local") or "").strip() family = str(info.get("family") or "") if local and family in {"inet", "inet6"} and local not in targets: targets.append(local) except Exception: pass for host in targets: try: with socket.create_connection((host, wanted), timeout=0.35): return { "port": wanted, "free": False, "owner": "service", "detail": f"TCP connection accepted on {host}:{wanted}", "source": "connect", } except OSError: continue return None def _https_listener(port: int) -> dict[str, Any]: wanted = int(port) rc, out, err = run(["ss", "-ltnp"], timeout=8) if rc == 0: lines = [] for line in out.splitlines(): if not line.startswith("LISTEN"): continue if re.search(rf":{wanted}(?:\s|$)", line): lines.append(line.strip()) if lines: detail = lines[0][:700] owner_match = re.search(r'users:\(\(\"([^\"]+)', detail) owner = owner_match.group(1) if owner_match else "process" return {"port": wanted, "free": False, "owner": owner, "detail": detail, "source": "socket"} else: # Never call a port free when the primary socket inspection itself failed. fallback_error = err or out or "ss failed" container = _https_container_port_listener(wanted) if container: return container nat = _https_nat_port_listener(wanted) if nat: return nat connectable = _https_connectable_port_listener(wanted) if connectable: return connectable if rc != 0: return {"port": wanted, "free": False, "owner": "unknown", "detail": fallback_error, "source": "unknown"} return {"port": wanted, "free": True, "owner": "", "detail": "", "source": "none"} def _https_cert_info() -> dict[str, Any]: result: dict[str, Any] = { "exists": HTTPS_CERT_FILE.is_file() and HTTPS_KEY_FILE.is_file(), "certificate_path": str(HTTPS_CERT_FILE), "private_key_path": str(HTTPS_KEY_FILE), "expires_at": 0, "subject": "", "sans": [], } if not result["exists"]: return result rc, out, err = run(["openssl", "x509", "-in", str(HTTPS_CERT_FILE), "-noout", "-enddate", "-subject", "-ext", "subjectAltName"], timeout=10) if rc != 0: result["error"] = err or out or "Could not read certificate" return result for line in out.splitlines(): line = line.strip() if line.startswith("notAfter="): raw = line.split("=", 1)[1].strip() try: dt = datetime.strptime(raw, "%b %d %H:%M:%S %Y %Z").replace(tzinfo=timezone.utc) result["expires_at"] = int(dt.timestamp()) except Exception: pass elif line.startswith("subject="): result["subject"] = line.split("=", 1)[1].strip() elif "DNS:" in line or "IP Address:" in line: for part in line.split(","): item = part.strip() if item.startswith("DNS:"): result["sans"].append(item[4:]) elif item.startswith("IP Address:"): result["sans"].append(item[len("IP Address:"):]) return result def _https_cert_contains_target(cert: dict[str, Any], kind: str, target: str) -> bool: for raw in cert.get("sans") or []: item = str(raw).strip() if kind == "ip": try: if ipaddress.ip_address(item) == ipaddress.ip_address(target): return True except ValueError: continue elif item.rstrip(".").lower() == target.rstrip(".").lower(): return True return False def _https_certbot_version() -> str: if not CERTBOT_PATH.exists(): return "" rc, out, _ = run([str(CERTBOT_PATH), "--version"], timeout=10) if rc != 0: return "" match = re.search(r"certbot\s+([^\s]+)", out, re.I) return match.group(1) if match else out.strip() def _https_timer_state() -> tuple[bool, bool]: systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" rc_enabled, out_enabled, _ = run([systemctl, "is-enabled", HTTPS_RENEW_TIMER], timeout=10) rc_active, out_active, _ = run([systemctl, "is-active", HTTPS_RENEW_TIMER], timeout=10) return rc_enabled == 0 and out_enabled.strip() == "enabled", rc_active == 0 and out_active.strip() == "active" def https_ports(payload: dict[str, Any] | None = None) -> dict[str, Any]: payload = payload or {} env = _https_env_settings() requested_port = _https_normalize_port(payload.get("https_port") or env.get("port") or 443) p80 = _https_listener(80) panel = _https_listener(requested_port) panel["wgtools"] = bool( env.get("enabled") and requested_port == int(env.get("port") or 443) and not panel.get("free") and panel.get("source") == "socket" and str(panel.get("owner") or "").lower() in {"python", "python3", "uvicorn", "wgtools-web"} ) return {"ok": True, "https_port": requested_port, "ports": {"80": p80, str(requested_port): panel}} def https_status() -> dict[str, Any]: state = _https_read_state() env = _https_env_settings() cert = _https_cert_info() timer_enabled, timer_active = _https_timer_state() https_port = _https_normalize_port(state.get("https_port") or env.get("port") or 443) access_path = _https_normalize_access_path(state.get("access_path") or env.get("access_path") or "", required=False) ports = https_ports({"https_port": https_port})["ports"] return { "ok": True, "enabled": bool(env.get("enabled")), "target_type": str(state.get("target_type") or "domain"), "target": str(state.get("target") or ""), "email": str(state.get("email") or ""), "https_port": https_port, "access_path": access_path, "issued_at": int(state.get("issued_at") or 0), "certbot_version": _https_certbot_version(), "certificate": cert, "renewal_timer_enabled": timer_enabled, "renewal_timer_active": timer_active, "ports": ports, } def https_issue(payload: dict[str, Any]) -> dict[str, Any]: kind, target = _https_normalize_target(str(payload.get("target_type") or "domain"), str(payload.get("target") or "")) email = _https_validate_email(str(payload.get("email") or "")) old_state = _https_read_state() desired_state = { "target_type": kind, "target": target, "email": email, "https_port": _https_normalize_port(payload.get("https_port") or old_state.get("https_port") or _https_env_settings().get("port") or 443), "access_path": _https_normalize_access_path(payload.get("access_path") or old_state.get("access_path") or _https_env_settings().get("access_path") or "", required=False), "issued_at": int(old_state.get("issued_at") or 0), } # When HTTPS is still disabled, the certificate button is also the Save step: # keep the entered settings even if Certbot later fails (for example because # TCP 80 is not reachable yet). Never replace the live HTTPS state before a # successful certificate change on an already enabled panel. if not _https_enabled_from_env(): _https_write_state(desired_state) if not CERTBOT_PATH.exists(): raise RuntimeError("Certbot is not installed in the WGTools environment. Reinstall or update WGTools and try again.") p80 = _https_listener(80) if not p80.get("free"): raise RuntimeError(f"TCP port 80 is already in use by {p80.get('owner') or 'another process'}. Free port 80 before requesting or renewing the certificate.") version = _https_certbot_version() if kind == "ip": match = re.match(r"(\d+)\.(\d+)", version) if not match or (int(match.group(1)), int(match.group(2))) < (5, 3): raise RuntimeError("IP certificates require Certbot 5.3 or newer") cmd = [ str(CERTBOT_PATH), "certonly", "--standalone", "--non-interactive", "--agree-tos", "--email", email, "--cert-name", HTTPS_CERT_NAME, "--keep-until-expiring", ] old_target = str(old_state.get("target") or "") old_kind = str(old_state.get("target_type") or "") if HTTPS_CERT_FILE.exists() and (old_target != target or old_kind != kind): cmd.append("--renew-with-new-domains") if kind == "ip": cmd += ["--preferred-profile", "shortlived", "--ip-address", target] else: cmd += ["-d", target] rc, out, err = run(cmd, timeout=240) if rc != 0: detail = (err or out or "Certbot failed").strip() raise RuntimeError(detail[-2500:]) cert = _https_cert_info() if not cert.get("exists"): raise RuntimeError("Certbot finished without creating the WGTools certificate files") if not _https_cert_contains_target(cert, kind, target): raise RuntimeError("The issued certificate does not contain the requested domain/IP") if int(cert.get("expires_at") or 0) <= int(time.time()) + 300: raise RuntimeError("The issued certificate is already expired or too close to expiry") state = dict(desired_state) state["issued_at"] = int(time.time()) _https_write_state(state) restart_warning = "" if _https_enabled_from_env(): try: _https_schedule_restart() except Exception as exc: restart_warning = str(exc) return {"ok": True, "message": "Certificate is ready", "certificate": cert, "state": state, "certbot_output": out[-1200:], "restart_warning": restart_warning} def _https_health_url(settings: dict[str, Any]) -> str: enabled = bool(settings.get("enabled")) if enabled: port = _https_normalize_port(settings.get("port") or 443) path = _https_normalize_access_path(settings.get("access_path") or "", required=False).rstrip("/") return f"https://127.0.0.1:{port}{path}/healthz" http_port = 8341 try: for raw in ENV_FILE.read_text(encoding="utf-8").splitlines(): if raw.strip().startswith("WGTOOLS_PORT="): http_port = int(raw.split("=", 1)[1].strip()) break except Exception: pass return f"http://127.0.0.1:{http_port}/healthz" def _https_wait_healthy(settings: dict[str, Any], timeout_seconds: int = 22) -> bool: url = _https_health_url(settings) curl = shutil.which("curl") or "/usr/bin/curl" deadline = time.time() + max(3, timeout_seconds) while time.time() < deadline: cmd = [curl, "-fsS", "--max-time", "2"] if url.startswith("https://"): cmd.insert(1, "-k") rc, _, _ = run(cmd + [url], timeout=4) if rc == 0: return True time.sleep(1) return False def https_switch_commit() -> dict[str, Any]: old_enabled = os.environ.get("WGTOOLS_HTTPS_ROLLBACK_ENABLED", "0") == "1" old_port = _https_normalize_port(os.environ.get("WGTOOLS_HTTPS_ROLLBACK_PORT") or 443) old_path = _https_normalize_access_path(os.environ.get("WGTOOLS_HTTPS_ROLLBACK_PATH") or "", required=False) old_settings = {"enabled": old_enabled, "port": old_port, "access_path": old_path} new_settings = _https_env_settings() systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" rc, out, err = run([systemctl, "restart", "wgtools.service"], timeout=30) if rc == 0 and _https_wait_healthy(new_settings): return {"ok": True, "healthy": True, "url": _https_health_url(new_settings)} _https_write_env(old_enabled, https_port=old_port, access_path=old_path) run([systemctl, "restart", "wgtools.service"], timeout=30) rollback_ok = _https_wait_healthy(old_settings, timeout_seconds=15) raise RuntimeError( "WGTools did not become healthy after the HTTPS switch; the previous web settings were restored" + ("" if rollback_ok else " but the previous web settings are also not healthy") + f": {err or out}" ) def _https_schedule_restart() -> None: systemd_run = shutil.which("systemd-run") or "/usr/bin/systemd-run" unit = f"wgtools-https-reload-{os.getpid()}-{int(time.time() * 1000) % 1000000}" rc, out, err = run([systemd_run, "--quiet", "--collect", f"--unit={unit}", "--on-active=5s", "/bin/systemctl", "restart", "wgtools.service"], timeout=15) if rc != 0: raise RuntimeError(f"Could not schedule WGTools web restart: {err or out}") def _https_schedule_switch(previous: dict[str, Any]) -> None: systemd_run = shutil.which("systemd-run") or "/usr/bin/systemd-run" unit = f"wgtools-https-switch-{os.getpid()}-{int(time.time() * 1000) % 1000000}" cmd = [ systemd_run, "--quiet", "--collect", f"--unit={unit}", "--on-active=5s", f"--setenv=WGTOOLS_HTTPS_ROLLBACK_ENABLED={'1' if previous.get('enabled') else '0'}", f"--setenv=WGTOOLS_HTTPS_ROLLBACK_PORT={_https_normalize_port(previous.get('port') or 443)}", f"--setenv=WGTOOLS_HTTPS_ROLLBACK_PATH={_https_normalize_access_path(previous.get('access_path') or '', required=False)}", str(HELPER_INSTALL_PATH), "https_switch_commit", "wg0", ] rc, out, err = run(cmd, timeout=15) if rc != 0: raise RuntimeError(f"Could not schedule the guarded HTTPS switch: {err or out}") def https_enable(payload: dict[str, Any]) -> dict[str, Any]: kind, target = _https_normalize_target(str(payload.get("target_type") or "domain"), str(payload.get("target") or "")) email = _https_validate_email(str(payload.get("email") or "")) https_port = _https_normalize_port(payload.get("https_port") or 443) access_path = _https_normalize_access_path(payload.get("access_path") or "", required=True) cert = _https_cert_info() if not cert.get("exists"): raise RuntimeError("Obtain a Let's Encrypt certificate before enabling HTTPS") if not _https_cert_contains_target(cert, kind, target): raise RuntimeError("The existing certificate does not contain the requested domain/IP") if int(cert.get("expires_at") or 0) <= int(time.time()) + 300: raise RuntimeError("The existing certificate is expired; renew it before enabling HTTPS") state = _https_read_state() if str(state.get("target") or "") != target or str(state.get("target_type") or "") != kind: raise RuntimeError("The existing certificate belongs to a different domain/IP. Obtain a certificate for the current value first.") env = _https_env_settings() old_enabled = bool(env.get("enabled")) old_port = int(env.get("port") or 443) if not (old_enabled and https_port == old_port): listener = _https_listener(https_port) if not listener.get("free"): raise RuntimeError(f"TCP port {https_port} is already in use by {listener.get('owner') or 'another process'}. WGTools will not replace or stop it.") state.update({ "target_type": kind, "target": target, "email": email, "https_port": https_port, "access_path": access_path, }) _https_write_state(state) _https_write_env(True, https_port=https_port, access_path=access_path) systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" rc, out, err = run([systemctl, "enable", "--now", HTTPS_RENEW_TIMER], timeout=20) if rc != 0: _https_write_env(old_enabled, https_port=old_port, access_path=str(env.get("access_path") or "")) raise RuntimeError(f"Could not enable automatic certificate renewal: {err or out}") try: _https_schedule_switch({"enabled": old_enabled, "port": old_port, "access_path": str(env.get("access_path") or "")}) except Exception: if not old_enabled: run([systemctl, "disable", "--now", HTTPS_RENEW_TIMER], timeout=20) _https_write_env(old_enabled, https_port=old_port, access_path=str(env.get("access_path") or "")) raise return { "ok": True, "enabled": True, "message": f"HTTPS enabled; WGTools will restart on TCP {https_port}", "redirect_host": target, "redirect_port": https_port, "access_path": access_path, } def https_disable() -> dict[str, Any]: env = _https_env_settings() was_enabled = bool(env.get("enabled")) _https_write_env(False, https_port=int(env.get("port") or 443), access_path=str(env.get("access_path") or "")) systemctl = shutil.which("systemctl") or "/usr/bin/systemctl" run([systemctl, "disable", "--now", HTTPS_RENEW_TIMER], timeout=20) try: _https_schedule_switch({"enabled": was_enabled, "port": int(env.get("port") or 443), "access_path": str(env.get("access_path") or "")}) except Exception: if was_enabled: _https_write_env(True, https_port=int(env.get("port") or 443), access_path=str(env.get("access_path") or "")) run([systemctl, "enable", "--now", HTTPS_RENEW_TIMER], timeout=20) raise http_port = 8341 try: for raw in ENV_FILE.read_text(encoding="utf-8").splitlines(): if raw.strip().startswith("WGTOOLS_PORT="): http_port = int(raw.split("=", 1)[1].strip()) break except Exception: pass return {"ok": True, "enabled": False, "message": "Built-in HTTPS disabled; WGTools will return to HTTP", "http_port": http_port} def locked_call(func): LOCK_PATH.parent.mkdir(parents=True, exist_ok=True) with LOCK_PATH.open("w") as lock: try: fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError as exc: raise RuntimeError("Another WGTools operation is already running") from exc return func() def update_locked_call(func): UPDATE_LOCK_PATH.parent.mkdir(parents=True, exist_ok=True) with UPDATE_LOCK_PATH.open("w") as lock: try: fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError as exc: raise RuntimeError("Another WGTools update is already running") from exc return func() def main() -> int: if os.geteuid() != 0: print(json.dumps({"ok": False, "error": "helper must run as root"})) return 1 if len(sys.argv) != 3: print(json.dumps({"ok": False, "error": "usage: wgtools-helper "})) return 2 action, iface = sys.argv[1], sys.argv[2] if action not in ALLOWED_ACTIONS or not ALLOWED_IFACE_RE.fullmatch(iface): print(json.dumps({"ok": False, "error": "invalid arguments"})) return 2 try: if action == "snapshot": payload = read_json_stdin() result = build_snapshot(iface, str(payload.get("view") or "full")) elif action == "interfaces_list": result = interfaces_list(iface) elif action == "interface_meta_set": payload = read_json_stdin() result = locked_call(lambda: interface_meta_set(iface, payload)) elif action == "interface_delete": result = locked_call(lambda: interface_delete(iface)) elif action == "metrics_sample": result = metrics_sample(iface) elif action == "metrics_history": result = metrics_history() elif action == "traffic_reset": result = locked_call(lambda: reset_wireguard_traffic(iface)) elif action == "diagnostics": result = build_diagnostics(iface) elif action == "network_trace": payload = read_json_stdin() result = network_trace(payload) elif action == "wireguard_start": result = locked_call(lambda: wireguard_service_action(iface, "start")) elif action == "wireguard_stop": result = locked_call(lambda: wireguard_service_action(iface, "stop")) elif action == "wireguard_restart": result = locked_call(lambda: wireguard_service_action(iface, "restart")) elif action == "install_wireguard": result = locked_call(install_wireguard) elif action == "create_server": payload = read_json_stdin() result = locked_call(lambda: create_server(iface, payload)) elif action == "create_client": payload = read_json_stdin() result = locked_call(lambda: create_client(iface, payload)) elif action == "update_client": payload = read_json_stdin() result = locked_call(lambda: update_client(iface, payload)) elif action == "delete_client": payload = read_json_stdin() result = locked_call(lambda: delete_client(iface, payload)) elif action == "rotate_client_credentials": payload = read_json_stdin() result = locked_call(lambda: rotate_client_credentials(iface, payload)) elif action == "expire_clients": result = locked_call(expire_clients) elif action == "client_config": payload = read_json_stdin() result = build_client_config(iface, str(payload.get("public_key", "")).strip()) elif action == "group_create": payload = read_json_stdin() result = locked_call(lambda: group_create(iface, payload)) elif action == "group_update": payload = read_json_stdin() result = locked_call(lambda: group_update(iface, payload)) elif action == "group_delete": payload = read_json_stdin() result = locked_call(lambda: group_delete(iface, payload)) elif action == "server_settings_apply": payload = read_json_stdin() result = locked_call(lambda: server_settings_apply(iface, payload)) elif action == "extended_snat_get": result = extended_snat_get(iface) elif action == "extended_host_ips": result = {"ok": True, "addresses": _extended_host_ips()} elif action == "extended_snat_apply": payload = read_json_stdin() result = locked_call(lambda: extended_snat_apply(iface, payload)) elif action == "extended_listen_get": result = extended_listen_get(iface) elif action == "extended_listen_apply": payload = read_json_stdin() result = locked_call(lambda: extended_listen_apply(iface, payload)) elif action == "extended_ip_groups_get": result = extended_ip_groups_get() elif action == "extended_ip_groups_set": payload = read_json_stdin() result = locked_call(lambda: extended_ip_groups_set(payload)) elif action == "extended_forward_get": result = extended_forward_get(iface) elif action == "extended_forward_add": payload = read_json_stdin() result = locked_call(lambda: extended_forward_add(iface, payload)) elif action == "extended_forward_update": payload = read_json_stdin() identifier = str(payload.get('id') or '') if not re.fullmatch(r'[0-9a-f]{16}', identifier): raise ValueError("Nieprawidłowy identyfikator przekierowania") result = locked_call(lambda: extended_forward_add(iface, payload, update_id=identifier)) elif action == "extended_forward_delete": payload = read_json_stdin() result = locked_call(lambda: extended_forward_delete(iface, payload)) elif action == "update_file_schedule": payload = read_json_stdin() result = locked_call(lambda: update_file_schedule(iface, payload)) elif action == "update_file_apply": result = update_locked_call(lambda: update_file_apply(iface)) elif action == "raw_config_get": result = raw_config_get(iface) elif action == "raw_config_apply": payload = read_json_stdin() result = locked_call(lambda: raw_config_apply(iface, payload)) elif action == "route_create": payload = read_json_stdin() result = locked_call(lambda: route_create(iface, payload)) elif action == "route_update": payload = read_json_stdin() result = locked_call(lambda: route_update(iface, payload)) elif action == "route_delete": payload = read_json_stdin() result = locked_call(lambda: route_delete(iface, payload)) elif action == "access_rule_create": payload = read_json_stdin() result = locked_call(lambda: access_rule_create(iface, payload)) elif action == "access_rule_update": payload = read_json_stdin() result = locked_call(lambda: access_rule_update(iface, payload)) elif action == "access_rule_delete": payload = read_json_stdin() result = locked_call(lambda: access_rule_delete(iface, payload)) elif action == "migration_backup_create": result = locked_call(lambda: migration_backup_create(iface)) elif action == "migration_restore": payload = read_json_stdin() result = locked_call(lambda: migration_restore(iface, payload)) elif action == "https_status": result = https_status() elif action == "https_ports": payload = read_json_stdin() result = https_ports(payload) elif action == "https_issue": payload = read_json_stdin() result = locked_call(lambda: https_issue(payload)) elif action == "https_enable": payload = read_json_stdin() result = locked_call(lambda: https_enable(payload)) elif action == "https_disable": result = locked_call(https_disable) elif action == "https_switch_commit": result = https_switch_commit() elif action == "update_check": result = update_check() elif action == "update_notice": result = update_notice() elif action == "update_status": result = update_status() elif action == "update_schedule": payload = read_json_stdin() result = update_schedule(iface, payload) elif action == "update_apply": result = update_locked_call(lambda: update_apply(iface)) else: raise RuntimeError("Unsupported action") print(json.dumps(result, ensure_ascii=False)) return 0 except Exception as exc: print(json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False)) return 1 if __name__ == "__main__": raise SystemExit(main())