Capture Neko/WG/network hubs, Studio viewer charts, physical deploy docs, and one-shot scripts so VPS vs physical can be toggled later without losing WIP. Co-authored-by: Cursor <cursoragent@cursor.com>
724 lines
29 KiB
Python
724 lines
29 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""WireGuard hub — adapted from sh2/d2ypp2 wireguard_config.py for douyinWEB.
|
||
|
||
Physical deploy rule: prefer overlay AllowedIPs (VPN subnet only), never 0.0.0.0/0,
|
||
so ShellCrash / soft-router default routes stay intact.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import ipaddress
|
||
import json
|
||
import os
|
||
import platform
|
||
import re
|
||
import shutil
|
||
import subprocess
|
||
import time
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
from .config import settings
|
||
|
||
MAX_WIREGUARD_CONFIG_BYTES = 128 * 1024
|
||
_SAFE_NAME_RE = re.compile(r"[^A-Za-z0-9_.-]+")
|
||
_BASE64_KEY_RE = re.compile(r"^[A-Za-z0-9+/]{43}=$")
|
||
_DEFAULT_ROUTES = {"0.0.0.0/0", "::/0"}
|
||
DEFAULT_OVERLAY_MTU = 1360
|
||
DEFAULT_KEEPALIVE_SECONDS = 25
|
||
PREFERRED_IFACE = "wg-dy"
|
||
|
||
|
||
class WireGuardConfigError(ValueError):
|
||
pass
|
||
|
||
|
||
def _imports_dir() -> Path:
|
||
p = settings.data_dir / "wireguard" / "imports"
|
||
p.mkdir(parents=True, exist_ok=True)
|
||
return p
|
||
|
||
|
||
def _run(cmd: list[str], *, timeout: float = 12.0) -> dict[str, Any]:
|
||
try:
|
||
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
|
||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||
return {"ok": False, "code": 124, "stdout": "", "stderr": str(exc)}
|
||
out = (proc.stdout or "").strip()
|
||
err = (proc.stderr or "").strip()
|
||
return {"ok": proc.returncode == 0, "code": proc.returncode or 0, "stdout": out, "stderr": err}
|
||
|
||
|
||
def _priv(cmd: list[str], *, timeout: float = 20.0) -> dict[str, Any]:
|
||
"""Run as root when needed (API may be non-root with passwordless sudo)."""
|
||
if hasattr(os, "geteuid") and os.geteuid() == 0:
|
||
return _run(cmd, timeout=timeout)
|
||
if shutil.which("sudo"):
|
||
return _run(["sudo", "-n", *cmd], timeout=timeout)
|
||
return _run(cmd, timeout=timeout)
|
||
|
||
|
||
def _unit_state(unit: str) -> dict[str, str]:
|
||
if not shutil.which("systemctl"):
|
||
return {"active": "unknown", "enabled": "unknown"}
|
||
active = _run(["systemctl", "is-active", unit], timeout=3.0)
|
||
enabled = _run(["systemctl", "is-enabled", unit], timeout=3.0)
|
||
return {
|
||
"active": (active["stdout"] or ("active" if active["ok"] else "inactive")).splitlines()[0],
|
||
"enabled": (enabled["stdout"] or ("enabled" if enabled["ok"] else "disabled")).splitlines()[0],
|
||
}
|
||
|
||
|
||
def _strip_inline_comment(line: str) -> str:
|
||
in_quote = False
|
||
quote = ""
|
||
for idx, ch in enumerate(line):
|
||
if ch in {"'", '"'}:
|
||
if in_quote and ch == quote:
|
||
in_quote = False
|
||
quote = ""
|
||
elif not in_quote:
|
||
in_quote = True
|
||
quote = ch
|
||
if not in_quote and ch in {"#", ";"}:
|
||
return line[:idx]
|
||
return line
|
||
|
||
|
||
def _normalized_config_text(content: str) -> str:
|
||
return content.replace("\r\n", "\n").replace("\r", "\n")
|
||
|
||
|
||
def safe_wireguard_name(name: str | None) -> str:
|
||
raw = (name or PREFERRED_IFACE).strip()
|
||
raw = raw[:-5] if raw.lower().endswith(".conf") else raw
|
||
safe = _SAFE_NAME_RE.sub("-", raw).strip(".-")
|
||
return (safe or PREFERRED_IFACE)[:64]
|
||
|
||
|
||
def _split_csv(value: str) -> list[str]:
|
||
return [p.strip() for p in value.split(",") if p.strip()]
|
||
|
||
|
||
def _validate_ip_networks(values: list[str], label: str) -> list[str]:
|
||
out: list[str] = []
|
||
for raw in values:
|
||
try:
|
||
out.append(str(ipaddress.ip_network(raw, strict=False)))
|
||
except ValueError as exc:
|
||
raise WireGuardConfigError(f"Invalid {label}: {raw}") from exc
|
||
return out
|
||
|
||
|
||
def _validate_ip_interfaces(values: list[str], label: str) -> list[str]:
|
||
out: list[str] = []
|
||
for raw in values:
|
||
try:
|
||
out.append(str(ipaddress.ip_interface(raw)))
|
||
except ValueError as exc:
|
||
raise WireGuardConfigError(f"Invalid {label}: {raw}") from exc
|
||
return out
|
||
|
||
|
||
def _parse_endpoint(value: str) -> tuple[str, int]:
|
||
raw = value.strip()
|
||
if raw.startswith("["):
|
||
end = raw.find("]")
|
||
if end < 0 or end + 2 > len(raw) or raw[end + 1] != ":":
|
||
raise WireGuardConfigError(f"Invalid Endpoint: {raw}")
|
||
host, port_raw = raw[1:end], raw[end + 2 :]
|
||
else:
|
||
host, sep, port_raw = raw.rpartition(":")
|
||
if not sep:
|
||
raise WireGuardConfigError(f"Invalid Endpoint: {raw}")
|
||
try:
|
||
port = int(port_raw)
|
||
except ValueError as exc:
|
||
raise WireGuardConfigError(f"Invalid Endpoint port: {raw}") from exc
|
||
if not host or port < 1 or port > 65535:
|
||
raise WireGuardConfigError(f"Invalid Endpoint: {raw}")
|
||
return host.strip(), port
|
||
|
||
|
||
def _redact_key(value: str) -> str:
|
||
v = value.strip()
|
||
if len(v) < 12:
|
||
return "***"
|
||
return v[:8] + "…" + v[-4:]
|
||
|
||
|
||
def redact_wireguard_config(content: str) -> str:
|
||
lines: list[str] = []
|
||
for raw in _normalized_config_text(content).splitlines():
|
||
stripped = _strip_inline_comment(raw)
|
||
if "=" in stripped:
|
||
key, _, _val = stripped.partition("=")
|
||
if key.strip().lower() in {"privatekey", "presharedkey"}:
|
||
lines.append(f"{key.strip()} = ***REDACTED***")
|
||
continue
|
||
lines.append(raw)
|
||
return "\n".join(lines).rstrip() + "\n"
|
||
|
||
|
||
def parse_wireguard_config(content: str, *, name: str | None = None) -> dict[str, Any]:
|
||
if "\x00" in content:
|
||
raise WireGuardConfigError("config contains NUL")
|
||
if len(content.encode("utf-8")) > MAX_WIREGUARD_CONFIG_BYTES:
|
||
raise WireGuardConfigError("config too large")
|
||
|
||
sections: list[dict[str, Any]] = []
|
||
current: dict[str, Any] | None = None
|
||
warnings: list[str] = []
|
||
for lineno, raw in enumerate(_normalized_config_text(content).splitlines(), start=1):
|
||
line = _strip_inline_comment(raw).strip()
|
||
if not line:
|
||
continue
|
||
if line.startswith("[") and line.endswith("]"):
|
||
section_name = line[1:-1].strip()
|
||
if section_name not in {"Interface", "Peer"}:
|
||
warnings.append(f"Line {lineno}: ignored [{section_name}]")
|
||
current = {"name": section_name, "items": {}}
|
||
sections.append(current)
|
||
continue
|
||
if current is None:
|
||
raise WireGuardConfigError(f"Line {lineno}: value before section")
|
||
if "=" not in line:
|
||
raise WireGuardConfigError(f"Line {lineno}: expected key=value")
|
||
key, _, value = line.partition("=")
|
||
current["items"].setdefault(key.strip(), []).append(value.strip().strip('"').strip("'"))
|
||
|
||
interfaces = [s for s in sections if s["name"] == "Interface"]
|
||
peers = [s for s in sections if s["name"] == "Peer"]
|
||
if not interfaces:
|
||
raise WireGuardConfigError("missing [Interface]")
|
||
if not peers:
|
||
raise WireGuardConfigError("missing [Peer]")
|
||
|
||
iface_items = interfaces[0]["items"]
|
||
addresses = _validate_ip_interfaces(_split_csv(",".join(iface_items.get("Address", []))), "Address")
|
||
peer_summaries: list[dict[str, Any]] = []
|
||
for idx, peer in enumerate(peers, start=1):
|
||
items = peer["items"]
|
||
allowed = _validate_ip_networks(_split_csv(",".join(items.get("AllowedIPs", []))), "AllowedIPs")
|
||
routes_default = any(a in _DEFAULT_ROUTES for a in allowed)
|
||
if routes_default:
|
||
warnings.append(
|
||
f"Peer {idx}: AllowedIPs has default route — overlay mode strips this so ShellCrash keeps working"
|
||
)
|
||
endpoint_raw = (items.get("Endpoint") or [""])[-1]
|
||
endpoint_host, endpoint_port = ("", None)
|
||
if endpoint_raw:
|
||
endpoint_host, endpoint_port = _parse_endpoint(endpoint_raw)
|
||
keepalive = None
|
||
if items.get("PersistentKeepalive"):
|
||
try:
|
||
keepalive = int(items["PersistentKeepalive"][-1])
|
||
except ValueError as exc:
|
||
raise WireGuardConfigError("Invalid PersistentKeepalive") from exc
|
||
if endpoint_raw and keepalive is None:
|
||
warnings.append(f"Peer {idx}: add PersistentKeepalive=25 for NAT/VPS links")
|
||
pub = (items.get("PublicKey") or [""])[-1]
|
||
peer_summaries.append(
|
||
{
|
||
"id": idx,
|
||
"public_key": _redact_key(pub) if pub else "",
|
||
"endpoint": endpoint_raw,
|
||
"endpoint_host": endpoint_host,
|
||
"endpoint_port": endpoint_port,
|
||
"allowed_ips": allowed,
|
||
"routes_default": routes_default,
|
||
"persistent_keepalive": keepalive,
|
||
}
|
||
)
|
||
|
||
return {
|
||
"name": safe_wireguard_name(name),
|
||
"interface": {
|
||
"addresses": addresses,
|
||
"listen_port": (iface_items.get("ListenPort") or [None])[-1],
|
||
"dns": _split_csv(",".join(iface_items.get("DNS", []))),
|
||
"mtu": int(iface_items["MTU"][-1]) if iface_items.get("MTU") else None,
|
||
"has_private_key": bool((iface_items.get("PrivateKey") or [""])[-1]),
|
||
},
|
||
"peers": peer_summaries,
|
||
"peer_count": len(peer_summaries),
|
||
"warnings": warnings,
|
||
"routes_default": any(p.get("routes_default") for p in peer_summaries),
|
||
}
|
||
|
||
|
||
def _infer_overlay_allowed_ips(summary: dict[str, Any]) -> list[str]:
|
||
out: list[str] = []
|
||
for raw in (summary.get("interface") or {}).get("addresses") or []:
|
||
try:
|
||
iface = ipaddress.ip_interface(str(raw))
|
||
except ValueError:
|
||
continue
|
||
if not iface.ip.is_private:
|
||
continue
|
||
network = iface.network if iface.network.prefixlen < 32 else ipaddress.ip_network(f"{iface.ip}/24", strict=False)
|
||
value = str(network)
|
||
if value not in out:
|
||
out.append(value)
|
||
return out
|
||
|
||
|
||
def normalize_wireguard_keepalive_config(content: str) -> tuple[str, dict[str, Any]]:
|
||
lines = _normalized_config_text(content).splitlines()
|
||
next_lines: list[str] = []
|
||
section = ""
|
||
peer_has_keepalive = False
|
||
peer_seen_endpoint = False
|
||
changed = False
|
||
added = 0
|
||
|
||
def flush() -> None:
|
||
nonlocal added, changed, peer_has_keepalive, peer_seen_endpoint
|
||
if section == "Peer" and peer_seen_endpoint and not peer_has_keepalive:
|
||
next_lines.append(f"PersistentKeepalive = {DEFAULT_KEEPALIVE_SECONDS}")
|
||
added += 1
|
||
changed = True
|
||
peer_has_keepalive = False
|
||
peer_seen_endpoint = False
|
||
|
||
for raw in lines:
|
||
stripped = _strip_inline_comment(raw).strip()
|
||
if stripped.startswith("[") and stripped.endswith("]"):
|
||
flush()
|
||
section = stripped[1:-1].strip()
|
||
next_lines.append(raw)
|
||
continue
|
||
if "=" in stripped and section == "Peer":
|
||
key = stripped.partition("=")[0].strip().lower()
|
||
if key == "endpoint":
|
||
peer_seen_endpoint = True
|
||
elif key == "persistentkeepalive":
|
||
peer_has_keepalive = True
|
||
next_lines.append(raw)
|
||
flush()
|
||
warnings = []
|
||
if added:
|
||
warnings.append(f"Added PersistentKeepalive={DEFAULT_KEEPALIVE_SECONDS} to {added} peer(s)")
|
||
return "\n".join(next_lines).strip() + "\n", {"changed": changed, "added_keepalive": added, "warnings": warnings}
|
||
|
||
|
||
def normalize_wireguard_overlay_config(content: str, *, name: str | None = None) -> tuple[str, dict[str, Any]]:
|
||
"""Strip default routes → VPN subnet only (SH2 overlay)."""
|
||
summary = parse_wireguard_config(content, name=name)
|
||
overlay_allowed = _infer_overlay_allowed_ips(summary)
|
||
warnings: list[str] = []
|
||
if not overlay_allowed:
|
||
warnings.append("No private Interface Address; kept AllowedIPs")
|
||
normalized, keepalive = normalize_wireguard_keepalive_config(content)
|
||
warnings.extend(keepalive.get("warnings") or [])
|
||
return normalized, {
|
||
"changed": bool(keepalive.get("changed")),
|
||
"allowed_ips": [],
|
||
"warnings": warnings,
|
||
"keepalive": keepalive,
|
||
}
|
||
|
||
lines = _normalized_config_text(content).splitlines()
|
||
next_lines: list[str] = []
|
||
section = ""
|
||
peer_has_keepalive = False
|
||
peer_seen_endpoint = False
|
||
changed = False
|
||
added_keepalive = 0
|
||
added_mtu = False
|
||
interface_has_mtu = False
|
||
interface_seen_address = False
|
||
|
||
def maybe_keepalive() -> None:
|
||
nonlocal added_keepalive, changed, peer_has_keepalive, peer_seen_endpoint
|
||
if section == "Peer" and peer_seen_endpoint and not peer_has_keepalive:
|
||
next_lines.append(f"PersistentKeepalive = {DEFAULT_KEEPALIVE_SECONDS}")
|
||
added_keepalive += 1
|
||
changed = True
|
||
peer_has_keepalive = False
|
||
peer_seen_endpoint = False
|
||
|
||
for raw in lines:
|
||
stripped = _strip_inline_comment(raw).strip()
|
||
if stripped.startswith("[") and stripped.endswith("]"):
|
||
if section == "Interface" and interface_seen_address and not interface_has_mtu:
|
||
next_lines.append(f"MTU = {DEFAULT_OVERLAY_MTU}")
|
||
added_mtu = True
|
||
changed = True
|
||
maybe_keepalive()
|
||
section = stripped[1:-1].strip()
|
||
if section == "Interface":
|
||
interface_has_mtu = False
|
||
interface_seen_address = False
|
||
next_lines.append(raw)
|
||
continue
|
||
if "=" not in stripped:
|
||
next_lines.append(raw)
|
||
continue
|
||
key, _, value = stripped.partition("=")
|
||
key_l = key.strip().lower()
|
||
if section == "Interface":
|
||
if key_l == "address":
|
||
interface_seen_address = True
|
||
elif key_l == "mtu":
|
||
interface_has_mtu = True
|
||
elif section == "Peer":
|
||
if key_l == "endpoint":
|
||
peer_seen_endpoint = True
|
||
elif key_l == "persistentkeepalive":
|
||
peer_has_keepalive = True
|
||
elif key_l == "allowedips":
|
||
allowed = _validate_ip_networks(_split_csv(value), "AllowedIPs")
|
||
if any(item in _DEFAULT_ROUTES for item in allowed):
|
||
next_lines.append(f"AllowedIPs = {', '.join(overlay_allowed)}")
|
||
changed = True
|
||
continue
|
||
next_lines.append(raw)
|
||
|
||
if section == "Interface" and interface_seen_address and not interface_has_mtu:
|
||
next_lines.append(f"MTU = {DEFAULT_OVERLAY_MTU}")
|
||
added_mtu = True
|
||
changed = True
|
||
maybe_keepalive()
|
||
|
||
if changed:
|
||
warnings.append("Overlay removed 0.0.0.0/0 so WireGuard will not hijack ShellCrash egress")
|
||
if added_mtu:
|
||
warnings.append(f"Added MTU {DEFAULT_OVERLAY_MTU}")
|
||
if added_keepalive:
|
||
warnings.append(f"Added PersistentKeepalive={DEFAULT_KEEPALIVE_SECONDS} ×{added_keepalive}")
|
||
return "\n".join(next_lines).strip() + "\n", {
|
||
"changed": changed,
|
||
"allowed_ips": overlay_allowed,
|
||
"warnings": warnings,
|
||
}
|
||
|
||
|
||
def save_imported_wireguard_config(
|
||
content: str,
|
||
*,
|
||
name: str | None = None,
|
||
route_mode: str = "overlay",
|
||
) -> dict[str, Any]:
|
||
route_mode = (route_mode or "overlay").strip().lower()
|
||
overlay: dict[str, Any] = {"changed": False, "allowed_ips": [], "warnings": []}
|
||
if route_mode == "overlay":
|
||
normalized, overlay = normalize_wireguard_overlay_config(content, name=name)
|
||
elif route_mode == "preserve":
|
||
normalized, keepalive = normalize_wireguard_keepalive_config(content)
|
||
overlay = {"changed": bool(keepalive.get("changed")), "allowed_ips": [], "warnings": keepalive.get("warnings") or [], "keepalive": keepalive}
|
||
else:
|
||
raise WireGuardConfigError(f"unsupported route_mode: {route_mode}")
|
||
|
||
summary = parse_wireguard_config(normalized, name=name)
|
||
summary["warnings"] = [*summary.get("warnings", []), *(overlay.get("warnings") or [])]
|
||
summary["route_mode"] = route_mode
|
||
summary["overlay"] = overlay
|
||
safe_name = str(summary["name"])
|
||
target = _imports_dir() / f"{safe_name}.conf"
|
||
target.write_text(normalized, encoding="utf-8")
|
||
try:
|
||
os.chmod(target, 0o600)
|
||
except OSError:
|
||
pass
|
||
(target.with_suffix(".summary.json")).write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||
return {
|
||
"name": safe_name,
|
||
"path": str(target),
|
||
"summary": summary,
|
||
"redacted_config": redact_wireguard_config(normalized),
|
||
"overlay": overlay,
|
||
"route_mode": route_mode,
|
||
}
|
||
|
||
|
||
def list_imported_configs() -> list[dict[str, Any]]:
|
||
out: list[dict[str, Any]] = []
|
||
for path in sorted(_imports_dir().glob("*.conf")):
|
||
try:
|
||
content = path.read_text(encoding="utf-8", errors="replace")
|
||
summary = parse_wireguard_config(content, name=path.stem)
|
||
out.append({"name": path.stem, "path": str(path), "source": "import", "peer_count": summary.get("peer_count"), "summary": summary})
|
||
except Exception as exc:
|
||
out.append({"name": path.stem, "path": str(path), "source": "import", "error": str(exc)})
|
||
return out
|
||
|
||
|
||
def list_system_configs() -> list[dict[str, Any]]:
|
||
etc = Path("/etc/wireguard")
|
||
# Non-root API: list via sudo when directory not readable.
|
||
names: list[str] = []
|
||
if etc.is_dir():
|
||
try:
|
||
names = [p.stem for p in sorted(etc.glob("*.conf"))]
|
||
except OSError:
|
||
names = []
|
||
if not names:
|
||
ls = _priv(["bash", "-lc", "ls -1 /etc/wireguard/*.conf 2>/dev/null"], timeout=5.0)
|
||
for line in (ls.get("stdout") or "").splitlines():
|
||
p = Path(line.strip())
|
||
if p.suffix == ".conf":
|
||
names.append(p.stem)
|
||
out: list[dict[str, Any]] = []
|
||
for stem in names:
|
||
try:
|
||
content = _read_conf_text(stem, prefer_system=True)
|
||
summary = parse_wireguard_config(content, name=stem)
|
||
out.append(
|
||
{
|
||
"name": stem,
|
||
"path": f"/etc/wireguard/{stem}.conf",
|
||
"source": "system",
|
||
"peer_count": summary.get("peer_count"),
|
||
"routes_default": summary.get("routes_default"),
|
||
"summary": summary,
|
||
}
|
||
)
|
||
except Exception as exc:
|
||
out.append({"name": stem, "path": f"/etc/wireguard/{stem}.conf", "source": "system", "error": str(exc)})
|
||
return out
|
||
|
||
|
||
def _read_conf_text(name: str, *, prefer_system: bool = False) -> str:
|
||
safe = safe_wireguard_name(name)
|
||
bases = [Path("/etc/wireguard"), _imports_dir()] if prefer_system else [_imports_dir(), Path("/etc/wireguard")]
|
||
for base in bases:
|
||
path = base / f"{safe}.conf"
|
||
if path.is_file():
|
||
try:
|
||
return path.read_text(encoding="utf-8", errors="replace")
|
||
except OSError:
|
||
pass
|
||
# sudo cat for /etc/wireguard
|
||
if str(base) == "/etc/wireguard":
|
||
r = _priv(["cat", str(path)], timeout=5.0)
|
||
if r.get("ok") and r.get("stdout") is not None:
|
||
return str(r.get("stdout") or "")
|
||
raise WireGuardConfigError(f"config not found: {safe}")
|
||
|
||
|
||
def read_config(name: str) -> dict[str, Any]:
|
||
safe = safe_wireguard_name(name)
|
||
# Prefer live system conf when present — that is what wg-quick is running.
|
||
content = _read_conf_text(safe, prefer_system=True)
|
||
sys_path = Path("/etc/wireguard") / f"{safe}.conf"
|
||
imp_path = _imports_dir() / f"{safe}.conf"
|
||
if sys_path.is_file() or _priv(["test", "-f", str(sys_path)], timeout=3.0).get("ok"):
|
||
path_hint = str(sys_path)
|
||
source = "system"
|
||
else:
|
||
path_hint = str(imp_path)
|
||
source = "import"
|
||
return {
|
||
"name": safe,
|
||
"path": path_hint,
|
||
"source": source,
|
||
"content": content,
|
||
"redacted_config": redact_wireguard_config(content),
|
||
"summary": parse_wireguard_config(content, name=safe),
|
||
}
|
||
|
||
|
||
def delete_imported_config(name: str) -> dict[str, Any]:
|
||
safe = safe_wireguard_name(name)
|
||
path = _imports_dir() / f"{safe}.conf"
|
||
if not path.is_file():
|
||
raise WireGuardConfigError(f"导入配置不存在: {safe}")
|
||
path.unlink(missing_ok=True)
|
||
path.with_suffix(".summary.json").unlink(missing_ok=True)
|
||
return {"ok": True, "deleted": safe}
|
||
|
||
|
||
def apply_wireguard_config(
|
||
content: str,
|
||
*,
|
||
name: str | None = None,
|
||
route_mode: str = "overlay",
|
||
) -> dict[str, Any]:
|
||
"""Save (overlay by default) + install to /etc/wireguard + enable/restart unit."""
|
||
result = save_imported_wireguard_config(content, name=name, route_mode=route_mode)
|
||
safe_name = str(result["name"])
|
||
source = Path(str(result["path"]))
|
||
if platform.system().lower() != "linux":
|
||
result["applied"] = False
|
||
result["apply_error"] = "WireGuard apply only on Linux"
|
||
return result
|
||
if not shutil.which("wg-quick"):
|
||
raise WireGuardConfigError("wg-quick 未安装")
|
||
|
||
target = Path("/etc/wireguard") / f"{safe_name}.conf"
|
||
for cmd in (
|
||
["mkdir", "-p", "/etc/wireguard"],
|
||
["install", "-m", "600", str(source), str(target)],
|
||
):
|
||
run = _priv(cmd, timeout=10.0)
|
||
if not run["ok"]:
|
||
raise WireGuardConfigError(run["stderr"] or run["stdout"] or f"failed: {' '.join(cmd)}")
|
||
|
||
unit = f"wg-quick@{safe_name}.service"
|
||
st = _unit_state(unit)
|
||
if st.get("active") == "active":
|
||
run = _priv(["systemctl", "restart", unit], timeout=30.0)
|
||
else:
|
||
run = _priv(["systemctl", "enable", "--now", unit], timeout=30.0)
|
||
if not run["ok"]:
|
||
# iface may already be up outside systemd — try wg-quick
|
||
fallback = _priv(["wg-quick", "down", safe_name], timeout=15.0)
|
||
up = _priv(["wg-quick", "up", safe_name], timeout=20.0)
|
||
if not up["ok"]:
|
||
raise WireGuardConfigError(
|
||
(run["stderr"] or run["stdout"] or "")
|
||
+ " | "
|
||
+ (up["stderr"] or up["stdout"] or fallback.get("stderr") or "wg-quick failed")
|
||
)
|
||
result["applied"] = True
|
||
result["system_path"] = str(target)
|
||
result["status"] = runtime_status()
|
||
return result
|
||
|
||
|
||
def iface_action(name: str, action: str) -> dict[str, Any]:
|
||
action = str(action or "").strip().lower()
|
||
if action not in {"start", "stop", "restart", "status"}:
|
||
raise WireGuardConfigError(f"unsupported action: {action}")
|
||
safe = safe_wireguard_name(name)
|
||
unit = f"wg-quick@{safe}.service"
|
||
if action == "status":
|
||
return {"ok": True, "name": safe, "unit": _unit_state(unit), "runtime": runtime_status()}
|
||
|
||
if platform.system().lower() != "linux":
|
||
raise WireGuardConfigError("only Linux")
|
||
conf = Path("/etc/wireguard") / f"{safe}.conf"
|
||
if not conf.is_file() and action != "stop":
|
||
raise WireGuardConfigError(f"/etc/wireguard/{safe}.conf missing — import/apply first")
|
||
|
||
if action == "start":
|
||
run = _priv(["systemctl", "enable", "--now", unit], timeout=30.0)
|
||
if not run["ok"]:
|
||
run = _priv(["wg-quick", "up", safe], timeout=20.0)
|
||
elif action == "stop":
|
||
run = _priv(["systemctl", "stop", unit], timeout=20.0)
|
||
_priv(["wg-quick", "down", safe], timeout=15.0) # best-effort if unit failed
|
||
else: # restart
|
||
run = _priv(["systemctl", "restart", unit], timeout=30.0)
|
||
if not run["ok"]:
|
||
_priv(["wg-quick", "down", safe], timeout=15.0)
|
||
run = _priv(["wg-quick", "up", safe], timeout=20.0)
|
||
|
||
if action != "stop" and not run["ok"]:
|
||
# stop is ok even if already down
|
||
if action == "stop":
|
||
pass
|
||
else:
|
||
raise WireGuardConfigError(run["stderr"] or run["stdout"] or f"{action} failed")
|
||
|
||
return {"ok": True, "name": safe, "action": action, "unit": _unit_state(unit), "detail": run.get("stdout") or run.get("stderr") or "", "runtime": runtime_status()}
|
||
|
||
|
||
def _parse_wg_show(text: str) -> list[dict[str, Any]]:
|
||
ifaces: list[dict[str, Any]] = []
|
||
current: dict[str, Any] | None = None
|
||
for line in (text or "").splitlines():
|
||
if line.startswith("interface:"):
|
||
if current:
|
||
ifaces.append(current)
|
||
current = {"name": line.split(":", 1)[1].strip(), "peers": [], "listening_port": None, "public_key": ""}
|
||
elif current is None:
|
||
continue
|
||
elif "listening port:" in line:
|
||
try:
|
||
current["listening_port"] = int(line.split(":")[-1].strip())
|
||
except Exception:
|
||
pass
|
||
elif "public key:" in line:
|
||
current["public_key"] = _redact_key(line.split(":", 1)[1].strip())
|
||
elif line.strip().startswith("peer:"):
|
||
current["peers"].append(
|
||
{
|
||
"public_key": _redact_key(line.split(":", 1)[1].strip()),
|
||
"endpoint": "",
|
||
"allowed_ips": "",
|
||
"latest_handshake": "",
|
||
"transfer": "",
|
||
}
|
||
)
|
||
elif current["peers"] and "endpoint:" in line:
|
||
current["peers"][-1]["endpoint"] = line.split(":", 1)[1].strip()
|
||
elif current["peers"] and "allowed ips:" in line:
|
||
current["peers"][-1]["allowed_ips"] = line.split(":", 1)[1].strip()
|
||
current["peers"][-1]["routes_default"] = any(
|
||
x.strip() in _DEFAULT_ROUTES for x in current["peers"][-1]["allowed_ips"].split(",")
|
||
)
|
||
elif current["peers"] and "latest handshake:" in line:
|
||
current["peers"][-1]["latest_handshake"] = line.split(":", 1)[1].strip()
|
||
elif current["peers"] and "transfer:" in line:
|
||
current["peers"][-1]["transfer"] = line.split(":", 1)[1].strip()
|
||
if current:
|
||
ifaces.append(current)
|
||
for item in ifaces:
|
||
item["systemd"] = _unit_state(f"wg-quick@{item['name']}.service")
|
||
# iface up counts as healthy even if systemd unit failed (common with manual wg)
|
||
item["link_up"] = True
|
||
return ifaces
|
||
|
||
|
||
def runtime_status() -> dict[str, Any]:
|
||
from . import shellcrash_hub
|
||
|
||
commands = {n: bool(shutil.which(n)) for n in ("wg", "wg-quick", "ip", "systemctl")}
|
||
show = _priv(["wg", "show"], timeout=5.0) if commands["wg"] else {"ok": False, "stdout": "", "stderr": "no wg"}
|
||
# wg show often needs root; try without if priv failed
|
||
if not show["ok"] and commands["wg"]:
|
||
show = _run(["wg", "show"], timeout=5.0)
|
||
interfaces = _parse_wg_show(show["stdout"]) if show.get("ok") or show.get("stdout") else []
|
||
if not interfaces and commands["ip"]:
|
||
# detect wg-* links
|
||
ip_out = _run(["ip", "-br", "link", "show", "type", "wireguard"], timeout=4.0)
|
||
for line in (ip_out.get("stdout") or "").splitlines():
|
||
name = line.split()[0].rstrip(":") if line.split() else ""
|
||
if name:
|
||
interfaces.append({"name": name, "peers": [], "link_up": True, "systemd": _unit_state(f"wg-quick@{name}.service")})
|
||
|
||
system_configs = list_system_configs()
|
||
repo_configs = list_imported_configs()
|
||
recommendations: list[str] = []
|
||
if not interfaces:
|
||
names = [c["name"] for c in system_configs + repo_configs]
|
||
if names:
|
||
recommendations.append(f"配置存在但接口未激活 — 启动 wg-quick@{names[0]}")
|
||
else:
|
||
recommendations.append("未检测到 WireGuard 接口;导入 conf 后 Apply(overlay)")
|
||
for iface in interfaces:
|
||
for peer in iface.get("peers") or []:
|
||
if peer.get("routes_default"):
|
||
recommendations.append(f"{iface.get('name')}: peer 含 0.0.0.0/0 — 建议 overlay 重导入,避免劫持 ShellCrash")
|
||
unit = (iface.get("systemd") or {}).get("active")
|
||
if unit == "failed" and iface.get("link_up"):
|
||
recommendations.append(f"{iface.get('name')}: 接口已 up 但 systemd 为 failed(可忽略或 systemctl reset-failed)")
|
||
|
||
preferred = next((i for i in interfaces if i.get("name") == PREFERRED_IFACE), interfaces[0] if interfaces else None)
|
||
active_names = {str(i.get("name") or "") for i in interfaces if i.get("name")}
|
||
for row in system_configs:
|
||
row["active"] = str(row.get("name") or "") in active_names
|
||
row["role"] = "current" if row.get("name") == (preferred or {}).get("name") else "system"
|
||
for row in repo_configs:
|
||
row["active"] = str(row.get("name") or "") in active_names
|
||
row["role"] = "import"
|
||
shell = shellcrash_hub.status()
|
||
return {
|
||
"ok": True,
|
||
"available": bool(commands.get("wg") and commands.get("wg-quick")),
|
||
"commands": commands,
|
||
"active": bool(interfaces),
|
||
"interfaces": interfaces,
|
||
"primary": preferred,
|
||
"active_config_name": str((preferred or {}).get("name") or PREFERRED_IFACE),
|
||
"unit_wg_dy": _unit_state(f"wg-quick@{PREFERRED_IFACE}.service").get("active"),
|
||
"system_configs": system_configs,
|
||
"repo_configs": repo_configs,
|
||
"shellcrash": shell,
|
||
"recommendations": recommendations,
|
||
"hint": "物理机 AllowedIPs 仅 VPN 网段(如 10.8.0.0/24);导入默认 overlay,勿写 0.0.0.0/0",
|
||
"last_checked_at": int(time.time()),
|
||
"wg_error": "" if (show.get("ok") or interfaces) else (show.get("stderr") or show.get("stdout") or ""),
|
||
}
|