fix: hardening

This commit is contained in:
FUFSoB committed 2026-10-05 22:44:09 +05:00
1 parent 017a947a18
commit a435942b4f
168 files changed
+9166 -1644

No files matched your search

+34 -29
View File
@@ -8,6 +8,13 @@
# (modules/proxy-suite/service/control.nix); proxy_ctl.py reads every name with env().
env,
guiRefreshInterval ? 3,
# Off where proxy-suitectl runs the units (nix-on-droid): proxy-ctl reaches it through
# SUPERVISOR_CTL, and systemd stays out of the closure.
withSystemd ? true,
# `proxy-ctl logs` follows in less without it.
withLnav ? true,
# Probes go through plain curl without it.
withCurlImpersonate ? true,
# These four are also passed as derivations: the checks read the files' contents through
# passthru.proxySuiteCheck, which toString in env would lose.
subscriptionTagsFile,
@@ -22,6 +29,17 @@ let
"#!${pkgs.python3}/bin/python3\n" + builtins.readFile ./proxy-ctl/proxy_ctl.py
);
wrapperEnv = env;
# Probes present a browser's TLS fingerprint: bot protection refuses plain
# curl. The newest Chrome profile the package ships, since the set varies by
# version; the build fails if there is none.
findProbeCurl = lib.optionalString withCurlImpersonate ''
probe_curl=$(ls ${pkgs.curl-impersonate}/bin/curl_chrome[0-9]* | grep -E '/curl_chrome[0-9]+$' | sort -V | tail -n 1)
[ -x "$probe_curl" ]
'';
# Unset, proxy_ctl.py probes with the curl on PATH.
probeCurlFlag = lib.optionalString withCurlImpersonate (
''--set PROBE_CURL "$probe_curl" \'' + "\n "
);
envFlags = lib.concatStringsSep " " (
lib.mapAttrsToList (name: value: "--set ${name} ${lib.escapeShellArg value}") wrapperEnv
);
@@ -47,12 +65,7 @@ let
# /run/wrappers/bin first: the store's sudo, earlier on a PATH, refuses to run without setuid.
wrapProgram "$out/bin/proxy-tui" \
--prefix PYTHONPATH : ${pythonModules} \
--prefix PATH : "${
lib.makeBinPath [
proxyCtl
pkgs.systemd
]
}" \
--prefix PATH : "${lib.makeBinPath ([ proxyCtl ] ++ lib.optional withSystemd pkgs.systemd)}" \
--prefix PATH : /run/wrappers/bin ${envFlags}
'';
};
@@ -133,11 +146,7 @@ let
"''${gappsWrapperArgs[@]}" \
--prefix PYTHONPATH : "${pythonModules}:$out/lib/proxy-suite-gui" \
--prefix PATH : "${
lib.makeBinPath [
proxyCtl
pkgs.systemd
pkgs.qrencode
]
lib.makeBinPath ([ proxyCtl ] ++ lib.optional withSystemd pkgs.systemd ++ [ pkgs.qrencode ])
}" \
--prefix PATH : /run/wrappers/bin \
--set PROXY_GUI_ICON_DIR "$out/share/proxy-suite-gui/icons" \
@@ -164,32 +173,28 @@ let
;
script = unwrapped.drvAttrs.text;
};
# Probes present a browser's TLS fingerprint: bot protection refuses plain
# curl. The newest Chrome profile the package ships, since the set varies by
# version; the build fails if there is none.
postBuild = ''
install -Dm644 ${./proxy-ctl/completions/proxy-ctl.bash} \
"$out/share/bash-completion/completions/proxy-ctl"
install -Dm644 ${./proxy-ctl/completions/_proxy-ctl} "$out/share/zsh/site-functions/_proxy-ctl"
install -Dm644 ${./proxy-ctl/completions/proxy-ctl.fish} \
"$out/share/fish/vendor_completions.d/proxy-ctl.fish"
probe_curl=$(ls ${pkgs.curl-impersonate}/bin/curl_chrome[0-9]* | grep -E '/curl_chrome[0-9]+$' | sort -V | tail -n 1)
[ -x "$probe_curl" ]
wrapProgram "$out/bin/proxy-ctl" \
--set PROBE_CURL "$probe_curl" \
--set PROXY_CTL_MODULES ${pythonModules} \
${findProbeCurl}wrapProgram "$out/bin/proxy-ctl" \
${probeCurlFlag}--set PROXY_CTL_MODULES ${pythonModules} \
--prefix PATH : "${
lib.makeBinPath [
lib.makeBinPath (
# curl-impersonate's curl_chrome* wrappers are `#!/usr/bin/env bash`.
pkgs.bash
pkgs.curl
pkgs.fzf
# `proxy-ctl logs` follows in lnav.
pkgs.lnav
pkgs.proxychains-ng
pkgs.qrencode
pkgs.systemd
]
lib.optional withCurlImpersonate pkgs.bash
++ [
pkgs.curl
pkgs.fzf
# `proxy-ctl logs` follows in lnav, or in less without it.
(if withLnav then pkgs.lnav else pkgs.less)
pkgs.proxychains-ng
pkgs.qrencode
]
++ lib.optional withSystemd pkgs.systemd
)
}" ${envFlags}
'';
};
+8 -3
View File
@@ -1,8 +1,13 @@
# proxy-ctl knows its own verbs, tags, profiles and units: ask it.
# It answers word<TAB>description; bash has no room for the description.
# Not `compgen -W`: it expands its words, and a tag or list entry is whatever a member of
# the userControl groups named a file.
_proxy_ctl() {
mapfile -t COMPREPLY < <(
compgen -W "$(proxy-ctl __complete "${COMP_WORDS[@]:1:COMP_CWORD-1}" 2>/dev/null | cut -f1)" \
-- "${COMP_WORDS[COMP_CWORD]}")
local cur=${COMP_WORDS[COMP_CWORD]} word
COMPREPLY=()
while IFS= read -r word; do
word=${word%%$'\t'*}
[[ $word == "$cur"* ]] && COMPREPLY+=("$word")
done < <(proxy-ctl __complete "${COMP_WORDS[@]:1:COMP_CWORD-1}" 2>/dev/null)
}
complete -F _proxy_ctl proxy-ctl
File diff suppressed because it is too large. Load diff
+79 -30
View File
@@ -6,11 +6,11 @@ Reads run on a worker thread; every change runs proxy-ctl, as in the TUI.
import os
import re
import shlex
import signal
import subprocess
import sys
import threading
import time
import gi
@@ -226,6 +226,10 @@ def plain(line):
return "".join(t for t, _ in ansi_segments(line))
# Failed state reads in a row before the tray says "Status unavailable" (one every 3 s).
STALE_READS_UNKNOWN = 3
def last_line(lines):
return next((plain(line).strip() for line in reversed(lines) if plain(line).strip()), "")
@@ -414,7 +418,7 @@ class Page(Gtk.Box):
("w", lambda *_: self.win.where()),
("<Shift>l", lambda *_: self.win.follow_logs()),
("o", lambda *_: self.win.show_last_output()),
("r", lambda *_: self.win.app.reload()),
("r", lambda *_: self.win.app.reload(fresh_root=True)),
("Menu|<Shift>F10", lambda *_: self.open_menu(None)),
):
if trigger not in self.triggers():
@@ -776,7 +780,7 @@ class Window(Adw.ApplicationWindow):
switcher = Adw.ViewSwitcher(stack=self.stack, policy=Adw.ViewSwitcherPolicy.WIDE)
header.set_title_widget(switcher)
refresh = Gtk.Button(icon_name="view-refresh-symbolic", tooltip_text="Refresh now (F5)")
refresh.connect("clicked", lambda *_: app.reload())
refresh.connect("clicked", lambda *_: app.reload(fresh_root=True))
# A slow load shows a spinner in the refresh button's place.
self.refresh_stack = Gtk.Stack(transition_type=Gtk.StackTransitionType.CROSSFADE)
self.refresh_stack.add_named(refresh, "idle")
@@ -955,7 +959,7 @@ class Window(Adw.ApplicationWindow):
return True
def paste(self):
"""Ctrl+V anywhere but a text field: whatever is in the clipboard is added to this tab."""
"""Ctrl+V anywhere but a text field: whatever is in the clipboard is added to this tab, once confirmed."""
if isinstance(self.get_focus(), Gtk.Editable) or self.get_visible_dialog() is not None:
return False
page = self.page()
@@ -973,7 +977,9 @@ class Window(Adw.ApplicationWindow):
if argv is None:
self.toast(what)
else:
self.app.run_argv("run", argv, self, stdin=stdin)
# Asked first: a web page can put a link in the clipboard, and one stray Ctrl+V
# would have root fetch its subscription.
self.app.confirm(argv, lambda: self.app.run_argv("run", argv, self, stdin=stdin), self, stdin=stdin)
def follow_logs(self):
self.app.run_argv("suspend", ["logs"], self)
@@ -1111,6 +1117,11 @@ class ProxySuiteGui(Adw.Application):
self.viewing = {}
self.seen = {}
self.root_read_refused = False # pkexec for a tab read was dismissed: not asked again until Ctrl+E flips
# tab id -> (rows, summary, when) of its last root read: pkexec asks for the password each
# time, so not on every refresh; again on F5, Ctrl+E, or after a root action.
self.root_reads = {}
self.pending_fresh = False
self.stale_reads = 0 # empty state reads in a row, after one that worked
self.timer = None
def do_startup(self):
@@ -1122,7 +1133,7 @@ class ProxySuiteGui(Adw.Application):
css.load_from_string(CSS)
# Above a user gtk.css theme: these rules are only for this window's own classes.
Gtk.StyleContext.add_provider_for_display(display, css, Gtk.STYLE_PROVIDER_PRIORITY_USER + 1)
for name, callback in (("quit", lambda *_: self.quit()), ("reload", lambda *_: self.reload()), ("present", lambda *_: self.present())):
for name, callback in (("quit", lambda *_: self.quit()), ("reload", lambda *_: self.reload(fresh_root=True)), ("present", lambda *_: self.present())):
action = Gio.SimpleAction.new(name, None)
action.connect("activate", callback)
self.add_action(action)
@@ -1174,9 +1185,10 @@ class ProxySuiteGui(Adw.Application):
def on_elevated(self, action, value):
action.set_state(value)
self.root_read_refused = False
self.root_reads.clear()
if self.window:
self.window.root_badge.set_visible(value.get_boolean())
self.reload() # tabs only root can read
self.reload(fresh_root=True) # tabs only root can read
def present(self, tab=None):
if self.window is None:
@@ -1214,9 +1226,11 @@ class ProxySuiteGui(Adw.Application):
self.reload()
return True
def reload(self):
def reload(self, fresh_root=False):
"""fresh_root: read a root-only tab as root again (F5, Ctrl+E), not from the last read."""
if self.loading:
self.pending = True # one more once this load lands
self.pending_fresh = self.pending_fresh or fresh_root
return
self.loading = True
self.generation += 1
@@ -1224,9 +1238,19 @@ class ProxySuiteGui(Adw.Application):
if window:
window.set_busy(True)
tab = window.pages[window.stack.get_visible_child_name()].tab if window and window.stack.get_visible_child_name() else None
threading.Thread(target=self.load, args=(self.generation, tab, self.elevated(), dict(self.seen)), daemon=True).start()
threading.Thread(target=self.load, args=(self.generation, tab, self.elevated(), dict(self.seen), fresh_root), daemon=True).start()
def load(self, generation, tab, elevated, seen):
def load(self, generation, tab, elevated, seen, fresh_root=False):
# landed() always runs: it is what clears self.loading, else no reload would start again.
result = None
try:
result = self.gather(tab, elevated, seen, fresh_root)
except (Exception, SystemExit) as e:
print(f"proxy-suite-gui: load failed: {e!r}", file=sys.stderr)
finally:
GLib.idle_add(self.landed, generation, result)
def gather(self, tab, elevated, seen, fresh_root=False):
model.new_load()
states = model._read_states()
marks = model._safe(model.failure_marks, states, fallback={})
@@ -1238,11 +1262,12 @@ class ProxySuiteGui(Adw.Application):
if tab is not None:
result["visible"] = model.available_tabs(states)
result["status"] = model._safe(model.status_items, states, fallback=[("", "Status unavailable", "bad")])
result["tab"] = (tab.id, *self.load_tab(tab, states, elevated))
GLib.idle_add(self.landed, generation, result)
result["tab"] = (tab.id, *self.load_tab(tab, states, elevated, fresh_root))
return result
def load_tab(self, tab, states, elevated):
"""The tab as this user reads it; what only root can read, through pkexec when actions run as root."""
def load_tab(self, tab, states, elevated, fresh_root=False):
"""The tab as this user reads it; what only root can read, through pkexec when actions run as root:
once, and again on fresh_root."""
rows, summary = model.load_tab(tab, states)
if not model.needs_root(summary.splitlines(), 1):
return rows, summary
@@ -1250,20 +1275,32 @@ class ProxySuiteGui(Adw.Application):
return rows, summary + "\nCtrl+E: read and run as root"
if self.root_read_refused:
return rows, summary + "\nRoot read cancelled: Ctrl+E twice to ask again."
cached = self.root_reads.get(tab.id)
if cached and not fresh_root:
root_rows, why, when = cached
return root_rows, why + f"\nRead as root at {time.strftime('%H:%M:%S', time.localtime(when))}: F5 to read again."
root_rows, why = model.load_tab_as_root(tab, "pkexec")
if root_rows is None:
# ponytail: one refusal stops the asking, else the password dialog is back every refresh
self.root_read_refused = why == "authentication cancelled"
return rows, summary + f"\nAs root: {why}"
self.root_reads[tab.id] = (root_rows, why, time.time())
return root_rows, why
def landed(self, generation, result):
self.loading = False
if self.window:
self.window.set_busy(False)
if generation == self.generation:
# None: the load failed; what is shown stays.
if generation == self.generation and result is not None:
# Nothing read, after a read that worked: keep the last good one, tray and all.
stale = not result["states"] and bool(self.states)
self.stale_reads = self.stale_reads + 1 if stale else 0
if stale and self.stale_reads >= STALE_READS_UNKNOWN and self.tray:
# One failed read is a blip; this many is no state to show at all: the last
# good one may say "tunnel" while nothing runs any more.
tree, overall, _ = result["tray"]
self.tray.update(model.icon_name(overall), overall["label"], tree, attention=True)
if not stale:
self.states = result["states"]
marks = result["marks"]
@@ -1282,8 +1319,8 @@ class ProxySuiteGui(Adw.Application):
if "tab" in result and self.window:
self.window.fill(self.states, result["visible"], result["status"], *result["tab"], stale=stale)
if self.pending:
self.pending = False
self.reload()
fresh, self.pending, self.pending_fresh = self.pending_fresh, False, False
self.reload(fresh_root=fresh)
return False
def notify_failures(self, snap):
@@ -1315,8 +1352,8 @@ class ProxySuiteGui(Adw.Application):
else:
run()
def confirm(self, argv, then, parent):
body = f"<tt>{GLib.markup_escape_text(f'proxy-ctl {shlex.join(argv)}')}</tt>"
def confirm(self, argv, then, parent, stdin=None):
body = f"<tt>{GLib.markup_escape_text(model.shown(argv, stdin=stdin))}</tt>"
dialog = Adw.AlertDialog(heading="Run this?", body=body, body_use_markup=True, close_response="cancel", default_response="run")
dialog.add_response("cancel", "Cancel")
dialog.add_response("run", "Run")
@@ -1328,8 +1365,10 @@ class ProxySuiteGui(Adw.Application):
"""run: a toast; dialog, suspend, pause: output streamed into a dialog; copy: the last line to the clipboard.
root, or the elevated toggle: through pkexec. Never `apps run`, which is per user.
stdin: text proxy-ctl reads (argv says "-"), kept out of argv and pkexec's log."""
root = (root or self.elevated()) and argv[:1] != ["apps"]
command = f"{'pkexec ' if root else ''}proxy-ctl {shlex.join(argv)}"
# "wrap" is proxy-ctl's alias of `apps run`: never as root either. `apps add`/`rm` may be.
root = (root or self.elevated()) and argv[:2] != ["apps", "run"] and argv[:1] != ["wrap"]
# Only ever shown (toast, dialog title, notification): credentials blanked.
command = model.shown(argv, "pkexec" if root else None)
retry_argv = argv
qr = "--qr" in argv
if qr:
@@ -1348,19 +1387,24 @@ class ProxySuiteGui(Adw.Application):
p = model.popen(argv, "pkexec" if root else None, stdin=stdin)
if dialog:
GLib.idle_add(lambda: dialog.running(p, stoppable=not root) and False)
for line in p.stdout:
out.append(line.rstrip("\n"))
for line in model.output_lines(p):
out.append(line)
if dialog:
GLib.idle_add(lambda line=out[-1]: dialog.write(line) and False)
status = p.wait()
if getattr(p, "proxy_suite_stopped", False):
# Root's may outlive its closed pipe a while: reaped whenever it goes.
threading.Thread(target=p.wait, daemon=True).start()
status = -signal.SIGTERM
else:
status = p.wait()
except OSError as e:
out.append(f"cannot run proxy-ctl: {e}")
status = 127
if root and status == 126 and not out:
out.append("authentication cancelled") # pkexec: the password dialog was dismissed
GLib.idle_add(lambda: self.ran(command, mode, win, dialog, qr, out, status, retry_argv, stdin) and False)
GLib.idle_add(lambda: self.ran(command, mode, win, dialog, qr, out, status, retry_argv, stdin, root) and False)
def ran(self, command, mode, win, dialog, qr, out, status, retry_argv, stdin=None):
def ran(self, command, mode, win, dialog, qr, out, status, retry_argv, stdin=None, root=False):
last = last_line(out)
text = "\n".join(out)
output = (command, text)
@@ -1375,22 +1419,27 @@ class ProxySuiteGui(Adw.Application):
elif status:
dialog.write(f"\x1b[31m(exit status {status})\x1b[0m")
elif qr and last:
dialog.show_qr(last)
# A --config is the whole multi-line .conf, not its last line.
dialog.show_qr("\n".join(plain(line) for line in out).strip("\n") if "--config" in retry_argv else last)
elif win is not None:
# A toast is on screen for anyone to see: the link copied, or one in an error, blanked.
if mode == "copy" and not status and last:
win.copy_text(last, f"Copied: {last}")
win.copy_text(last, f"Copied: {model.redact(last)}")
else:
message = f"{last} ({command})" if last else command
message = f"{model.redact(last)} ({command})" if last else command
# Anything it printed is worth a button: the toast shows a few lines of it at most.
win.toast(f"exit {status}: {message}" if status else message, output if out else None, retry)
elif status:
# From the tray: nothing else would say it failed.
note = Gio.Notification.new(f"{command} failed")
note.set_body(last or f"exit status {status}")
note.set_body(model.redact(last) if last else f"exit status {status}")
note.set_default_action("app.present")
if retry:
note.add_button_with_target("Retry as Root", "app.retry-root", GLib.Variant("as", retry_argv))
self.send_notification(None, note)
if root and not status:
# What root just changed: the last root reads no longer show it.
self.root_reads.clear()
self.reload()
+139 -20
View File
@@ -5,15 +5,18 @@ validation, permission errors and systemd triggers stay in one place, and its
die() cannot take a front end down.
"""
import base64
import json
import os
import re
import select
import shlex
import shutil
import signal
import subprocess
import sys
import time
import zlib
from dataclasses import dataclass, field
from typing import Callable
@@ -367,10 +370,8 @@ def subscription_rows(_):
rows = []
for source, tags in (("static", ctl._sub_tags()), ("runtime", ctl._runtime_tags("subscription"))):
for t in tags:
cache = ctl._subscription_cache(t)
cached = os.path.isfile(cache)
count = ctl._subscription_proxy_count_text(cache) if cached else "-"
updated = ctl._ago(int(os.path.getmtime(cache)), int(time.time())) + " ago" if cached else "-"
mtime, count = ctl._subscription_state(t) or (None, "-")
updated = ctl._ago(int(mtime), int(time.time())) + " ago" if mtime else "-"
rows.append({"key": t, "tag": t, "proxies": count, "updated": updated, "source": source})
# Nothing visible and the runtime entries out of reach: an error, not an empty tab.
if not rows and (hidden := ctl._runtime_hidden("subscription")):
@@ -621,20 +622,29 @@ def _sub_url(row, user="user"):
return bool(row[user]) and bool(ctl.env("INBOUNDS_SUB_BASE_URL"))
def _add_args(text):
"""[tag] <url>, or JSON with spaces in it, as `proxy-ctl ... add` takes them.
An AmneziaWG config becomes "-": _add_stdin hands it over on stdin."""
def _add_source(text):
"""[tag] <url, JSON or config> as typed: (tag or None, the rest)."""
text = text.strip()
if text.startswith("{"):
return [text]
name, source = _awg_add(text)
if ctl._awg_source(source):
return [*([name] if name else []), "-"]
return text.split(None, 1)
return (None, text) if text.startswith("{") else _awg_add(text)
def _secret(source):
# A link's userinfo and query, a JSON outbound, a config: credentials, all of them.
return "://" in source or source.startswith("{") or ctl._awg_source(source)
def _add_args(text):
"""[tag] <source> as `proxy-ctl ... add` takes them. A link, JSON or AmneziaWG config
becomes "-": _add_stdin hands it over on stdin, out of ps and pkexec's or sudo's log."""
name, source = _add_source(text)
if not source:
return [] # proxy-ctl says what it wants
return [*([name] if name else []), "-" if _secret(source) else source]
def _add_stdin(text):
return _awg_add_stdin(text)
_, source = _add_source(text)
return source if source and _secret(source) else None
def _zapret_auto():
@@ -689,7 +699,9 @@ TABS = [
Action(
"j",
"set the call it joins…",
lambda r, t, _: ["wl", "join", _wl_entry(r)["name"], t.strip()],
# On stdin: the call link is what lets anyone into the call.
lambda r, t, _: ["wl", "join", _wl_entry(r)["name"], "-"],
stdin=lambda r, t: t.strip(),
when=_wl_role("joiner"),
prompt="<call link> - a room id, a slug or a URL",
),
@@ -830,6 +842,7 @@ TABS = [
lambda r, t, _: ["proxy", "outbounds", "add", *_add_args(t), "--detour", r["tag"]],
when=_exit,
prompt="[tag] <url or JSON> - e.g. de-1 vless://… or just vless://…",
stdin=lambda r, t: _add_stdin(t),
),
Action(
"H",
@@ -873,6 +886,7 @@ TABS = [
"add a subscription…",
lambda r, t, _: ["proxy", "subs", "add", *_add_args(t)],
prompt="[tag] <url> - e.g. work https://… or just https://…",
stdin=lambda r, t: _add_stdin(t),
),
Action("d", "remove it", lambda r, *_: ["proxy", "subs", "rm", r["tag"]], when=lambda r: r["source"] == "runtime", confirm=True),
Action("s", "URL", lambda r, *_: ["proxy", "subs", "link", r["tag"]], when=ROW, mode="dialog"),
@@ -1013,6 +1027,7 @@ def paste_argv(tab_id, text):
Dumb on purpose: a share link becomes an outbound, a subscription URL a subscription,
a bare host a pinned or learned one, an AmneziaWG vpn:// link or .conf a global profile
(an outbound on the outbounds tab). The tag comes from the link, as `add` derives it.
Links and JSON carry credentials: they go on stdin, never into argv.
"""
text = (text or "").strip()
if not text:
@@ -1020,14 +1035,14 @@ def paste_argv(tab_id, text):
if ctl._awg_source(text):
return _awg_paste(tab_id, text)
if text.startswith("{"):
return [*OUTBOUND_ADD, text], "", None # only outbounds take JSON
return [*OUTBOUND_ADD, "-"], "", text # only outbounds take JSON
if len(text.splitlines()) > 1:
return None, "Paste one link at a time.", None
scheme = text.split("://", 1)[0].lower() if "://" in text else ""
if scheme in PROXY_SCHEMES:
return [*OUTBOUND_ADD, text], "", None
return [*OUTBOUND_ADD, "-"], "", text
if scheme in ("http", "https"):
return ([*OUTBOUND_ADD, text] if tab_id == "outbounds" else ["proxy", "subs", "add", text]), "", None
return ([*OUTBOUND_ADD, "-"] if tab_id == "outbounds" else ["proxy", "subs", "add", "-"]), "", text
if scheme:
return None, f"Nothing takes a {scheme}:// link.", None
if HOST.fullmatch(text) and tab_id in HOST_ARGV:
@@ -1098,6 +1113,78 @@ def short(label):
return label.split(" (")[0].removesuffix("…")
LINK = re.compile(r"\b[A-Za-z][A-Za-z0-9+.-]*://[^\s'\"]+")
USERINFO = re.compile(r"^([^:]+://)[^/?#]*@")
QUERY_VALUE = re.compile(r"([?&][^=&#]*=)[^&#]*")
# A path segment that reads as a token: a subscription's (/sub/<token>, proxy-ctl's own
# <base>/<32 hex>) is the credential itself.
TOKEN_SEGMENT = re.compile(r"(?<=/)[A-Za-z0-9_-]{16,}(?=[/?#]|$)")
def _redact_link(link):
scheme, _, body = link.partition("://")
authority = re.split(r"[/?#]", body, maxsplit=1)[0]
# One blob, credentials and all: vmess:// (base64 JSON), vpn:// (AmneziaWG's whole config,
# private key and all), ss://base64(method:password@host:port), ssr://. Its server stays.
if scheme.lower() == "vmess" or ("@" not in authority and ":" not in authority and scheme.lower() not in ("http", "https")):
server = _blob_server(scheme.lower(), body)
return f"{scheme}://***" + (f"@{server}" if server else "")
link = QUERY_VALUE.sub(r"\1***", USERINFO.sub(r"\1***@", link))
head, sep, rest = link.partition("://")
host, slash, path = rest.partition("/")
return head + sep + host + TOKEN_SEGMENT.sub("***", slash + path) if slash else link
SERVER = re.compile(r"[A-Za-z0-9.-]+(:\d+)?|\[[0-9A-Fa-f:.]+\](:\d+)?")
def _blob_server(scheme, body):
"""host:port inside a vmess://, ss:// or vpn:// blob; "" when it cannot be read."""
body = re.split(r"[?#]", body, maxsplit=1)[0].strip()
try:
raw = base64.urlsafe_b64decode(body.replace("+", "-").replace("/", "_") + "=" * (-len(body) % 4))
if scheme == "vmess":
data = json.loads(raw)
host, port = str(data.get("add") or ""), str(data.get("port") or "")
server = (f"[{host}]" if ":" in host else host) + (f":{port}" if port else "")
elif scheme == "ss":
_, at, server = raw.decode().rpartition("@")
server = server if at else ""
elif scheme == "vpn":
# 4 bytes of length, then zlib'd JSON whose config text names the peer.
match = re.search(r"Endpoint\s*=\s*([^\s\\\"]+)", zlib.decompress(raw[4:]).decode())
server = match.group(1) if match else ""
else:
return ""
except (ValueError, AttributeError, zlib.error):
return ""
return server if SERVER.fullmatch(server) else ""
def redact(text):
"""text with the credentials in its links blanked: the userinfo (vless://<uuid>@, ss://<key>@),
the query's values (?token=…), token-like path segments, and links that are one opaque blob
(vpn://, vmess://). Links go on stdin; this is for any that still reach argv."""
return LINK.sub(lambda m: _redact_link(m.group()), text)
def shown(argv, via=None, stdin=None):
"""The command line a toast, a dialog title or a notification shows for argv; with stdin,
what goes on it too, so a confirmation shows what it would add."""
line = f"{via + ' ' if via else ''}proxy-ctl {shlex.join(argv)}"
if stdin is not None:
if stdin.startswith("{"):
fed = "<an outbound's JSON>"
elif "\n" in stdin or not LINK.fullmatch(stdin):
fed = "<a config>" # an AmneziaWG .conf: keys throughout
else:
fed = stdin
line += f" < {fed}"
return redact(line)
def _capture(argv):
try:
p = subprocess.run([CTL, *argv], capture_output=True, text=True, stdin=subprocess.DEVNULL)
@@ -1107,7 +1194,8 @@ def _capture(argv):
def elevated(argv, via):
"""proxy-ctl argv run as root through via (sudo, pkexec): by its full path, the one the polkit rule names."""
"""proxy-ctl argv run as root through via (sudo, pkexec): by its full path, which pkexec
matches (after realpath) against the one proxy-suite's polkit action names."""
return [via, shutil.which(CTL) or CTL, *argv]
@@ -1126,6 +1214,16 @@ def load_tab_as_root(tab, via):
return None, (p.stderr.strip().splitlines() or [f"exit status {p.returncode}"])[-1]
# What this GUI's and TUI's own wrappers set (pkgs/proxy-ctl.nix: PYTHONPATH, wrapGAppsHook4's
# GTK paths): an app started with `apps run` would inherit them, and another nixpkgs' GTK or
# Python app breaks on modules of this one's.
WRAPPER_ENV = ("PYTHONPATH", "GI_TYPELIB_PATH", "GIO_EXTRA_MODULES", "GDK_PIXBUF_MODULE_FILE")
def app_env():
return {k: v for k, v in os.environ.items() if k not in WRAPPER_ENV}
def popen(argv, root=None, stdin=None):
"""proxy-ctl with its output streamed: its own process group, so stop() takes down what it spawned too.
root: "pkexec" to run it as root, asking through the desktop's polkit agent.
@@ -1133,7 +1231,7 @@ def popen(argv, root=None, stdin=None):
p = subprocess.Popen(
elevated(argv, root) if root else [CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
stdin=subprocess.DEVNULL if stdin is None else subprocess.PIPE,
text=True, errors="replace", start_new_session=True,
text=True, errors="replace", start_new_session=True, env=app_env() if argv[:1] in (["apps"], ["wrap"]) else None,
)
feed(p, stdin)
return p
@@ -1150,8 +1248,29 @@ def feed(p, stdin):
pass # it exited first: its output says why
def output_lines(p, poll=0.2):
"""p's output, line by line, until EOF or soon after stop(p) even when nothing comes. Then
the pipe is closed: a root process (pkexec) takes no signal of ours, and `journalctl -f`
exits once its stdout is gone, the rest at their next write."""
fd, pending = p.stdout.fileno(), b""
while not getattr(p, "proxy_suite_stopped", False):
if not select.select([fd], [], [], poll)[0]:
continue
chunk = os.read(fd, 65536)
if not chunk:
if pending.rstrip(b"\r"):
yield pending.rstrip(b"\r").decode("utf-8", "replace")
return
# Lines as text mode splits them (\r too); a final \r waits for a \n that may follow.
data = pending + chunk
*done, pending = re.split(rb"\r\n|\r(?!$)|\n", data)
yield from (line.decode("utf-8", "replace") for line in done)
p.stdout.close()
def stop(proc):
if proc and proc.poll() is None:
proc.proxy_suite_stopped = True # for output_lines
try:
os.killpg(proc.pid, signal.SIGTERM)
except OSError:
+308 -65
View File
@@ -24,6 +24,7 @@ import random
import re
import resource
import shlex
import shutil
import signal
import socket
import socketserver
@@ -38,6 +39,7 @@ SUPERVISOR_DIR = os.environ.get("PROXY_SUITE_SUPERVISOR_DIR") or os.path.join(
MANIFEST = os.environ.get("PROXY_SUITE_MANIFEST", "")
SOCKET = os.path.join(SUPERVISOR_DIR, "control.sock")
LOCK = os.path.join(SUPERVISOR_DIR, "daemon.lock")
GROUPS = os.path.join(SUPERVISOR_DIR, "groups.json")
LOG_DIR = os.path.join(SUPERVISOR_DIR, "logs")
CREDENTIALS_DIR = os.path.join(SUPERVISOR_DIR, "credentials")
LOG_LIMIT = 1024 * 1024
@@ -141,9 +143,13 @@ def append_log(unit, text):
os.replace(path, path + ".1")
except OSError:
pass
with open(path, "a", encoding="utf-8") as f:
for line in text.splitlines() or [""]:
f.write(f"{time.time():.6f}\t{line}\n")
# A full disk loses the line, nothing else: raised, it would end pump() and block the unit.
try:
with open(path, "a", encoding="utf-8") as f:
for line in text.splitlines() or [""]:
f.write(f"{time.time():.6f}\t{line}\n")
except OSError:
pass
def pump(unit, stream):
@@ -152,6 +158,161 @@ def pump(unit, stream):
stream.close()
# --- process groups -------------------------------------------------------------
def proc_stat(pid):
"""(state, process group, start time in clock ticks since boot) of a process, or None once it is gone."""
try:
with open(f"/proc/{pid}/stat", "rb") as f:
# After the last ")": comm may hold spaces and parentheses itself.
fields = f.read().rsplit(b")", 1)[1].split()
return fields[0].decode(), int(fields[2]), int(fields[19])
except (OSError, IndexError, ValueError):
return None
def wait_exit(proc, timeout=None):
"""proc's status (as Popen.returncode), None on timeout, left unreaped (WNOWAIT): its zombie
keeps the group's id from reuse while the group is killed. ChildProcessError once reaped."""
deadline = None if timeout is None else time.monotonic() + timeout
while True:
info = os.waitid(os.P_PID, proc.pid, os.WEXITED | os.WNOWAIT | (0 if deadline is None else os.WNOHANG))
if info is not None:
return info.si_status if info.si_code == os.CLD_EXITED else -info.si_status
if time.monotonic() >= deadline:
return None
time.sleep(0.05)
def private_dir(path):
"""Made 0700, or tightened to it: makedirs leaves an existing one's mode alone."""
os.makedirs(path, mode=0o700, exist_ok=True)
os.chmod(path, 0o700)
def clear_credentials(units=None):
"""Drops what LoadCredential copied for units (or all), which a daemon killed outright left."""
try:
names = os.listdir(CREDENTIALS_DIR)
except OSError:
return
for name in names:
if units is None or name in units:
shutil.rmtree(os.path.join(CREDENTIALS_DIR, name), ignore_errors=True)
class Groups:
"""The process groups the daemon started, on disk as {unit: [[pgid, start time], ...]}: a
daemon killed outright leaves them running, and the next one ends them first (end_orphans)."""
def __init__(self, path=GROUPS):
self.path = path
self.lock = threading.Lock()
self.groups = {}
def add(self, unit, pid):
# Not reaped yet, so readable even if it already exited.
stat = proc_stat(pid)
if stat is None:
return
with self.lock:
self.groups.setdefault(unit, []).append([pid, stat[2]])
self.save()
def remove(self, pid):
"""On reap: with its leader gone, end_orphans would skip the record anyway."""
with self.lock:
changed = False
for unit, entries in list(self.groups.items()):
kept = [e for e in entries if e[0] != pid]
if len(kept) != len(entries):
changed = True
if kept:
self.groups[unit] = kept
else:
del self.groups[unit]
if changed:
self.save()
def save(self):
tmp = f"{self.path}.tmp"
try:
with open(tmp, "w", encoding="utf-8") as f:
json.dump(self.groups, f)
os.replace(tmp, self.path) # atomic: a daemon killed mid-write leaves the last whole record
except OSError as e:
print(f"proxy-suitectl: cannot record process groups: {e}", file=sys.stderr)
def end_orphans(path=GROUPS, grace=5, units=None):
"""Ends the groups a dead daemon left running (of units, or all), under the daemon lock. Only
a leader still running with its recorded start time: a reused pid is left alone."""
try:
with open(path, encoding="utf-8") as f:
recorded = json.load(f)
except FileNotFoundError:
return
except (OSError, ValueError) as e:
print(f"proxy-suitectl: cannot read {path}: {e}", file=sys.stderr)
recorded = {}
ended, kept = [], {}
for unit, entries in recorded.items() if isinstance(recorded, dict) else ():
if units is not None and unit not in units:
kept[unit] = entries
continue
for entry in entries if isinstance(entries, list) else ():
try:
pgid, started = int(entry[0]), int(entry[1])
except (TypeError, ValueError, IndexError):
continue
stat = proc_stat(pgid)
if pgid <= 1 or stat is None or stat[0] == "Z" or stat[1] != pgid or stat[2] != started:
continue
try:
append_log(unit, f"proxy-suitectl: stopping process group {pgid}, left running by a supervisor that died")
except OSError:
pass
try:
os.killpg(pgid, signal.SIGTERM)
ended.append(pgid)
except OSError:
pass
deadline = time.monotonic() + grace
while time.monotonic() < deadline and any((s := proc_stat(p)) and s[0] != "Z" for p in ended):
time.sleep(0.1)
# The rest of each group too: its id stays taken while any member is left.
for pgid in ended:
try:
os.killpg(pgid, signal.SIGKILL)
except OSError:
pass
if kept:
groups = Groups(path)
groups.groups = kept
groups.save()
return
try:
os.unlink(path)
except OSError:
pass
def end_orphans_unsupervised(units=None):
"""stop and shutdown with no daemon to ask: a killed one's services stop here, under its lock."""
try:
lock = open(LOCK, "a")
except OSError:
return
with lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
return # a daemon is starting: it ends them itself, and its own are not ours to touch
end_orphans(units=units)
clear_credentials(units)
# --- units ----------------------------------------------------------------------
@@ -244,6 +405,7 @@ class Supervisor:
self.timers = {}
self.paths = {}
self.guard = threading.RLock()
self.groups = Groups()
self.started_at = time.time()
self.booted = False
self.quit = threading.Event()
@@ -266,6 +428,11 @@ class Supervisor:
unit = self.units[name] = Unit(name, definition)
return unit
def unit_list(self):
"""The units now, to loop over: instance() adds to them from other threads."""
with self.guard:
return list(self.units.values())
# specifiers and commands
def specifiers(self, unit, text):
@@ -287,9 +454,9 @@ class Supervisor:
return re.sub(r"%(.)", lambda m: table.get(m.group(1), m.group(0)), text)
def environment(self, unit):
env = dict(os.environ)
for key in ("PROXY_SUITE_SUPERVISOR_DIR", "PROXY_SUITE_MANIFEST", "NOTIFY_SOCKET"):
env.pop(key, None)
# What a service manager hands its services, not the starting shell's (https_proxy,
# LD_PRELOAD); the unit's own Environment comes next.
env = {key: value for key, value in os.environ.items() if _inherited(key)}
for entry in as_list(unit.service.get("Environment")):
for item in shlex.split(str(entry)):
if "=" in item:
@@ -307,7 +474,8 @@ class Supervisor:
if not entries:
return
target = self.credentials_dir(unit)
os.makedirs(target, mode=0o700, exist_ok=True)
private_dir(CREDENTIALS_DIR)
private_dir(target)
for entry in entries:
ident, _, source = str(entry).partition(":")
source = self.specifiers(unit, source or ident)
@@ -370,6 +538,7 @@ class Supervisor:
start_new_session=True,
umask=int(str(umask), 8) if umask is not None else -1,
)
self.groups.add(unit.name, proc.pid)
threading.Thread(target=pump, args=(unit.name, proc.stdout), daemon=True).start()
return proc, ignore
@@ -385,6 +554,7 @@ class Supervisor:
continue
unit.current = proc
status = proc.wait()
self.groups.remove(proc.pid)
unit.current = None
if status and not ignore:
append_log(unit.name, f"proxy-suitectl: {key} exited with status {status}")
@@ -393,22 +563,28 @@ class Supervisor:
@staticmethod
def kill_group(proc, sig):
# Not once reaped: its pid, the group's id, may lead another group by now.
if proc is None or proc.returncode is not None:
return
try:
os.killpg(proc.pid, sig)
except (ProcessLookupError, PermissionError):
pass
def terminate(self, proc):
if proc is None:
return
if proc is None or proc.returncode is not None:
return # reaped by watch(), which ended the group then
self.kill_group(proc, signal.SIGTERM)
try:
proc.wait(STOP_TIMEOUT)
except subprocess.TimeoutExpired:
if wait_exit(proc, STOP_TIMEOUT) is None:
self.kill_group(proc, signal.SIGKILL)
wait_exit(proc)
# What the main process left behind in its group, before the reap frees the group's id.
self.kill_group(proc, signal.SIGKILL)
proc.wait()
# What the main process left behind in its group.
self.kill_group(proc, signal.SIGKILL)
except ChildProcessError:
pass
proc.wait()
self.groups.remove(proc.pid)
# jobs
@@ -445,52 +621,67 @@ class Supervisor:
with unit.job:
if restarting and (unit.state != AUTO_RESTART or unit.cancel.is_set()):
return 0
if unit.state in (ACTIVE, ACTIVATING) or (unit.state == AUTO_RESTART and not restarting):
if unit.state in (ACTIVE, ACTIVATING):
return 0 if unit.state != ACTIVATING else self.wait_settled(unit)
if unit.state == AUTO_RESTART:
# Started now, not left down until RestartSec is up: this wakes watch() out of its wait.
unit.cancel.set()
unit.stopping = False
unit.cancel.clear()
unit.last_activated = time.time()
unit.set_state(ACTIVATING)
service = unit.service
kind = service.get("Type", "simple")
try:
self.load_credentials(unit)
except OSError as e:
append_log(unit.name, f"proxy-suitectl: LoadCredential: {e}")
return self._activate(unit)
except Exception as e:
# Left activating, the unit would hold every later start in wait_settled for good.
append_log(unit.name, f"proxy-suitectl: {e}")
main, unit.main = unit.main, None
self.terminate(main)
return self.fail(unit, "resources")
if not self.run_commands(unit, "ExecStartPre"):
def _activate(self, unit):
service = unit.service
kind = service.get("Type", "simple")
try:
self.load_credentials(unit)
except OSError as e:
append_log(unit.name, f"proxy-suitectl: LoadCredential: {e}")
return self.fail(unit, "resources")
if not self.run_commands(unit, "ExecStartPre"):
return self.fail(unit, "exit-code")
if kind in ("oneshot", "forking"):
if not self.run_commands(unit, "ExecStart"):
return self.fail(unit, "exit-code")
if kind in ("oneshot", "forking"):
if not self.run_commands(unit, "ExecStart"):
return self.fail(unit, "exit-code")
if unit.stopping:
return 0
if not self.run_commands(unit, "ExecStartPost"):
return self.fail(unit, "exit-code")
unit.result = "success"
if service.get("RemainAfterExit") or kind == "forking":
unit.set_state(ACTIVE)
else:
self.run_commands(unit, "ExecStopPost")
self.drop_credentials(unit)
unit.set_state(INACTIVE)
if unit.stopping:
return 0
commands = as_list(service.get("ExecStart"))
try:
proc, _ = self.spawn(unit, commands[0]) if commands else (None, False)
except OSError as e:
append_log(unit.name, f"proxy-suitectl: ExecStart: {e}")
return self.fail(unit, "exit-code")
if proc is None:
return self.fail(unit, "resources")
unit.main = proc
threading.Thread(target=self.watch, args=(unit, proc), daemon=True).start()
if not self.run_commands(unit, "ExecStartPost", {"MAINPID": str(proc.pid)}):
self.terminate(proc)
if not self.run_commands(unit, "ExecStartPost"):
return self.fail(unit, "exit-code")
unit.result = "success"
unit.set_state(ACTIVE)
if service.get("RemainAfterExit") or kind == "forking":
unit.set_state(ACTIVE)
else:
self.run_commands(unit, "ExecStopPost")
self.drop_credentials(unit)
unit.set_state(INACTIVE)
return 0
commands = as_list(service.get("ExecStart"))
try:
proc, _ = self.spawn(unit, commands[0]) if commands else (None, False)
except OSError as e:
append_log(unit.name, f"proxy-suitectl: ExecStart: {e}")
return self.fail(unit, "exit-code")
if proc is None:
return self.fail(unit, "resources")
unit.main = proc
threading.Thread(target=self.watch, args=(unit, proc), daemon=True).start()
if not self.run_commands(unit, "ExecStartPost", {"MAINPID": str(proc.pid)}):
# Not watch()'s exit to handle: it would run the stop commands again and turn FAILED into a restart.
unit.main = None
self.terminate(proc)
return self.fail(unit, "exit-code")
unit.result = "success"
unit.set_state(ACTIVE)
return 0
def wait_settled(self, unit):
with unit.done:
@@ -506,17 +697,27 @@ class Supervisor:
def watch(self, unit, proc):
"""After the main process exits on its own: stop commands, then Restart=."""
status = proc.wait()
try:
status = wait_exit(proc)
except ChildProcessError:
return # reaped by stop() or a failed start, which took it from unit.main and ended its group
# Reaped only under unit.job, as terminate() does, so neither signals a pid the other freed.
with unit.job:
if unit.stopping or unit.main is not proc:
if unit.main is not proc:
return
service = unit.service
unit.main = None
if status == 0 and service.get("RemainAfterExit"):
return
remain = status == 0 and service.get("RemainAfterExit") and not unit.stopping
if not remain:
# What it left behind, before the reap: once the leader is reaped and its group
# empties, the pid is free, and a later killpg could hit a new group of that id.
self.kill_group(proc, signal.SIGKILL)
proc.wait()
self.groups.remove(proc.pid)
if remain or unit.stopping:
return # a stop() under way runs the stop commands
env = {"SERVICE_RESULT": "success" if status == 0 else "exit-code", "EXIT_STATUS": str(status)}
self.run_commands(unit, "ExecStop", env)
self.kill_group(proc, signal.SIGKILL)
self.run_commands(unit, "ExecStopPost", env)
restart = service.get("Restart", "no")
again = restart == "always" or (restart in ("on-failure", "on-abnormal", "on-abort") and status != 0)
@@ -543,15 +744,18 @@ class Supervisor:
unit.stopping = True
unit.cancel.set()
# Bound to this one: they go first.
for other in list(self.units.values()):
for other in self.unit_list():
if other is not unit and other.state != INACTIVE:
if unit.name in map(full_name, as_list(other.unit.get("PartOf")) + as_list(other.unit.get("BindsTo"))):
self.stop(other.name)
if unit.current is not None:
self.kill_group(unit.current, signal.SIGTERM)
# Read once: run_commands clears it from the activating thread.
self.kill_group(unit.current, signal.SIGTERM)
with unit.job:
unit.stopping = True
if unit.state in (INACTIVE, FAILED, AUTO_RESTART):
if unit.state == AUTO_RESTART:
# A restart keeps them; one that will not come leaves none behind.
self.drop_credentials(unit)
unit.set_state(INACTIVE)
return 0
unit.set_state(DEACTIVATING)
@@ -691,6 +895,16 @@ class Supervisor:
os.chmod(fields[1], mode)
except OSError as e:
print(f"proxy-suitectl: tmpfiles: {fields[1]}: {e}", file=sys.stderr)
# C <path> <mode> - - - <source>: a copy where there is no file yet (the empty rule
# sets sing-box needs before their first download; without them it never starts).
elif len(fields) >= 7 and fields[0] == "C" and not os.path.lexists(fields[1]):
mode = int(fields[2], 8) if fields[2] != "-" else 0o644
try:
os.makedirs(os.path.dirname(fields[1]) or ".", exist_ok=True)
shutil.copyfile(fields[6], fields[1])
os.chmod(fields[1], mode)
except OSError as e:
print(f"proxy-suitectl: tmpfiles: {fields[1]}: {e}", file=sys.stderr)
def boot_units(self):
"""The units a login would start, services ordered by After=."""
@@ -726,18 +940,19 @@ class Supervisor:
old = self.manifest
self.manifest = load_manifest(self.manifest_path)
if not restart_changed:
for unit in self.units.values():
for unit in self.unit_list():
unit.definition = self.definition(unit.name) or unit.definition
return 0
self.make_tmpfiles()
status = 0
for unit in list(self.units.values()):
for unit in self.unit_list():
new = self.definition(unit.name)
running = unit.state not in (INACTIVE, FAILED)
if new is None:
if running:
self.stop(unit.name)
del self.units[unit.name]
with self.guard:
self.units.pop(unit.name, None)
elif new != unit.definition:
unit.definition = new
if running:
@@ -766,7 +981,7 @@ class Supervisor:
timer.active = False
for watch in self.paths.values():
watch.active = False
active = [u for u in self.units.values() if u.state not in (INACTIVE, FAILED)]
active = [u for u in self.unit_list() if u.state not in (INACTIVE, FAILED)]
for unit in sorted(active, key=lambda u: u.last_activated or 0, reverse=True):
self.stop(unit.name)
self.quit.set()
@@ -870,7 +1085,7 @@ def handle(supervisor, request):
status = status or result
return status, ""
if verb == "reset-failed":
for unit in supervisor.units.values():
for unit in supervisor.unit_list():
if unit.state == FAILED and (not units or unit.name in map(full_name, units)):
unit.set_state(INACTIVE)
return 0, ""
@@ -891,7 +1106,7 @@ def handle(supervisor, request):
if verb == "list-timers":
return 0, json.dumps(supervisor.list_timers(units))
if verb == "status":
names = units or [u.name for u in supervisor.units.values()]
names = units or [u.name for u in supervisor.unit_list()]
status = 0
for name in names:
props = supervisor.properties(name)
@@ -925,14 +1140,18 @@ def handle(supervisor, request):
def serve(manifest_path=None):
os.makedirs(SUPERVISOR_DIR, mode=0o700, exist_ok=True)
os.makedirs(LOG_DIR, mode=0o700, exist_ok=True)
private_dir(SUPERVISOR_DIR)
private_dir(LOG_DIR)
lock = open(LOCK, "w")
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
print("proxy-suitectl: the supervisor is already running", file=sys.stderr)
return 0
# Before anything starts: what a killed daemon left running holds the ports its successors want.
end_orphans()
clear_credentials()
private_dir(CREDENTIALS_DIR)
soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
try:
resource.setrlimit(resource.RLIMIT_NOFILE, (hard, hard))
@@ -1010,7 +1229,8 @@ def start_daemon():
if not MANIFEST or not os.path.exists(MANIFEST):
print(f"proxy-suitectl: no manifest at {MANIFEST or '(unset)'}: switch the configuration first", file=sys.stderr)
sys.exit(1)
os.makedirs(LOG_DIR, mode=0o700, exist_ok=True)
private_dir(SUPERVISOR_DIR)
private_dir(LOG_DIR)
with open(log_path("supervisor"), "a") as log:
subprocess.Popen(
[sys.executable, os.path.abspath(__file__), "daemon"],
@@ -1083,6 +1303,9 @@ def offline(verb, units, options):
supervisor = Supervisor()
except (OSError, ValueError):
supervisor = None
if verb in ("stop", "shutdown"):
# Nothing is active as far as a daemon knows, but one killed outright may have left them running.
end_orphans_unsupervised([full_name(u) for u in units] if verb == "stop" else None)
if verb in ("stop", "try-restart", "reset-failed", "daemon-reload", "shutdown", "reload"):
return 0, ""
if supervisor is None:
@@ -1173,8 +1396,28 @@ def read_entries(unit, since=None):
return entries
# Control characters but tab: C0, DEL and C1, as proxy_ctl shows them.
_UNPRINTABLE = re.compile("[\x00-\x08\x0a-\x1f\x7f-\x9f]")
# The variables services keep from the supervisor's environment: identity, locale and time zone
# data, temporary and runtime directories, the CA bundle, Android's and proot's. PATH as a default.
INHERITED_ENV = {
"HOME", "USER", "LOGNAME", "SHELL", "LANG", "LANGUAGE", "LOCALE_ARCHIVE", "TZ", "TZDIR", "TMPDIR", "XDG_RUNTIME_DIR", "PATH",
"SSL_CERT_FILE", "SSL_CERT_DIR", "NIX_SSL_CERT_FILE", "CURL_CA_BUNDLE",
}
INHERITED_ENV_PREFIXES = ("LC_", "ANDROID_", "PROOT_")
def _inherited(key):
return key in INHERITED_ENV or key.startswith(INHERITED_ENV_PREFIXES)
def format_entry(entry, fmt):
"""A log line to print, escape sequences shown rather than obeyed: a unit's output can quote
a subscription server's text."""
at, unit, text = entry
text = _UNPRINTABLE.sub(lambda m: f"\\x{ord(m.group()):02x}", text)
if fmt == "cat":
return text
stamp = datetime.datetime.fromtimestamp(at).strftime("%b %d %H:%M:%S")
+41 -20
View File
@@ -5,9 +5,10 @@ What it shows and does lives in proxy_model, shared with proxy-suite-gui; this i
import faulthandler
import os
import shlex
import re
import shutil
import signal
import stat
import subprocess
import tempfile
import traceback
@@ -73,8 +74,11 @@ def trace_path():
def open_trace():
try:
fd = os.open(trace_path(), os.O_WRONLY | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW, 0o600)
if os.fstat(fd).st_uid != os.getuid(): # someone else's file in a shared /tmp
# Nonblocking: a fifo planted there does not hang the open.
fd = os.open(trace_path(), os.O_WRONLY | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600)
st = os.fstat(fd)
# Someone else's file in a shared /tmp, or a hard link to one of ours (root's under sudo).
if st.st_uid != os.getuid() or not stat.S_ISREG(st.st_mode) or st.st_nlink != 1:
os.close(fd)
return None
return os.fdopen(fd, "a", buffering=1)
@@ -152,8 +156,21 @@ CELL_STYLES = {
}
def printable(text):
"""Control characters shown, not obeyed: rows carry what subscriptions and the userControl group wrote."""
return ctl._UNPRINTABLE.sub(lambda m: f"\\x{ord(m.group()):02x}", text)
_SGR = re.compile(r"(\x1b\[[0-9;]*m)")
def printable_ansi(text):
"""printable, but colors kept: Text.from_ansi drops only the escapes it knows."""
return "".join(part if i % 2 else printable(part) for i, part in enumerate(_SGR.split(text)))
def cell(name, value):
value = "" if value is None else str(value)
value = "" if value is None else printable(str(value))
if name == "state":
return Text(f"{STATE_ICONS.get(value, '?')} {value}", style=STATE_STYLES.get(value, ""))
return Text(value, style=CELL_STYLES.get(value, ""))
@@ -228,7 +245,7 @@ class Confirm(Dialog):
def compose(self) -> ComposeResult:
with Vertical(classes="dialog"):
yield Label("Run this?", classes="dialog-title")
yield Label(self.command, markup=False)
yield Label(printable(self.command), markup=False)
yield hint(("y/enter run", "dismiss(True)"), ("n/esc cancel", "dismiss(False)"))
@@ -250,7 +267,7 @@ class Menu(Dialog):
def compose(self) -> ComposeResult:
with Vertical(classes="dialog menu"):
yield Label(self.heading, classes="dialog-title", markup=False)
yield Label(printable(self.heading), classes="dialog-title", markup=False)
yield Choices(
*(Option(Text.assemble((f"{model.display_key(a.key):<8}", ACCENT), a.label), id=str(i)) for i, a in enumerate(self.actions))
)
@@ -289,11 +306,11 @@ class Output(Dialog):
def compose(self) -> ComposeResult:
with Vertical(classes="dialog output"):
yield Label(self.heading, classes="dialog-title", markup=False)
yield Label(printable(self.heading), classes="dialog-title", markup=False)
# Follow a streaming command; show finished text from its top.
log = RichLog(wrap=self.wrap, min_width=1, markup=False, auto_scroll=self.initial is None)
if self.initial is not None:
text = self.initial if isinstance(self.initial, Text) else Text.from_ansi(self.initial)
text = self.initial if isinstance(self.initial, Text) else Text.from_ansi(printable_ansi(self.initial))
self.text.append(text.plain)
log.write(text)
yield log
@@ -301,7 +318,7 @@ class Output(Dialog):
def write(self, line):
if self.is_attached:
text = Text.from_ansi(line)
text = Text.from_ansi(printable_ansi(line))
self.text.append(text.plain)
self.query_one(RichLog).write(text)
@@ -567,7 +584,7 @@ class ProxyTui(App):
if sort := self.sorts.get(tab_id):
rows = sorted(rows, key=lambda r: _natural(r.get(sort[0])), reverse=sort[1])
widget = self.main.query_one(f"#{tab_id}-summary", Static)
_update(widget, Text(summary))
_update(widget, Text(printable(summary)))
widget.display = bool(summary)
self.rows[tab_id] = {r["key"]: r for r in rows}
tab, table = self.tabs[tab_id], self.table(tab_id)
@@ -639,7 +656,7 @@ class ProxyTui(App):
self.perform(self.tabs[self.active_tab()].actions[index], self.selected_row())
def on_paste(self, event):
"""The terminal's paste, bracketed: whatever it carries is added to the tab it lands on.
"""The terminal's paste, bracketed: whatever it carries is added to the tab it lands on, once confirmed.
A prompt or a dialog takes its own paste, so this only fires on the table."""
if self.screen is not self.main:
return
@@ -648,7 +665,9 @@ class ProxyTui(App):
if argv is None:
self.feedback(what, False)
else:
self.run_argv("run", argv, stdin)
# Asked first: a web page can put a link in the clipboard, and one stray paste
# would have root fetch its subscription.
self.push_screen(Confirm(model.shown(argv, stdin=stdin)), lambda ok: ok and self.run_argv("run", argv, stdin))
def action_where(self):
self.perform(model.WHERE, None)
@@ -722,7 +741,7 @@ class ProxyTui(App):
self.feedback(f"Cannot run that: {e}", False)
return
if model.needs_confirm(action, row):
self.push_screen(Confirm(f"proxy-ctl {shlex.join(argv)}"), lambda ok: ok and self.run_argv(action.mode, argv, stdin))
self.push_screen(Confirm(model.shown(argv)), lambda ok: ok and self.run_argv(action.mode, argv, stdin))
else:
self.run_argv(action.mode, argv, stdin)
@@ -739,7 +758,7 @@ class ProxyTui(App):
def run_argv(self, mode, argv, stdin=None):
"""stdin: text proxy-ctl reads (argv says "-"); only for runs that stay in the TUI."""
command = f"proxy-ctl {shlex.join(argv)}"
command = model.shown(argv) # only shown: credentials blanked
if mode in ("suspend", "pause"):
self.foreground(mode, [CTL, *argv])
return
@@ -752,7 +771,7 @@ class ProxyTui(App):
def foreground(self, mode, argv):
with self.suspend():
ctl._run_foreground(argv)
ctl._run_foreground(argv, env=model.app_env() if argv[1:2] in (["apps"], ["wrap"]) else None)
if mode == "pause":
try:
input("\n[enter] back to proxy-tui")
@@ -783,14 +802,15 @@ class ProxyTui(App):
for line in out:
dialog.write(line)
last = Text.from_ansi(next((line for line in reversed(out) if line.strip()), "")).plain.strip()
message = f"{last} ({command})" if last else command
# The bar is on screen for anyone to see: a link in it, copied or in an error, blanked.
message = f"{model.redact(last)} ({command})" if last else command
self.last_output = (command, "\n".join(out))
if status == -signal.SIGTERM and dialog:
self.feedback(f"stopped: {command}", False)
return
if copy and not status and last:
self.copy_to_clipboard(last)
message = f"copied: {last}"
message = f"copied: {model.redact(last)}"
if status:
message = f"exit {status}: {message}"
if dialog:
@@ -811,7 +831,7 @@ class ProxyTui(App):
return
(mode, argv, *rest), self.retry = self.retry, None
stdin = rest[0] if rest else None
command = f"sudo proxy-ctl {shlex.join(argv)}"
command = model.shown(argv, "sudo")
root_argv = model.elevated(argv, "sudo")
# sudo asks on the terminal, so the run happens there; the output comes back as usual.
out = []
@@ -833,7 +853,8 @@ class ProxyTui(App):
old = signal.signal(signal.SIGINT, signal.SIG_IGN)
try:
for line in p.stdout:
print(line, end="", flush=True)
# Through a pipe proxy-ctl leaves its output as it is: shown, not obeyed.
print(printable(line), end="", flush=True)
out.append(line.rstrip("\n"))
status = p.wait()
finally:
@@ -860,7 +881,7 @@ class ProxyTui(App):
def feedback(self, message, ok=None, hints=()):
"""The bar is one line: what to press next is pinned, so only the message is ellipsized."""
icon, style = {True: ("✓ ", "green"), False: ("✗ ", "red"), None: ("", "")}[ok]
text = Text(icon + message, style=style, no_wrap=True, overflow="ellipsis")
text = Text(icon + printable(message), style=style, no_wrap=True, overflow="ellipsis")
if tail := "".join(f" · {h}" for h in hints):
text.truncate(max(len(icon) + 1, self.size.width - 2 - len(tail)), overflow="ellipsis")
text.append(tail, ACCENT) # a rich style: the theme's ansi_* names are markup, not rich colors
+424 -57
View File
@@ -2,6 +2,7 @@
import contextlib
import datetime
import fcntl
import io
import json
import os
@@ -55,31 +56,58 @@ class TerminalSafeTest(unittest.TestCase):
self.assertEqual(out.getvalue(), "vless://u@h:1#\\x1b]52;c;cm0gLXJmIH4=\\x07name\\x0d\tok\n\\x9b2J")
class StubResolverTest(unittest.TestCase):
def resolv(self, content):
tmp = tempfile.NamedTemporaryFile("w", suffix=".conf", delete=False)
tmp.write(content)
tmp.close()
self.addCleanup(os.unlink, tmp.name)
return tmp.name
def test_only_stub_nameservers_are_reported(self):
path = self.resolv("nameserver 127.0.0.53\noptions edns0\n")
assert ctl._stub_resolver_nameservers(path) == ["127.0.0.53"]
def test_a_real_resolver_alongside_the_stub_is_not_a_leak(self):
path = self.resolv("nameserver 127.0.0.53\nnameserver 192.168.1.1\n")
assert ctl._stub_resolver_nameservers(path) == []
def test_missing_resolv_conf_is_quiet(self):
assert ctl._stub_resolver_nameservers("/nonexistent/resolv.conf") == []
def test_wrap_warns_once_on_the_stub(self):
with mock.patch.object(ctl, "_stub_resolver_nameservers", return_value=["127.0.0.53"]):
status, out, err = run(ctl._warn_stub_resolver, "tun")
class NscdWarningTest(unittest.TestCase):
def test_wrap_warns_on_nscd(self):
# glibc goes through nscd, which looks names up from its own cgroup.
with tempfile.NamedTemporaryFile() as sock, mock.patch.dict(os.environ, {"NSCD_SOCKET": sock.name}):
status, out, err = run(ctl._warn_nscd, "tproxy")
assert status == 0, (status, out, err)
assert "route=tun" in err
assert "127.0.0.53" in err
assert "nscd" in err and "route=tproxy" in err
def test_no_nscd_is_quiet(self):
# A stub resolver on loopback is no leak: the route's forwarder answers it.
with mock.patch.dict(os.environ, {"NSCD_SOCKET": "/nonexistent/socket"}):
assert run(ctl._warn_nscd, "tun")[2] == ""
class SharedFilesTest(unittest.TestCase):
def test_completion_words_are_never_shell_code(self):
words = {"ok-tag": "", "sub-Россия": "", "$(id>/tmp/p)": "", "`id`": "", "a b": "", "x": "d\tescr\x1b[31m"}
with mock.patch.object(ctl, "_complete_tree", lambda *w: words):
_, out, _ = run(ctl.cmd_complete, "proxy")
self.assertEqual(out.splitlines(), ["ok-tag", "sub-Россия", "x\td escr[31m"])
def test_a_list_swapped_for_a_link_is_not_copied(self):
with tempfile.TemporaryDirectory() as d:
secret = os.path.join(d, "secret")
with open(secret, "w") as f:
f.write("root:hash\n")
os.chmod(secret, 0o600)
listed = os.path.join(d, "zapret-hosts-auto.txt")
os.symlink(secret, listed)
status, _, _ = run(ctl._replace_lines, listed, lambda line: True)
self.assertNotEqual(status, 0)
self.assertTrue(os.path.islink(listed))
os.unlink(listed)
os.mkfifo(listed)
with self.assertRaises(OSError):
ctl.read_shared_text(listed)
class SliceCleanupTest(unittest.TestCase):
def test_a_run_still_starting_keeps_the_marking(self):
with tempfile.TemporaryDirectory() as runtime, mock.patch.dict(os.environ, {"XDG_RUNTIME_DIR": runtime}), \
mock.patch.object(ctl, "_has_units", return_value=False), \
mock.patch.object(ctl, "systemctl", return_value=(0, "")) as systemctl:
ending = ctl._slice_lock("proxy-suite-app-tun")
starting = ctl._slice_lock("proxy-suite-app-tun")
self.assertIsNotNone(ending)
# The other run has its units up but no scope yet: nothing is stopped under it.
ctl._cleanup_slice_if_idle("proxy-suite-app-tun", "a.service", "u.service", ending)
systemctl.assert_not_called()
# The last one out stops them.
ctl._cleanup_slice_if_idle("proxy-suite-app-tun", "a.service", "u.service", starting)
self.assertEqual([c.args for c in systemctl.call_args_list], [("stop", "u.service"), ("--user", "stop", "a.service")])
class EnvTest(unittest.TestCase):
@@ -120,13 +148,18 @@ class ClashApiTest(EnvTest):
class ClashBrokerTest(EnvTest):
def test_what_each_scope_may_ask(self):
allows = ctl._broker_allows
os.environ["OUTBOUND_INVENTORY_FILE"] = self.write("outbounds.json", {"url": "https://t.test/204"})
allows = lambda method, target, scopes: ctl._broker_allows(method, target.split("?")[0], scopes, target.partition("?")[2]) # noqa: E731
member, routing, secrets = set(), {"routing"}, {"secrets"}
for method, path, scopes, expected in (
("GET", "/proxies", member, True),
("GET", "/proxies/proxy", member, True),
("GET", "/proxies/DE%20one/delay", member, True),
("GET", "/group/g/delay", member, True),
("GET", "/proxies/DE%20one/delay?url=https%3A%2F%2Ft.test%2F204&timeout=8000", member, True),
("GET", "/group/g/delay?timeout=1&url=https://t.test/204", member, True),
# Only the configured test URL: any other is the backend fetching what the caller names.
("GET", "/proxies/proxy/delay?url=http://192.168.1.1/admin", member, False),
("GET", "/group/g/delay?url=https://t.test/204&url=http://10.0.0.1/", member, False),
("GET", "/proxies/proxy/delay", member, False),
("PUT", "/proxies/proxy-suite-test", member, True),
("PUT", "/proxies/proxy", member, False),
("PUT", "/proxies/proxy", routing, True),
@@ -145,6 +178,10 @@ class ClashBrokerTest(EnvTest):
):
with self.subTest(method=method, path=path, scopes=scopes):
self.assertEqual(allows(method, path, scopes), expected)
# outbound-test.json's URL, which `proxy outbounds test` asks with, as much as the inventory's.
self.write("outbound-test.json", {"url": "https://other.test/"})
self.assertTrue(allows("GET", "/proxies/p/delay?url=https://other.test/", member))
self.assertTrue(allows("GET", "/proxies/p/delay?url=https://t.test/204", member))
def test_root_reads_the_secret_everyone_else_asks_the_broker(self):
os.environ["CLASH_BROKER"] = self.write("api.sock", "")
@@ -188,7 +225,7 @@ class ClashBrokerTest(EnvTest):
sock = self.path("api.sock")
os.environ.update(
CLASH_API=f"http://127.0.0.1:{api.server_address[1]}",
OUTBOUND_INVENTORY_FILE=self.path("outbounds.json"),
OUTBOUND_INVENTORY_FILE=self.write("outbounds.json", {"url": "x"}),
USER_CONTROL_GROUPS=json.dumps({group: ["routing"]}),
)
self.patch("CLASH_BROKER_TIMEOUT", 1)
@@ -203,6 +240,7 @@ class ClashBrokerTest(EnvTest):
self.assertEqual(ask("PUT", "/proxies/proxy", {"name": "de"})[0], 200)
with contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(ask("GET", "/connections")[0], 403)
self.assertEqual(ask("GET", "/proxies/proxy/delay?url=http://127.0.0.1:22/")[0], 403)
# The secret reaches the API, never the caller; the refused request never left.
self.assertEqual([s[2] for s in seen], ["Bearer s3cret", "Bearer s3cret"])
self.assertNotIn("/connections", [s[1] for s in seen])
@@ -298,7 +336,7 @@ class ClashBrokerTest(EnvTest):
self.write("clash-secret", "s3cret\n")
os.environ.update(
CLASH_API=f"http://127.0.0.1:{api.server_address[1]}",
OUTBOUND_INVENTORY_FILE=self.path("outbounds.json"),
OUTBOUND_INVENTORY_FILE=self.write("outbounds.json", {"url": "x"}),
USER_CONTROL_GROUPS=json.dumps({group: ["outbounds"]}),
)
sock = self.path("api.sock")
@@ -321,6 +359,11 @@ class WarpDevicesTest(EnvTest):
status, out, _ = run(ctl.cmd_warp)
self.assertEqual(status, 0)
self.assertEqual(out.split(), ["warp-1", "active", "warp-2", "active"])
# Status exits as `systemctl is-active` would: 3 once none is active.
self.patch("systemctl", lambda *a, **kw: (3, "inactive\n"))
self.assertEqual(run(ctl.cmd_warp)[0], 3)
self.assertEqual(run(ctl.cmd_warp, "status", "warp-1")[0], 3)
self.patch("systemctl", lambda *a, **kw: calls.append(a) or (0, "active\n"))
calls.clear()
run(ctl.cmd_warp, "restart", "warp-2")
self.assertEqual(calls, [("restart", "proxy-suite-awg-warp-2")])
@@ -384,6 +427,18 @@ class GroupWatchTest(EnvTest):
# A hint about a member that still works changes nothing.
self.assertEqual(self.step(1, hinted=["warp-2"]), [])
def test_hints_outside_the_groups_are_ignored(self):
# A name no watched group holds is neither tested nor kept.
self.step(0)
self.calls.clear()
self.step(1, hinted=["../etc", "nobody"])
self.assertEqual(self.calls, [])
self.assertEqual(set(self.watch.health), {"warp-1", "warp-2"})
# A member's is tested each time it comes.
self.step(1, hinted=["warp-1"])
self.step(1, hinted=["warp-1"])
self.assertEqual(sum(p.startswith("/proxies/warp-1/delay") for _, p in self.calls), 2)
def test_without_failback_it_stays(self):
self.inventory["groups"]["warp"]["failback"] = False
self.step(0)
@@ -491,10 +546,14 @@ class ProbeVerdictTest(unittest.TestCase):
class ProbeFetchTest(EnvTest):
def test_listener_login_goes_through_a_file(self):
"""With listener.auth the probe listeners want the login; never on curl's argv."""
"""The probe listeners take the login drawn per start, the local proxy its own
(listener.auth); never on curl's argv."""
os.environ["PROXYCHAINS_CONFIG"] = self.write(
"proxychains.conf", 'strict_chain\n\n[ProxyList]\nsocks5 127.0.0.1 1080 user pa"ss\\w\n'
)
os.environ["OUTBOUND_INVENTORY_FILE"] = self.write("outbounds.json", "{}")
self.write("probe-login", "probe:0123abcd\n")
os.environ["LOCAL_PROXY_URL"] = "http://127.0.0.1:1080"
seen = []
def curl(argv):
@@ -505,6 +564,10 @@ class ProbeFetchTest(EnvTest):
self.patch("run_curl", curl)
ctl._probe_fetch("site.test", "/", "--proxy", "http://127.0.0.1:18600")
argv, curlrc = seen[0]
self.assertEqual(curlrc, 'proxy-user = "probe:0123abcd"\n')
self.assertFalse(any("0123abcd" in a for a in argv))
ctl._probe_fetch("site.test", "/", "--proxy", "http://127.0.0.1:1080")
argv, curlrc = seen[-1]
self.assertEqual(curlrc, 'proxy-user = "user:pa\\"ss\\\\w"\n')
self.assertFalse(any("pa" in a and "ss" in a for a in argv))
# Direct fetches, and a config without a login, carry none.
@@ -535,6 +598,12 @@ class ProbeFetchTest(EnvTest):
calls.clear()
ctl._probe_fetch("loop.test", "/", "--noproxy", "*")
self.assertLessEqual(len(calls), 6)
# A Location at this host or the LAN, by literal, is never fetched.
for target in ("http://127.1/", "http://localhost/", "http://[::ffff:10.0.0.1]/", "http://u@192.168.1.1:80/", "http://0.0.0.0/"):
with self.subTest(target=target):
self.assertTrue(ctl._probe_local_target(target))
self.assertFalse(ctl._probe_local_target("https://www.spotify.test/"))
self.assertFalse(ctl._probe_local_target("https://203.0.113.0.example/"))
def test_block_pages(self):
waf_head = "HTTP/2 403\r\nserver: CloudFront\r\nx-cache: Error from cloudfront\r\n\r\n"
@@ -702,6 +771,16 @@ class ServiceManagerTest(EnvTest):
self.assertEqual(seen, [["systemctl", "--user", "start", "anchor.service"], ["systemctl", "start", "proxy-suite-socks"]])
self.assertEqual(ctl.journal_hint("proxy-suite-autoproxy-learn", 20), "journalctl -u proxy-suite-autoproxy-learn -n 20")
def test_unit_escape(self):
# As systemd-escape prints them.
self.assertEqual(ctl.unit_escape("ssh-proxy"), "ssh\\x2dproxy")
self.assertEqual(ctl.unit_escape("de_1:x.y"), "de_1:x.y")
self.assertEqual(ctl.unit_escape(".a/b c\\"), "\\x2ea-b\\x20c\\x5c")
self.assertEqual(ctl.unit_escape("é"), "\\xc3\\xa9")
seen = self.calls()
ctl._start_pin_unit("my-vps")
self.assertEqual(seen, [["systemctl", "start", "proxy-suite-outbound-pin@my\\x2dvps.service"]])
def test_logs(self):
ran = []
@@ -752,6 +831,25 @@ class ServiceManagerTest(EnvTest):
seen.clear()
ctl.COMMANDS["killswitch"]("off")
self.assertEqual(stops(), [ctl.KILL_SWITCH])
# Another global tunnel still up keeps it: turning off one that is not running lifts nothing.
self.patch("_awg_profiles", lambda: ["home"])
running = {ctl._awg_service("home"): "active"}
self.patch("_unit_states", lambda units: {u: running.get(u, "inactive") for u in units})
for off in (lambda: ctl.cmd_proxy("tun", "off"), lambda: ctl.cmd_proxy("tproxy", "off"), lambda: ctl.cmd_proxy("off")):
seen.clear()
with contextlib.redirect_stderr(io.StringIO()) as err:
off()
self.assertNotIn(ctl.KILL_SWITCH, stops())
self.assertIn("stays up for proxy-suite-awg-home", err.getvalue())
running = {"proxy-suite-tproxy": "activating"}
seen.clear()
with contextlib.redirect_stderr(io.StringIO()):
ctl.cmd_awg("off", "home")
self.assertEqual(stops(), [ctl._awg_service("home")])
# Still, killswitch off always lifts it.
seen.clear()
ctl.COMMANDS["killswitch"]("off")
self.assertEqual(stops(), [ctl.KILL_SWITCH])
def test_toggle_and_restart(self):
seen = self.calls()
@@ -881,10 +979,11 @@ class ServiceManagerTest(EnvTest):
self.assertEqual(ctl.journal_hint("proxy-suite-socks", 5), "/bin/proxy-suitectl journal -u proxy-suite-socks -n 5")
def test_paths_follow_host_dirs(self):
for name in ("SUB_CACHE_DIR", "AUTOPROXY_STATE_DIR", "INBOUNDS_STATS_FILE", "OUTBOUND_INVENTORY_FILE"):
for name in ("SUB_CACHE_DIR", "AUTOPROXY_STATE_DIR", "AUTOPROXY_SPOOL_DIR", "INBOUNDS_STATS_FILE", "OUTBOUND_INVENTORY_FILE"):
os.environ.pop(name, None)
os.environ.update(STATE_DIR="/home/u/.local/state/proxy-suite", RUNTIME_DIR="/tmp/ps")
self.assertEqual(ctl._autoproxy_dir(), "/home/u/.local/state/proxy-suite/autoproxy")
self.assertEqual(ctl._autoproxy_spool(), "/home/u/.local/state/proxy-suite/autoproxy-requests")
self.assertEqual(os.path.dirname(ctl._subscription_cache("x")), "/home/u/.local/state/proxy-suite/subscriptions")
def test_rootless_hosts_never_ask_for_root(self):
@@ -902,7 +1001,8 @@ class ServiceManagerTest(EnvTest):
class AutoProxyTest(EnvTest):
def setUp(self):
super().setUp()
os.environ.update(AUTOPROXY_ENABLED="1", AUTOPROXY_STATE_DIR=self.dir)
os.environ.update(AUTOPROXY_ENABLED="1", AUTOPROXY_STATE_DIR=self.dir, AUTOPROXY_SPOOL_DIR=self.path("spool"))
os.makedirs(self.path("spool"))
def state_on_start(self, state):
def systemctl(*args, **kw):
@@ -925,8 +1025,12 @@ class AutoProxyTest(EnvTest):
self.assertNotEqual(run(ctl.cmd_proxy_learn, "x;rm -rf /")[0], 0)
self.assertNotEqual(run(ctl.cmd_proxy_learn, "-evil.test/path")[0], 0)
out = ok(ctl.cmd_proxy_learn, "www.last.fm")
self.assertEqual(ctl.read_text(self.path("requests")), "www.last.fm\n")
self.assertEqual(ctl._autoproxy_queued("requests"), "www.last.fm\n")
self.assertIn("last.fm: destination - routed via primary", out)
# A file of its own in the spool, never in root's state dir.
(queued,) = os.listdir(self.path("spool"))
self.assertRegex(queued, r"^requests\.[0-9]+\.[0-9]+$")
self.assertFalse(os.path.exists(self.path("requests")))
def test_learn_nothing_to_route(self):
# A verdict that routes nothing is kept for its host and reported.
@@ -939,11 +1043,16 @@ class AutoProxyTest(EnvTest):
status, _, err = run(ctl.cmd_proxy_learn, "www.last.fm")
self.assertNotEqual(status, 0)
self.assertIn("still queued", err)
self.assertIn("www.last.fm\n", ctl.read_text(self.path("requests")))
self.assertIn("www.last.fm\n", ctl._autoproxy_queued("requests"))
def test_queue_and_learned(self):
self.patch("systemctl", lambda *args, **kw: (0, ""))
self.write("requests", "www.last.fm\n")
self.write("spool/requests.2.1", "www.last.fm\n")
# What a member left besides: not followed, not waited on, not shown.
self.write("secret", "root.only\n")
os.symlink(self.path("secret"), self.path("spool/requests.3.1"))
os.mkfifo(self.path("spool/requests.4.1"))
self.write("spool/.requests.5.1.tmp", "half.written\n")
self.write(
"state.json",
{
@@ -957,6 +1066,8 @@ class AutoProxyTest(EnvTest):
)
q = ok(ctl.cmd_proxy_queue)
self.assertIn("\n www.last.fm\n", q)
self.assertNotIn("root.only", q)
self.assertNotIn("half.written", q)
# Most-dialled first.
self.assertLess(q.index("b.example"), q.index("a.example"))
learned = ok(ctl.cmd_proxy_learned)
@@ -973,7 +1084,7 @@ class AutoProxyTest(EnvTest):
self.patch("systemctl", lambda *args, **kw: started.append(args) or (0, ""))
# A host names its domain: the route is the domain's.
out = ok(ctl.cmd_proxy_forget, "www.last.fm")
self.assertEqual(ctl.read_text(self.path("edits")), "forget last.fm\n")
self.assertEqual(ctl._autoproxy_queued("edits"), "forget last.fm\n")
self.assertEqual(started, [("start", "proxy-suite-autoproxy-learn.service")])
self.assertIn("Forgot last.fm (was via primary)", out)
self.assertNotEqual(run(ctl.cmd_proxy_forget, "x;rm -rf /")[0], 0)
@@ -987,8 +1098,8 @@ class AutoProxyTest(EnvTest):
self.state_on_start(before) # the same exit wins again
out = ok(ctl.cmd_proxy_relearn, "last.fm")
# Forgotten first, then probed again from the host it was learned from.
self.assertEqual(ctl.read_text(self.path("edits")), "forget last.fm\n")
self.assertEqual(ctl.read_text(self.path("requests")), "www.last.fm\n")
self.assertEqual(ctl._autoproxy_queued("edits"), "forget last.fm\n")
self.assertEqual(ctl._autoproxy_queued("requests"), "www.last.fm\n")
self.assertIn("probing www.last.fm", out)
self.assertIn("proxy-ctl proxy outbounds disable primary", out)
@@ -997,7 +1108,20 @@ class AutoProxyTest(EnvTest):
status, _, err = run(ctl.cmd_proxy_clear)
self.assertNotEqual(status, 0)
self.assertIn("still queued", err)
self.assertEqual(ctl.read_text(self.path("edits")), "clear\n")
self.assertEqual(ctl._autoproxy_queued("edits"), "clear\n")
# Again: queued after the first, not in its place.
run(ctl.cmd_proxy_clear)
self.assertEqual(ctl._autoproxy_queued("edits"), "clear\nclear\n")
@unittest.skipIf(os.geteuid() == 0, "root writes anything")
def test_unwritable_spool_asks_for_sudo(self):
os.chmod(self.path("spool"), 0o500)
try:
status, _, err = run(ctl.cmd_proxy_learn, "www.last.fm")
finally:
os.chmod(self.path("spool"), 0o755)
self.assertNotEqual(status, 0)
self.assertIn(f"Cannot write to {self.path('spool')}", err)
@unittest.skipIf(os.geteuid() == 0, "root reads anything")
def test_unreadable_state_asks_for_sudo(self):
@@ -1056,6 +1180,7 @@ class RuntimeEntryTest(RuntimeSpoolTest):
self.assertEqual(tag("outbound", "vless://u@www.example.org:443"), "vless-example-2")
self.assertEqual(tag("outbound", '{"type": "socks", "server": "127.0.0.1"}'), "socks")
self.assertEqual(tag("outbound", '{"tag": "proxy", "type": "socks"}'), "proxy-2") # reserved
self.assertEqual(tag("outbound", "vless://u@t.test:443#tor"), "tor-2")
self.assertEqual(tag("outbound", "vmess://" + __import__("base64").b64encode(b'{"ps": "JP 2", "add": "jp.test"}').decode()), "JP-2")
self.assertEqual(tag("outbound", "{not json"), "outbound")
self.assertEqual(tag("subscription", "https://sub.provider.com/api/v1/client?token=x"), "provider-2")
@@ -1076,10 +1201,67 @@ class RuntimeEntryTest(RuntimeSpoolTest):
self.assertNotEqual(status, 0)
self.assertIn("The tag goes first", err)
self.assertNotEqual(run(ctl.cmd_subscription, "add", "lonely")[0], 0)
# Plain http: anyone on the path could rewrite what root fetches. Refused, piped or not.
for args, stdin in ((("plain", "http://sub.plain.test/s"), ""), (("plain", "-"), " HTTP://sub.plain.test/s\n"), (("ftp://sub.plain.test/s",), "")):
with self.subTest(args=args), mock.patch.object(sys, "stdin", io.StringIO(stdin)):
status, _, err = run(ctl.cmd_subscription, "add", *args)
self.assertNotEqual(status, 0)
self.assertIn("must be an https:// URL", err)
self.assertIn("runtimeSubscriptions.allowHttp", run(ctl.cmd_subscription, "add", "plain", "http://sub.plain.test/s")[2])
self.assertFalse([n for n in os.listdir(self.path("subscriptions.d")) if not n.startswith(("work", "home", "."))])
# Unless the admin allows it; other schemes stay refused.
with mock.patch.dict(os.environ, {"RUNTIME_SUBS_ALLOW_HTTP": "1"}):
ok(ctl.cmd_subscription, "add", "plain", "http://sub.plain.test/s")
self.assertNotEqual(run(ctl.cmd_subscription, "add", "ftp", "ftp://sub.plain.test/s")[0], 0)
os.unlink(self.path("subscriptions.d/plain.url"))
# An HTTP proxy is still an outbound.
ok(ctl.cmd_outbounds, "add", "httpproxy", "http://proxy.test:3128")
# Names the start script skips: priority.json's, the Tor outbound's and its own selectors'.
for reserved in ("priority", "tor", "proxy-suite-test"):
with self.subTest(tag=reserved):
status, _, err = run(ctl.cmd_outbounds, "add", reserved, "vless://u@r.test:443")
self.assertNotEqual(status, 0)
self.assertIn("is reserved", err)
self.assertFalse(os.path.exists(self.path(f"outbounds.d/{reserved}.url")))
# Outbound JSON alone, and a JSON-looking word for a subscription is not a source.
self.assertIn("Tag: socks", ok(ctl.cmd_outbounds, "add", '{"type": "socks", "server": "127.0.0.1", "server_port": 1080}'))
self.assertTrue(os.path.exists(self.path("outbounds.d/socks.json")))
self.assertNotEqual(run(ctl.cmd_subscription, "add", "-")[0], 0)
@unittest.skipIf(os.geteuid() == 0, "root reads any cache")
def test_a_root_only_cache_is_counted_from_the_inventory(self):
"""Without "secrets" the cache is out of reach: add and list go by the outbounds the proxy took from it."""
os.makedirs(self.path("subscriptions"))
os.chmod(self.path("subscriptions"), 0)
self.addCleanup(os.chmod, self.path("subscriptions"), 0o755)
def started():
tags = self.declared + ctl._runtime_tags("outbound")
sources = {f"{t}-{n}": f"sub:{t}" for t in ctl._runtime_tags("subscription") for n in (1, 2)}
self.write("outbounds.json", {"tags": tags + list(sources), "sources": sources})
self.backend_start = started
self.assertIn("Added subscription: work (2 proxies)", ok(ctl.cmd_subscription, "add", "work", "https://sub.work.test/s"))
self.assertRegex(ok(ctl.cmd_subscription, "list"), r"(?m)^ work +unknown +2 +runtime$")
self.assertRegex(ok(ctl.cmd_subscription, "list"), r"(?m)^ provider +\(no cache\) +- +static$")
def test_add_from_stdin(self):
# "-": the link on stdin, so its credentials stay out of argv (ps, pkexec's log).
with mock.patch.object(sys, "stdin", io.StringIO("https://sub.piped.test/s?token=t\n")):
self.assertIn("Tag: piped", ok(ctl.cmd_subscription, "add", "-"))
self.assertEqual(ctl.read_text(self.path("subscriptions.d/piped.url")), "https://sub.piped.test/s?token=t\n")
with mock.patch.object(sys, "stdin", io.StringIO("https://sub.x.test/s")):
ok(ctl.cmd_subscription, "add", "mine", "-")
self.assertTrue(os.path.exists(self.path("subscriptions.d/mine.url")))
with mock.patch.object(sys, "stdin", io.StringIO("vless://u@de.test:443#DE")):
ok(ctl.cmd_outbounds, "add", "-", "--detour", "primary")
self.assertEqual(ctl.read_text(self.path("outbounds.d/DE.url")), "vless://u@de.test:443#DE\n")
# Nothing piped in: nothing written.
for fn in (ctl.cmd_subscription, ctl.cmd_outbounds):
with self.subTest(fn=fn.__name__), mock.patch.object(sys, "stdin", io.StringIO("")):
status, _, err = run(fn, "add", "empty", "-")
self.assertNotEqual(status, 0)
self.assertIn("Nothing on stdin", err)
self.assertFalse([n for n in os.listdir(self.path("subscriptions.d")) + os.listdir(self.path("outbounds.d")) if n.startswith("empty")])
def test_json_naming_local_files_is_refused(self):
"""The backend holds CAP_NET_ADMIN: a tor outbound runs a program, *_path and *File are read."""
@@ -1087,6 +1269,8 @@ class RuntimeEntryTest(RuntimeSpoolTest):
("t", {"type": "tor", "executable_path": "/tmp/x"}),
("s", {"type": "ssh", "server": "h", "private_key_path": "/root/.ssh/id_ed25519"}),
("x", {"protocol": "vless", "streamSettings": {"tlsSettings": {"masterKeyLog": "/etc/x"}}}),
# XRay's JSON decoding folds U+017F to s: this is masterKeyLog to it.
("u", {"protocol": "vless", "streamSettings": {"tlsSettings": {"ma\u017fterKeyLog": "/etc/x"}}}),
):
status, _, err = run(ctl.cmd_outbounds, "add", tag, json.dumps(ob))
self.assertNotEqual(status, 0)
@@ -1110,6 +1294,8 @@ class RuntimeEntryTest(RuntimeSpoolTest):
self.assertFalse(os.path.islink(self.path(f"outbounds.d/{name}")), name)
self.assertFalse(os.path.exists(self.path(f"created-{name}")), name)
self.assertEqual(ctl.read_text(self.path("outbounds.d/new.detour")), "primary\n")
# The link holds credentials: no other member reads it without the "secrets" scope.
self.assertEqual(stat.S_IMODE(os.stat(self.path("outbounds.d/new.url")).st_mode), 0o600)
def test_disable_enable(self):
self.pinned = "primary"
@@ -1193,7 +1379,62 @@ class RuntimeEntryTest(RuntimeSpoolTest):
ok(ctl.cmd_outbounds, "add", "de", "vless://u@de.test:443")
ok(ctl.cmd_outbounds, "disable", "de")
ok(ctl.cmd_outbounds, "rm", "de")
self.assertEqual(os.listdir(self.path("outbounds.d")), [])
self.assertEqual(os.listdir(self.path("outbounds.d")), [".entries.lock"])
def test_priority_and_group_edits_are_locked(self):
"""Read to write under .<name>.lock: the GUI and a terminal at once would drop one's change."""
ok(ctl.cmd_groups, "add", "pool", "primary")
for name, fn, args in [
("priority.json", ctl.cmd_priority, ("primary", "5")),
("pool.group", ctl.cmd_groups, ("strategy", "pool", "urltest")),
("pool.group", ctl.cmd_groups, ("members", "pool", "add", "vless-example")),
]:
with self.subTest(args=args), open(self.path(f"outbounds.d/.{name}.lock"), "a") as held:
fcntl.flock(held, fcntl.LOCK_EX)
with mock.patch.object(ctl, "LOCK_WAIT", 0.2):
status, _, err = run(fn, *args)
self.assertNotEqual(status, 0)
self.assertIn("Something else is still changing", err)
self.assertFalse(os.path.exists(self.path("outbounds.d/priority.json")))
self.assertEqual(json.loads(ctl.read_text(self.path("outbounds.d/pool.group")))["outbounds"], ["primary"])
# Released, they go through.
ok(ctl.cmd_groups, "members", "pool", "add", "vless-example")
self.assertEqual(json.loads(ctl.read_text(self.path("outbounds.d/pool.group")))["outbounds"], ["primary", "vless-example"])
# rm takes its lock file along; one waiting on the old one locks the new one instead.
lock = self.path("outbounds.d/.pool.group.lock")
ok(ctl.cmd_groups, "rm", "pool")
self.assertFalse(os.path.exists(lock))
opened = []
real_open = os.open
def open_once(path, *a, **kw):
# The first open finds the old, removed lock (as one already waiting holds it).
if path == lock and not opened:
opened.append(path)
stale = real_open(lock, os.O_RDONLY | os.O_CREAT, 0o600)
os.unlink(lock)
return stale
return real_open(path, *a, **kw)
with mock.patch.object(ctl.os, "open", open_once), ctl._file_lock(self.path("outbounds.d/pool.group")) as held:
self.assertTrue(held)
self.assertTrue(os.path.exists(lock))
def test_rm_and_group_edits_stay_in_the_spool(self):
# Root runs these: a tag with ../ in it must not reach files outside the spool.
for name in ("victim.url", "victim.group"):
self.write(name, "{}")
for fn, args in [
(ctl.cmd_outbounds, ("rm", "../victim")),
(ctl.cmd_groups, ("rm", "../victim")),
(ctl.cmd_groups, ("strategy", "../victim", "failover")),
(ctl.cmd_groups, ("members", "../victim", "rm", "a")),
]:
with self.subTest(args=args):
status, _, err = run(fn, *args)
self.assertNotEqual(status, 0)
self.assertIn("Invalid", err)
self.assertTrue(os.path.exists(self.path("victim.url")) and os.path.exists(self.path("victim.group")))
AWG_CONF = """[Interface]
@@ -1417,6 +1658,54 @@ class ZapretAutoTest(EnvTest):
self.assertNotIn("chat.example", ctl.read_text(verdicts))
self.assertIn("discord.com", ctl.read_text(verdicts))
def test_rewrite_keeps_what_nfqws2_appended_meanwhile(self):
"""nfqws2 appends verdicts without our lock: a line it added after the read survives the rename."""
path = self.write("verdicts.tsv", "works\ta.example\ttcp\nunfixable\tb.example\ttcp\n")
mkstemp = tempfile.mkstemp
def appended_meanwhile(*args, **kwargs):
with open(path, "a") as f:
f.write("works\tc.example\ttcp\n")
return mkstemp(*args, **kwargs)
with mock.patch.object(ctl.tempfile, "mkstemp", appended_meanwhile):
ctl._replace_lines(path, lambda line: "b.example" not in line)
self.assertEqual(ctl.read_text(path), "works\ta.example\ttcp\nworks\tc.example\ttcp\n")
def test_rewrites_take_the_lock(self):
"""Another proxy-ctl mid-edit holds .<name>.lock: this one waits for it, then gives up."""
path = self.write("zapret-hosts-auto.txt", "a.example\n")
with open(self.path(".zapret-hosts-auto.txt.lock"), "w") as held:
fcntl.flock(held, fcntl.LOCK_EX)
with mock.patch.object(ctl, "LOCK_WAIT", 0.2):
status, _, err = run(ctl._replace_lines, path, lambda _: False)
self.assertNotEqual(status, 0)
self.assertIn("Something else is still changing", err)
self.assertEqual(ctl.read_text(path), "a.example\n")
# A lock planted as a symlink is not followed: the edit goes ahead without it.
os.unlink(self.path(".zapret-hosts-auto.txt.lock"))
victim = self.write("victim", "")
os.symlink(victim, self.path(".zapret-hosts-auto.txt.lock"))
ctl._replace_lines(path, lambda _: False)
self.assertEqual(ctl.read_text(path), "")
self.assertTrue(os.path.islink(self.path(".zapret-hosts-auto.txt.lock")))
def test_strategy_drop_takes_z2ks_lock(self):
"""z2k writes state.tsv whole under state.tsv.lock: a fresh one is waited for, a stale one taken."""
os.environ.update(ZAPRET_AUTO_ENABLED="1", ZAPRET_STATE_DIR=self.dir)
state = self.write("circular/state.tsv", "rkn_tcp\ta.example\t3\t1\tauto\t\nrkn_tcp\tb.example\t2\t1\tauto\t\n")
lock = self.write("circular/state.tsv.lock", str(int(time.time())))
with mock.patch.object(ctl, "LOCK_WAIT", 0.2):
status, _, err = run(ctl._zapret_strategy_drop, "a.example")
self.assertNotEqual(status, 0)
self.assertIn("zapret2 is still writing", err)
self.assertIn("a.example", ctl.read_text(state))
self.assertTrue(os.path.exists(lock)) # z2k's, not ours to remove
self.write("circular/state.tsv.lock", str(int(time.time()) - 60))
ctl._zapret_strategy_drop("a.example")
self.assertEqual(ctl.read_text(state), "rkn_tcp\tb.example\t2\t1\tauto\t\n")
self.assertFalse(os.path.exists(lock))
class InboundsTest(EnvTest):
def test_stats(self):
@@ -1453,9 +1742,14 @@ class InboundsTest(EnvTest):
self.assertNotEqual(status, 0)
self.assertIn("No traffic recorded yet", err)
def api(self):
"""The stats API's socket, as root (or the daemon's own user) reaches it."""
os.environ["INBOUNDS_API"] = "unix://" + self.write("stats.sock", "")
def test_online(self):
answer = {"users": [{"email": "fufsob", "ips": [{"ip": "203.0.113.7", "lastSeen": 1789471207}]}]}
self.patch("_run", lambda *a, **kw: (0, json.dumps(answer)))
self.api()
os.environ["INBOUNDS_STATS_FILE"] = self.write("stats.json", {"seen": {"phone": 1789135690}})
os.environ["INBOUNDS_LINKS_FILE"] = self.write("links.json", [{"tag": "a", "user": "fufsob"}, {"tag": "a", "user": "teri"}])
out = ok(ctl._inbound_online)
@@ -1466,9 +1760,49 @@ class InboundsTest(EnvTest):
self.patch("_run", lambda *a, **kw: (1, ""))
self.assertNotEqual(run(ctl._inbound_online)[0], 0)
@unittest.skipIf(os.geteuid() == 0, "root reaches any socket")
def test_online_without_the_api(self):
"""A stats member cannot reach the API (it may reset the counters): who was online
comes from the collector's file, read again first."""
self.patch("_run", lambda *a, **kw: self.fail("asked the API"))
started = []
self.patch("systemctl", lambda *a, **kw: started.append(a))
now = 1789471300
self.patch("time", mock.Mock(time=lambda: now))
os.environ["INBOUNDS_API"] = "unix://" + self.write("stats.sock", "")
os.chmod(self.path("stats.sock"), 0o400)
online = [{"email": "fufsob", "ips": [{"ip": "203.0.113.7", "lastSeen": now - 5}]}]
os.environ["INBOUNDS_STATS_FILE"] = self.write("stats.json", {"at": now - 10, "online": online, "seen": {"phone": now - 9000}})
os.environ["INBOUNDS_LINKS_FILE"] = self.write("links.json", [{"tag": "a", "user": "fufsob"}, {"tag": "a", "user": "teri"}])
status, out, err = run(ctl._inbound_online)
self.assertEqual(status, 0)
self.assertEqual(started, [("--no-ask-password", "start", "proxy-suite-inbound-stats.service")])
self.assertRegex(out, r"(?m)^ fufsob +online +203\.0\.113\.7$")
self.assertRegex(out, r"(?m)^ phone +seen ")
self.assertRegex(out, r"(?m)^ teri +never seen")
self.assertNotIn("as of", err)
# A reading a few minutes old says so; one the collector could not refresh is no answer.
self.write("stats.json", {"at": now - 300, "online": online})
status, out, err = run(ctl._inbound_online)
self.assertEqual(status, 0)
self.assertIn("collector's last reading", err)
for stats in ({"at": now - 3600, "online": online}, {"at": now, "seen": {}}):
with self.subTest(stats=stats):
self.write("stats.json", stats)
status, _, err = run(ctl._inbound_online)
self.assertNotEqual(status, 0)
self.assertIn("not answering", err)
# No socket at all: the inbounds are down, whatever the collector last read.
self.write("stats.json", {"at": now - 10, "online": online})
os.unlink(self.path("stats.sock"))
status, _, err = run(ctl._inbound_online)
self.assertNotEqual(status, 0)
self.assertIn("is proxy-suite-inbounds running", err)
def test_online_amneziawg(self):
answer = {"users": [{"email": "fufsob", "ips": [{"ip": "203.0.113.7", "lastSeen": 1789471207}]}]}
self.patch("_run", lambda *a, **kw: (0, json.dumps(answer)))
self.api()
started = []
self.patch("systemctl", lambda *a, **kw: started.append(a))
now = 1789471300
@@ -1566,15 +1900,18 @@ class AppsRunTest(EnvTest):
self.assertIn(f"--slice={base}", scope)
self.assertEqual(scope[-2:], ("curl", "x"))
self.assertIn(("start", f"{base}-user@{os.getuid()}.service"), self.calls)
# Nothing else runs in the slice, so it is torn down afterwards.
self.assertIn(("stop", f"{base}.service"), self.calls)
# Nothing else runs in the slice, so this user's marking goes afterwards.
self.assertIn(("stop", f"{base}-user@{os.getuid()}.service"), self.calls)
self.assertIn(("--user", "stop", f"{base}-anchor.service"), self.calls)
# The backend every user shares: brought up by the marking unit (Requires=), and
# gone after the last one by itself (StopWhenUnneeded=), never stopped here.
self.assertFalse([c for c in self.calls if c[0] in ("start", "stop") and c[-1] == f"{base}.service"])
def test_cleanup_when_scope_fails(self):
self.scope_status = 3
status, _, _ = run(ctl.cmd_apps, "run", "tun", "--", "false")
self.assertEqual(status, 3)
self.assertIn(("stop", "proxy-suite-per-app-tun.service"), self.calls)
self.assertIn(("stop", f"proxy-suite-per-app-tun-user@{os.getuid()}.service"), self.calls)
def test_global_proxy_runs_plain(self):
# A wrapPerApp launcher must still start the app; the global mode carries it.
@@ -1599,11 +1936,12 @@ class AppsRunTest(EnvTest):
self.assertIn(f"--slice={base}", scope)
self.assertEqual(scope[-2:], ("curl", "x"))
self.assertIn(("--user", "start", f"proxy-suite-per-app-via-anchor@{key}.service"), self.calls)
self.assertIn(("start", f"proxy-suite-per-app-via@{key}.service"), self.calls)
self.assertIn(("start", f"proxy-suite-per-app-via-user@{uid}-{key}.service"), self.calls)
self.assertIn(("stop", f"proxy-suite-per-app-via@{key}.service"), self.calls)
listed = next(c for c in self.calls if c[0] == "list-units" and c[-1].startswith("proxy-suite-per-app-via-user@"))
self.assertEqual(listed[-1], f"proxy-suite-per-app-via-user@*-{key}.service")
# The via unit first: the marking goes in its table.
starts = [c[1] for c in self.calls if c[0] == "start"]
self.assertEqual(starts, [f"proxy-suite-per-app-via@{key}.service", f"proxy-suite-per-app-via-user@{uid}-{key}.service"])
# Only this user's marking stops; the last one's takes the via unit down itself.
stops = [c[1] for c in self.calls if c[0] == "stop"]
self.assertEqual(stops, [f"proxy-suite-per-app-via-user@{uid}-{key}.service"])
def test_via_without_pin_slots(self):
status, _, err = run(ctl.cmd_apps, "run", "--via", "nl", "--", "curl")
@@ -1634,9 +1972,8 @@ class AppsRunTest(EnvTest):
self.assertIn(f"--unit=proxy-suite-per-app-via-{key}-{label}-{os.getpid()}", scope)
self.assertIn(("start", f"proxy-suite-per-app-via-{route}@{hexed}.service"), self.calls)
self.assertIn(("start", f"proxy-suite-per-app-via-user@{uid}-{key}.service"), self.calls)
self.assertIn(("stop", f"proxy-suite-per-app-via-{route}@{hexed}.service"), self.calls)
# The per-app TUN backend goes too once nothing uses it; the socks backend stays.
self.assertEqual(("stop", "proxy-suite-per-app-tun.service") in self.calls, route == "tun")
# The pin, and the per-app TUN backend it holds, go by themselves.
self.assertEqual([c[1] for c in self.calls if c[0] == "stop"], [f"proxy-suite-per-app-via-user@{uid}-{key}.service"])
self.assertIn("Unknown outbound: fr", run(ctl.cmd_apps, "run", "--via", "fr", "--", "curl")[2])
self.assertIn("--route is tun or tproxy", run(ctl.cmd_apps, "run", "--via", "nl", "--route", "zapret", "--", "curl")[2])
os.environ["PER_APP_PIN_TUN"] = "0"
@@ -1684,8 +2021,18 @@ class AppsRunTest(EnvTest):
self.assertFalse(os.path.exists(self.path("apps.d/play.json")))
self.assertIn("No app profile", run(ctl.cmd_apps, "rm", "play")[2])
def test_runtime_profiles_read_only_regular_files(self):
# apps.d is the group's: a FIFO or a symlink to /dev/zero would hang or fill root's proxy-ctl.
os.environ["RUNTIME_APPS_DIR"] = self.path("apps.d")
self.write("apps.d/play.json", {"route": "direct"})
self.write("apps.d/big.json", json.dumps({"route": "direct", "pad": "x" * ctl.RUNTIME_APP_MAX_BYTES}))
os.mkfifo(self.path("apps.d/fifo.json"))
os.symlink("/dev/zero", self.path("apps.d/zero.json"))
os.symlink(self.path("apps.d/play.json"), self.path("apps.d/link.json"))
self.assertEqual([p["name"] for p in ctl._runtime_apps()], ["play"])
def test_via_global_awg_profile(self):
# Brought up apart for the app, first, and taken down with the last app through it.
# Brought up apart for the app, first; the last user's marking takes it down.
os.environ.update(PER_APP_VIA_PROFILES="1", AWG_PROFILES_FILE=self.write("awg.json", ["netcup"]))
key = "app-" + "netcup".encode().hex()
status, _, _ = run(ctl.cmd_apps, "run", "--via", "netcup", "--", "curl", "x")
@@ -1694,7 +2041,7 @@ class AppsRunTest(EnvTest):
self.assertEqual(starts[:2], ["proxy-suite-awg-app@netcup.service", f"proxy-suite-per-app-via@{key}.service"])
scope = next(c for c in self.calls if c[0] == "systemd-run")
self.assertIn(f"--slice=proxy-suite-per-app-via-{key}", scope)
self.assertIn(("stop", "proxy-suite-awg-app@netcup.service"), self.calls)
self.assertNotIn(("stop", "proxy-suite-awg-app@netcup.service"), self.calls)
self.assertIn("netcup", ctl._complete_tree("apps", "run", "--via"))
# Up globally, it carries the app as it is.
self.calls.clear()
@@ -1723,11 +2070,13 @@ class AppsRunTest(EnvTest):
self.assertIn("No global AmneziaWG profile 'fr'", run(ctl.cmd_apps, "run", "--via", "awg:fr", "--", "curl")[2])
self.assertIn("--via takes an outbound", run(ctl.cmd_apps, "run", "--via", "wg:nl", "--", "curl")[2])
def test_tun_profile_keeps_backend_for_pins(self):
def test_cleanup_reads_only_own_scopes(self):
# Other users' marking and the pins of per-app TUN are systemd's to weigh
# (StopWhenUnneeded=): cleanup asks only after this user's own apps.
self.calls.clear()
run(ctl.cmd_apps, "run", "tun", "--", "curl")
listed = next(c for c in self.calls if c[0] == "list-units" and "proxy-suite-per-app-tun-user@*.service" in c)
self.assertIn("proxy-suite-per-app-via-tun@*.service", listed)
self.assertFalse([c for c in self.calls if c[0] == "list-units"])
self.assertIn(("--user", "list-units", "--type=scope", "--state=running", "--plain", "--no-legend", "proxy-suite-per-app-tun-*"), self.calls)
def test_via_under_global_tun_runs_plain(self):
self.active = {"proxy-suite-tun.service"}
@@ -2097,6 +2446,16 @@ class TorTest(EnvTest):
self.assertIn("bootstrap unknown", out)
self.assertIn("not running", err)
def test_status_exit_code_is_is_actives(self):
"""`if proxy-ctl tor status` means running: 3 when not, as systemctl says it, and no bootstrap line."""
self.patch("systemctl", lambda *a, **kw: (0, None) if a[0] == "cat" else (3, "inactive\n"))
status, out, _ = run(ctl.cmd_tor)
self.assertEqual(status, 3)
self.assertNotIn("bootstrap", out)
for fn in (ctl.cmd_proxy, ctl.cmd_zapret, ctl.COMMANDS["ssh"]):
with self.subTest(fn=fn):
self.assertEqual(run(fn, "status")[0], 3)
class BadExitTest(EnvTest):
def test_shown_from_state(self):
@@ -2212,6 +2571,14 @@ class StatusSnapshotTest(EnvTest):
self.assertEqual(data["outbound"], "b (pinned)")
self.assertEqual(data["route_mode"], {"available": True, "current": "default", "default": "blacklist"})
def test_unit_states_by_id(self):
blocks = "Id=proxy-suite-tun.service\nLoadState=loaded\nActiveState=failed\n\nId=proxy-suite-socks.service\nLoadState=loaded\nActiveState=active\n"
self.patch("systemctl", lambda *a, **kw: (0, blocks))
# Out of order, one missing: each state still lands on its own unit.
self.assertEqual(ctl._unit_states(["proxy-suite-socks", "proxy-suite-zapret", "proxy-suite-tun"]), {"proxy-suite-socks": "active", "proxy-suite-tun": "failed"})
self.patch("systemctl", lambda *a, **kw: (1, blocks))
self.assertEqual(ctl._unit_states(["proxy-suite-socks"]), {})
def test_warp_over_amneziawg_is_watched(self):
# An outbound WARP profile is no `awg` profile, but its unit can still fail.
self.assertIn("proxy-suite-awg-warp", ctl._snapshot_units())
+26 -4
View File
@@ -109,29 +109,51 @@ class GuiTest(unittest.TestCase):
def test_root_toggle_reads_too(self):
"""A tab only root can read goes through pkexec when the toggle is on, and one refusal stops the asking."""
tab = model.Tab("x", "X", model.ROW, [], list)
app = types.SimpleNamespace(root_read_refused=False)
app = types.SimpleNamespace(root_read_refused=False, root_reads={})
denied = ([], "✗ Cannot read /x - join the proxy-suite group, or re-run with sudo.")
asked = []
def as_root(result):
return mock.patch.object(model, "load_tab_as_root", lambda tab, via: asked.append(via) or result)
load = lambda elevated: gui.ProxySuiteGui.load_tab(app, tab, {}, elevated)
load = lambda elevated, fresh=False: gui.ProxySuiteGui.load_tab(app, tab, {}, elevated, fresh)
with mock.patch.object(model, "load_tab", lambda tab, states: denied), mock.patch.object(model.os, "geteuid", lambda: 1000):
with as_root(([{"key": "a"}], "")):
self.assertIn("Ctrl+E", load(False)[1])
self.assertEqual(asked, [])
self.assertEqual(load(True), ([{"key": "a"}], ""))
self.assertEqual(asked, ["pkexec"])
# A refresh shows that read again: pkexec asks for the password every time.
rows, summary = load(True)
self.assertEqual(rows, [{"key": "a"}])
self.assertIn("F5 to read again", summary)
self.assertEqual(asked, ["pkexec"])
with as_root((None, "authentication cancelled")):
self.assertIn("As root: authentication cancelled", load(True)[1])
self.assertIn("Ctrl+E twice", load(True)[1])
self.assertIn("As root: authentication cancelled", load(True, fresh=True)[1])
self.assertIn("Ctrl+E twice", load(True, fresh=True)[1])
self.assertEqual(len(asked), 2)
with mock.patch.object(model, "load_tab", lambda tab, states: ([], "Nothing here yet.")), as_root(None):
app.root_read_refused = False
self.assertEqual(load(True), ([], "Nothing here yet.")) # readable: no pkexec
self.assertEqual(len(asked), 2)
def test_paste_asks_first(self):
"""A web page can plant a link in the clipboard: Ctrl+V only asks, and runs on yes."""
ran, asked = [], []
app = types.SimpleNamespace(
run_argv=lambda mode, argv, win, stdin=None: ran.append((argv, stdin)),
confirm=lambda argv, then, parent, stdin=None: asked.append((argv, then, stdin)),
)
win = types.SimpleNamespace(app=app, toast=lambda text: None)
clipboard = types.SimpleNamespace(read_text_finish=lambda result: "https://evil.test/s")
page = types.SimpleNamespace(tab=types.SimpleNamespace(id="subs"))
gui.Window.pasted(win, page, clipboard, None)
self.assertEqual(ran, [])
[(argv, then, stdin)] = asked
self.assertEqual((argv, stdin), (["proxy", "subs", "add", "-"], "https://evil.test/s"))
then()
self.assertEqual(ran, [(["proxy", "subs", "add", "-"], "https://evil.test/s")])
def test_every_tray_icon_is_drawn(self):
here = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons")
with tempfile.TemporaryDirectory() as out:
+68 -15
View File
@@ -1,13 +1,17 @@
#!/usr/bin/env python3
"""proxy_model without a front end: the status line and the tray menu turn state into the right proxy-ctl argv."""
import base64
import contextlib
import io
import json
import os
import signal
import subprocess
import tempfile
import time
import unittest
import zlib
from unittest import mock
import proxy_ctl as ctl
@@ -212,7 +216,8 @@ class ModelTest(unittest.TestCase):
self.assertEqual(keys(vk)["Q"].argv(vk), ["wl", "link", "vk", "--qr"])
self.assertEqual(keys(vk)["N"].argv(vk), ["wl", "new", "vk"])
self.assertEqual(keys(vk)["a"].argv(vk, "/tmp/c.json", {}), ["wl", "auth", "vk", "/tmp/c.json"])
self.assertEqual(keys(home)["j"].argv(home, " abc-def ", {}), ["wl", "join", "home", "abc-def"])
self.assertEqual(keys(home)["j"].argv(home, " abc-def ", {}), ["wl", "join", "home", "-"])
self.assertEqual(keys(home)["j"].stdin(home, " abc-def "), "abc-def")
self.assertNotIn("N", keys(dion)) # a fixed link: its linkFile sets the call
self.assertNotIn("A", keys(vk)) # VK logs in only in a browser
self.assertEqual(keys(dion)["A"].argv(dion), ["wl", "auth", "dion"])
@@ -317,16 +322,18 @@ class ModelTest(unittest.TestCase):
def test_paste_argv(self):
paste = model.paste_argv
self.assertEqual(paste("outbounds", " vless://u@de.test:443#DE\n")[0], ["proxy", "outbounds", "add", "vless://u@de.test:443#DE"])
# Links and JSON carry credentials: on stdin, never in argv (ps, pkexec's log).
self.assertEqual(paste("outbounds", " vless://u@de.test:443#DE\n"), (["proxy", "outbounds", "add", "-"], "", "vless://u@de.test:443#DE"))
# The tab pasted onto does not matter for an unambiguous link.
self.assertEqual(paste("services", "ss://x@a.test:8388")[0], ["proxy", "outbounds", "add", "ss://x@a.test:8388"])
self.assertEqual(paste("services", '{"type": "socks",\n "server": "1.2.3.4"}')[0][:3], ["proxy", "outbounds", "add"])
self.assertEqual(paste("services", "ss://x@a.test:8388"), (["proxy", "outbounds", "add", "-"], "", "ss://x@a.test:8388"))
json_text = '{"type": "socks",\n "server": "1.2.3.4"}'
self.assertEqual(paste("services", json_text), (["proxy", "outbounds", "add", "-"], "", json_text))
# http(s) is both a subscription and an HTTP proxy: the tab decides.
self.assertEqual(paste("subs", "https://sub.test/s")[0], ["proxy", "subs", "add", "https://sub.test/s"])
self.assertEqual(paste("services", "https://sub.test/s")[0], ["proxy", "subs", "add", "https://sub.test/s"])
self.assertEqual(paste("outbounds", "https://u:p@proxy.test:8443")[0], ["proxy", "outbounds", "add", "https://u:p@proxy.test:8443"])
self.assertEqual(paste("subs", "https://sub.test/s?token=t"), (["proxy", "subs", "add", "-"], "", "https://sub.test/s?token=t"))
self.assertEqual(paste("services", "https://sub.test/s")[0], ["proxy", "subs", "add", "-"])
self.assertEqual(paste("outbounds", "https://u:p@proxy.test:8443"), (["proxy", "outbounds", "add", "-"], "", "https://u:p@proxy.test:8443"))
# A bare host means something only where a tab collects hosts.
self.assertEqual(paste("zapret", "blocked.example")[0], ["zapret", "auto", "add", "blocked.example"])
self.assertEqual(paste("zapret", "blocked.example"), (["zapret", "auto", "add", "blocked.example"], "", None))
self.assertEqual(paste("autoproxy", "blocked.example")[0], ["proxy", "auto", "learn", "blocked.example"])
for tab, text, why in [
("outbounds", "", "Nothing to paste."),
@@ -386,8 +393,8 @@ class ModelTest(unittest.TestCase):
outbound_add = next(a for a in next(t for t in model.TABS if t.id == "outbounds").actions if a.key == "n")
self.assertEqual(outbound_add.argv(None, "de vpn://AAAA", {}), ["proxy", "outbounds", "add", "de", "-"])
self.assertEqual(outbound_add.stdin(None, "de vpn://AAAA"), "vpn://AAAA")
self.assertEqual(outbound_add.argv(None, "de vless://x", {}), ["proxy", "outbounds", "add", "de", "vless://x"])
self.assertIsNone(outbound_add.stdin(None, "de vless://x"))
self.assertEqual(outbound_add.argv(None, "de vless://x", {}), ["proxy", "outbounds", "add", "de", "-"])
self.assertEqual(outbound_add.stdin(None, "de vless://x"), "vless://x")
def test_popen_feeds_stdin(self):
with mock.patch.object(model, "CTL", "cat"):
@@ -397,6 +404,18 @@ class ModelTest(unittest.TestCase):
self.assertEqual(p.stdout.read(), out)
p.wait()
def test_output_lines_end_soon_after_stop(self):
# A quiet process (root's `logs -f`) stops being read without waiting for its next line.
p = subprocess.Popen(["sh", "-c", "printf 'a\\r\\nb\\rc\\n'; exec sleep 30"], stdout=subprocess.PIPE, text=True, start_new_session=True)
self.addCleanup(lambda: (os.killpg(p.pid, signal.SIGKILL), p.wait()))
lines = model.output_lines(p, poll=0.05)
self.assertEqual([next(lines), next(lines), next(lines)], ["a", "b", "c"])
p.proxy_suite_stopped = True
started = time.monotonic()
self.assertEqual(list(lines), [])
self.assertLess(time.monotonic() - started, 5)
self.assertTrue(p.stdout.closed)
def test_load_tab(self):
tab = next(t for t in model.TABS if t.id == "outbounds")
inventory = {"tags": ["a", "b"], "pinned": "b", "detours": {"a": "b"}, "excluded": ["b"]}
@@ -407,7 +426,8 @@ class ModelTest(unittest.TestCase):
with mock.patch.object(ctl, "env", lambda name, default="": ""):
self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["p", "t", "ctrl+t", "T", "n", "g", "y", "plus", "minus", "h", "H", "x", "s", "c", "Q", "J", "k", "K", "V"])
chain = next(a for a in tab.actions if a.key == "h")
self.assertEqual(chain.argv(rows[1], 'c {"type": "socks"}', {}), ["proxy", "outbounds", "add", "c", '{"type": "socks"}', "--detour", "b"])
self.assertEqual(chain.argv(rows[1], 'c {"type": "socks"}', {}), ["proxy", "outbounds", "add", "c", "-", "--detour", "b"])
self.assertEqual(chain.stdin(rows[1], 'c {"type": "socks"}'), '{"type": "socks"}')
# Probe exits go by the backend's tag.
probe = next(a for a in tab.actions if a.key == "P")
with mock.patch.object(ctl, "env", lambda name, default="": "1" if name == "AUTOPROXY_ENABLED" else ""), mock.patch.object(ctl, "_backend_tags", lambda: {"b": "b-backend"}):
@@ -485,12 +505,45 @@ class ModelTest(unittest.TestCase):
subs = next(t for t in model.TABS if t.id == "subs")
add = next(a for a in subs.actions if a.key == "n")
self.assertIn("[tag]", add.prompt)
self.assertEqual(add.argv(None, "https://x.test/s", {}), ["proxy", "subs", "add", "https://x.test/s"])
self.assertEqual(add.argv(None, " work https://x.test/s ", {}), ["proxy", "subs", "add", "work", "https://x.test/s"])
# The URL, token and all, on stdin.
self.assertEqual((add.argv(None, "https://x.test/s", {}), add.stdin(None, "https://x.test/s")), (["proxy", "subs", "add", "-"], "https://x.test/s"))
self.assertEqual((add.argv(None, " work https://x.test/s ", {}), add.stdin(None, " work https://x.test/s ")), (["proxy", "subs", "add", "work", "-"], "https://x.test/s"))
# Only a tag: proxy-ctl says what is missing.
self.assertEqual((add.argv(None, "work", {}), add.stdin(None, "work")), (["proxy", "subs", "add", "work"], None))
outbounds = next(t for t in model.TABS if t.id == "outbounds")
add = next(a for a in outbounds.actions if a.key == "n")
# JSON has spaces in it: all one argument.
self.assertEqual(add.argv(None, '{"type": "socks"}', {}), ["proxy", "outbounds", "add", '{"type": "socks"}'])
# JSON has spaces in it: all of it on stdin.
self.assertEqual((add.argv(None, '{"type": "socks"}', {}), add.stdin(None, '{"type": "socks"}')), (["proxy", "outbounds", "add", "-"], '{"type": "socks"}'))
def test_shown_commands_hide_credentials(self):
argv = ["proxy", "outbounds", "add", "de", "vless://uuid-1@de.test:443?security=reality&pbk=K&sid=S#DE"]
self.assertEqual(model.shown(argv, "pkexec"), "pkexec proxy-ctl proxy outbounds add de 'vless://***@de.test:443?security=***&pbk=***&sid=***#DE'")
self.assertEqual(model.redact("https://sub.test/api?token=abc and ss://a2V5@h:1"), "https://sub.test/api?token=*** and ss://***@h:1")
self.assertEqual(model.redact("vmess://eyJhZGQiOiJ4In0= then"), "vmess://***@x then")
# Nothing to hide: as it was.
self.assertEqual(model.shown(["proxy", "subs", "add", "-"]), "proxy-ctl proxy subs add -")
self.assertEqual(model.redact("https://example.com/path"), "https://example.com/path")
# The token in a subscription URL's path, and links that are one blob: an AmneziaWG
# vpn:// carries the private key, a legacy ss:// the password.
self.assertEqual(model.redact("https://s.test/sub/0123456789abcdef0123456789abcdef"), "https://s.test/sub/***")
self.assertEqual(model.redact("https://s.test/0123456789abcdef0123456789abcdef"), "https://s.test/***")
self.assertEqual(model.redact("vpn://AAAAAbbbbbCCCCddddEEEE"), "vpn://***")
self.assertEqual(model.redact("ss://YWVzLTEyOC1nY206cGFzc0BoOjE=#n"), "ss://***@h:1")
# The server, never the rest: a blob without one shows none.
vmess = base64.b64encode(json.dumps({"add": "de.test", "port": 443, "id": "uuid-secret", "ps": "DE"}).encode()).decode()
self.assertEqual(model.redact(f"vmess://{vmess}"), "vmess://***@de.test:443")
self.assertEqual(model.redact("ss://" + base64.b64encode(b"aes-128-gcm:12345").decode()), "ss://***")
conf = json.dumps({"containers": [{"awg": {"last_config": json.dumps({"config": "[Interface]\nPrivateKey = k\n[Peer]\nEndpoint = vpn.test:51820\n"})}}]}).encode()
vpn = base64.urlsafe_b64encode(len(conf).to_bytes(4, "big") + zlib.compress(conf)).decode().rstrip("=")
self.assertEqual(model.redact(f"vpn://{vpn}"), "vpn://***@vpn.test:51820")
self.assertEqual(model.redact("socks5://h.test:1080"), "socks5://h.test:1080")
# A paste's confirmation shows where its stdin points, credentials blanked.
subs = ["proxy", "subs", "add", "-"]
self.assertEqual(model.shown(subs, stdin="https://evil.test/s?token=t"), "proxy-ctl proxy subs add - < https://evil.test/s?token=***")
self.assertEqual(model.shown(subs, stdin="https://evil.test/sub/0123456789abcdef0123456789abcdef"), "proxy-ctl proxy subs add - < https://evil.test/sub/***")
self.assertEqual(model.shown(["awg", "add", "-"], stdin="vpn://AAAAAbbbbb"), "proxy-ctl awg add - < vpn://***")
self.assertEqual(model.shown(["awg", "add", "-"], stdin="[Interface]\nPrivateKey = k"), "proxy-ctl awg add - < <a config>")
self.assertEqual(model.shown(["proxy", "outbounds", "add", "-"], stdin='{"uuid": "u"}'), "proxy-ctl proxy outbounds add - < <an outbound's JSON>")
def test_autoproxy_forget_relearn_clear(self):
tab = next(t for t in model.TABS if t.id == "autoproxy")
+212 -1
View File
@@ -1,9 +1,11 @@
import json
import os
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
import time
import unittest
@@ -11,6 +13,16 @@ HERE = os.path.dirname(os.path.abspath(__file__))
SUPERVISOR = os.path.join(HERE, "proxy_supervisor.py")
def stat(pid):
"""/proc/<pid>/stat from its third field (state, ppid, pgrp, ...), or None once it is gone or a zombie."""
try:
with open(f"/proc/{pid}/stat") as f:
fields = f.read().rsplit(")", 1)[1].split()
except OSError:
return None
return None if fields[0] == "Z" else fields
def wait_for(predicate, timeout=10):
deadline = time.time() + timeout
while time.time() < deadline:
@@ -26,6 +38,7 @@ class SupervisorTest(unittest.TestCase):
self.tmp = tempfile.mkdtemp(prefix="proxy-supervisor-")
self.run_dir = os.path.join(self.tmp, "run")
self.manifest = os.path.join(self.tmp, "manifest.json")
self.empty_rule_set = os.path.join(self.tmp, "empty.srs")
self.env = dict(
os.environ,
# Deeper than a socket address holds.
@@ -68,6 +81,19 @@ class SupervisorTest(unittest.TestCase):
},
"Install": {"WantedBy": ["default.target"]},
},
# Its ExecStartPost fails: a failed start, not a crash to restart.
"proxy-suite-post": {
"Unit": {"Description": "failing ExecStartPost"},
"Service": {
"Type": "simple",
"Restart": "on-failure",
"RestartSec": "100ms",
"ExecStartPre": [f'/bin/sh -c "mkdir -p {out}"'],
"ExecStart": sh("exec sleep 1000"),
"ExecStartPost": sh("exit 1"),
"ExecStopPost": sh(f"echo stopped >> {out}/post-stops"),
},
},
"proxy-suite-once": {
"Unit": {"Description": "oneshot", "After": ["proxy-suite-counter.service"]},
"Service": {
@@ -104,10 +130,16 @@ class SupervisorTest(unittest.TestCase):
"Install": {"WantedBy": ["paths.target"]},
},
},
"tmpfiles": [f"d {self.run_dir} 0700 - - -"],
"tmpfiles": [
f"d {self.run_dir} 0700 - - -",
# An empty rule set, copied where none is yet (rulesets.nix).
f"C {os.path.join(self.tmp, 'rule-sets', 'geo.srs')} - - - - {self.empty_rule_set}",
],
}
with open(self.manifest + ".tmp", "w") as f:
json.dump(manifest, f)
with open(self.empty_rule_set, "w") as f:
f.write("{}")
os.replace(self.manifest + ".tmp", self.manifest)
def ctl(self, *args):
@@ -134,6 +166,8 @@ class SupervisorTest(unittest.TestCase):
def test_boot_restart_timers_and_stop(self):
self.assertEqual(self.ctl("boot")[0], 0)
with open(os.path.join(self.tmp, "rule-sets", "geo.srs")) as f:
self.assertEqual(f.read(), "{}")
self.assertTrue(os.path.isdir(self.run_dir))
# Crashed once, restarted, then up.
wait_for(lambda: self.ctl("show", "-p", "SubState", "--value", "proxy-suite-counter")[1].strip() == "running")
@@ -178,6 +212,40 @@ class SupervisorTest(unittest.TestCase):
self.assertEqual(self.read("once"), ["ran"])
def test_failed_start_post_stays_failed(self):
self.assertNotEqual(self.ctl("start", "proxy-suite-post")[0], 0)
time.sleep(1) # time enough for a restart, were the main process's exit taken for a crash
self.assertEqual(self.ctl("is-active", "proxy-suite-post")[1], "failed\n")
self.assertEqual(self.read("post-stops"), ["stopped"])
def test_a_killed_daemon_leaves_nothing_running(self):
"""Android may kill the daemon outright: what it ran is ended, not started again beside it."""
self.write_manifest(crash_times=0)
main_pid = lambda: int(self.ctl("show", "-p", "MainPID", "--value", "proxy-suite-counter")[1])
def kill_daemon(main):
daemon = int(stat(main)[1]) # the main process's parent
os.kill(daemon, signal.SIGKILL)
wait_for(lambda: stat(daemon) is None)
self.assertIsNotNone(stat(main)) # left running, in a session of its own
self.assertEqual(self.ctl("start", "proxy-suite-counter")[0], 0)
old = main_pid()
kill_daemon(old)
# The next daemon ends it before it starts anything.
self.assertEqual(self.ctl("start", "proxy-suite-counter")[0], 0)
self.assertIsNone(stat(old))
new = main_pid()
self.assertNotEqual(new, old)
self.assertEqual(self.read("starts"), ["2"])
self.assertIn("left running by a supervisor that died", self.ctl("journal", "-u", "proxy-suite-counter", "-o", "cat")[1])
# With no daemon at all, stop still reaches it.
kill_daemon(new)
self.assertEqual(self.ctl("stop", "proxy-suite-counter")[0], 0)
self.assertIsNone(stat(new))
os.unlink(os.path.join(self.env["PROXY_SUITE_SUPERVISOR_DIR"], "control.sock")) # the killed daemon's
def test_path_unit_starts_its_service_when_the_file_changes(self):
trigger = os.path.join(self.tmp, "trigger")
# boot brings up the .path unit with the rest of paths.target.
@@ -197,6 +265,149 @@ class SupervisorTest(unittest.TestCase):
time.sleep(1)
self.assertEqual(self.read("watched"), ["changed"])
def test_daemon_dirs_are_private_and_stale_credentials_go(self):
base = self.env["PROXY_SUITE_SUPERVISOR_DIR"]
stale = os.path.join(base, "credentials", "proxy-suite-gone.service")
os.makedirs(stale) # 0755, as makedirs left them before
with open(os.path.join(stale, "key"), "w") as f:
f.write("secret")
self.assertEqual(self.ctl("start", "proxy-suite-tick.timer")[0], 0)
self.assertFalse(os.path.exists(stale))
for path in (base, os.path.join(base, "logs"), os.path.join(base, "credentials")):
self.assertEqual(os.stat(path).st_mode & 0o777, 0o700, path)
class InProcessTest(unittest.TestCase):
"""The Supervisor itself, driven from here, for races a client cannot time."""
def setUp(self):
sys.path.insert(0, HERE)
import proxy_supervisor
self.ps = proxy_supervisor
self.tmp = tempfile.mkdtemp(prefix="proxy-supervisor-")
self.saved = {k: getattr(self.ps, k) for k in ("LOG_DIR", "CREDENTIALS_DIR")}
self.ps.LOG_DIR = os.path.join(self.tmp, "logs")
self.ps.CREDENTIALS_DIR = os.path.join(self.tmp, "credentials")
os.makedirs(self.ps.LOG_DIR)
self.sup = None
def tearDown(self):
if self.sup:
self.sup.shutdown()
for k, v in self.saved.items():
setattr(self.ps, k, v)
shutil.rmtree(self.tmp, ignore_errors=True)
def supervisor(self, services):
path = os.path.join(self.tmp, "manifest.json")
with open(path, "w") as f:
json.dump({"services": services}, f)
self.sup = self.ps.Supervisor(path)
self.sup.groups = self.ps.Groups(os.path.join(self.tmp, "groups.json"))
return self.sup
def path(self, name):
return os.path.join(self.tmp, name)
def pid(self, name):
def read():
try:
with open(self.path(name)) as f:
return int(f.read())
except (OSError, ValueError):
return None
return wait_for(read)
def test_main_exiting_during_stop_leaves_nothing_and_its_pid_unsignalled(self):
"""The main process exits while stop() is still stopping what is bound to it."""
sup = self.supervisor({
"main": {"Service": {"ExecStart": "/bin/sh -c " + json.dumps(
f"sleep 1000 & echo $! > {self.path('left')}; echo $$ > {self.path('main')}; wait")}},
# Its own stop ends main's process, then takes a while.
"bound": {
"Unit": {"PartOf": "main.service"},
"Service": {
"ExecStart": "sleep 1000",
"ExecStop": "/bin/sh -c " + json.dumps(f"kill $(cat {self.path('main')}); sleep 0.5"),
},
},
})
self.assertEqual(sup.start("main"), 0)
self.assertEqual(sup.start("bound"), 0)
left = self.pid("left")
signalled_reaped = []
kill_group = sup.kill_group
def recording(proc, sig):
if proc is not None and proc.returncode is not None:
signalled_reaped.append((proc.pid, sig))
kill_group(proc, sig)
sup.kill_group = recording
self.assertEqual(sup.stop("main"), 0)
self.assertEqual(sup.units["main.service"].state, self.ps.INACTIVE)
self.assertIsNone(sup.units["main.service"].main)
wait_for(lambda: stat(left) is None)
self.assertEqual(signalled_reaped, [])
def test_an_exception_while_activating_fails_the_unit(self):
sup = self.supervisor({"svc": {"Service": {"ExecStart": "sleep 1000"}}})
spawned, spawn = [], sup.spawn
sup.spawn = lambda *a: spawned.append(spawn(*a)[0]) or (spawned[-1], False)
real = threading.Thread
class NoWatch(real):
def start(self):
if getattr(self, "_target", None) == sup.watch:
raise RuntimeError("can't start new thread")
super().start()
self.ps.threading.Thread = NoWatch
try:
self.assertEqual(sup.start("svc"), 1)
finally:
self.ps.threading.Thread = real
unit = sup.units["svc.service"]
self.assertEqual((unit.state, unit.result, unit.main), (self.ps.FAILED, "resources", None))
self.assertIsNotNone(spawned[0].returncode) # ended and reaped
# Not stuck activating: the next start runs.
self.assertEqual(sup.start("svc"), 0)
self.assertEqual(unit.state, self.ps.ACTIVE)
def test_an_unparsable_command_fails_the_start(self):
sup = self.supervisor({"svc": {"Service": {"ExecStartPre": "/bin/sh -c 'unbalanced", "ExecStart": "sleep 1000"}}})
self.assertEqual(sup.start("svc"), 1)
self.assertEqual(sup.units["svc.service"].state, self.ps.FAILED)
def test_start_while_waiting_to_restart_starts_now(self):
sup = self.supervisor({"svc": {"Service": {
"Restart": "on-failure",
"RestartSec": "1h",
"ExecStart": "/bin/sh -c " + json.dumps(
f"[ -e {self.path('ran')} ] && exec sleep 1000; touch {self.path('ran')}; exit 3"),
}}})
self.assertEqual(sup.start("svc"), 0)
unit = sup.units["svc.service"]
wait_for(lambda: unit.state == self.ps.AUTO_RESTART)
self.assertEqual(sup.start("svc"), 0)
self.assertEqual(unit.state, self.ps.ACTIVE)
self.assertIsNotNone(stat(unit.main.pid))
class EnvironmentTest(unittest.TestCase):
def test_services_get_no_shell_proxy_or_preload(self):
# An exported https_proxy would send a subscription fetch through the proxy it is
# starting; LD_PRELOAD would ride into every daemon.
sys.path.insert(0, HERE)
import proxy_supervisor
for key in ("https_proxy", "ALL_PROXY", "LD_PRELOAD", "PYTHONPATH", "SECRET_TOKEN"):
self.assertFalse(proxy_supervisor._inherited(key), key)
for key in ("HOME", "PATH", "LANG", "LC_ALL", "TZ", "SSL_CERT_FILE", "ANDROID_ROOT", "PROOT_TMP_DIR"):
self.assertTrue(proxy_supervisor._inherited(key), key)
if __name__ == "__main__":
unittest.main()
+47 -3
View File
@@ -116,6 +116,37 @@ class TuiTest(unittest.TestCase):
if (tab.id, action.key) not in same_meaning:
self.assertNotIn(action.key, screen, f"{tab.id}: {action.label}")
def test_untrusted_text_is_shown_not_obeyed(self):
"""An escape in a row (OSC 52 sets the clipboard) reaches the screen as text, root's included."""
evil = "a\x1b]52;c;aGk=\x07\x9bb"
self.assertEqual(tui.cell("host", evil).plain, "a\\x1b]52;c;aGk=\\x07\\x9bb")
self.assertEqual(tui.cell("state", "\x1b[2J").plain, "? \\x1b[2J")
tab = mock.Mock(columns=[("host", "Host")])
self.assertNotIn("\x1b", tui.detail(tab, {"host": evil}, []).plain)
self.assertEqual(tui.printable("a\tb\nc"), "a\tb\nc")
# Output keeps its colors and nothing else.
text = tui.Text.from_ansi(tui.printable_ansi(f"\x1b[31mred\x1b[0m {evil}"))
self.assertEqual(text.plain, "red a\\x1b]52;c;aGk=\\x07\\x9bb")
self.assertTrue(text.spans)
def test_trace_file_is_only_ever_our_own(self):
with tempfile.TemporaryDirectory() as run, mock.patch.dict(tui.os.environ, {"XDG_RUNTIME_DIR": run}):
path, other = tui.trace_path(), tui.os.path.join(run, "other")
with tui.open_trace() as trace:
trace.write("ok\n")
# A hard link to a file of ours (root's, under sudo) is not written through.
open(other, "w").close()
tui.os.unlink(path)
tui.os.link(other, path)
self.assertIsNone(tui.open_trace())
tui.os.unlink(path)
tui.os.symlink(other, path)
self.assertIsNone(tui.open_trace())
tui.os.unlink(path)
tui.os.mkfifo(path) # and a fifo neither hangs it nor is written
self.assertIsNone(tui.open_trace())
self.assertEqual(tui.os.path.getsize(other), 0)
def test_failed_load_keeps_the_tui_going(self, rows=None):
async def run():
tui_trace = tempfile.TemporaryDirectory()
@@ -146,9 +177,19 @@ class TuiTest(unittest.TestCase):
await self.settle(app, pilot)
app.main.query_one("#tabs", tui.TabbedContent).active = "outbounds"
await self.settle(app, pilot)
# Nothing is added before a yes: a web page can plant a link in the clipboard.
app.post_message(events.Paste("vless://u@de.test:443#DE"))
await pilot.pause()
self.assertEqual(self.ran.pop(), ["proxy", "outbounds", "add", "vless://u@de.test:443#DE"])
self.assertIsInstance(app.screen, tui.Confirm)
self.assertEqual(app.screen.command, "proxy-ctl proxy outbounds add - < vless://***@de.test:443#DE")
await pilot.press("n")
await pilot.pause()
self.assertEqual(self.ran, [])
app.post_message(events.Paste("vless://u@de.test:443#DE"))
await pilot.pause()
await pilot.press("y")
await pilot.pause()
self.assertEqual(self.ran.pop(), (["proxy", "outbounds", "add", "-"], "vless://u@de.test:443#DE"))
# Whatever else was in the clipboard runs nothing, and the bar says why.
app.post_message(events.Paste("ftp://a.test/x"))
await pilot.pause()
@@ -159,6 +200,9 @@ class TuiTest(unittest.TestCase):
conf = "[Interface]\nPrivateKey = k\n[Peer]\nPublicKey = p"
app.post_message(events.Paste(conf))
await pilot.pause()
self.assertNotIn("PrivateKey", app.screen.command)
await pilot.press("y")
await pilot.pause()
self.assertEqual(self.ran.pop(), (["proxy", "outbounds", "add", "-"], conf))
asyncio.run(run())
@@ -281,10 +325,10 @@ class TuiTest(unittest.TestCase):
self.assertEqual(app.screen.query_one(tui.Choices).highlighted, 1)
await pilot.press("escape")
# Prompts: add takes "<tag> <url>".
# Prompts: add takes "<tag> <url>", the URL on stdin.
await pilot.press("n", *"x vless://h", "enter")
await pilot.pause()
self.assertEqual(self.ran.pop(), ["proxy", "outbounds", "add", "x", "vless://h"])
self.assertEqual(self.ran.pop(), (["proxy", "outbounds", "add", "x", "-"], "vless://h"))
# A prompt remembers what was typed into it last.
await pilot.press("n")
await pilot.pause()
+7 -2
View File
@@ -26,8 +26,9 @@ pkgs.buildGo126Module (finalAttrs: {
"headless/dion-joiner"
"headless/bitrix-joiner"
];
# The call link (WB_LINK) and the local proxy's password (WB_UPSTREAM_PASS) from the
# environment, not argv: these run for good, and every local user reads a command line.
# The call link (WB_LINK), the local proxy's password (WB_UPSTREAM_PASS) and a joiner's
# SOCKS password (WB_SOCKS_PASS) from the environment, not argv: these run for good, and
# every local user reads a command line.
postPatch = ''
envDefault() {
substituteInPlace "headless/$1/main.go" --replace-fail \
@@ -39,6 +40,10 @@ pkgs.buildGo126Module (finalAttrs: {
for p in bitrix dion dion-joiner wbstream wbstream-joiner; do
envDefault $p room WB_LINK
done
# The joiners' SOCKS password (the hop login proxy-suite gives them) likewise.
for p in telemost-joiner wbstream-joiner dion-joiner bitrix-joiner; do
envDefault $p socks-pass WB_SOCKS_PASS
done
envDefault bitrix-joiner link WB_LINK
envDefault telemost tm-link WB_LINK
envDefault telemost-joiner tm-link WB_LINK