diff --git a/README.md b/README.md index b159954..e0da4eb 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,7 @@ See the [options reference](./docs/options/index.md), one page per option group. ```text Usage: proxy-ctl [verb] [args] A group without a verb shows its status or list. +Secrets and changes need root, or the userControl group. status [--json] services and routing mode (--tray: deprecated key=value lines) restart restart active services @@ -125,7 +126,7 @@ A group without a verb shows its status or list. proxy outbounds test [tag...] [--ping] [--delay] [--download] TCP ping, real delay, download speed (default: ping, delay) proxy outbounds link [--qr|--json|--config] - its URL, QR code, backend JSON, or a client config for it (sudo) + its URL, QR code, backend JSON, or a client config for it proxy pin [tag] always use this outbound (no tag: pick from a menu) proxy unpin let the configured selection pick again proxy mode [default|whitelist|blacklist|all-proxy|all-bypass] @@ -133,24 +134,24 @@ A group without a verb shows its status or list. proxy subs [list|update] subscription caches; update refetches them proxy subs add add a subscription at runtime proxy subs rm remove a runtime subscription - proxy subs link [--qr] its URL (sudo) - proxy config [--raw] client config to import elsewhere; --raw: as running (sudo) + proxy subs link [--qr] its URL + proxy config [--raw] client config to import elsewhere; --raw: as running proxy tun [status|on|off] global TUN mode proxy tproxy [status|on|off] global TProxy mode - proxy auto [list] what autoProxy routed, and via which exit (sudo, or userControl) + proxy auto [list] what autoProxy routed, and via which exit proxy auto probe [/path] [--json] [--keep-going] [--exits a,b | --via tag] find an exit that reaches a domain - proxy auto learn probe now and route it if an exit works (sudo) - proxy auto queue [count] destinations waiting to be probed (sudo, or userControl) + proxy auto learn probe now and route it if an exit works + proxy auto queue [count] destinations waiting to be probed zapret [status|on|off] DPI bypass zapret auto [list] hosts zapret2 learned as blocked zapret auto add|forget|exclude - pin, forget, or never learn a host (sudo) - zapret auto unpin|include undo add, or undo exclude (sudo) - zapret auto clear forget learned hosts and strategies (sudo) + pin, forget, or never learn a host + zapret auto unpin|include undo add, or undo exclude + zapret auto clear forget learned hosts and strategies zapret cutoff [status] networks this line cuts at 16 KB, and their names - zapret cutoff probe probe this line again now (sudo) + zapret cutoff probe probe this line again now awg [list] AmneziaWG profiles and their state awg on | off [profile] | restart [profile] @@ -165,10 +166,10 @@ A group without a verb shows its status or list. inbounds [list] server inbounds inbounds link [user] [--qr|--json] client share link, or the client's outbound JSON - inbounds link --server-json the server's inbound JSON (sudo) + inbounds link --server-json the server's inbound JSON inbounds sub [user] [--qr] subscription users, or one user's URL inbounds stats [days] [--by user|inbound|outbound] - traffic per user, listener or exit (sudo, or userControl) + traffic per user, listener or exit inbounds online who is connected now, and when the rest were last seen ``` diff --git a/docs/options/inbounds.md b/docs/options/inbounds.md index fcccad9..81b94a1 100644 --- a/docs/options/inbounds.md +++ b/docs/options/inbounds.md @@ -1045,7 +1045,7 @@ null ## services\.proxy-suite\.inbounds\.shareLinks -Write client share links for ` proxy-ctl inbounds link ` (root and userControl\.group only)\. +Write client share links for ` proxy-ctl inbounds link ` (root, and userControl\.group with the secrets scope)\. *Type:* boolean diff --git a/docs/options/index.md b/docs/options/index.md index be412c9..31853d4 100644 --- a/docs/options/index.md +++ b/docs/options/index.md @@ -258,11 +258,9 @@ services.proxy-suite = { enable = true; }; userControl = { - allow = [ - "global" - "perApp" - ]; + enable = false; group = "proxy-suite"; + scopes = [ ]; }; warp = { asAmneziaWg = false; diff --git a/docs/options/userControl.md b/docs/options/userControl.md index b0d78b5..e61e0a3 100644 --- a/docs/options/userControl.md +++ b/docs/options/userControl.md @@ -5,36 +5,28 @@ Part of the [proxy-suite options reference](./index.md). ## Options - userControl - - [allow](#services-proxy-suite-usercontrol-allow) + - [enable](#services-proxy-suite-usercontrol-enable) - [group](#services-proxy-suite-usercontrol-group) + - [scopes](#services-proxy-suite-usercontrol-scopes) - -## services\.proxy-suite\.userControl\.allow + +## services\.proxy-suite\.userControl\.enable -What userControl\.group may control without a password: - - - “global”: the global units (proxy, tun, tproxy, zapret, restart, subs update)\. - - “perApp”: the per-app backend units used by ` proxy-ctl apps run `\. - Empty grants no passwordless control\. +Whether to enable passwordless ` proxy-ctl ` control for the members of userControl\.group\. *Type:* -list of (one of “global”, “perApp”) +boolean *Default:* ```nix -[ - "global" - "perApp" -] +false ``` *Example:* ```nix -[ - "global" -] +true ``` @@ -50,3 +42,35 @@ string matching the pattern ^\[a-z_]\[a-z0-9_-]\*$ ```nix "proxy-suite" ``` + + +## services\.proxy-suite\.userControl\.scopes + +What userControl\.group may do; empty allows every scope\. + + - “services”: turn the proxy-suite units on and off (proxy, tun, tproxy, zapret, ssh, warp, tg, awg, inbounds), and ` restart `\. + - “perApp”: the per-app backend units used by ` proxy-ctl apps run `\. + - “routing”: ` proxy pin `, ` proxy unpin ` and ` proxy mode `\. + - “outbounds”: add and remove runtime outbounds and subscriptions, and update subscriptions\. + - “secrets”: read share links, subscription URLs and the running configs\. + - “autoProxy”: read what autoProxy learned, and ` proxy auto learn `\. + - “zapret”: edit zapret2’s learned hosts, and ` zapret cutoff probe `\. + - “stats”: ` inbounds stats `\. + +*Type:* +list of (one of “services”, “perApp”, “routing”, “outbounds”, “secrets”, “autoProxy”, “zapret”, “stats”) + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "services" + "routing" +] +``` diff --git a/modules/proxy-suite/autoproxy.nix b/modules/proxy-suite/autoproxy.nix index 4e8835c..77403f2 100644 --- a/modules/proxy-suite/autoproxy.nix +++ b/modules/proxy-suite/autoproxy.nix @@ -7,10 +7,13 @@ cfg, proxyCtl, autoProxyStateDir, + userControlAllows, }: let apCfg = cfg.proxy.autoProxy; + # The autoProxy scope's group writes the directory: `proxy auto learn` queues there. + stateDirMode = if userControlAllows "autoProxy" then "0771" else "0751"; render = import ./autoproxy-render.nix { inherit pkgs; }; jqFile = path: @@ -52,7 +55,7 @@ let echo "sing-box has no Clash API (selection = \"first\"?); nothing to sample" exit 0 fi - install -d -m 0751 "$state_dir" + install -d -m ${stateDirMode} "$state_dir" # Eleven snapshots a second apart: ten one-second deltas per connection. lines=$( @@ -86,7 +89,7 @@ let echo "no probe listeners - is proxy-suite-socks running with autoProxy on?" exit 0 fi - install -d -m 0751 "$state_dir" + install -d -m ${stateDirMode} "$state_dir" # Timer runs and learn requests take turns on the state. exec 9> "$state_dir/lock" @@ -97,6 +100,8 @@ let if [ -e "$requests.taking" ]; then cat "$requests.taking" >> "$requests" rm -f "$requests.taking" + # Made here by root: the group appends to it too. + chmod 0660 "$requests" fi if [ -e "$state" ] && ! jq -e 'type == "object"' "$state" > /dev/null 2>&1; then @@ -392,16 +397,17 @@ let ${render} "$index" "$state" ''; - # Group: `proxy-ctl proxy auto list|queue` reads state.json. Set on every unit that - # declares the directory - systemd re-applies the ownership on each start. + # Group: `proxy-ctl proxy auto list|queue` reads state.json, `learn` queues requests. + # Set on every unit that declares the directory - systemd re-applies the ownership + # on each start. stateDirConfig = { StateDirectory = "proxy-suite/autoproxy"; # 0751 and a 027 umask: sing-box (proxy-suite) can open the rule-sets, which are # made 0644, and nothing else. - StateDirectoryMode = "0751"; + StateDirectoryMode = stateDirMode; UMask = "0027"; } - // lib.optionalAttrs (cfg.userControl.allow != [ ]) { Group = cfg.userControl.group; }; + // lib.optionalAttrs (userControlAllows "autoProxy") { Group = cfg.userControl.group; }; mkUnit = description: args: { inherit description; diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index 85aaf7e..29378ca 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -192,7 +192,11 @@ let # The cut-off networks no whitelisted name fixes go through the proxy outbound. zapretCutoffProxyFallback = zapretCutoffEnabled && zapretCfg.zapret2.cutoff.proxyFallback && hasAvailableOutbounds; - userControlEnabled = userControlCfg.allow != [ ]; + userControlEnabled = userControlCfg.enable; + # Whether the group holds a scope; no scopes listed means all of them. + userControlAllows = + scope: + userControlEnabled && (userControlCfg.scopes == [ ] || builtins.elem scope userControlCfg.scopes); constants = { # Daemons (sing-box, XRay, the WARP tunnel, OpenSSH, tg-ws-proxy, wgcf) run as this # user. Its group is not the userControl group: backend configs hold credentials. Start @@ -333,6 +337,7 @@ in zapretCutoffProxyFallback userControlCfg userControlEnabled + userControlAllows sshProxyCfg sshProxyOutboundTag sshProxyOutboundEnabled diff --git a/modules/proxy-suite/options/inbounds.nix b/modules/proxy-suite/options/inbounds.nix index 6a5d1d6..0b0d358 100644 --- a/modules/proxy-suite/options/inbounds.nix +++ b/modules/proxy-suite/options/inbounds.nix @@ -36,7 +36,7 @@ in }; openFirewall = bool true "Open every non-loopback listener port."; - shareLinks = bool true "Write client share links for `proxy-ctl inbounds link` (root and userControl.group only)."; + shareLinks = bool true "Write client share links for `proxy-ctl inbounds link` (root, and userControl.group with the secrets scope)."; subscriptions = { enable = mkEnableOption "" // { diff --git a/modules/proxy-suite/options/removed.nix b/modules/proxy-suite/options/removed.nix index 821ce2b..fa30ddf 100644 --- a/modules/proxy-suite/options/removed.nix +++ b/modules/proxy-suite/options/removed.nix @@ -66,8 +66,9 @@ in (rm "tgWsProxy.logBackups" "Use services.proxy-suite.tgWsProxy.log.keep.") # userControl. - (rm "userControl.global.enable" ''Use services.proxy-suite.userControl.allow, which lists "global" by default.'') - (rm "userControl.perApp.enable" ''Use services.proxy-suite.userControl.allow, which lists "perApp" by default.'') + (rm "userControl.global.enable" ''Use services.proxy-suite.userControl.enable, with "services" in userControl.scopes.'') + (rm "userControl.perApp.enable" ''Use services.proxy-suite.userControl.enable, with "perApp" in userControl.scopes.'') + (rm "userControl.allow" "Use services.proxy-suite.userControl.enable, and userControl.scopes to limit it.") ] ++ lib.mapAttrsToList ( old: new: rm "zapret.${old}" "Use services.proxy-suite.zapret.zapret-discord-youtube.${new}." diff --git a/modules/proxy-suite/options/user-control.nix b/modules/proxy-suite/options/user-control.nix index 1ce63b2..610d6ff 100644 --- a/modules/proxy-suite/options/user-control.nix +++ b/modules/proxy-suite/options/user-control.nix @@ -5,30 +5,43 @@ let in { options.services.proxy-suite.userControl = { + enable = lib.mkEnableOption "passwordless `proxy-ctl` control for the members of userControl.group"; + group = mkOption { type = types.strMatching "^[a-z_][a-z0-9_-]*$"; default = "proxy-suite"; description = "Group whose members may run privileged `proxy-ctl` commands without a password."; }; - allow = mkOption { + scopes = mkOption { type = types.listOf ( types.enum [ - "global" + "services" "perApp" + "routing" + "outbounds" + "secrets" + "autoProxy" + "zapret" + "stats" ] ); - default = [ - "global" - "perApp" - ]; + default = [ ]; description = '' - What userControl.group may control without a password: - - "global": the global units (proxy, tun, tproxy, zapret, restart, subs update). + What userControl.group may do; empty allows every scope. + - "services": turn the proxy-suite units on and off (proxy, tun, tproxy, zapret, ssh, warp, tg, awg, inbounds), and `restart`. - "perApp": the per-app backend units used by `proxy-ctl apps run`. - Empty grants no passwordless control. + - "routing": `proxy pin`, `proxy unpin` and `proxy mode`. + - "outbounds": add and remove runtime outbounds and subscriptions, and update subscriptions. + - "secrets": read share links, subscription URLs and the running configs. + - "autoProxy": read what autoProxy learned, and `proxy auto learn`. + - "zapret": edit zapret2's learned hosts, and `zapret cutoff probe`. + - "stats": `inbounds stats`. ''; - example = [ "global" ]; + example = [ + "services" + "routing" + ]; }; }; } diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index abb4e9b..7ab8011 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -84,6 +84,9 @@ let (mkAssertion (cfg.userControl.group != derived.constants.serviceUser) "proxy-suite: userControl.group must not be ${derived.constants.serviceUser}, the group that can read backend configs" ) + (mkAssertion (cfg.userControl.scopes == [ ] || cfg.userControl.enable) + "proxy-suite: userControl.scopes is set but userControl.enable is false, so the group gets nothing" + ) (requireEnabled (cfg.warp.enable && cfg.warp.asOutbound != null) proxyEnabled "proxy-suite: warp.asOutbound requires proxy.enable = true" ) diff --git a/modules/proxy-suite/service/context.nix b/modules/proxy-suite/service/context.nix index 20e23f1..35bd72d 100644 --- a/modules/proxy-suite/service/context.nix +++ b/modules/proxy-suite/service/context.nix @@ -56,7 +56,7 @@ let proxyInboundsNeedLocalProxy proxyInboundsGuardPrivate proxyInboundViaOutbounds - userControlEnabled + userControlAllows ; # Tool paths – defined once here and passed into sub-modules as needed. @@ -88,9 +88,7 @@ let builders = import ./builders.nix { inherit lib pkgs; }; - polkit = import ./polkit.nix { - inherit lib cfg userControlCfg; - }; + polkit = import ./polkit.nix { inherit userControlCfg; }; scripts = import ./scripts.nix { inherit @@ -135,7 +133,7 @@ let proxyInboundsNeedLocalProxy proxyInboundsGuardPrivate proxyInboundViaOutbounds - userControlEnabled + userControlAllows builders ; }; diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index 5d6e48b..058f743 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -62,6 +62,7 @@ let perAppRoutingTproxy userControlCfg userControlEnabled + userControlAllows perAppZapretEnabled sshProxyOutboundEnabled sshProxyUnitEnabled @@ -129,6 +130,7 @@ let inherit lib pkgs cfg; inherit (control) proxyCtl; inherit (constants) autoProxyStateDir; + inherit userControlAllows; } ); in @@ -170,36 +172,51 @@ lib.mkMerge [ "${userControlCfg.group}" = { }; }; - security.polkit.enable = lib.mkIf (cfg.enable && userControlEnabled) true; - security.polkit.extraConfig = lib.mkIf (cfg.enable && userControlEnabled) ( - lib.mkAfter '' - polkit.addRule(function(action, subject) { - if (!subject.isInGroup("${userControlCfg.group}")) { + security.polkit.enable = lib.mkIf (cfg.enable && (userControlEnabled || cfg.gui.enable)) true; + # The GUI's "Retry as Root" and root toggle run proxy-ctl through pkexec: one + # admin password then covers the next few minutes, as sudo's does in the TUI. + security.polkit.extraConfig = lib.mkMerge [ + (lib.mkIf (cfg.enable && cfg.gui.enable) ( + lib.mkAfter '' + polkit.addRule(function(action, subject) { + if (action.id === "org.freedesktop.policykit.exec" && + action.lookup("program") === "${control.proxyCtl}/bin/proxy-ctl") { + return polkit.Result.AUTH_ADMIN_KEEP; + } return null; - } + }); + '' + )) + (lib.mkIf (cfg.enable && userControlEnabled) ( + lib.mkAfter '' + polkit.addRule(function(action, subject) { + if (!subject.isInGroup("${userControlCfg.group}")) { + return null; + } + + if (action.id !== "org.freedesktop.systemd1.manage-units") { + return null; + } + + var unit = action.lookup("unit"); + ${polkit.userControlPolkitRules} - if (action.id !== "org.freedesktop.systemd1.manage-units") { return null; - } - - var unit = action.lookup("unit"); - ${polkit.userControlPolkitRules} - - return null; - }); - '' - ); + }); + '' + )) + ]; # Spool dirs for outbounds and subscriptions added at runtime. Setgid so the - # files proxy-ctl drops here inherit the group; without userControl only root - # writes them. tmpfiles rather than the start scripts, so the group can add an + # files proxy-ctl drops here inherit the group; without the outbounds scope + # only root writes them. tmpfiles rather than the start scripts, so the group can add an # outbound before the proxy has ever run. systemd.tmpfiles.rules = lib.mkIf (cfg.enable && proxyEnabled) ( map ( dir: "d ${dir} ${ - if userControlEnabled then "2770 root ${userControlCfg.group}" else "0700 root root" + if userControlAllows "outbounds" then "2770 root ${userControlCfg.group}" else "0700 root root" } -" ) [ diff --git a/modules/proxy-suite/service/polkit.nix b/modules/proxy-suite/service/polkit.nix index ff82347..6503cbf 100644 --- a/modules/proxy-suite/service/polkit.nix +++ b/modules/proxy-suite/service/polkit.nix @@ -1,26 +1,35 @@ -# Polkit rules granting proxy-suite group members passwordless control over services. -{ - lib, - cfg, - userControlCfg, -}: +# Polkit rule body granting userControl group members passwordless control over the +# units of their scopes. +{ userControlCfg }: let - userControlEnabled = userControlCfg.allow != [ ]; - - userControlPolkitRules = - lib.optionalString (builtins.elem "perApp" userControlCfg.allow) '' - if (unit.indexOf("proxy-suite-per-app-") === 0) { - return polkit.Result.YES; - } - '' - + lib.optionalString (builtins.elem "global" userControlCfg.allow) '' - if (unit.indexOf("proxy-suite-") === 0 && - unit.indexOf("proxy-suite-per-app-") !== 0) { - return polkit.Result.YES; - } - ''; + # Units a narrower scope starts; every other proxy-suite unit is "services". + scopeByUnitPrefix = { + "proxy-suite-per-app-" = "perApp"; + "proxy-suite-outbound-pin@" = "routing"; + "proxy-suite-outbound-unpin." = "routing"; + "proxy-suite-route-mode@" = "routing"; + "proxy-suite-outbound-reload." = "outbounds"; + "proxy-suite-subscription-update." = "outbounds"; + "proxy-suite-autoproxy-learn." = "autoProxy"; + "proxy-suite-zapret2-cutoff." = "zapret"; + "proxy-suite-inbound-stats." = "stats"; + }; in { - inherit userControlEnabled userControlPolkitRules; + userControlPolkitRules = '' + var scopeByUnitPrefix = ${builtins.toJSON scopeByUnitPrefix}; + var scope = unit.indexOf("proxy-suite-") === 0 ? "services" : null; + for (var prefix in scopeByUnitPrefix) { + if (unit.indexOf(prefix) === 0) { + scope = scopeByUnitPrefix[prefix]; + break; + } + } + // No scopes listed means all of them. + var scopes = ${builtins.toJSON userControlCfg.scopes}; + if (scope !== null && (scopes.length === 0 || scopes.indexOf(scope) !== -1)) { + return polkit.Result.YES; + } + ''; } diff --git a/modules/proxy-suite/service/proxy-inbounds-scripts.nix b/modules/proxy-suite/service/proxy-inbounds-scripts.nix index 4f2d65f..232243f 100644 --- a/modules/proxy-suite/service/proxy-inbounds-scripts.nix +++ b/modules/proxy-suite/service/proxy-inbounds-scripts.nix @@ -8,7 +8,7 @@ proxyInboundsNeedLocalProxy, proxyInboundViaOutbounds, userControlCfg, - userControlEnabled, + userControlAllows, localProxyAuth, localProxyAuthEnabled, localProxyAuthPasswordSource, @@ -91,10 +91,10 @@ let writeLinksBlock = lib.optionalString proxyInboundsCfg.shareLinks '' ${jq} -c '.links' <<< "$RENDERED" > "${linksFile}" - ${lib.optionalString userControlEnabled '' + ${lib.optionalString (userControlAllows "secrets") '' ${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${linksFile}" ''} - chmod ${if userControlEnabled then "640" else "600"} "${linksFile}" + chmod ${if userControlAllows "secrets" then "640" else "600"} "${linksFile}" ''; # One file per user for the web server, plus a token index for proxy-ctl. Filled aside @@ -113,10 +113,10 @@ let rm -rf "$SUB_DIR" mv "$SUB_DIR.new" "$SUB_DIR" ${jq} -c '[.subscriptions[] | {user, token}]' <<< "$RENDERED" > "${subscriptionsFile}" - ${lib.optionalString userControlEnabled '' + ${lib.optionalString (userControlAllows "secrets") '' ${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${subscriptionsFile}" ''} - chmod ${if userControlEnabled then "640" else "600"} "${subscriptionsFile}" + chmod ${if userControlAllows "secrets" then "640" else "600"} "${subscriptionsFile}" ''; startInbounds = pkgs.writeShellScript "proxy-suite-inbounds" '' @@ -177,8 +177,20 @@ let done < <(${jq} -r '[.inbounds[].streamSettings.tlsSettings.certificates[]? | (.certificateFile, .keyFile) | strings] | unique[]' "$RUNTIME_DIR/config.json.tmp") - ${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$RUNTIME_DIR/config.json.tmp" - chmod 640 "$RUNTIME_DIR/config.json.tmp" + # Read by XRay as ${constants.serviceUser}, and by the userControl group: the daemon + # as owner then, since a file has one group. + ${ + if userControlAllows "secrets" then + '' + ${pkgs.coreutils}/bin/chown ${constants.serviceUser}:${lib.escapeShellArg userControlCfg.group} "$RUNTIME_DIR/config.json.tmp" + chmod 440 "$RUNTIME_DIR/config.json.tmp" + '' + else + '' + ${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$RUNTIME_DIR/config.json.tmp" + chmod 640 "$RUNTIME_DIR/config.json.tmp" + '' + } mv "$RUNTIME_DIR/config.json.tmp" "$RUNTIME_DIR/config.json" ${writeLinksBlock} @@ -213,11 +225,11 @@ let path = ../inbound-stats-add.jq; } } "$file" > "$tmp" - ${lib.optionalString userControlEnabled '' + ${lib.optionalString (userControlAllows "stats") '' ${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$tmp" || echo "proxy-suite: group ${userControlCfg.group} cannot read the stats; they stay root-only" >&2 ''} - chmod ${if userControlEnabled then "640" else "600"} "$tmp" + chmod ${if userControlAllows "stats" then "640" else "600"} "$tmp" mv -f "$tmp" "$file" ''; in diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index da442d0..2dc35f2 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -32,7 +32,7 @@ proxyInboundsNeedLocalProxy, proxyInboundsGuardPrivate, proxyInboundViaOutbounds, - userControlEnabled, + userControlAllows, buildInboundPy, proxyInboundsFile, proxyInboundsSpecFile, @@ -162,6 +162,7 @@ let proxyCfg perAppRoutingCfg userControlCfg + userControlAllows globalTproxy xrayEnabled hybridEnabled @@ -199,7 +200,7 @@ let proxyInboundsNeedLocalProxy proxyInboundViaOutbounds userControlCfg - userControlEnabled + userControlAllows localProxyAuth localProxyAuthEnabled localProxyAuthPasswordSource diff --git a/modules/proxy-suite/service/start-scripts.nix b/modules/proxy-suite/service/start-scripts.nix index e7b0261..6d77c04 100644 --- a/modules/proxy-suite/service/start-scripts.nix +++ b/modules/proxy-suite/service/start-scripts.nix @@ -5,6 +5,7 @@ proxyCfg, perAppRoutingCfg, userControlCfg, + userControlAllows, globalTproxy, xrayEnabled, hybridEnabled, @@ -41,6 +42,8 @@ let autoProxyRender = import ../autoproxy-render.nix { inherit pkgs; }; runBackend = constants.runAsServiceUser pkgs constants.backendCaps; + userControlGroup = lib.escapeShellArg userControlCfg.group; + chgrp = "${pkgs.coreutils}/bin/chgrp"; routeModeBlacklistTail = if pureXrayEnabled then @@ -207,8 +210,9 @@ let AUTOPROXY_RULES_JSON='[]' ${lib.optionalString enableAutoProxy '' AUTOPROXY_DIR=${lib.escapeShellArg autoProxyStateDir} - # 0751: sing-box, running as ${constants.serviceUser}, reads the rule-sets inside. - install -d -m 0751 "$AUTOPROXY_DIR" + # 0751: sing-box, running as ${constants.serviceUser}, reads the rule-sets inside; + # 0771 with userControl's autoProxy scope, whose group queues learn requests there. + install -d -m ${if userControlAllows "autoProxy" then "0771" else "0751"} "$AUTOPROXY_DIR" [ -s "$AUTOPROXY_DIR/state.json" ] || echo '{"domains":{},"hosts":{},"exits":{},"backlog":{}}' > "$AUTOPROXY_DIR/state.json" # direct is always exit 0; state is keyed by tag, so shifting indices are @@ -263,7 +267,7 @@ let ' <<< "$OUTBOUNDS_JSON" > "$ENDPOINTS_TMP" # Where each proxy server is: not credentials, but not for every local user either. ${ - if userControlCfg.allow != [ ] || localProxyAuthEnabled then + if userControlCfg.enable || localProxyAuthEnabled then '' ${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$ENDPOINTS_TMP" chmod 640 "$ENDPOINTS_TMP" @@ -274,7 +278,7 @@ let mv "$ENDPOINTS_TMP" "$RUNTIME_DIR/outbound-endpoints.json" # proxy-ctl's share links: the URL each outbound was given, and its backend JSON. - # Credentials, so root only, whatever userControl allows. + # Credentials: root and the userControl group only. SHARE_TMP="$RUNTIME_DIR/outbound-share.json.tmp" (umask 077 && ${jq} -c --argjson sidecar "''${XRAY_OUTBOUNDS_JSON:-[]}" --arg collapsed "''${PROXY_TAG:-}" \ --argjson urls "$OUTBOUND_URLS_JSON" --argjson subs "$SUBSCRIPTION_URLS_JSON" ' @@ -285,7 +289,8 @@ let | from_entries), subscriptions: $subs} ' <<< "$OUTBOUNDS_JSON" > "$SHARE_TMP") - chmod 600 "$SHARE_TMP" + ${lib.optionalString (userControlAllows "secrets") ''${chgrp} ${userControlGroup} "$SHARE_TMP"''} + chmod ${if userControlAllows "secrets" then "640" else "600"} "$SHARE_TMP" mv "$SHARE_TMP" "$RUNTIME_DIR/outbound-share.json" ${lib.optionalString (!pureXrayEnabled) '' @@ -313,7 +318,8 @@ let # rule-set path and reloads the file when the probe renames a new one in. if [ "$ROUTE_MODE" != all-bypass ]; then CUTOFF_RULE_SET=${lib.escapeShellArg "${constants.zapret2CutoffDir}/proxy.json"} - install -d -m 0755 "$(dirname "$CUTOFF_RULE_SET")" + # The cutoff unit owns the directory's mode (the group asks for probes there). + mkdir -p "$(dirname "$CUTOFF_RULE_SET")" [ -s "$CUTOFF_RULE_SET" ] || echo '{"version":1,"rules":[]}' > "$CUTOFF_RULE_SET" chmod 644 "$CUTOFF_RULE_SET" AUTOPROXY_RULE_SETS_JSON=$(${jq} -c --arg p "$CUTOFF_RULE_SET" \ @@ -353,11 +359,23 @@ let "$RUNTIME_DIR/config.json" > "$RUNTIME_DIR/config.json.next" mv "$RUNTIME_DIR/config.json.next" "$RUNTIME_DIR/config.json" ''} - # The backend runs as ${constants.serviceUser}: its configs are group-readable. + # Credentials, read by the backend running as ${constants.serviceUser}. With + # userControl its group reads them too; a file has one group, so the daemon + # reads as owner then. for backend_config in "$RUNTIME_DIR/config.json" "$RUNTIME_DIR/xray-sidecar.json"; do [ -e "$backend_config" ] || continue - ${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$backend_config" - chmod ${if enableLocalProxyAuth then "640" else "g+r"} "$backend_config" + ${ + if userControlAllows "secrets" then + '' + ${pkgs.coreutils}/bin/chown ${constants.serviceUser}:${userControlGroup} "$backend_config" + chmod 440 "$backend_config" + '' + else + '' + ${chgrp} ${constants.serviceUser} "$backend_config" + chmod 640 "$backend_config" + '' + } done FAKE_IP_CACHE=$(${jq} -r '.experimental.cache_file.path? // empty' "$RUNTIME_DIR/config.json") if [ -n "$FAKE_IP_CACHE" ]; then diff --git a/modules/proxy-suite/zapret2.nix b/modules/proxy-suite/zapret2.nix index 83c15ca..1bac874 100644 --- a/modules/proxy-suite/zapret2.nix +++ b/modules/proxy-suite/zapret2.nix @@ -16,7 +16,7 @@ let zapretCfg = cfg.zapret; perAppZapretCfg = cfg.perAppRouting.zapret; cutoffCfg = zapretCfg.zapret2.cutoff; - inherit (import ./derived.nix { inherit lib cfg; }) constants; + inherit (import ./derived.nix { inherit lib cfg; }) constants userControlAllows; # Global AmneziaWG profiles only: an outbound one leaves the host's routes alone. awgServiceNames = map (name: "proxy-suite-awg-${name}.service") ( builtins.attrNames (lib.filterAttrs (_: profile: profile.asOutbound == null) cfg.amneziaWg.profiles) @@ -71,10 +71,13 @@ let if tunInterfaces != [ ] then runtime.mkCustomScript { inherit tunInterfaces; } else null; }; - # nfqws2 and proxy-ctl expect the list files to exist. + # nfqws2 and proxy-ctl expect the list files to exist. With userControl its group + # edits them: proxy-ctl renames a new list in, so the directories are what it writes. mkPreStart = '' ${lib.getExe' pkgs.kmod "modprobe"} nfnetlink_queue 2>/dev/null || true - install -d -m 0755 ${runtime.stateDir} ${runtime.circularStateDir} + install -d -m ${ + if userControlAllows "zapret" then "2775 -g ${lib.escapeShellArg cfg.userControl.group}" else "0755" + } ${runtime.stateDir} ${runtime.circularStateDir} touch ${runtime.autoHostlistFile} ${runtime.userHostlistFile} ${runtime.excludeHostlistFile} ''; diff --git a/modules/proxy-suite/zapret2/cutoff.nix b/modules/proxy-suite/zapret2/cutoff.nix index 82f1ea2..9139d40 100644 --- a/modules/proxy-suite/zapret2/cutoff.nix +++ b/modules/proxy-suite/zapret2/cutoff.nix @@ -12,7 +12,7 @@ }: let - inherit (import ../derived.nix { inherit lib cfg; }) constants; + inherit (import ../derived.nix { inherit lib cfg; }) constants userControlAllows; z2k = zapret2Sources.z2k; lists = "${z2k}/files/lists"; dir = constants.zapret2CutoffDir; @@ -156,6 +156,11 @@ in ExecStartPre = "${exempt}"; ExecStart = "${probe}"; ExecStopPost = "-${nft} delete table inet ${table}"; + } + # The group's `proxy-ctl zapret cutoff probe` drops its `force` file here. + // lib.optionalAttrs (userControlAllows "zapret") { + Group = cfg.userControl.group; + StateDirectoryMode = "2775"; }; }; diff --git a/nix/checks/amnezia-wg.nix b/nix/checks/amnezia-wg.nix index f7fb7e6..ace6b66 100644 --- a/nix/checks/amnezia-wg.nix +++ b/nix/checks/amnezia-wg.nix @@ -25,6 +25,7 @@ let system.stateVersion = "26.05"; services.proxy-suite = { enable = true; + userControl.enable = true; amneziaWg = { enable = true; kernelModulePackage = null; diff --git a/nix/checks/gui.nix b/nix/checks/gui.nix index e36010a..b4a75cf 100644 --- a/nix/checks/gui.nix +++ b/nix/checks/gui.nix @@ -60,6 +60,18 @@ in assert builtins.match ".*/bin/proxy-suite-gui --hidden$" unit.serviceConfig.ExecStart != null; true ) + ( + # pkexec of this proxy-ctl, and only it, keeps the admin password for a while. + let + rules = guiFixture.config.security.polkit.extraConfig; + in + assert guiFixture.config.security.polkit.enable; + assert + builtins.match ''.*action\.lookup\("program"\) === "/nix/store/[^"]*proxy-ctl/bin/proxy-ctl".*AUTH_ADMIN_KEEP.*'' rules + != null; + assert builtins.match ".*AUTH_ADMIN_KEEP.*" tuiOffFixture.config.security.polkit.extraConfig == null; + true + ) ( assert !(guiManualFixture.config.systemd.user.services ? proxy-suite-gui); assert !(tuiOffFixture.config.systemd.user.services ? proxy-suite-gui); diff --git a/nix/checks/per-app-routing-tun.nix b/nix/checks/per-app-routing-tun.nix index fa46365..a2b4c1e 100644 --- a/nix/checks/per-app-routing-tun.nix +++ b/nix/checks/per-app-routing-tun.nix @@ -148,10 +148,9 @@ in true ) - # -- perAppRouting: app TUN enables nftables and user control group -- + # -- perAppRouting: app TUN enables nftables -- ( assert perAppRoutingTunFixture.config.networking.nftables.enable; - assert perAppRoutingTunFixture.config.users.groups ? "proxy-suite"; true ) ]; diff --git a/nix/checks/proxy-inbounds.nix b/nix/checks/proxy-inbounds.nix index 6e18a64..bd780b3 100644 --- a/nix/checks/proxy-inbounds.nix +++ b/nix/checks/proxy-inbounds.nix @@ -186,13 +186,13 @@ let fixture: (import ./read-generated.nix).readDerivation fixture.config.systemd.services."proxy-suite-inbound-stats".serviceConfig.ExecStart; - noControlFixture = evalProxySuite [ + controlFixture = evalProxySuite [ baseModule { services.proxy-suite = { inbounds.enable = true; inbounds.listeners.vless-in = realityListener; - userControl.allow = [ ]; + userControl.enable = true; }; } ]; @@ -571,10 +571,10 @@ let # The collected stats are group-readable with userControl, root-only without. ( - assert lib.hasInfix "chgrp proxy-suite \"$tmp\"" (statsScript relayFixture); - assert lib.hasInfix "chmod 640 \"$tmp\"" (statsScript relayFixture); - assert !lib.hasInfix "chgrp" (statsScript noControlFixture); - assert lib.hasInfix "chmod 600 \"$tmp\"" (statsScript noControlFixture); + assert lib.hasInfix "chgrp proxy-suite \"$tmp\"" (statsScript controlFixture); + assert lib.hasInfix "chmod 640 \"$tmp\"" (statsScript controlFixture); + assert !lib.hasInfix "chgrp" (statsScript relayFixture); + assert lib.hasInfix "chmod 600 \"$tmp\"" (statsScript relayFixture); true ) diff --git a/nix/checks/subscriptions-runtime.nix b/nix/checks/subscriptions-runtime.nix index e552e28..3f2f57d 100644 --- a/nix/checks/subscriptions-runtime.nix +++ b/nix/checks/subscriptions-runtime.nix @@ -188,15 +188,15 @@ in true ) - # Runtime spool dirs are group-writable and setgid, so proxy-ctl needs no sudo. + # Runtime spool dirs are root-only unless userControl grants outbounds (see user-control.nix). ( assert builtins.any ( - rule: builtins.match "d /var/lib/proxy-suite/outbounds\\.d 2770 root .*" rule != null + rule: builtins.match "d /var/lib/proxy-suite/outbounds\\.d 0700 root root -" rule != null ) minimal.config.systemd.tmpfiles.rules; assert builtins.any ( - rule: builtins.match "d /var/lib/proxy-suite/subscriptions\\.d 2770 root .*" rule != null + rule: builtins.match "d /var/lib/proxy-suite/subscriptions\\.d 0700 root root -" rule != null ) minimal.config.systemd.tmpfiles.rules; true ) diff --git a/nix/checks/user-control.nix b/nix/checks/user-control.nix index 8317dec..09149fa 100644 --- a/nix/checks/user-control.nix +++ b/nix/checks/user-control.nix @@ -5,129 +5,129 @@ }: let - userControlDefaultFixture = evalProxySuite [ - baseModule - { - services.proxy-suite = { - perAppRouting = { - enable = true; - createDefaultProfiles = true; - tun.enable = true; - }; - }; - } - ]; - userControlDefaultPolkitConfig = userControlDefaultFixture.config.security.polkit.extraConfig; + inherit (pkgs.lib) hasInfix; - userControlGlobalOnlyFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.userControl.allow = [ "global" ]; - } - ]; - userControlGlobalOnlyPolkitConfig = userControlGlobalOnlyFixture.config.security.polkit.extraConfig; - - userControlPerAppOnlyFixture = evalProxySuite [ - baseModule - { - services.proxy-suite = { - perAppRouting = { - enable = true; - createDefaultProfiles = true; - tun.enable = true; - }; - userControl.allow = [ "perApp" ]; - }; - } - ]; - userControlPerAppOnlyPolkitConfig = userControlPerAppOnlyFixture.config.security.polkit.extraConfig; - - userControlDisabledFixture = evalProxySuite [ - baseModule - { - services.proxy-suite.userControl.allow = [ ]; - } - ]; - - # Every unit declaring the autoProxy state directory must carry the group, or - # the next start chowns it back and `proxy auto list|queue` loses its read. - mkAutoProxyFixture = - extra: + mkFixture = + userControl: evalProxySuite [ baseModule { services.proxy-suite = { + perAppRouting = { + enable = true; + createDefaultProfiles = true; + tun.enable = true; + }; proxy.autoProxy.enable = true; - } - // extra; + inherit userControl; + }; } ]; + + allFixture = mkFixture { enable = true; }; + routingOnlyFixture = mkFixture { + enable = true; + scopes = [ "routing" ]; + }; + otherGroupFixture = mkFixture { + enable = true; + group = "vpnops"; + }; + disabledFixture = mkFixture { }; + scopesWithoutEnableFixture = mkFixture { scopes = [ "routing" ]; }; + + polkitConfig = fixture: fixture.config.security.polkit.extraConfig; + service = fixture: name: fixture.config.systemd.services.${name}.serviceConfig; + + # Every unit declaring the autoProxy state directory must carry the group, or + # the next start chowns it back and `proxy auto list|queue` loses its read. autoProxyGroups = fixture: - map (unit: fixture.config.systemd.services.${unit}.serviceConfig.Group or null) [ + map (unit: (service fixture unit).Group or null) [ "proxy-suite-autoproxy" "proxy-suite-autoproxy-learn" "proxy-suite-autoproxy-sample" ]; + + socksStart = + fixture: + (import ./read-generated.nix).readDerivation (service fixture "proxy-suite-socks").ExecStart; + + groupReadsSecrets = + fixture: + let + start = socksStart fixture; + in + hasInfix "chmod 440 \"$backend_config\"" start && hasInfix "chmod 640 \"$SHARE_TMP\"" start; + rootOnlySecrets = + fixture: + let + start = socksStart fixture; + in + hasInfix "chmod 640 \"$backend_config\"" start + && hasInfix "chmod 600 \"$SHARE_TMP\"" start + && !(hasInfix "g+r" start); in { assertions = [ - # -- userControl: default polkit rule covers both per-app and global proxy-ctl managed units -- + # -- userControl: enabled without scopes grants every scope -- ( - assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-per-app-\") === 0" - userControlDefaultPolkitConfig; - assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-\") === 0" userControlDefaultPolkitConfig; - assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-per-app-\") !== 0" - userControlDefaultPolkitConfig; - true - ) - - # -- userControl: global-only rule excludes per-app units -- - ( - assert userControlGlobalOnlyFixture.config.users.groups ? "proxy-suite"; - assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-\") === 0" userControlGlobalOnlyPolkitConfig; - assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-per-app-\") !== 0" - userControlGlobalOnlyPolkitConfig; + assert allFixture.config.users.groups ? "proxy-suite"; + assert hasInfix "var scopes = [];" (polkitConfig allFixture); + assert hasInfix "subject.isInGroup(\"proxy-suite\")" (polkitConfig allFixture); + assert hasInfix "\"proxy-suite-zapret2-cutoff.\":\"zapret\"" (polkitConfig allFixture); + assert groupReadsSecrets allFixture; + assert hasInfix "chown proxy-suite-daemon:proxy-suite \"$backend_config\"" (socksStart allFixture); assert - builtins.match ".*unit\\.indexOf\\(\"proxy-suite-per-app-\"\\) === 0.*" userControlGlobalOnlyPolkitConfig - == null; - true - ) - - # -- userControl: per-app-only rule covers per-app-scoped helpers only -- - ( - assert userControlPerAppOnlyFixture.config.users.groups ? "proxy-suite"; - assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-per-app-\") === 0" - userControlPerAppOnlyPolkitConfig; - assert - builtins.match ".*unit\\.indexOf\\(\"proxy-suite-per-app-\"\\) !== 0.*" userControlPerAppOnlyPolkitConfig - == null; - assert - builtins.match ".*unit\\.indexOf\\(\"proxy-suite-\"\\) === 0.*" userControlPerAppOnlyPolkitConfig - == null; - true - ) - - # -- userControl: the autoProxy state directory is group-owned, and only then -- - ( - assert - autoProxyGroups (mkAutoProxyFixture { }) == [ + autoProxyGroups allFixture == [ "proxy-suite" "proxy-suite" "proxy-suite" ]; + assert (service allFixture "proxy-suite-autoproxy").StateDirectoryMode == "0771"; + assert builtins.elem "d /var/lib/proxy-suite/outbounds.d 2770 root proxy-suite -" ( + allFixture.config.systemd.tmpfiles.rules + ); + true + ) + + # -- userControl: the group name follows userControl.group -- + ( assert - autoProxyGroups (mkAutoProxyFixture { - userControl.group = "vpnops"; - }) == [ + autoProxyGroups otherGroupFixture == [ "vpnops" "vpnops" "vpnops" ]; + assert hasInfix "subject.isInGroup(\"vpnops\")" (polkitConfig otherGroupFixture); + true + ) + + # -- userControl: a listed scope grants only itself -- + ( + assert hasInfix "var scopes = [\"routing\"];" (polkitConfig routingOnlyFixture); + assert rootOnlySecrets routingOnlyFixture; assert - autoProxyGroups (mkAutoProxyFixture { - userControl.allow = [ ]; - }) == [ + autoProxyGroups routingOnlyFixture == [ + null + null + null + ]; + assert (service routingOnlyFixture "proxy-suite-autoproxy").StateDirectoryMode == "0751"; + assert builtins.elem "d /var/lib/proxy-suite/outbounds.d 0700 root root -" ( + routingOnlyFixture.config.systemd.tmpfiles.rules + ); + true + ) + + # -- userControl: off by default, with no group, polkit rule or grants -- + ( + assert !(disabledFixture.config.users.groups ? "proxy-suite"); + assert !(hasInfix "subject.isInGroup(\"proxy-suite\")" (polkitConfig disabledFixture)); + assert !(hasInfix "org.freedesktop.systemd1.manage-units" (polkitConfig disabledFixture)); + assert rootOnlySecrets disabledFixture; + assert + autoProxyGroups disabledFixture == [ null null null @@ -135,16 +135,11 @@ in true ) - # -- userControl: disabling both scopes removes group and polkit wiring -- + # -- userControl: scopes without enable is refused, not silently ignored -- ( - assert !(userControlDisabledFixture.config.users.groups ? "proxy-suite"); - assert !userControlDisabledFixture.config.security.polkit.enable; - assert - builtins.match ".*subject\\.isInGroup\\(\"proxy-suite\"\\).*" userControlDisabledFixture.config.security.polkit.extraConfig - == null; - assert - builtins.match ".*org\\.freedesktop\\.systemd1\\.manage-units.*" userControlDisabledFixture.config.security.polkit.extraConfig - == null; + assert builtins.any ( + a: !a.assertion && hasInfix "userControl.scopes is set" a.message + ) scopesWithoutEnableFixture.config.assertions; true ) ]; diff --git a/pkgs/proxy-ctl.nix b/pkgs/proxy-ctl.nix index 4657b44..b87e4ac 100644 --- a/pkgs/proxy-ctl.nix +++ b/pkgs/proxy-ctl.nix @@ -109,7 +109,8 @@ let proxyCtl pkgs.systemd ] - }" ${envFlags} + }" \ + --suffix PATH : /run/wrappers/bin ${envFlags} ''; }; guiPython = pkgs.python3.withPackages (ps: [ ps.pygobject3 ]); @@ -194,6 +195,7 @@ let pkgs.qrencode ] }" \ + --suffix PATH : /run/wrappers/bin \ --set PROXY_GUI_ICON_DIR "$out/share/proxy-suite-gui/icons" \ --set PROXY_GUI_REFRESH ${toString guiRefreshInterval} ${envFlags} ''; diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index 5095d20..ea9fa03 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -45,6 +45,7 @@ RESTART_SERVICES = [ HELP = """\ Usage: proxy-ctl [verb] [args] A group without a verb shows its status or list. +Secrets and changes need root, or the userControl group. status [--json] services and routing mode (--tray: deprecated key=value lines) restart restart active services @@ -60,7 +61,7 @@ A group without a verb shows its status or list. proxy outbounds test [tag...] [--ping] [--delay] [--download] TCP ping, real delay, download speed (default: ping, delay) proxy outbounds link [--qr|--json|--config] - its URL, QR code, backend JSON, or a client config for it (sudo) + its URL, QR code, backend JSON, or a client config for it proxy pin [tag] always use this outbound (no tag: pick from a menu) proxy unpin let the configured selection pick again proxy mode [default|whitelist|blacklist|all-proxy|all-bypass] @@ -68,24 +69,24 @@ A group without a verb shows its status or list. proxy subs [list|update] subscription caches; update refetches them proxy subs add add a subscription at runtime proxy subs rm remove a runtime subscription - proxy subs link [--qr] its URL (sudo) - proxy config [--raw] client config to import elsewhere; --raw: as running (sudo) + proxy subs link [--qr] its URL + proxy config [--raw] client config to import elsewhere; --raw: as running proxy tun [status|on|off] global TUN mode proxy tproxy [status|on|off] global TProxy mode - proxy auto [list] what autoProxy routed, and via which exit (sudo, or userControl) + proxy auto [list] what autoProxy routed, and via which exit proxy auto probe [/path] [--json] [--keep-going] [--exits a,b | --via tag] find an exit that reaches a domain - proxy auto learn probe now and route it if an exit works (sudo) - proxy auto queue [count] destinations waiting to be probed (sudo, or userControl) + proxy auto learn probe now and route it if an exit works + proxy auto queue [count] destinations waiting to be probed zapret [status|on|off] DPI bypass zapret auto [list] hosts zapret2 learned as blocked zapret auto add|forget|exclude - pin, forget, or never learn a host (sudo) - zapret auto unpin|include undo add, or undo exclude (sudo) - zapret auto clear forget learned hosts and strategies (sudo) + pin, forget, or never learn a host + zapret auto unpin|include undo add, or undo exclude + zapret auto clear forget learned hosts and strategies zapret cutoff [status] networks this line cuts at 16 KB, and their names - zapret cutoff probe probe this line again now (sudo) + zapret cutoff probe probe this line again now awg [list] AmneziaWG profiles and their state awg on | off [profile] | restart [profile] @@ -100,10 +101,10 @@ A group without a verb shows its status or list. inbounds [list] server inbounds inbounds link [user] [--qr|--json] client share link, or the client's outbound JSON - inbounds link --server-json the server's inbound JSON (sudo) + inbounds link --server-json the server's inbound JSON inbounds sub [user] [--qr] subscription users, or one user's URL inbounds stats [days] [--by user|inbound|outbound] - traffic per user, listener or exit (sudo, or userControl) + traffic per user, listener or exit inbounds online who is connected now, and when the rest were last seen """ @@ -163,6 +164,15 @@ def readable(path): return bool(path) and os.access(path, os.R_OK) +def ask_group(): + """What lets a refused user in: root, or userControl's group with the scope for it.""" + return f"join the {env('USER_CONTROL_GROUP', 'proxy-suite')} group, or re-run with sudo" + + +def denied(path, what="read"): + die(f"Cannot {what} {path} - {ask_group()}.") + + def _run(argv, capture=False, quiet=False, stdin=None): """Runs argv; (exit status, stdout if captured). A missing binary is 127.""" sys.stdout.flush() @@ -937,7 +947,7 @@ def cmd_outbounds_test(*args): try: endpoints = read_json(_runtime_file("outbound-endpoints.json")) except PermissionError: - notes.append("ping: cannot read the servers - enable userControl, or run with sudo.") + notes.append(f"ping: cannot read the servers - {ask_group()}.") except (OSError, ValueError): pass test = {} @@ -1006,9 +1016,9 @@ def _outbounds_list(): # --- sharing ------------------------------------------------------------------ # -# The socks start script writes outbound-share.json, root only: the URL each outbound -# was given (none for one declared as JSON, WARP or SSH) and its backend JSON. A URL is -# never rebuilt from JSON. `proxy config` turns the running config into one another +# The socks start script writes outbound-share.json, root and userControl's group only: +# the URL each outbound was given (none for one declared as JSON, WARP or SSH) and its +# backend JSON. A URL is never rebuilt from JSON. `proxy config` turns the running config into one another # device can import (proxy_export). @@ -1016,7 +1026,7 @@ def _read_root_json(path, what): if not os.path.isfile(path): die(f"No {what} yet - is proxy-suite-socks running?") if not readable(path): - die(f"Cannot read {path} - re-run with sudo.") + denied(path) return read_json(path) @@ -1211,7 +1221,7 @@ def _runtime_entry_add(kind, tag="", url="", *_, detour=""): with open(path, "w", encoding="utf-8") as f: f.write(f"{url}\n") except OSError: - die(f"Cannot write {path} - join the {env('USER_CONTROL_GROUP', 'proxy-suite')} group, or re-run with sudo.") + denied(path, "write") finally: os.umask(old) _runtime_reload() @@ -1231,7 +1241,7 @@ def _runtime_entry_rm(kind, tag="", *_): except FileNotFoundError: pass except OSError: - die(f"Cannot remove {path} - join the {env('USER_CONTROL_GROUP', 'proxy-suite')} group, or re-run with sudo.") + denied(path, "remove") _runtime_reload() print(f"Removed {kind}: {tag}") @@ -1731,7 +1741,7 @@ def _require_autoproxy_readable(path): if not os.path.isdir(path): die("No autoProxy state yet - the prober has not completed a run.") if not os.access(path, os.R_OK | os.X_OK): - die(f"Cannot read {path} - enable userControl, or run with sudo.") + denied(path) def _autoproxy_state(path): @@ -1866,7 +1876,7 @@ def cmd_proxy_learn(host="", *_): with open(requests, "a", encoding="utf-8") as f: f.write(f"{host}\n") except OSError: - die(f"Cannot write {requests} - re-run with sudo.") + denied(requests, "write") print(f"Probing {host} through each exit...") if systemctl("start", "proxy-suite-autoproxy-learn.service", quiet=True)[0]: sys.stdout.flush() @@ -1911,7 +1921,7 @@ def _replace_lines(path, keep, extra=()): old = lines(read_text(path)) if os.path.exists(path) else [] fd, tmp = tempfile.mkstemp(prefix=os.path.basename(path) + ".", dir=os.path.dirname(path) or ".") except OSError: - die(f"Cannot write {path} - re-run with sudo.") + denied(path, "write") try: with os.fdopen(fd, "w", encoding="utf-8") as f: f.writelines(f"{line}\n" for line in [*filter(keep, old), *extra]) @@ -1922,7 +1932,7 @@ def _replace_lines(path, keep, extra=()): os.unlink(tmp) except OSError: pass - die(f"Cannot replace {path} - re-run with sudo.") + denied(path, "replace") def _zapret_auto_edit(path, domain, action): @@ -1951,10 +1961,7 @@ def _zapret_strategy_drop(domain): def _truncate(path): - try: - open(path, "w").close() - except OSError: - die(f"Cannot write {path} - re-run with sudo.") + _replace_lines(path, lambda _: False) def cmd_zapret_auto(verb="list", domain="", *_): @@ -2021,7 +2028,7 @@ def cmd_zapret_cutoff(verb="status", *_): try: open(os.path.join(path, "force"), "w").close() except OSError: - die(f"Cannot write {path} - re-run with sudo.") + denied(path, "write") print("Probing this line; this takes a few minutes...") if systemctl("start", "proxy-suite-zapret2-cutoff.service")[0]: die("The probe failed. Details: journalctl -u proxy-suite-zapret2-cutoff -n 30") @@ -2205,7 +2212,7 @@ def cmd_where(domain="", *_): if env("INBOUNDS_ENABLED") == "1": inbounds_path = "/run/proxy-suite-inbounds/config.json" if not readable(inbounds_path): - _where_row("inbounds", "routing is not readable - run with sudo") + _where_row("inbounds", f"routing is not readable - {ask_group()}") else: try: tag, why = _where_inbounds(read_json(inbounds_path), domain, geosite_dir) @@ -2217,7 +2224,7 @@ def cmd_where(domain="", *_): if env("AUTOPROXY_ENABLED") == "1": if not readable(os.path.join(_autoproxy_dir(), "state.json")): - _where_row("autoProxy", "state is not readable - enable userControl, or run with sudo") + _where_row("autoProxy", f"state is not readable - {ask_group()}") else: domains = _autoproxy_state(_autoproxy_dir()).get("domains") hit = _where_in(domains if isinstance(domains, dict) else {}, domain) @@ -2418,7 +2425,7 @@ def _inbound_links(): if not os.path.isfile(path): die("No share links available. Is proxy-suite-inbounds running, and is inbounds.shareLinks enabled?") if not readable(path): - die("Share links are not readable by this user. Enable userControl, or run as root.") + denied(path) return read_json(path) @@ -2428,7 +2435,7 @@ def _inbound_server_json(tag): if not os.path.isfile(path): die("No inbound config yet - is proxy-suite-inbounds running?") if not readable(path): - die(f"Cannot read {path} - re-run with sudo.") + denied(path) inbound = next((x for x in read_json(path).get("inbounds") or [] if x.get("tag") == tag), None) if inbound is None: die(f"Unknown inbound: {tag}") @@ -2487,7 +2494,7 @@ def _inbound_stats(*args): if not os.path.exists(path): die("No traffic recorded yet - the collector runs every 5 minutes.") if not readable(path): - die(f"Cannot read {path} - enable userControl, or run with sudo.") + denied(path) stats = read_json(path) since = (_today() - datetime.timedelta(days=int(days) - 1)).isoformat() print(f"Traffic through the inbounds since {since}, by {kind}:") @@ -2560,7 +2567,7 @@ def _inbound_online(): for user, (state, addresses) in presence.items(): print(row.format(user, state, addresses)) sys.stdout.flush() - print("A user counts as online while a connection is open; one relayed through a local web server shows as never seen.", file=sys.stderr) + print("A user counts as online while a connection is open; one relayed through a local web server shows as never seen unless it sets X-Forwarded-For.", file=sys.stderr) def _inbound_subscriptions(*args): @@ -2577,7 +2584,7 @@ def _inbound_subscriptions(*args): if not os.path.isfile(path): die("No subscriptions available. Is proxy-suite-inbounds running, and is inbounds.subscriptions enabled?") if not readable(path): - die("Subscriptions are not readable by this user. Enable userControl, or run as root.") + denied(path) subs = read_json(path) if not user: if qr: diff --git a/pkgs/proxy-ctl/proxy_gui.py b/pkgs/proxy-ctl/proxy_gui.py index 3005d93..874dd5a 100644 --- a/pkgs/proxy-ctl/proxy_gui.py +++ b/pkgs/proxy-ctl/proxy_gui.py @@ -67,6 +67,7 @@ GLOBAL_SHORTCUTS = [ ("w", "How is a domain routed"), ("l", "Follow all logs"), ("o", "Output of the last command"), + ("e", "Run actions as root (pkexec)"), ("F5 r", "Refresh now"), ("question", "Keyboard shortcuts"), ("w", "Close the window (the tray keeps running)"), @@ -637,6 +638,10 @@ class OutputDialog(Adw.Dialog): self.stop = Gtk.Button(label="Stop", css_classes=["destructive-action"], visible=False, valign=Gtk.Align.CENTER) self.stop.connect("clicked", lambda *_: self.terminate()) header.pack_end(self.stop) + self.retry_with = None # () -> run it again as root + self.retry = Gtk.Button(label="Retry as Root", css_classes=["suggested-action"], visible=False, valign=Gtk.Align.CENTER) + self.retry.connect("clicked", lambda *_: (self.close(), self.retry_with())) + header.pack_end(self.retry) self.spinner = Adw.Spinner(visible=False) header.pack_end(self.spinner) self.result = Gtk.Label(visible=False, valign=Gtk.Align.CENTER) @@ -676,14 +681,16 @@ class OutputDialog(Adw.Dialog): self.tags[name].set_property("foreground_rgba", rgba(dark_color if dark else light_color)) self.tags["dim"].set_property("foreground_rgba", rgba("#9a9996" if dark else "#77767b")) - def running(self, proc): + def running(self, proc, stoppable=True): self.proc = proc - self.stop.set_visible(True) + self.stop.set_visible(stoppable) # a run as root is not ours to stop self.spinner.set_visible(True) - def finished(self, status=0): + def finished(self, status=0, retry=None): self.stop.set_visible(False) self.spinner.set_visible(False) + self.retry.set_visible(retry is not None) + self.retry_with = retry if status == -signal.SIGTERM: text, classes = "stopped", ["dim-label"] elif status: @@ -733,6 +740,7 @@ class Window(Adw.ApplicationWindow): self.pages = {} self.typed = {} # action label -> what was last typed there self.last_output = None # (title, text) + self.last_retry = None # () -> the last run again as root, when only root could do it self.toasts = Adw.ToastOverlay() view = Adw.ToolbarView(top_bar_style=Adw.ToolbarStyle.RAISED) @@ -748,6 +756,8 @@ class Window(Adw.ApplicationWindow): self.refresh_stack.add_named(Adw.Spinner(halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER), "busy") self.busy_timer = None header.pack_start(self.refresh_stack) + self.root_badge = Gtk.Image(icon_name="dialog-password-symbolic", tooltip_text="Actions run as root (Ctrl+E)", visible=app.elevated(), css_classes=["warning"]) + header.pack_start(self.root_badge) menu = Gio.Menu() section = Gio.Menu() section.append("How is a domain routed…", "win.where") @@ -755,6 +765,9 @@ class Window(Adw.ApplicationWindow): section.append("Output of the last command", "win.last-output") menu.append_section(None, section) section = Gio.Menu() + section.append("Run actions as root", "app.elevated") + menu.append_section(None, section) + section = Gio.Menu() section.append("Keyboard Shortcuts", "win.shortcuts") section.append("About Proxy Suite", "win.about") section.append("Quit", "app.quit") @@ -807,6 +820,7 @@ class Window(Adw.ApplicationWindow): action.connect("activate", callback) self.add_action(action) app.set_accels_for_action("win.filter", ["f"]) + app.set_accels_for_action("app.elevated", ["e"]) app.set_accels_for_action("win.shortcuts", ["question"]) app.set_accels_for_action("app.reload", ["F5"]) app.set_accels_for_action("app.quit", ["q"]) @@ -910,7 +924,10 @@ class Window(Adw.ApplicationWindow): def show_last_output(self): if self.last_output: - OutputDialog(self, *self.last_output).present(self) + dialog = OutputDialog(self, *self.last_output) + dialog.retry.set_visible(self.last_retry is not None) + dialog.retry_with = self.last_retry + dialog.present(self) else: self.toast("Nothing has run yet.") return True @@ -950,9 +967,12 @@ class Window(Adw.ApplicationWindow): dialog.present(self) entry.grab_focus() - def toast(self, message, output=None): + def toast(self, message, output=None, retry=None): toast = Adw.Toast(title=GLib.markup_escape_text(message), timeout=6) - if output: + if retry: # one button: the output stays a keypress away (o) + toast.set_button_label("Retry as Root") + toast.connect("button-clicked", lambda *_: retry()) + elif output: toast.set_button_label("Output") toast.connect("button-clicked", lambda *_: OutputDialog(self, *output).present(self)) self.toasts.add_toast(toast) @@ -1023,6 +1043,12 @@ class ProxySuiteGui(Adw.Application): action = Gio.SimpleAction.new(name, None) action.connect("activate", callback) self.add_action(action) + elevated = Gio.SimpleAction.new_stateful("elevated", None, GLib.Variant.new_boolean(False)) + elevated.connect("change-state", self.on_elevated) + self.add_action(elevated) + retry = Gio.SimpleAction.new("retry-root", GLib.VariantType.new("as")) + retry.connect("activate", lambda _, argv: self.run_argv("run", argv.unpack(), None, root=True)) + self.add_action(retry) self.hold() # the tray and notifications outlive the window try: from proxy_sni import StatusNotifierItem @@ -1058,6 +1084,14 @@ class ProxySuiteGui(Adw.Application): # --- window ------------------------------------------------------------------------------ + def elevated(self): + return self.lookup_action("elevated").get_state().get_boolean() + + def on_elevated(self, action, value): + action.set_state(value) + if self.window: + self.window.root_badge.set_visible(value.get_boolean()) + def present(self, tab=None): if self.window is None: self.window = Window(self) @@ -1169,9 +1203,12 @@ class ProxySuiteGui(Adw.Application): dialog.connect("response", lambda _, r: r == "run" and then()) dialog.present(parent) - def run_argv(self, mode, argv, win): - """run: a toast; dialog, suspend, pause: output streamed into a dialog; copy: the last line to the clipboard.""" - command = f"proxy-ctl {shlex.join(argv)}" + def run_argv(self, mode, argv, win, root=False): + """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.""" + root = (root or self.elevated()) and argv[:1] != ["apps"] + command = f"{'pkexec ' if root else ''}proxy-ctl {shlex.join(argv)}" + retry_argv = argv qr = "--qr" in argv if qr: argv = [a for a in argv if a != "--qr"] @@ -1181,14 +1218,14 @@ class ProxySuiteGui(Adw.Application): dialog.present(win) elif win is not None: win.toast(f"… {command}") - threading.Thread(target=self.stream, args=(command, argv, mode, win, dialog, qr), daemon=True).start() + threading.Thread(target=self.stream, args=(command, argv, mode, win, dialog, qr, root, retry_argv), daemon=True).start() - def stream(self, command, argv, mode, win, dialog, qr): + def stream(self, command, argv, mode, win, dialog, qr, root, retry_argv): out = [] try: - p = model.popen(argv) + p = model.popen(argv, "pkexec" if root else None) if dialog: - GLib.idle_add(lambda: dialog.running(p) and False) + GLib.idle_add(lambda: dialog.running(p, stoppable=not root) and False) for line in p.stdout: out.append(line.rstrip("\n")) if dialog: @@ -1197,16 +1234,20 @@ class ProxySuiteGui(Adw.Application): except OSError as e: out.append(f"cannot run proxy-ctl: {e}") status = 127 - GLib.idle_add(lambda: self.ran(command, mode, win, dialog, qr, out, status) and False) + 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) and False) - def ran(self, command, mode, win, dialog, qr, out, status): + def ran(self, command, mode, win, dialog, qr, out, status, retry_argv): last = last_line(out) text = "\n".join(out) output = (command, text) + retry = (lambda: self.run_argv(mode, retry_argv, win, root=True)) if model.needs_root(out, status) else None if win is not None: win.last_output = output + win.last_retry = retry if dialog: - dialog.finished(status) + dialog.finished(status, retry) if status == -signal.SIGTERM: dialog.write("\x1b[2m(stopped)\x1b[0m") elif status: @@ -1218,12 +1259,14 @@ class ProxySuiteGui(Adw.Application): win.copy_text(last, f"Copied: {last}") else: message = f"{last} ({command})" if last else command - win.toast(f"exit {status}: {message}" if status else message, output if len(out) > 1 or status else None) + win.toast(f"exit {status}: {message}" if status else message, output if len(out) > 1 or status 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_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) self.reload() diff --git a/pkgs/proxy-ctl/proxy_model.py b/pkgs/proxy-ctl/proxy_model.py index b20c633..6e98d97 100644 --- a/pkgs/proxy-ctl/proxy_model.py +++ b/pkgs/proxy-ctl/proxy_model.py @@ -8,6 +8,7 @@ die() cannot take a front end down. import os import re import shlex +import shutil import signal import subprocess import sys @@ -83,6 +84,20 @@ def needs_confirm(action, row): return action.confirm(row) if callable(action.confirm) else action.confirm +# What proxy-ctl and systemctl print when only root may do it. +# ponytail: matches the wording; an exit status of its own (77) if that ever drifts. +ROOT_HINT = re.compile(r"re-run with sudo|run with sudo|run as root|Interactive authentication required|Access denied") + + +def is_root(): + return os.geteuid() == 0 + + +def needs_root(out, status): + """A failed run that root could do: the front ends offer to retry it elevated.""" + return bool(status) and status > 0 and not is_root() and any(ROOT_HINT.search(line) for line in out) + + STATE_ICONS = {"active": "●", "inactive": "○", "failed": "✗", "activating": "◐", "deactivating": "◐", "reloading": "◐"} @@ -281,7 +296,7 @@ def snapshot(states): def status_items(states): """(label, value, style) for the status line: style is "", "ok", "warn" or "bad".""" - items = [] + items = [("", "root", "warn")] if is_root() else [] overall = ctl._overall_state(snapshot(states) if states else None) items.append(("", overall["label"], {"failed": "bad", "busy": "warn", "unknown": "bad"}.get(overall["badge"], ""))) if "proxy-suite-socks" in states: @@ -406,7 +421,7 @@ TABS = [ prompt=" ", ), Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"], confirm=True), - # Credentials: proxy-ctl refuses these without root, and the dialog says so. + # Credentials: proxy-ctl refuses these without root or the group, and the dialog says so. Action("l", "its URL", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=ROW, mode="dialog"), Action("c", "copy its URL", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=ROW, mode="copy"), Action("Q", "its URL as QR", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--qr"], when=ROW, mode="dialog"), @@ -492,7 +507,8 @@ TABS = [ Tab( "apps", "Apps", - _enabled("PER_APP_ROUTING_ENABLED"), + # `apps run` is per user (its uid, systemctl --user): nothing a root session can use. + lambda states: not is_root() and _enabled("PER_APP_ROUTING_ENABLED")(states), [("profile", "Profile"), ("route", "Route")], app_rows, actions=[ @@ -537,10 +553,16 @@ def _capture(argv): return p.stdout + p.stderr -def popen(argv): - """proxy-ctl with its output streamed: its own process group, so stop() takes down what it spawned too.""" +def elevated(argv, via): + """proxy-ctl argv run as root through via (sudo, pkexec): by its full path, the one the polkit rule names.""" + return [via, shutil.which(CTL) or CTL, *argv] + + +def popen(argv, root=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.""" return subprocess.Popen( - [CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, + elevated(argv, root) if root else [CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, text=True, errors="replace", start_new_session=True, ) @@ -550,7 +572,10 @@ def stop(proc): try: os.killpg(proc.pid, signal.SIGTERM) except OSError: - proc.terminate() + try: + proc.terminate() + except OSError: + pass # running as root: not ours to signal def _safe(fn, *args, fallback=None): diff --git a/pkgs/proxy-ctl/proxy_tui.py b/pkgs/proxy-ctl/proxy_tui.py index 7feb444..05fb5d8 100644 --- a/pkgs/proxy-ctl/proxy_tui.py +++ b/pkgs/proxy-ctl/proxy_tui.py @@ -3,8 +3,11 @@ What it shows and does lives in proxy_model, shared with proxy-suite-gui; this is the drawing. """ +import os import shlex +import shutil import signal +import subprocess from rich.text import Text from textual import events, work @@ -51,6 +54,8 @@ GLOBAL_KEYS = [ ("w", "how is a domain routed"), ("L", "follow all logs"), ("o", "output of the last command"), + ("!", "retry what just failed as root (sudo)"), + ("#", "switch to root: proxy-tui again under sudo"), ("r", "refresh now"), ("?", "keys"), ("q", "quit"), @@ -229,14 +234,32 @@ class Menu(Dialog): class Output(Dialog): - BINDINGS = [Binding("escape,q", "dismiss", "close"), Binding("c", "copy", "copy")] + BINDINGS = [Binding("escape,q", "dismiss", "close"), Binding("c", "copy", "copy"), Binding("exclamation_mark", "retry_root", "retry as root")] - def __init__(self, title, text=None, wrap=True): + def __init__(self, title, text=None, wrap=True, retry=False): super().__init__() - self.heading, self.initial, self.wrap = title, text, wrap + self.heading, self.initial, self.wrap, self.retry = title, text, wrap, retry self.proc = None # the streaming command, stopped when the dialog closes self.text = [] # plain lines, for copying + def hints(self): + retry = [("! retry as root", "retry_root")] if self.retry else [] + return hint(*retry, ("c copy", "copy"), ("esc close", "dismiss")) + + def offer_retry(self): + """The run failed where root could do it: ! and a click on the hint run it again under sudo.""" + self.retry = True + if self.is_attached: + self.query_one(".dialog-hint").remove() + self.query_one(".dialog").mount(self.hints()) + + def check_action(self, action, parameters): + return self.retry if action == "retry_root" else True + + def action_retry_root(self): + self.dismiss() + self.app.action_retry_root() + def compose(self) -> ComposeResult: with Vertical(classes="dialog output"): yield Label(self.heading, classes="dialog-title", markup=False) @@ -247,7 +270,7 @@ class Output(Dialog): self.text.append(text.plain) log.write(text) yield log - yield hint(("c copy", "copy"), ("esc close", "dismiss")) + yield self.hints() def write(self, line): if self.is_attached: @@ -297,6 +320,8 @@ class MainScreen(Screen): Binding("w", "app.where"), Binding("L", "app.logs"), Binding("o", "app.last_output"), + Binding("exclamation_mark", "app.retry_root"), + Binding("number_sign", "app.switch_root"), Binding("r", "app.reload"), Binding("q", "app.quit"), ] @@ -381,6 +406,7 @@ class ProxyTui(App): self.typed = {} # prompt title -> what was last typed there self.feedback_timer = None self.last_output = None # (title, text) + self.retry = None # (mode, argv) of the last run that only root could do self.animation_level = "none" # tab switches land at once self.register_theme(THEME) self.theme = THEME.name @@ -529,6 +555,8 @@ class ProxyTui(App): return model.applicable(self.tabs[self.active_tab()], row) def check_action(self, action, parameters): + if action in ("retry_root", "switch_root"): + return not model.is_root() # A row action that does not apply: its key does nothing. if action != "act" or self.screen is not self.main: return True @@ -588,7 +616,7 @@ class ProxyTui(App): def action_last_output(self): if self.last_output: - self.push_screen(Output(*self.last_output)) + self.push_screen(Output(*self.last_output, retry=self.retry is not None)) else: self.feedback("Nothing has run yet.") @@ -629,14 +657,7 @@ class ProxyTui(App): def run_argv(self, mode, argv): command = f"proxy-ctl {shlex.join(argv)}" if mode in ("suspend", "pause"): - with self.suspend(): - ctl._run_foreground([CTL, *argv]) - if mode == "pause": - try: - input("\n[enter] back to proxy-tui") - except (EOFError, KeyboardInterrupt): - pass - self.action_reload() + self.foreground(mode, [CTL, *argv]) return # A wrapped QR code no longer scans: it scrolls sideways instead. dialog = Output(command, wrap="--qr" not in argv) if mode == "dialog" else None @@ -645,6 +666,16 @@ class ProxyTui(App): self.feedback(f"… {command}") self.stream(command, argv, dialog, mode == "copy") + def foreground(self, mode, argv): + with self.suspend(): + ctl._run_foreground(argv) + if mode == "pause": + try: + input("\n[enter] back to proxy-tui") + except (EOFError, KeyboardInterrupt): + pass + self.action_reload() + @work(thread=True) def stream(self, command, argv, dialog, copy=False): out = [] @@ -660,23 +691,77 @@ class ProxyTui(App): except OSError as e: out.append(f"cannot run proxy-ctl: {e}") status = 127 + self.call_from_thread(self.finish, command, argv, dialog, copy, out, status, stream_shown=True) + + def finish(self, command, argv, dialog, copy, out, status, stream_shown=False): + """A run's end: the feedback line, the clipboard, and the dialog's tail.""" + if dialog and not stream_shown: + 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 self.last_output = (command, "\n".join(out)) if status == -signal.SIGTERM and dialog: - self.call_from_thread(self.feedback, f"stopped: {command}", False) + self.feedback(f"stopped: {command}", False) return if copy and not status and last: - self.call_from_thread(self.copy_to_clipboard, last) + self.copy_to_clipboard(last) message = f"copied: {last}" if status: message = f"exit {status}: {message}" if dialog: - self.call_from_thread(dialog.write, f"\x1b[31m(exit status {status})\x1b[0m") + dialog.write(f"\x1b[31m(exit status {status})\x1b[0m") if len(out) > 1 and not dialog: message += " · o: full output" - self.call_from_thread(self.feedback, message, status == 0) - self.call_from_thread(self.action_reload) + self.retry = None + if model.needs_root(out, status): + self.retry = ("dialog" if dialog else "copy" if copy else "run", argv) + message = f"{message} · !: retry as root" + if dialog: + dialog.offer_retry() + self.feedback(message, status == 0) + self.action_reload() + + def action_retry_root(self): + if not self.retry: + self.feedback("Nothing to retry as root.") + return + (mode, argv), self.retry = self.retry, None + command = f"sudo proxy-ctl {shlex.join(argv)}" + root_argv = model.elevated(argv, "sudo") + # sudo asks on the terminal, so the run happens there; the output comes back as usual. + out, p = [], None + with self.suspend(): + print(f"$ {command}", flush=True) + try: + p = subprocess.Popen(root_argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace") + for line in p.stdout: + print(line, end="", flush=True) + out.append(line.rstrip("\n")) + status = p.wait() + except OSError as e: + out.append(f"cannot run sudo: {e}") + status = 127 + except KeyboardInterrupt: # the terminal's Ctrl-C reached sudo too + status = p.wait() if p else 130 + dialog = Output(command, wrap="--qr" not in argv) if mode == "dialog" else None + if dialog: + self.push_screen(dialog) + self.finish(command, argv, dialog, mode == "copy", out, status) + + def action_switch_root(self): + def switch(ok): + if not ok: + return + with self.suspend(): + # Asks here, once: the TUI under sudo then starts without asking again. + status = ctl._run_foreground(["sudo", "-v"]) + if status: + self.feedback("sudo: not authenticated", False) + else: + self.exit("root") + + self.push_screen(Confirm("sudo proxy-tui"), switch) def feedback(self, message, ok=None): icon, style = {True: ("✓ ", "green"), False: ("✗ ", "red"), None: ("", "")}[ok] @@ -690,4 +775,6 @@ class ProxyTui(App): if __name__ == "__main__": - ProxyTui().run() + if ProxyTui().run() == "root": + # The wrapper by name: sudo resets the environment, and the wrapper sets it again. + os.execvp("sudo", ["sudo", shutil.which("proxy-tui") or "proxy-tui"]) diff --git a/pkgs/proxy-ctl/test_proxy_ctl.py b/pkgs/proxy-ctl/test_proxy_ctl.py index 5abf922..49cc404 100644 --- a/pkgs/proxy-ctl/test_proxy_ctl.py +++ b/pkgs/proxy-ctl/test_proxy_ctl.py @@ -352,7 +352,21 @@ class AutoProxyTest(EnvTest): finally: os.chmod(self.dir, 0o755) self.assertNotEqual(status, 0) - self.assertIn("enable userControl, or run with sudo", err) + self.assertIn("proxy-suite group, or re-run with sudo", err) + + +class ZapretAutoTest(EnvTest): + @unittest.skipIf(os.geteuid() == 0, "root writes anything") + def test_clear_replaces_what_it_cannot_write(self): + """The group writes the state directory, not root's list files in it.""" + os.environ.update(ZAPRET_AUTO_ENABLED="1", ZAPRET_STATE_DIR=self.dir) + auto = self.write("zapret-hosts-auto.txt", "a.example\n") + state = self.write("circular/state.tsv", "1\ta.example\n") + os.chmod(auto, 0o444) + os.chmod(state, 0o444) + ok(ctl.cmd_zapret_auto, "clear") + self.assertEqual(ctl.read_text(auto), "") + self.assertEqual(ctl.read_text(state), "") class InboundsTest(EnvTest): @@ -568,7 +582,7 @@ class OutboundTestTest(EnvTest): os.chmod(self.write("outbound-endpoints.json", {}), 0) status, _, err = run(ctl.cmd_outbounds, "test", "--ping") self.assertEqual(status, 0) - self.assertIn("enable userControl, or run with sudo", err) + self.assertIn("proxy-suite group, or re-run with sudo", err) class ShareTest(EnvTest): diff --git a/pkgs/proxy-ctl/test_proxy_model.py b/pkgs/proxy-ctl/test_proxy_model.py index fc88170..98cc8c7 100644 --- a/pkgs/proxy-ctl/test_proxy_model.py +++ b/pkgs/proxy-ctl/test_proxy_model.py @@ -43,6 +43,22 @@ class ModelTest(unittest.TestCase): self.assertEqual(items[-1], ("", "1 failed", "bad")) self.assertEqual(model.status_items({})[0], ("", "Status unavailable", "bad")) + def test_root(self): + with mock.patch.object(model.os, "geteuid", lambda: 1000): + self.assertTrue(model.needs_root(["Cannot read /run/x - re-run with sudo."], 1)) + self.assertTrue(model.needs_root(["Failed to start proxy-suite-tun.service: Access denied"], 1)) + self.assertFalse(model.needs_root(["re-run with sudo"], 0)) + self.assertFalse(model.needs_root(["Unknown outbound: x"], 1)) + self.assertFalse(model.needs_root(["re-run with sudo"], -15)) # stopped, not refused + with mock.patch.object(model.os, "geteuid", lambda: 0): + self.assertFalse(model.needs_root(["re-run with sudo"], 1)) + self.assertEqual(model.status_items({})[0], ("", "root", "warn")) + apps = next(t for t in model.TABS if t.id == "apps") + with mock.patch.object(ctl, "env", lambda name, default="": "1"): + self.assertFalse(apps.available({})) + with mock.patch.object(model.shutil, "which", lambda name: f"/nix/store/x/bin/{name}"): + self.assertEqual(model.elevated(["proxy", "config"], "pkexec"), ["pkexec", "/nix/store/x/bin/proxy-ctl", "proxy", "config"]) + def test_services_skip_the_subscription_update(self): rows = model.service_rows({"proxy-suite-socks": "active", ctl.SUBSCRIPTION_UPDATE: "inactive"}) self.assertEqual([r["unit"] for r in rows], ["proxy-suite-socks"]) diff --git a/pkgs/proxy-ctl/test_proxy_tui.py b/pkgs/proxy-ctl/test_proxy_tui.py index 8aa88d5..09fea26 100644 --- a/pkgs/proxy-ctl/test_proxy_tui.py +++ b/pkgs/proxy-ctl/test_proxy_tui.py @@ -2,6 +2,7 @@ """Headless proxy-tui: arrows, the action menu and shortcuts turn into the right proxy-ctl argv.""" import asyncio +import contextlib import tempfile import unittest from unittest import mock @@ -279,6 +280,38 @@ class TuiTest(unittest.TestCase): await pilot.pause() killpg.assert_called_once_with(4242, model.signal.SIGTERM) + # A copy only root may make offers ! to retry it under sudo, and still copies. + with mock.patch.object(model.os, "geteuid", lambda: 1000): + app.finish("proxy-ctl proxy outbounds link b", ["proxy", "outbounds", "link", "b"], None, True, ["Cannot read x - re-run with sudo."], 1) + self.assertIn("!: retry as root", str(app.main.query_one("#feedback").content)) + sudo = mock.Mock(stdout=iter(["vless://b\n"]), **{"wait.return_value": 0}) + popen = mock.Mock(return_value=sudo) + # proxy-tui's own subprocess only: reads in the background spawn through proxy_ctl's. + with mock.patch.object(app, "suspend", contextlib.nullcontext), \ + mock.patch.object(tui, "subprocess", mock.Mock(Popen=popen)), \ + mock.patch.object(model.shutil, "which", lambda name: f"/bin/{name}"), \ + mock.patch.object(app, "copy_to_clipboard") as copy, \ + mock.patch("builtins.print"): + await pilot.press("exclamation_mark") + await pilot.pause() + self.assertEqual(popen.call_args[0][0], ["sudo", "/bin/proxy-ctl", "proxy", "outbounds", "link", "b"]) + copy.assert_called_once_with("vless://b") + self.assertIsNone(app.retry) + + # A dialog run only root may do offers it in the dialog itself, and ! there retries. + dialog = tui.Output("proxy-ctl inbounds stats") + app.push_screen(dialog) + await pilot.pause() + self.assertFalse(dialog.check_action("retry_root", ())) + app.finish("proxy-ctl inbounds stats", ["inbounds", "stats"], dialog, False, ["Cannot read x - enable userControl, or run with sudo."], 1, stream_shown=True) + await pilot.pause() + self.assertIn("retry as root", str(dialog.query_one(".dialog-hint").render())) + with mock.patch.object(app, "action_retry_root") as retry: + await pilot.press("exclamation_mark") + await pilot.pause() + retry.assert_called_once_with() + self.assertIsNot(app.screen, dialog) + if __name__ == "__main__": unittest.main()