diff --git a/scripts/netcore/diag.sh b/scripts/netcore/diag.sh new file mode 100644 index 0000000..2d720c9 --- /dev/null +++ b/scripts/netcore/diag.sh @@ -0,0 +1,94 @@ +#!/bin/sh +# BroV network core — TUN diagnosis, about a minute without internet (run by hand): +# sudo sh scripts/netcore/diag.sh +# +# A: the core with traffic capture on and a debug log, as is. +# B: the same with the AmneziaVPN background service stopped (it stays up after the app +# is closed and may own the routes / pf rules) — put back afterwards. +# Then the core service comes back as it was (capture off). The report goes to +# /tmp/brov-diag.txt (owner: you, 0600); the subscription URL is cut out of the logs. + +set -u +[ "$(id -u)" -eq 0 ] || { echo "Запусти через sudo: sudo sh $0"; exit 1; } +USER_NAME="${SUDO_USER:?запусти через sudo из своей учётной записи}" +if pgrep -qx AmneziaVPN; then echo "Закрой приложение AmneziaVPN (⌘Q) и запусти снова."; exit 1; fi + +ROOT="/Library/Application Support/BroV" +CORE="$ROOT/netcore" +BIN="$ROOT/mihomo" +LABEL="local.maksar.brov.netd" +AMZ_PLIST="/Library/LaunchDaemons/AmneziaVPN.plist" +OUT=/tmp/brov-diag.txt +T=$(mktemp -d) +: > "$OUT"; chmod 600 "$OUT"; chown "$USER_NAME" "$OUT" + +sec() { echo "→ $1"; printf '\n########## %s\n' "$1" >> "$OUT"; } +run() { printf '\n$ %s\n' "$*" >> "$OUT"; "$@" >> "$OUT" 2>&1; } +redact() { sed -E 's#https?://[^" ]*/sub/[^" ]*##g'; } + +snapshot() { + run netstat -rn -f inet + run sh -c 'ifconfig | grep -A2 "^utun"' + run route -n get 1.1.1.1 + run route -n get 198.18.0.2 + run sh -c 'scutil --dns | grep -E "resolver|nameserver|if_index" | head -20' + run sh -c 'curl -s -m 6 -o /dev/null -w "google %{http_code} %{time_total}s\n" https://www.google.com' + run sh -c 'curl -s -m 6 -o /dev/null -w "ya.ru %{http_code} %{time_total}s\n" https://ya.ru' + run sh -c 'curl -s -m 6 -o /dev/null -w "1.1.1.1 by IP %{http_code} %{time_total}s\n" https://1.1.1.1' + run sh -c 'dig +time=2 +tries=1 example.com +short | head -2' +} + +core_test() { # $1 = A|B + "$BIN" -d "$CORE" -f "$T/diag.yaml" > "$T/$1.log" 2>&1 & + pid=$! + sleep 7 + snapshot + kill "$pid" 2>/dev/null; sleep 2; kill -9 "$pid" 2>/dev/null + printf '\n--- core log %s (TUN, routes, errors) ---\n' "$1" >> "$OUT" + grep -iE "tun|route|interface|listen|error|warn|fatal|hijack|stack" "$T/$1.log" \ + | grep -v "Health Checked" | redact | head -120 >> "$OUT" +} + +sec "Система" +run sw_vers +run "$BIN" -v +run sh -c "pgrep -lf AmneziaVPN-service" +run sh -c "pfctl -s info 2>&1 | head -3" +run sh -c "pfctl -s Anchors 2>&1" +run sh -c "pfctl -s rules 2>&1 | head -40" + +sec "До теста (ядро без перехвата)" +snapshot + +# Test config: the real one with capture on and a debug log. +/usr/bin/python3 - "$CORE/config.yaml" "$T/diag.yaml" <<'EOF' +import sys +s = open(sys.argv[1]).read() +s = s.replace("tun:\n enable: false", "tun:\n enable: true") +s = s.replace('log-level: "error"', 'log-level: "debug"') +open(sys.argv[2], "w").write(s) +EOF +chmod 600 "$T/diag.yaml" + +launchctl bootout "system/$LABEL" 2>/dev/null +sleep 1 + +sec "A: ядро с перехватом" +core_test A + +if [ -f "$AMZ_PLIST" ]; then + sec "B: то же, служба AmneziaVPN остановлена" + launchctl bootout system "$AMZ_PLIST" 2>/dev/null + sleep 2 + run sh -c "pfctl -s Anchors 2>&1" + run sh -c "pfctl -s rules 2>&1 | head -40" + core_test B + launchctl bootstrap system "$AMZ_PLIST" 2>/dev/null +fi + +sec "Возвращаю ядро как было" +launchctl bootstrap system "/Library/LaunchDaemons/$LABEL.plist" 2>/dev/null || launchctl kickstart -k "system/$LABEL" +sleep 3 +snapshot +rm -rf "$T" +echo "Готово. Отчёт: $OUT — напиши в чат, я его прочитаю." diff --git a/scripts/netcore/netctl.py b/scripts/netcore/netctl.py index fe83be2..471152b 100644 --- a/scripts/netcore/netctl.py +++ b/scripts/netcore/netctl.py @@ -117,6 +117,66 @@ def cmd_delay(r): return {"ok": False, "error": "замер не разрешён"} +# MARK: - System DNS +# +# With capture on, the Mac's DNS must go into the core (198.18.0.2 sits inside the TUN and +# is hijacked). A DNS server in the local network — e.g. the home router — is reached +# around the TUN, and when it doesn't answer nothing resolves. The previous servers are +# saved and put back when capture goes off. + +CORE_DNS = "198.18.0.2" +DNS_BACKUP = os.path.join(CORE, "dns-backup.json") + + +def network_services(): + out = subprocess.run(["/usr/sbin/networksetup", "-listallnetworkservices"], + capture_output=True, text=True, timeout=10).stdout.splitlines() + return [l for l in out[1:] if l and not l.startswith("*")] + + +def dns_of(service): + out = subprocess.run(["/usr/sbin/networksetup", "-getdnsservers", service], + capture_output=True, text=True, timeout=10).stdout.splitlines() + ip = r"\d{1,3}(\.\d{1,3}){3}|[0-9a-fA-F]*:[0-9a-fA-F:]+" + return [x.strip() for x in out if re.fullmatch(ip, x.strip())] + + +def set_dns(service, servers): + subprocess.run(["/usr/sbin/networksetup", "-setdnsservers", service] + (servers or ["Empty"]), + capture_output=True, timeout=10) + + +def dns_to_core(): + try: + with open(DNS_BACKUP) as f: + backup = json.load(f) + except (OSError, ValueError): + backup = {} + for svc in network_services(): + cur = dns_of(svc) + if cur != [CORE_DNS]: + backup[svc] = cur + set_dns(svc, [CORE_DNS]) + fd = os.open(DNS_BACKUP, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, "w") as f: + json.dump(backup, f) + + +def dns_restore(): + try: + with open(DNS_BACKUP) as f: + backup = json.load(f) + except (OSError, ValueError): + backup = {} + for svc in network_services(): + if dns_of(svc) == [CORE_DNS]: + set_dns(svc, [x for x in backup.get(svc, []) if x != CORE_DNS]) + try: + os.remove(DNS_BACKUP) + except OSError: + pass + + 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) @@ -139,6 +199,7 @@ def cmd_tun(r): save_tun(on) gen() if not on: + dns_restore() api("PATCH", "/configs", {"tun": {"enable": False}}) return {"ok": True} subprocess.run(["/bin/launchctl", "kickstart", "-k", "system/" + CORE_LABEL], capture_output=True, timeout=20) @@ -146,6 +207,7 @@ def cmd_tun(r): time.sleep(0.25) try: if api("GET", "/configs", timeout=2).get("tun", {}).get("enable"): + dns_to_core() return {"ok": True} except Exception: pass @@ -311,9 +373,24 @@ def handle(conn): conn.close() +def sync_dns_at_start(): + """At boot the core starts with capture as the user left it: DNS follows.""" + on = True + try: + with open(os.path.join(CORE, "tun.json")) as f: + on = bool(json.load(f).get("on", True)) + except (OSError, ValueError, AttributeError): + pass + try: + dns_to_core() if on else dns_restore() + except Exception: + pass + + def main(): if ALLOWED_UID < 0: sys.exit("usage: netctl.py ") + threading.Thread(target=sync_dns_at_start, daemon=True).start() try: os.unlink(SOCK) except FileNotFoundError: diff --git a/scripts/netcore/uninstall.sh b/scripts/netcore/uninstall.sh index cc2f977..c48a505 100644 --- a/scripts/netcore/uninstall.sh +++ b/scripts/netcore/uninstall.sh @@ -4,6 +4,10 @@ # After this the Mac goes online by itself; turn AmneziaVPN back on if needed. set -e [ "$(id -u)" -eq 0 ] || { echo "Запусти через sudo: sudo sh $0"; exit 1; } +# DNS pointed into the core goes back to automatic. +networksetup -listallnetworkservices | tail -n +2 | grep -v '^\*' | while read -r svc; do + [ "$(networksetup -getdnsservers "$svc")" = "198.18.0.2" ] && networksetup -setdnsservers "$svc" Empty +done for label in local.maksar.brov.netctl local.maksar.brov.netd; do launchctl bootout "system/$label" 2>/dev/null || true rm -f "/Library/LaunchDaemons/$label.plist"