3077404ebf
After the AmneziaVPN app held the routes, the running core kept Amnezia's utun as its way out; its own TUN reused the same utun name and sent everything into itself (no routes, no DNS). "tun on" now refuses while AmneziaVPN is open and restarts the core; the on/off choice is saved (tun.json) and used on the next start. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
335 lines
13 KiB
Python
335 lines
13 KiB
Python
#!/usr/bin/python3
|
|
"""BroV network core — narrow root helper (LaunchDaemon local.maksar.brov.netctl).
|
|
|
|
The core (mihomo) runs as root with its config, keys and API secret in
|
|
/Library/Application Support/BroV/netcore (root, 0700). BroV never sees those: it talks
|
|
to this helper over a Unix socket that only the installing user may open, and the helper
|
|
allows exactly these operations:
|
|
|
|
state groups, provider nodes with delays, hidden connections, TUN on/off
|
|
select {group, name} ai-out / amnezia / saga-sw / planet9-sw / home-sw, name must be a member
|
|
delay {group}|{proxy} speed test of exit / ai-out / amnezia, or of a client tunnel
|
|
tun {on} traffic capture on (fresh core start) / off; remembered
|
|
add_key {text} vpn:// Amnezia key: checked by gen.py, stored, provider reloaded
|
|
hide {name} take an Amnezia connection or a VLESS node out of the list and
|
|
out of "auto" (the key / subscription stay, nothing is deleted)
|
|
unhide {name} put it back
|
|
|
|
One JSON object per line in, one per line out. Nothing here can rewrite the core config
|
|
or point traffic elsewhere.
|
|
"""
|
|
import json
|
|
import os
|
|
import re
|
|
import socket
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
ROOT = "/Library/Application Support/BroV"
|
|
CORE = os.path.join(ROOT, "netcore")
|
|
KEYS = os.path.join(CORE, "keys")
|
|
SOCK = "/var/run/brov-netctl.sock"
|
|
API = "http://127.0.0.1:9097"
|
|
TEST_URL = "https://www.gstatic.com/generate_204"
|
|
|
|
SELECT_GROUPS = {"ai-out", "amnezia", "saga-sw", "planet9-sw", "home-sw"}
|
|
DELAY_GROUPS = {"exit", "ai-out", "auto", "amnezia"}
|
|
CLIENT_TUNNELS = {"saga", "planet9", "home"}
|
|
MAX_REQUEST = 64 * 1024
|
|
|
|
CORE_LABEL = "local.maksar.brov.netd"
|
|
HIDDEN = os.path.join(CORE, "hidden.json")
|
|
CONFIG = os.path.join(CORE, "config.yaml")
|
|
MIHOMO = os.path.join(ROOT, "mihomo")
|
|
|
|
ALLOWED_UID = int(sys.argv[1]) if len(sys.argv) > 1 else -1
|
|
gen_lock = threading.Lock()
|
|
|
|
|
|
def secret():
|
|
with open(os.path.join(CORE, "api.secret")) as f:
|
|
return f.read().strip()
|
|
|
|
|
|
def api(method, path, body=None, timeout=8):
|
|
data = json.dumps(body).encode() if body is not None else None
|
|
req = urllib.request.Request(API + path, method=method, data=data, headers={
|
|
"Authorization": "Bearer " + secret(), "Content-Type": "application/json"})
|
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
raw = r.read()
|
|
return json.loads(raw) if raw else {}
|
|
|
|
|
|
def q(name):
|
|
return urllib.parse.quote(name, safe="")
|
|
|
|
|
|
def gen(*args):
|
|
return subprocess.run(["/usr/bin/python3", os.path.join(CORE, "gen.py"), *args], cwd=CORE,
|
|
capture_output=True, text=True, timeout=60).stdout
|
|
|
|
|
|
# MARK: - Commands
|
|
|
|
def cmd_state(_):
|
|
proxies = api("GET", "/proxies").get("proxies", {})
|
|
keep = {}
|
|
for name, p in proxies.items():
|
|
keep[name] = {"now": p.get("now"), "all": p.get("all"), "history": (p.get("history") or [])[-1:]}
|
|
providers = {}
|
|
for prov in ("vless-cluster", "amnezia-keys"):
|
|
try:
|
|
lst = api("GET", "/providers/proxies/" + prov).get("proxies", [])
|
|
except Exception:
|
|
lst = []
|
|
providers[prov] = [{"name": x.get("name"), "history": (x.get("history") or [])[-1:]} for x in lst]
|
|
tun = api("GET", "/configs").get("tun", {}).get("enable", False)
|
|
return {"ok": True, "proxies": keep, "providers": providers, "tun": tun, "hidden": load_hidden()}
|
|
|
|
|
|
def cmd_select(r):
|
|
group, name = r.get("group"), r.get("name")
|
|
if group not in SELECT_GROUPS or not isinstance(name, str):
|
|
return {"ok": False, "error": "группа не разрешена"}
|
|
members = api("GET", "/proxies/" + q(group)).get("all", [])
|
|
if name not in members:
|
|
return {"ok": False, "error": "такого варианта нет в группе"}
|
|
api("PUT", "/proxies/" + q(group), {"name": name})
|
|
return {"ok": True}
|
|
|
|
|
|
def cmd_delay(r):
|
|
test = "url=" + q(TEST_URL) + "&timeout=5000"
|
|
if r.get("group") in DELAY_GROUPS:
|
|
return {"ok": True, "delays": api("GET", "/group/%s/delay?%s" % (q(r["group"]), test), timeout=10)}
|
|
if r.get("proxy") in CLIENT_TUNNELS:
|
|
try:
|
|
d = api("GET", "/proxies/%s/delay?%s" % (q(r["proxy"]), test), timeout=10).get("delay", 0)
|
|
except Exception:
|
|
d = 0
|
|
return {"ok": True, "delays": {r["proxy"]: d}}
|
|
return {"ok": False, "error": "замер не разрешён"}
|
|
|
|
|
|
def save_tun(on):
|
|
tmp = os.path.join(CORE, "tun.json.tmp")
|
|
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
|
with os.fdopen(fd, "w") as f:
|
|
json.dump({"on": on}, f)
|
|
os.rename(tmp, os.path.join(CORE, "tun.json"))
|
|
|
|
|
|
def cmd_tun(r):
|
|
"""On = a fresh core start. A core that has been running while the AmneziaVPN app held
|
|
the routes keeps treating Amnezia's utun as the way out; its own TUN often gets the same
|
|
utun name and then sends everything into itself (no routes, no DNS). A restart forgets
|
|
that. The state is saved so the core comes back the same way after a reboot."""
|
|
on = r.get("on")
|
|
if not isinstance(on, bool):
|
|
return {"ok": False, "error": "нужно on: true/false"}
|
|
if on and subprocess.run(["/usr/bin/pgrep", "-x", "AmneziaVPN"], capture_output=True).returncode == 0:
|
|
return {"ok": False, "error": "открыто приложение AmneziaVPN — закрой его (⌘Q), потом включай"}
|
|
with gen_lock:
|
|
save_tun(on)
|
|
gen()
|
|
if not on:
|
|
api("PATCH", "/configs", {"tun": {"enable": False}})
|
|
return {"ok": True}
|
|
subprocess.run(["/bin/launchctl", "kickstart", "-k", "system/" + CORE_LABEL], capture_output=True, timeout=20)
|
|
for _ in range(40):
|
|
time.sleep(0.25)
|
|
try:
|
|
if api("GET", "/configs", timeout=2).get("tun", {}).get("enable"):
|
|
return {"ok": True}
|
|
except Exception:
|
|
pass
|
|
return {"ok": False, "error": "ядро не поднялось после перезапуска"}
|
|
|
|
|
|
def provider_reload_and_test(proxy):
|
|
api("PUT", "/providers/proxies/amnezia-keys")
|
|
try:
|
|
hc = api("GET", "/providers/proxies/amnezia-keys/%s/healthcheck?url=%s&timeout=6000"
|
|
% (q(proxy), q(TEST_URL)), timeout=10)
|
|
return hc.get("delay", 0)
|
|
except Exception:
|
|
return 0
|
|
|
|
|
|
def cmd_add_key(r):
|
|
text = r.get("text")
|
|
if not isinstance(text, str) or not text.strip().startswith("vpn://") or len(text) > 20000:
|
|
return {"ok": False, "error": "ключ должен начинаться с vpn://"}
|
|
with gen_lock:
|
|
pending = os.path.join(KEYS, ".pending.vpnkey")
|
|
fd = os.open(pending, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
|
with os.fdopen(fd, "w") as f:
|
|
f.write(text.strip())
|
|
try:
|
|
check = json.loads(gen("--check", pending).strip().splitlines()[-1])
|
|
except Exception:
|
|
check = {"ok": False, "error": "не удалось разобрать ключ"}
|
|
if not check.get("ok"):
|
|
os.remove(pending)
|
|
return {"ok": False, "error": check.get("error", "ключ не подходит")}
|
|
slug = re.sub(r"[^a-z0-9]+", "-", str(check.get("name", "amnezia")).lower()).strip("-") or "amnezia"
|
|
dest, n = os.path.join(KEYS, slug + ".vpnkey"), 2
|
|
while os.path.exists(dest):
|
|
dest, n = os.path.join(KEYS, "%s-%d.vpnkey" % (slug, n)), n + 1
|
|
os.rename(pending, dest)
|
|
gen()
|
|
proxy = "AWG " + os.path.basename(dest)[:-len(".vpnkey")]
|
|
return {"ok": True, "name": check.get("name"), "server": "%s:%s" % (check.get("server"), check.get("port")),
|
|
"proxy": proxy, "delay": provider_reload_and_test(proxy)}
|
|
|
|
|
|
def load_hidden():
|
|
try:
|
|
with open(HIDDEN) as f:
|
|
h = json.load(f)
|
|
return {"amnezia": list(h.get("amnezia", [])), "vless": list(h.get("vless", []))}
|
|
except (OSError, ValueError, AttributeError):
|
|
return {"amnezia": [], "vless": []}
|
|
|
|
|
|
def save_hidden(h):
|
|
tmp = HIDDEN + ".tmp"
|
|
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
|
|
with os.fdopen(fd, "w") as f:
|
|
json.dump(h, f, ensure_ascii=False)
|
|
os.rename(tmp, HIDDEN)
|
|
|
|
|
|
def awg_key_exists(name):
|
|
m = re.fullmatch(r"AWG ([a-z0-9-]+)", name)
|
|
path = os.path.join(KEYS, m.group(1) + ".vpnkey") if m else ""
|
|
return bool(m) and os.path.isfile(path) and not os.path.islink(path)
|
|
|
|
|
|
def reload_core():
|
|
"""Full config reload (needed for the VLESS filter): drops open connections for a moment.
|
|
The new config is checked first; TUN comes from tun.json, i.e. as the user left it."""
|
|
check = subprocess.run([MIHOMO, "-t", "-d", CORE, "-f", CONFIG], capture_output=True, text=True, timeout=30)
|
|
if check.returncode != 0:
|
|
raise RuntimeError("ядро не приняло новый конфиг")
|
|
api("PUT", "/configs?force=true", {"path": CONFIG}, timeout=20)
|
|
|
|
|
|
def change_hidden(name, hide):
|
|
if not isinstance(name, str) or not name or len(name) > 200 or "\n" in name:
|
|
return {"ok": False, "error": "неверное имя подключения"}
|
|
with gen_lock:
|
|
h = load_hidden()
|
|
if name.startswith("AWG "):
|
|
if not awg_key_exists(name):
|
|
return {"ok": False, "error": "такого подключения нет"}
|
|
kind = "amnezia"
|
|
else:
|
|
vless = [x.get("name") for x in api("GET", "/providers/proxies/vless-cluster").get("proxies", [])]
|
|
if hide and name not in vless:
|
|
return {"ok": False, "error": "такого узла нет"}
|
|
if not hide and name not in h["vless"]:
|
|
return {"ok": False, "error": "этот узел не скрыт"}
|
|
kind = "vless"
|
|
if hide:
|
|
# Leave the connection before it disappears.
|
|
if kind == "amnezia" and api("GET", "/proxies/amnezia").get("now") == name:
|
|
api("PUT", "/proxies/amnezia", {"name": "amnezia-auto"})
|
|
if kind == "vless" and api("GET", "/proxies/ai-out").get("now") == name:
|
|
api("PUT", "/proxies/ai-out", {"name": "auto"})
|
|
if name not in h[kind]:
|
|
h[kind].append(name)
|
|
else:
|
|
h[kind] = [x for x in h[kind] if x != name]
|
|
before = load_hidden()
|
|
save_hidden(h)
|
|
gen()
|
|
if kind == "amnezia":
|
|
api("PUT", "/providers/proxies/amnezia-keys")
|
|
else:
|
|
try:
|
|
reload_core()
|
|
except Exception:
|
|
save_hidden(before) # keep disk and core in step
|
|
gen()
|
|
raise
|
|
return {"ok": True, "reloaded": kind == "vless"}
|
|
|
|
|
|
def cmd_hide(r):
|
|
return change_hidden(r.get("name"), True)
|
|
|
|
|
|
def cmd_unhide(r):
|
|
return change_hidden(r.get("name"), False)
|
|
|
|
|
|
COMMANDS = {"state": cmd_state, "select": cmd_select, "delay": cmd_delay, "tun": cmd_tun,
|
|
"add_key": cmd_add_key, "hide": cmd_hide, "unhide": cmd_unhide}
|
|
|
|
|
|
# MARK: - Socket server
|
|
|
|
def peer_uid(conn):
|
|
# LOCAL_PEERCRED (SOL_LOCAL=0, opt=1) → struct xucred { u_int cr_version; uid_t cr_uid; … }
|
|
cred = conn.getsockopt(0, 1, 76)
|
|
return struct.unpack_from("I", cred, 4)[0]
|
|
|
|
|
|
def handle(conn):
|
|
try:
|
|
if peer_uid(conn) not in (0, ALLOWED_UID):
|
|
return
|
|
conn.settimeout(30)
|
|
buf = b""
|
|
while b"\n" not in buf and len(buf) < MAX_REQUEST:
|
|
chunk = conn.recv(8192)
|
|
if not chunk:
|
|
break
|
|
buf += chunk
|
|
req = json.loads(buf.split(b"\n", 1)[0] or b"{}")
|
|
fn = COMMANDS.get(req.get("cmd"))
|
|
if fn is None:
|
|
resp = {"ok": False, "error": "неизвестная команда"}
|
|
else:
|
|
try:
|
|
resp = fn(req)
|
|
except urllib.error.URLError:
|
|
resp = {"ok": False, "error": "ядро не отвечает"}
|
|
except Exception as e:
|
|
resp = {"ok": False, "error": str(e) or e.__class__.__name__}
|
|
conn.sendall((json.dumps(resp, ensure_ascii=False) + "\n").encode())
|
|
except Exception:
|
|
pass
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def main():
|
|
if ALLOWED_UID < 0:
|
|
sys.exit("usage: netctl.py <uid allowed to connect>")
|
|
try:
|
|
os.unlink(SOCK)
|
|
except FileNotFoundError:
|
|
pass
|
|
srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
old = os.umask(0o177)
|
|
srv.bind(SOCK)
|
|
os.umask(old)
|
|
os.chown(SOCK, ALLOWED_UID, -1)
|
|
os.chmod(SOCK, 0o600)
|
|
srv.listen(8)
|
|
while True:
|
|
conn, _ = srv.accept()
|
|
threading.Thread(target=handle, args=(conn,), daemon=True).start()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|