fix: root actions in tui/gui & userControl

This commit is contained in:
fufsob committed 2026-09-15 20:02:43 +00:00
1 parent 2ce8da3f43
commit 9cdd6dada7
32 files changed
+665 -317

No files matched your search

+13 -12
View File
@@ -110,6 +110,7 @@ See the [options reference](./docs/options/index.md), one page per option group.
```text ```text
Usage: proxy-ctl <group> [verb] [args] Usage: proxy-ctl <group> [verb] [args]
A group without a verb shows its status or list. 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) status [--json] services and routing mode (--tray: deprecated key=value lines)
restart restart active services 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] proxy outbounds test [tag...] [--ping] [--delay] [--download]
TCP ping, real delay, download speed (default: ping, delay) TCP ping, real delay, download speed (default: ping, delay)
proxy outbounds link <tag> [--qr|--json|--config] proxy outbounds link <tag> [--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 pin [tag] always use this outbound (no tag: pick from a menu)
proxy unpin let the configured selection pick again proxy unpin let the configured selection pick again
proxy mode [default|whitelist|blacklist|all-proxy|all-bypass] 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 [list|update] subscription caches; update refetches them
proxy subs add <tag> <url> add a subscription at runtime proxy subs add <tag> <url> add a subscription at runtime
proxy subs rm <tag> remove a runtime subscription proxy subs rm <tag> remove a runtime subscription
proxy subs link <tag> [--qr] its URL (sudo) proxy subs link <tag> [--qr] its URL
proxy config [--raw] client config to import elsewhere; --raw: as running (sudo) proxy config [--raw] client config to import elsewhere; --raw: as running
proxy tun [status|on|off] global TUN mode proxy tun [status|on|off] global TUN mode
proxy tproxy [status|on|off] global TProxy 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 <domain>[/path] [--json] [--keep-going] [--exits a,b | --via tag] proxy auto probe <domain>[/path] [--json] [--keep-going] [--exits a,b | --via tag]
find an exit that reaches a domain find an exit that reaches a domain
proxy auto learn <domain> probe now and route it if an exit works (sudo) proxy auto learn <domain> probe now and route it if an exit works
proxy auto queue [count] destinations waiting to be probed (sudo, or userControl) proxy auto queue [count] destinations waiting to be probed
zapret [status|on|off] DPI bypass zapret [status|on|off] DPI bypass
zapret auto [list] hosts zapret2 learned as blocked zapret auto [list] hosts zapret2 learned as blocked
zapret auto add|forget|exclude <domain> zapret auto add|forget|exclude <domain>
pin, forget, or never learn a host (sudo) pin, forget, or never learn a host
zapret auto unpin|include <domain> undo add, or undo exclude (sudo) zapret auto unpin|include <domain> undo add, or undo exclude
zapret auto clear forget learned hosts and strategies (sudo) zapret auto clear forget learned hosts and strategies
zapret cutoff [status] networks this line cuts at 16 KB, and their names 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 [list] AmneziaWG profiles and their state
awg on <profile> | off [profile] | restart [profile] awg on <profile> | off [profile] | restart [profile]
@@ -165,10 +166,10 @@ A group without a verb shows its status or list.
inbounds [list] server inbounds inbounds [list] server inbounds
inbounds link <tag> [user] [--qr|--json] inbounds link <tag> [user] [--qr|--json]
client share link, or the client's outbound JSON client share link, or the client's outbound JSON
inbounds link <tag> --server-json the server's inbound JSON (sudo) inbounds link <tag> --server-json the server's inbound JSON
inbounds sub [user] [--qr] subscription users, or one user's URL inbounds sub [user] [--qr] subscription users, or one user's URL
inbounds stats [days] [--by user|inbound|outbound] 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 inbounds online who is connected now, and when the rest were last seen
``` ```
<!-- proxy-ctl-help:end --> <!-- proxy-ctl-help:end -->
+1 -1
View File
@@ -1045,7 +1045,7 @@ null
<a id="services-proxy-suite-inbounds-sharelinks"></a> <a id="services-proxy-suite-inbounds-sharelinks"></a>
## services\.proxy-suite\.inbounds\.shareLinks ## 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:* *Type:*
boolean boolean
+2 -4
View File
@@ -258,11 +258,9 @@ services.proxy-suite = {
enable = true; enable = true;
}; };
userControl = { userControl = {
allow = [ enable = false;
"global"
"perApp"
];
group = "proxy-suite"; group = "proxy-suite";
scopes = [ ];
}; };
warp = { warp = {
asAmneziaWg = false; asAmneziaWg = false;
+40 -16
View File
@@ -5,36 +5,28 @@ Part of the [proxy-suite options reference](./index.md).
## Options ## Options
- userControl - userControl
- [allow](#services-proxy-suite-usercontrol-allow) - [enable](#services-proxy-suite-usercontrol-enable)
- [group](#services-proxy-suite-usercontrol-group) - [group](#services-proxy-suite-usercontrol-group)
- [scopes](#services-proxy-suite-usercontrol-scopes)
<a id="services-proxy-suite-usercontrol-allow"></a> <a id="services-proxy-suite-usercontrol-enable"></a>
## services\.proxy-suite\.userControl\.allow ## services\.proxy-suite\.userControl\.enable
What userControl\.group may control without a password: Whether to enable passwordless ` proxy-ctl ` control for the members of userControl\.group\.
- “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\.
*Type:* *Type:*
list of (one of “global”, “perApp”) boolean
*Default:* *Default:*
```nix ```nix
[ false
"global"
"perApp"
]
``` ```
*Example:* *Example:*
```nix ```nix
[ true
"global"
]
``` ```
<a id="services-proxy-suite-usercontrol-group"></a> <a id="services-proxy-suite-usercontrol-group"></a>
@@ -50,3 +42,35 @@ string matching the pattern ^\[a-z_]\[a-z0-9_-]\*$
```nix ```nix
"proxy-suite" "proxy-suite"
``` ```
<a id="services-proxy-suite-usercontrol-scopes"></a>
## 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"
]
```
+12 -6
View File
@@ -7,10 +7,13 @@
cfg, cfg,
proxyCtl, proxyCtl,
autoProxyStateDir, autoProxyStateDir,
userControlAllows,
}: }:
let let
apCfg = cfg.proxy.autoProxy; 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; }; render = import ./autoproxy-render.nix { inherit pkgs; };
jqFile = jqFile =
path: path:
@@ -52,7 +55,7 @@ let
echo "sing-box has no Clash API (selection = \"first\"?); nothing to sample" echo "sing-box has no Clash API (selection = \"first\"?); nothing to sample"
exit 0 exit 0
fi fi
install -d -m 0751 "$state_dir" install -d -m ${stateDirMode} "$state_dir"
# Eleven snapshots a second apart: ten one-second deltas per connection. # Eleven snapshots a second apart: ten one-second deltas per connection.
lines=$( lines=$(
@@ -86,7 +89,7 @@ let
echo "no probe listeners - is proxy-suite-socks running with autoProxy on?" echo "no probe listeners - is proxy-suite-socks running with autoProxy on?"
exit 0 exit 0
fi fi
install -d -m 0751 "$state_dir" install -d -m ${stateDirMode} "$state_dir"
# Timer runs and learn requests take turns on the state. # Timer runs and learn requests take turns on the state.
exec 9> "$state_dir/lock" exec 9> "$state_dir/lock"
@@ -97,6 +100,8 @@ let
if [ -e "$requests.taking" ]; then if [ -e "$requests.taking" ]; then
cat "$requests.taking" >> "$requests" cat "$requests.taking" >> "$requests"
rm -f "$requests.taking" rm -f "$requests.taking"
# Made here by root: the group appends to it too.
chmod 0660 "$requests"
fi fi
if [ -e "$state" ] && ! jq -e 'type == "object"' "$state" > /dev/null 2>&1; then if [ -e "$state" ] && ! jq -e 'type == "object"' "$state" > /dev/null 2>&1; then
@@ -392,16 +397,17 @@ let
${render} "$index" "$state" ${render} "$index" "$state"
''; '';
# Group: `proxy-ctl proxy auto list|queue` reads state.json. Set on every unit that # Group: `proxy-ctl proxy auto list|queue` reads state.json, `learn` queues requests.
# declares the directory - systemd re-applies the ownership on each start. # Set on every unit that declares the directory - systemd re-applies the ownership
# on each start.
stateDirConfig = { stateDirConfig = {
StateDirectory = "proxy-suite/autoproxy"; StateDirectory = "proxy-suite/autoproxy";
# 0751 and a 027 umask: sing-box (proxy-suite) can open the rule-sets, which are # 0751 and a 027 umask: sing-box (proxy-suite) can open the rule-sets, which are
# made 0644, and nothing else. # made 0644, and nothing else.
StateDirectoryMode = "0751"; StateDirectoryMode = stateDirMode;
UMask = "0027"; UMask = "0027";
} }
// lib.optionalAttrs (cfg.userControl.allow != [ ]) { Group = cfg.userControl.group; }; // lib.optionalAttrs (userControlAllows "autoProxy") { Group = cfg.userControl.group; };
mkUnit = description: args: { mkUnit = description: args: {
inherit description; inherit description;
+6 -1
View File
@@ -192,7 +192,11 @@ let
# The cut-off networks no whitelisted name fixes go through the proxy outbound. # The cut-off networks no whitelisted name fixes go through the proxy outbound.
zapretCutoffProxyFallback = zapretCutoffProxyFallback =
zapretCutoffEnabled && zapretCfg.zapret2.cutoff.proxyFallback && hasAvailableOutbounds; 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 = { constants = {
# Daemons (sing-box, XRay, the WARP tunnel, OpenSSH, tg-ws-proxy, wgcf) run as this # 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 # user. Its group is not the userControl group: backend configs hold credentials. Start
@@ -333,6 +337,7 @@ in
zapretCutoffProxyFallback zapretCutoffProxyFallback
userControlCfg userControlCfg
userControlEnabled userControlEnabled
userControlAllows
sshProxyCfg sshProxyCfg
sshProxyOutboundTag sshProxyOutboundTag
sshProxyOutboundEnabled sshProxyOutboundEnabled
+1 -1
View File
@@ -36,7 +36,7 @@ in
}; };
openFirewall = bool true "Open every non-loopback listener port."; 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 = { subscriptions = {
enable = mkEnableOption "" // { enable = mkEnableOption "" // {
+3 -2
View File
@@ -66,8 +66,9 @@ in
(rm "tgWsProxy.logBackups" "Use services.proxy-suite.tgWsProxy.log.keep.") (rm "tgWsProxy.logBackups" "Use services.proxy-suite.tgWsProxy.log.keep.")
# userControl. # userControl.
(rm "userControl.global.enable" ''Use services.proxy-suite.userControl.allow, which lists "global" 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.allow, which lists "perApp" by default.'') (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 ( ++ lib.mapAttrsToList (
old: new: rm "zapret.${old}" "Use services.proxy-suite.zapret.zapret-discord-youtube.${new}." old: new: rm "zapret.${old}" "Use services.proxy-suite.zapret.zapret-discord-youtube.${new}."
+23 -10
View File
@@ -5,30 +5,43 @@ let
in in
{ {
options.services.proxy-suite.userControl = { options.services.proxy-suite.userControl = {
enable = lib.mkEnableOption "passwordless `proxy-ctl` control for the members of userControl.group";
group = mkOption { group = mkOption {
type = types.strMatching "^[a-z_][a-z0-9_-]*$"; type = types.strMatching "^[a-z_][a-z0-9_-]*$";
default = "proxy-suite"; default = "proxy-suite";
description = "Group whose members may run privileged `proxy-ctl` commands without a password."; description = "Group whose members may run privileged `proxy-ctl` commands without a password.";
}; };
allow = mkOption { scopes = mkOption {
type = types.listOf ( type = types.listOf (
types.enum [ types.enum [
"global" "services"
"perApp" "perApp"
"routing"
"outbounds"
"secrets"
"autoProxy"
"zapret"
"stats"
] ]
); );
default = [ default = [ ];
"global"
"perApp"
];
description = '' description = ''
What userControl.group may control without a password: What userControl.group may do; empty allows every scope.
- "global": the global units (proxy, tun, tproxy, zapret, restart, subs update). - "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`. - "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"
];
}; };
}; };
} }
@@ -84,6 +84,9 @@ let
(mkAssertion (cfg.userControl.group != derived.constants.serviceUser) (mkAssertion (cfg.userControl.group != derived.constants.serviceUser)
"proxy-suite: userControl.group must not be ${derived.constants.serviceUser}, the group that can read backend configs" "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 (requireEnabled (cfg.warp.enable && cfg.warp.asOutbound != null) proxyEnabled
"proxy-suite: warp.asOutbound requires proxy.enable = true" "proxy-suite: warp.asOutbound requires proxy.enable = true"
) )
+3 -5
View File
@@ -56,7 +56,7 @@ let
proxyInboundsNeedLocalProxy proxyInboundsNeedLocalProxy
proxyInboundsGuardPrivate proxyInboundsGuardPrivate
proxyInboundViaOutbounds proxyInboundViaOutbounds
userControlEnabled userControlAllows
; ;
# Tool paths – defined once here and passed into sub-modules as needed. # Tool paths – defined once here and passed into sub-modules as needed.
@@ -88,9 +88,7 @@ let
builders = import ./builders.nix { inherit lib pkgs; }; builders = import ./builders.nix { inherit lib pkgs; };
polkit = import ./polkit.nix { polkit = import ./polkit.nix { inherit userControlCfg; };
inherit lib cfg userControlCfg;
};
scripts = import ./scripts.nix { scripts = import ./scripts.nix {
inherit inherit
@@ -135,7 +133,7 @@ let
proxyInboundsNeedLocalProxy proxyInboundsNeedLocalProxy
proxyInboundsGuardPrivate proxyInboundsGuardPrivate
proxyInboundViaOutbounds proxyInboundViaOutbounds
userControlEnabled userControlAllows
builders builders
; ;
}; };
+36 -19
View File
@@ -62,6 +62,7 @@ let
perAppRoutingTproxy perAppRoutingTproxy
userControlCfg userControlCfg
userControlEnabled userControlEnabled
userControlAllows
perAppZapretEnabled perAppZapretEnabled
sshProxyOutboundEnabled sshProxyOutboundEnabled
sshProxyUnitEnabled sshProxyUnitEnabled
@@ -129,6 +130,7 @@ let
inherit lib pkgs cfg; inherit lib pkgs cfg;
inherit (control) proxyCtl; inherit (control) proxyCtl;
inherit (constants) autoProxyStateDir; inherit (constants) autoProxyStateDir;
inherit userControlAllows;
} }
); );
in in
@@ -170,36 +172,51 @@ lib.mkMerge [
"${userControlCfg.group}" = { }; "${userControlCfg.group}" = { };
}; };
security.polkit.enable = lib.mkIf (cfg.enable && userControlEnabled) true; security.polkit.enable = lib.mkIf (cfg.enable && (userControlEnabled || cfg.gui.enable)) true;
security.polkit.extraConfig = lib.mkIf (cfg.enable && userControlEnabled) ( # The GUI's "Retry as Root" and root toggle run proxy-ctl through pkexec: one
lib.mkAfter '' # admin password then covers the next few minutes, as sudo's does in the TUI.
polkit.addRule(function(action, subject) { security.polkit.extraConfig = lib.mkMerge [
if (!subject.isInGroup("${userControlCfg.group}")) { (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; 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; return null;
} });
''
var unit = action.lookup("unit"); ))
${polkit.userControlPolkitRules} ];
return null;
});
''
);
# Spool dirs for outbounds and subscriptions added at runtime. Setgid so the # Spool dirs for outbounds and subscriptions added at runtime. Setgid so the
# files proxy-ctl drops here inherit the group; without userControl only root # files proxy-ctl drops here inherit the group; without the outbounds scope
# writes them. tmpfiles rather than the start scripts, so the group can add an # only root writes them. tmpfiles rather than the start scripts, so the group can add an
# outbound before the proxy has ever run. # outbound before the proxy has ever run.
systemd.tmpfiles.rules = lib.mkIf (cfg.enable && proxyEnabled) ( systemd.tmpfiles.rules = lib.mkIf (cfg.enable && proxyEnabled) (
map map
( (
dir: dir:
"d ${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"
} -" } -"
) )
[ [
+30 -21
View File
@@ -1,26 +1,35 @@
# Polkit rules granting proxy-suite group members passwordless control over services. # Polkit rule body granting userControl group members passwordless control over the
{ # units of their scopes.
lib, { userControlCfg }:
cfg,
userControlCfg,
}:
let let
userControlEnabled = userControlCfg.allow != [ ]; # Units a narrower scope starts; every other proxy-suite unit is "services".
scopeByUnitPrefix = {
userControlPolkitRules = "proxy-suite-per-app-" = "perApp";
lib.optionalString (builtins.elem "perApp" userControlCfg.allow) '' "proxy-suite-outbound-pin@" = "routing";
if (unit.indexOf("proxy-suite-per-app-") === 0) { "proxy-suite-outbound-unpin." = "routing";
return polkit.Result.YES; "proxy-suite-route-mode@" = "routing";
} "proxy-suite-outbound-reload." = "outbounds";
'' "proxy-suite-subscription-update." = "outbounds";
+ lib.optionalString (builtins.elem "global" userControlCfg.allow) '' "proxy-suite-autoproxy-learn." = "autoProxy";
if (unit.indexOf("proxy-suite-") === 0 && "proxy-suite-zapret2-cutoff." = "zapret";
unit.indexOf("proxy-suite-per-app-") !== 0) { "proxy-suite-inbound-stats." = "stats";
return polkit.Result.YES; };
}
'';
in 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;
}
'';
} }
@@ -8,7 +8,7 @@
proxyInboundsNeedLocalProxy, proxyInboundsNeedLocalProxy,
proxyInboundViaOutbounds, proxyInboundViaOutbounds,
userControlCfg, userControlCfg,
userControlEnabled, userControlAllows,
localProxyAuth, localProxyAuth,
localProxyAuthEnabled, localProxyAuthEnabled,
localProxyAuthPasswordSource, localProxyAuthPasswordSource,
@@ -91,10 +91,10 @@ let
writeLinksBlock = lib.optionalString proxyInboundsCfg.shareLinks '' writeLinksBlock = lib.optionalString proxyInboundsCfg.shareLinks ''
${jq} -c '.links' <<< "$RENDERED" > "${linksFile}" ${jq} -c '.links' <<< "$RENDERED" > "${linksFile}"
${lib.optionalString userControlEnabled '' ${lib.optionalString (userControlAllows "secrets") ''
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${linksFile}" ${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 # 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" rm -rf "$SUB_DIR"
mv "$SUB_DIR.new" "$SUB_DIR" mv "$SUB_DIR.new" "$SUB_DIR"
${jq} -c '[.subscriptions[] | {user, token}]' <<< "$RENDERED" > "${subscriptionsFile}" ${jq} -c '[.subscriptions[] | {user, token}]' <<< "$RENDERED" > "${subscriptionsFile}"
${lib.optionalString userControlEnabled '' ${lib.optionalString (userControlAllows "secrets") ''
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${subscriptionsFile}" ${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" '' startInbounds = pkgs.writeShellScript "proxy-suite-inbounds" ''
@@ -177,8 +177,20 @@ let
done < <(${jq} -r '[.inbounds[].streamSettings.tlsSettings.certificates[]? | (.certificateFile, .keyFile) | strings] done < <(${jq} -r '[.inbounds[].streamSettings.tlsSettings.certificates[]? | (.certificateFile, .keyFile) | strings]
| unique[]' "$RUNTIME_DIR/config.json.tmp") | unique[]' "$RUNTIME_DIR/config.json.tmp")
${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$RUNTIME_DIR/config.json.tmp" # Read by XRay as ${constants.serviceUser}, and by the userControl group: the daemon
chmod 640 "$RUNTIME_DIR/config.json.tmp" # 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" mv "$RUNTIME_DIR/config.json.tmp" "$RUNTIME_DIR/config.json"
${writeLinksBlock} ${writeLinksBlock}
@@ -213,11 +225,11 @@ let
path = ../inbound-stats-add.jq; path = ../inbound-stats-add.jq;
} }
} "$file" > "$tmp" } "$file" > "$tmp"
${lib.optionalString userControlEnabled '' ${lib.optionalString (userControlAllows "stats") ''
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$tmp" || ${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$tmp" ||
echo "proxy-suite: group ${userControlCfg.group} cannot read the stats; they stay root-only" >&2 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" mv -f "$tmp" "$file"
''; '';
in in
+3 -2
View File
@@ -32,7 +32,7 @@
proxyInboundsNeedLocalProxy, proxyInboundsNeedLocalProxy,
proxyInboundsGuardPrivate, proxyInboundsGuardPrivate,
proxyInboundViaOutbounds, proxyInboundViaOutbounds,
userControlEnabled, userControlAllows,
buildInboundPy, buildInboundPy,
proxyInboundsFile, proxyInboundsFile,
proxyInboundsSpecFile, proxyInboundsSpecFile,
@@ -162,6 +162,7 @@ let
proxyCfg proxyCfg
perAppRoutingCfg perAppRoutingCfg
userControlCfg userControlCfg
userControlAllows
globalTproxy globalTproxy
xrayEnabled xrayEnabled
hybridEnabled hybridEnabled
@@ -199,7 +200,7 @@ let
proxyInboundsNeedLocalProxy proxyInboundsNeedLocalProxy
proxyInboundViaOutbounds proxyInboundViaOutbounds
userControlCfg userControlCfg
userControlEnabled userControlAllows
localProxyAuth localProxyAuth
localProxyAuthEnabled localProxyAuthEnabled
localProxyAuthPasswordSource localProxyAuthPasswordSource
+27 -9
View File
@@ -5,6 +5,7 @@
proxyCfg, proxyCfg,
perAppRoutingCfg, perAppRoutingCfg,
userControlCfg, userControlCfg,
userControlAllows,
globalTproxy, globalTproxy,
xrayEnabled, xrayEnabled,
hybridEnabled, hybridEnabled,
@@ -41,6 +42,8 @@ let
autoProxyRender = import ../autoproxy-render.nix { inherit pkgs; }; autoProxyRender = import ../autoproxy-render.nix { inherit pkgs; };
runBackend = constants.runAsServiceUser pkgs constants.backendCaps; runBackend = constants.runAsServiceUser pkgs constants.backendCaps;
userControlGroup = lib.escapeShellArg userControlCfg.group;
chgrp = "${pkgs.coreutils}/bin/chgrp";
routeModeBlacklistTail = routeModeBlacklistTail =
if pureXrayEnabled then if pureXrayEnabled then
@@ -207,8 +210,9 @@ let
AUTOPROXY_RULES_JSON='[]' AUTOPROXY_RULES_JSON='[]'
${lib.optionalString enableAutoProxy '' ${lib.optionalString enableAutoProxy ''
AUTOPROXY_DIR=${lib.escapeShellArg autoProxyStateDir} AUTOPROXY_DIR=${lib.escapeShellArg autoProxyStateDir}
# 0751: sing-box, running as ${constants.serviceUser}, reads the rule-sets inside. # 0751: sing-box, running as ${constants.serviceUser}, reads the rule-sets inside;
install -d -m 0751 "$AUTOPROXY_DIR" # 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" [ -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 # direct is always exit 0; state is keyed by tag, so shifting indices are
@@ -263,7 +267,7 @@ let
' <<< "$OUTBOUNDS_JSON" > "$ENDPOINTS_TMP" ' <<< "$OUTBOUNDS_JSON" > "$ENDPOINTS_TMP"
# Where each proxy server is: not credentials, but not for every local user either. # 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" ${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$ENDPOINTS_TMP"
chmod 640 "$ENDPOINTS_TMP" chmod 640 "$ENDPOINTS_TMP"
@@ -274,7 +278,7 @@ let
mv "$ENDPOINTS_TMP" "$RUNTIME_DIR/outbound-endpoints.json" mv "$ENDPOINTS_TMP" "$RUNTIME_DIR/outbound-endpoints.json"
# proxy-ctl's share links: the URL each outbound was given, and its backend 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" SHARE_TMP="$RUNTIME_DIR/outbound-share.json.tmp"
(umask 077 && ${jq} -c --argjson sidecar "''${XRAY_OUTBOUNDS_JSON:-[]}" --arg collapsed "''${PROXY_TAG:-}" \ (umask 077 && ${jq} -c --argjson sidecar "''${XRAY_OUTBOUNDS_JSON:-[]}" --arg collapsed "''${PROXY_TAG:-}" \
--argjson urls "$OUTBOUND_URLS_JSON" --argjson subs "$SUBSCRIPTION_URLS_JSON" ' --argjson urls "$OUTBOUND_URLS_JSON" --argjson subs "$SUBSCRIPTION_URLS_JSON" '
@@ -285,7 +289,8 @@ let
| from_entries), | from_entries),
subscriptions: $subs} subscriptions: $subs}
' <<< "$OUTBOUNDS_JSON" > "$SHARE_TMP") ' <<< "$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" mv "$SHARE_TMP" "$RUNTIME_DIR/outbound-share.json"
${lib.optionalString (!pureXrayEnabled) '' ${lib.optionalString (!pureXrayEnabled) ''
@@ -313,7 +318,8 @@ let
# rule-set path and reloads the file when the probe renames a new one in. # rule-set path and reloads the file when the probe renames a new one in.
if [ "$ROUTE_MODE" != all-bypass ]; then if [ "$ROUTE_MODE" != all-bypass ]; then
CUTOFF_RULE_SET=${lib.escapeShellArg "${constants.zapret2CutoffDir}/proxy.json"} 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" [ -s "$CUTOFF_RULE_SET" ] || echo '{"version":1,"rules":[]}' > "$CUTOFF_RULE_SET"
chmod 644 "$CUTOFF_RULE_SET" chmod 644 "$CUTOFF_RULE_SET"
AUTOPROXY_RULE_SETS_JSON=$(${jq} -c --arg p "$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" "$RUNTIME_DIR/config.json" > "$RUNTIME_DIR/config.json.next"
mv "$RUNTIME_DIR/config.json.next" "$RUNTIME_DIR/config.json" 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 for backend_config in "$RUNTIME_DIR/config.json" "$RUNTIME_DIR/xray-sidecar.json"; do
[ -e "$backend_config" ] || continue [ -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 done
FAKE_IP_CACHE=$(${jq} -r '.experimental.cache_file.path? // empty' "$RUNTIME_DIR/config.json") FAKE_IP_CACHE=$(${jq} -r '.experimental.cache_file.path? // empty' "$RUNTIME_DIR/config.json")
if [ -n "$FAKE_IP_CACHE" ]; then if [ -n "$FAKE_IP_CACHE" ]; then
+6 -3
View File
@@ -16,7 +16,7 @@ let
zapretCfg = cfg.zapret; zapretCfg = cfg.zapret;
perAppZapretCfg = cfg.perAppRouting.zapret; perAppZapretCfg = cfg.perAppRouting.zapret;
cutoffCfg = zapretCfg.zapret2.cutoff; 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. # Global AmneziaWG profiles only: an outbound one leaves the host's routes alone.
awgServiceNames = map (name: "proxy-suite-awg-${name}.service") ( awgServiceNames = map (name: "proxy-suite-awg-${name}.service") (
builtins.attrNames (lib.filterAttrs (_: profile: profile.asOutbound == null) cfg.amneziaWg.profiles) 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; 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 = '' mkPreStart = ''
${lib.getExe' pkgs.kmod "modprobe"} nfnetlink_queue 2>/dev/null || true ${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} touch ${runtime.autoHostlistFile} ${runtime.userHostlistFile} ${runtime.excludeHostlistFile}
''; '';
+6 -1
View File
@@ -12,7 +12,7 @@
}: }:
let let
inherit (import ../derived.nix { inherit lib cfg; }) constants; inherit (import ../derived.nix { inherit lib cfg; }) constants userControlAllows;
z2k = zapret2Sources.z2k; z2k = zapret2Sources.z2k;
lists = "${z2k}/files/lists"; lists = "${z2k}/files/lists";
dir = constants.zapret2CutoffDir; dir = constants.zapret2CutoffDir;
@@ -156,6 +156,11 @@ in
ExecStartPre = "${exempt}"; ExecStartPre = "${exempt}";
ExecStart = "${probe}"; ExecStart = "${probe}";
ExecStopPost = "-${nft} delete table inet ${table}"; 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";
}; };
}; };
+1
View File
@@ -25,6 +25,7 @@ let
system.stateVersion = "26.05"; system.stateVersion = "26.05";
services.proxy-suite = { services.proxy-suite = {
enable = true; enable = true;
userControl.enable = true;
amneziaWg = { amneziaWg = {
enable = true; enable = true;
kernelModulePackage = null; kernelModulePackage = null;
+12
View File
@@ -60,6 +60,18 @@ in
assert builtins.match ".*/bin/proxy-suite-gui --hidden$" unit.serviceConfig.ExecStart != null; assert builtins.match ".*/bin/proxy-suite-gui --hidden$" unit.serviceConfig.ExecStart != null;
true 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 !(guiManualFixture.config.systemd.user.services ? proxy-suite-gui);
assert !(tuiOffFixture.config.systemd.user.services ? proxy-suite-gui); assert !(tuiOffFixture.config.systemd.user.services ? proxy-suite-gui);
+1 -2
View File
@@ -148,10 +148,9 @@ in
true true
) )
# -- perAppRouting: app TUN enables nftables and user control group -- # -- perAppRouting: app TUN enables nftables --
( (
assert perAppRoutingTunFixture.config.networking.nftables.enable; assert perAppRoutingTunFixture.config.networking.nftables.enable;
assert perAppRoutingTunFixture.config.users.groups ? "proxy-suite";
true true
) )
]; ];
+6 -6
View File
@@ -186,13 +186,13 @@ let
fixture: fixture:
(import ./read-generated.nix).readDerivation (import ./read-generated.nix).readDerivation
fixture.config.systemd.services."proxy-suite-inbound-stats".serviceConfig.ExecStart; fixture.config.systemd.services."proxy-suite-inbound-stats".serviceConfig.ExecStart;
noControlFixture = evalProxySuite [ controlFixture = evalProxySuite [
baseModule baseModule
{ {
services.proxy-suite = { services.proxy-suite = {
inbounds.enable = true; inbounds.enable = true;
inbounds.listeners.vless-in = realityListener; 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. # The collected stats are group-readable with userControl, root-only without.
( (
assert lib.hasInfix "chgrp proxy-suite \"$tmp\"" (statsScript relayFixture); assert lib.hasInfix "chgrp proxy-suite \"$tmp\"" (statsScript controlFixture);
assert lib.hasInfix "chmod 640 \"$tmp\"" (statsScript relayFixture); assert lib.hasInfix "chmod 640 \"$tmp\"" (statsScript controlFixture);
assert !lib.hasInfix "chgrp" (statsScript noControlFixture); assert !lib.hasInfix "chgrp" (statsScript relayFixture);
assert lib.hasInfix "chmod 600 \"$tmp\"" (statsScript noControlFixture); assert lib.hasInfix "chmod 600 \"$tmp\"" (statsScript relayFixture);
true true
) )
+3 -3
View File
@@ -188,15 +188,15 @@ in
true 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 assert
builtins.any ( 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; ) minimal.config.systemd.tmpfiles.rules;
assert assert
builtins.any ( 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; ) minimal.config.systemd.tmpfiles.rules;
true true
) )
+98 -103
View File
@@ -5,129 +5,129 @@
}: }:
let let
userControlDefaultFixture = evalProxySuite [ inherit (pkgs.lib) hasInfix;
baseModule
{
services.proxy-suite = {
perAppRouting = {
enable = true;
createDefaultProfiles = true;
tun.enable = true;
};
};
}
];
userControlDefaultPolkitConfig = userControlDefaultFixture.config.security.polkit.extraConfig;
userControlGlobalOnlyFixture = evalProxySuite [ mkFixture =
baseModule userControl:
{
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:
evalProxySuite [ evalProxySuite [
baseModule baseModule
{ {
services.proxy-suite = { services.proxy-suite = {
perAppRouting = {
enable = true;
createDefaultProfiles = true;
tun.enable = true;
};
proxy.autoProxy.enable = true; proxy.autoProxy.enable = true;
} inherit userControl;
// extra; };
} }
]; ];
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 = autoProxyGroups =
fixture: 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"
"proxy-suite-autoproxy-learn" "proxy-suite-autoproxy-learn"
"proxy-suite-autoproxy-sample" "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 in
{ {
assertions = [ 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" assert allFixture.config.users.groups ? "proxy-suite";
userControlDefaultPolkitConfig; assert hasInfix "var scopes = [];" (polkitConfig allFixture);
assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-\") === 0" userControlDefaultPolkitConfig; assert hasInfix "subject.isInGroup(\"proxy-suite\")" (polkitConfig allFixture);
assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-per-app-\") !== 0" assert hasInfix "\"proxy-suite-zapret2-cutoff.\":\"zapret\"" (polkitConfig allFixture);
userControlDefaultPolkitConfig; assert groupReadsSecrets allFixture;
true assert hasInfix "chown proxy-suite-daemon:proxy-suite \"$backend_config\"" (socksStart allFixture);
)
# -- 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 assert
builtins.match ".*unit\\.indexOf\\(\"proxy-suite-per-app-\"\\) === 0.*" userControlGlobalOnlyPolkitConfig autoProxyGroups allFixture == [
== 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 { }) == [
"proxy-suite" "proxy-suite"
"proxy-suite" "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 assert
autoProxyGroups (mkAutoProxyFixture { autoProxyGroups otherGroupFixture == [
userControl.group = "vpnops";
}) == [
"vpnops" "vpnops"
"vpnops" "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 assert
autoProxyGroups (mkAutoProxyFixture { autoProxyGroups routingOnlyFixture == [
userControl.allow = [ ]; 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 null
null null
@@ -135,16 +135,11 @@ in
true 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 builtins.any (
assert !userControlDisabledFixture.config.security.polkit.enable; a: !a.assertion && hasInfix "userControl.scopes is set" a.message
assert ) scopesWithoutEnableFixture.config.assertions;
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;
true true
) )
]; ];
+3 -1
View File
@@ -109,7 +109,8 @@ let
proxyCtl proxyCtl
pkgs.systemd pkgs.systemd
] ]
}" ${envFlags} }" \
--suffix PATH : /run/wrappers/bin ${envFlags}
''; '';
}; };
guiPython = pkgs.python3.withPackages (ps: [ ps.pygobject3 ]); guiPython = pkgs.python3.withPackages (ps: [ ps.pygobject3 ]);
@@ -194,6 +195,7 @@ let
pkgs.qrencode pkgs.qrencode
] ]
}" \ }" \
--suffix PATH : /run/wrappers/bin \
--set PROXY_GUI_ICON_DIR "$out/share/proxy-suite-gui/icons" \ --set PROXY_GUI_ICON_DIR "$out/share/proxy-suite-gui/icons" \
--set PROXY_GUI_REFRESH ${toString guiRefreshInterval} ${envFlags} --set PROXY_GUI_REFRESH ${toString guiRefreshInterval} ${envFlags}
''; '';
+42 -35
View File
@@ -45,6 +45,7 @@ RESTART_SERVICES = [
HELP = """\ HELP = """\
Usage: proxy-ctl <group> [verb] [args] Usage: proxy-ctl <group> [verb] [args]
A group without a verb shows its status or list. 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) status [--json] services and routing mode (--tray: deprecated key=value lines)
restart restart active services 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] proxy outbounds test [tag...] [--ping] [--delay] [--download]
TCP ping, real delay, download speed (default: ping, delay) TCP ping, real delay, download speed (default: ping, delay)
proxy outbounds link <tag> [--qr|--json|--config] proxy outbounds link <tag> [--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 pin [tag] always use this outbound (no tag: pick from a menu)
proxy unpin let the configured selection pick again proxy unpin let the configured selection pick again
proxy mode [default|whitelist|blacklist|all-proxy|all-bypass] 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 [list|update] subscription caches; update refetches them
proxy subs add <tag> <url> add a subscription at runtime proxy subs add <tag> <url> add a subscription at runtime
proxy subs rm <tag> remove a runtime subscription proxy subs rm <tag> remove a runtime subscription
proxy subs link <tag> [--qr] its URL (sudo) proxy subs link <tag> [--qr] its URL
proxy config [--raw] client config to import elsewhere; --raw: as running (sudo) proxy config [--raw] client config to import elsewhere; --raw: as running
proxy tun [status|on|off] global TUN mode proxy tun [status|on|off] global TUN mode
proxy tproxy [status|on|off] global TProxy 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 <domain>[/path] [--json] [--keep-going] [--exits a,b | --via tag] proxy auto probe <domain>[/path] [--json] [--keep-going] [--exits a,b | --via tag]
find an exit that reaches a domain find an exit that reaches a domain
proxy auto learn <domain> probe now and route it if an exit works (sudo) proxy auto learn <domain> probe now and route it if an exit works
proxy auto queue [count] destinations waiting to be probed (sudo, or userControl) proxy auto queue [count] destinations waiting to be probed
zapret [status|on|off] DPI bypass zapret [status|on|off] DPI bypass
zapret auto [list] hosts zapret2 learned as blocked zapret auto [list] hosts zapret2 learned as blocked
zapret auto add|forget|exclude <domain> zapret auto add|forget|exclude <domain>
pin, forget, or never learn a host (sudo) pin, forget, or never learn a host
zapret auto unpin|include <domain> undo add, or undo exclude (sudo) zapret auto unpin|include <domain> undo add, or undo exclude
zapret auto clear forget learned hosts and strategies (sudo) zapret auto clear forget learned hosts and strategies
zapret cutoff [status] networks this line cuts at 16 KB, and their names 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 [list] AmneziaWG profiles and their state
awg on <profile> | off [profile] | restart [profile] awg on <profile> | off [profile] | restart [profile]
@@ -100,10 +101,10 @@ A group without a verb shows its status or list.
inbounds [list] server inbounds inbounds [list] server inbounds
inbounds link <tag> [user] [--qr|--json] inbounds link <tag> [user] [--qr|--json]
client share link, or the client's outbound JSON client share link, or the client's outbound JSON
inbounds link <tag> --server-json the server's inbound JSON (sudo) inbounds link <tag> --server-json the server's inbound JSON
inbounds sub [user] [--qr] subscription users, or one user's URL inbounds sub [user] [--qr] subscription users, or one user's URL
inbounds stats [days] [--by user|inbound|outbound] 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 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) 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): def _run(argv, capture=False, quiet=False, stdin=None):
"""Runs argv; (exit status, stdout if captured). A missing binary is 127.""" """Runs argv; (exit status, stdout if captured). A missing binary is 127."""
sys.stdout.flush() sys.stdout.flush()
@@ -937,7 +947,7 @@ def cmd_outbounds_test(*args):
try: try:
endpoints = read_json(_runtime_file("outbound-endpoints.json")) endpoints = read_json(_runtime_file("outbound-endpoints.json"))
except PermissionError: 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): except (OSError, ValueError):
pass pass
test = {} test = {}
@@ -1006,9 +1016,9 @@ def _outbounds_list():
# --- sharing ------------------------------------------------------------------ # --- sharing ------------------------------------------------------------------
# #
# The socks start script writes outbound-share.json, root only: the URL each outbound # The socks start script writes outbound-share.json, root and userControl's group only:
# was given (none for one declared as JSON, WARP or SSH) and its backend JSON. A URL is # the URL each outbound was given (none for one declared as JSON, WARP or SSH) and its
# never rebuilt from JSON. `proxy config` turns the running config into one another # backend JSON. A URL is never rebuilt from JSON. `proxy config` turns the running config into one another
# device can import (proxy_export). # device can import (proxy_export).
@@ -1016,7 +1026,7 @@ def _read_root_json(path, what):
if not os.path.isfile(path): if not os.path.isfile(path):
die(f"No {what} yet - is proxy-suite-socks running?") die(f"No {what} yet - is proxy-suite-socks running?")
if not readable(path): if not readable(path):
die(f"Cannot read {path} - re-run with sudo.") denied(path)
return read_json(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: with open(path, "w", encoding="utf-8") as f:
f.write(f"{url}\n") f.write(f"{url}\n")
except OSError: 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: finally:
os.umask(old) os.umask(old)
_runtime_reload() _runtime_reload()
@@ -1231,7 +1241,7 @@ def _runtime_entry_rm(kind, tag="", *_):
except FileNotFoundError: except FileNotFoundError:
pass pass
except OSError: 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() _runtime_reload()
print(f"Removed {kind}: {tag}") print(f"Removed {kind}: {tag}")
@@ -1731,7 +1741,7 @@ def _require_autoproxy_readable(path):
if not os.path.isdir(path): if not os.path.isdir(path):
die("No autoProxy state yet - the prober has not completed a run.") die("No autoProxy state yet - the prober has not completed a run.")
if not os.access(path, os.R_OK | os.X_OK): 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): def _autoproxy_state(path):
@@ -1866,7 +1876,7 @@ def cmd_proxy_learn(host="", *_):
with open(requests, "a", encoding="utf-8") as f: with open(requests, "a", encoding="utf-8") as f:
f.write(f"{host}\n") f.write(f"{host}\n")
except OSError: except OSError:
die(f"Cannot write {requests} - re-run with sudo.") denied(requests, "write")
print(f"Probing {host} through each exit...") print(f"Probing {host} through each exit...")
if systemctl("start", "proxy-suite-autoproxy-learn.service", quiet=True)[0]: if systemctl("start", "proxy-suite-autoproxy-learn.service", quiet=True)[0]:
sys.stdout.flush() sys.stdout.flush()
@@ -1911,7 +1921,7 @@ def _replace_lines(path, keep, extra=()):
old = lines(read_text(path)) if os.path.exists(path) else [] 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 ".") fd, tmp = tempfile.mkstemp(prefix=os.path.basename(path) + ".", dir=os.path.dirname(path) or ".")
except OSError: except OSError:
die(f"Cannot write {path} - re-run with sudo.") denied(path, "write")
try: try:
with os.fdopen(fd, "w", encoding="utf-8") as f: with os.fdopen(fd, "w", encoding="utf-8") as f:
f.writelines(f"{line}\n" for line in [*filter(keep, old), *extra]) 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) os.unlink(tmp)
except OSError: except OSError:
pass pass
die(f"Cannot replace {path} - re-run with sudo.") denied(path, "replace")
def _zapret_auto_edit(path, domain, action): def _zapret_auto_edit(path, domain, action):
@@ -1951,10 +1961,7 @@ def _zapret_strategy_drop(domain):
def _truncate(path): def _truncate(path):
try: _replace_lines(path, lambda _: False)
open(path, "w").close()
except OSError:
die(f"Cannot write {path} - re-run with sudo.")
def cmd_zapret_auto(verb="list", domain="", *_): def cmd_zapret_auto(verb="list", domain="", *_):
@@ -2021,7 +2028,7 @@ def cmd_zapret_cutoff(verb="status", *_):
try: try:
open(os.path.join(path, "force"), "w").close() open(os.path.join(path, "force"), "w").close()
except OSError: except OSError:
die(f"Cannot write {path} - re-run with sudo.") denied(path, "write")
print("Probing this line; this takes a few minutes...") print("Probing this line; this takes a few minutes...")
if systemctl("start", "proxy-suite-zapret2-cutoff.service")[0]: if systemctl("start", "proxy-suite-zapret2-cutoff.service")[0]:
die("The probe failed. Details: journalctl -u proxy-suite-zapret2-cutoff -n 30") 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": if env("INBOUNDS_ENABLED") == "1":
inbounds_path = "/run/proxy-suite-inbounds/config.json" inbounds_path = "/run/proxy-suite-inbounds/config.json"
if not readable(inbounds_path): 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: else:
try: try:
tag, why = _where_inbounds(read_json(inbounds_path), domain, geosite_dir) 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 env("AUTOPROXY_ENABLED") == "1":
if not readable(os.path.join(_autoproxy_dir(), "state.json")): 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: else:
domains = _autoproxy_state(_autoproxy_dir()).get("domains") domains = _autoproxy_state(_autoproxy_dir()).get("domains")
hit = _where_in(domains if isinstance(domains, dict) else {}, domain) hit = _where_in(domains if isinstance(domains, dict) else {}, domain)
@@ -2418,7 +2425,7 @@ def _inbound_links():
if not os.path.isfile(path): if not os.path.isfile(path):
die("No share links available. Is proxy-suite-inbounds running, and is inbounds.shareLinks enabled?") die("No share links available. Is proxy-suite-inbounds running, and is inbounds.shareLinks enabled?")
if not readable(path): 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) return read_json(path)
@@ -2428,7 +2435,7 @@ def _inbound_server_json(tag):
if not os.path.isfile(path): if not os.path.isfile(path):
die("No inbound config yet - is proxy-suite-inbounds running?") die("No inbound config yet - is proxy-suite-inbounds running?")
if not readable(path): 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) inbound = next((x for x in read_json(path).get("inbounds") or [] if x.get("tag") == tag), None)
if inbound is None: if inbound is None:
die(f"Unknown inbound: {tag}") die(f"Unknown inbound: {tag}")
@@ -2487,7 +2494,7 @@ def _inbound_stats(*args):
if not os.path.exists(path): if not os.path.exists(path):
die("No traffic recorded yet - the collector runs every 5 minutes.") die("No traffic recorded yet - the collector runs every 5 minutes.")
if not readable(path): if not readable(path):
die(f"Cannot read {path} - enable userControl, or run with sudo.") denied(path)
stats = read_json(path) stats = read_json(path)
since = (_today() - datetime.timedelta(days=int(days) - 1)).isoformat() since = (_today() - datetime.timedelta(days=int(days) - 1)).isoformat()
print(f"Traffic through the inbounds since {since}, by {kind}:") print(f"Traffic through the inbounds since {since}, by {kind}:")
@@ -2560,7 +2567,7 @@ def _inbound_online():
for user, (state, addresses) in presence.items(): for user, (state, addresses) in presence.items():
print(row.format(user, state, addresses)) print(row.format(user, state, addresses))
sys.stdout.flush() 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): def _inbound_subscriptions(*args):
@@ -2577,7 +2584,7 @@ def _inbound_subscriptions(*args):
if not os.path.isfile(path): if not os.path.isfile(path):
die("No subscriptions available. Is proxy-suite-inbounds running, and is inbounds.subscriptions enabled?") die("No subscriptions available. Is proxy-suite-inbounds running, and is inbounds.subscriptions enabled?")
if not readable(path): if not readable(path):
die("Subscriptions are not readable by this user. Enable userControl, or run as root.") denied(path)
subs = read_json(path) subs = read_json(path)
if not user: if not user:
if qr: if qr:
+60 -17
View File
@@ -67,6 +67,7 @@ GLOBAL_SHORTCUTS = [
("w", "How is a domain routed"), ("w", "How is a domain routed"),
("<Shift>l", "Follow all logs"), ("<Shift>l", "Follow all logs"),
("o", "Output of the last command"), ("o", "Output of the last command"),
("<Control>e", "Run actions as root (pkexec)"),
("F5 r", "Refresh now"), ("F5 r", "Refresh now"),
("<Control>question", "Keyboard shortcuts"), ("<Control>question", "Keyboard shortcuts"),
("<Control>w", "Close the window (the tray keeps running)"), ("<Control>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 = Gtk.Button(label="Stop", css_classes=["destructive-action"], visible=False, valign=Gtk.Align.CENTER)
self.stop.connect("clicked", lambda *_: self.terminate()) self.stop.connect("clicked", lambda *_: self.terminate())
header.pack_end(self.stop) 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) self.spinner = Adw.Spinner(visible=False)
header.pack_end(self.spinner) header.pack_end(self.spinner)
self.result = Gtk.Label(visible=False, valign=Gtk.Align.CENTER) 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[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")) 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.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) self.spinner.set_visible(True)
def finished(self, status=0): def finished(self, status=0, retry=None):
self.stop.set_visible(False) self.stop.set_visible(False)
self.spinner.set_visible(False) self.spinner.set_visible(False)
self.retry.set_visible(retry is not None)
self.retry_with = retry
if status == -signal.SIGTERM: if status == -signal.SIGTERM:
text, classes = "stopped", ["dim-label"] text, classes = "stopped", ["dim-label"]
elif status: elif status:
@@ -733,6 +740,7 @@ class Window(Adw.ApplicationWindow):
self.pages = {} self.pages = {}
self.typed = {} # action label -> what was last typed there self.typed = {} # action label -> what was last typed there
self.last_output = None # (title, text) 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() self.toasts = Adw.ToastOverlay()
view = Adw.ToolbarView(top_bar_style=Adw.ToolbarStyle.RAISED) 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.refresh_stack.add_named(Adw.Spinner(halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER), "busy")
self.busy_timer = None self.busy_timer = None
header.pack_start(self.refresh_stack) 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() menu = Gio.Menu()
section = Gio.Menu() section = Gio.Menu()
section.append("How is a domain routed…", "win.where") 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") section.append("Output of the last command", "win.last-output")
menu.append_section(None, section) menu.append_section(None, section)
section = Gio.Menu() 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("Keyboard Shortcuts", "win.shortcuts")
section.append("About Proxy Suite", "win.about") section.append("About Proxy Suite", "win.about")
section.append("Quit", "app.quit") section.append("Quit", "app.quit")
@@ -807,6 +820,7 @@ class Window(Adw.ApplicationWindow):
action.connect("activate", callback) action.connect("activate", callback)
self.add_action(action) self.add_action(action)
app.set_accels_for_action("win.filter", ["<Control>f"]) app.set_accels_for_action("win.filter", ["<Control>f"])
app.set_accels_for_action("app.elevated", ["<Control>e"])
app.set_accels_for_action("win.shortcuts", ["<Control>question"]) app.set_accels_for_action("win.shortcuts", ["<Control>question"])
app.set_accels_for_action("app.reload", ["F5"]) app.set_accels_for_action("app.reload", ["F5"])
app.set_accels_for_action("app.quit", ["<Control>q"]) app.set_accels_for_action("app.quit", ["<Control>q"])
@@ -910,7 +924,10 @@ class Window(Adw.ApplicationWindow):
def show_last_output(self): def show_last_output(self):
if self.last_output: 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: else:
self.toast("Nothing has run yet.") self.toast("Nothing has run yet.")
return True return True
@@ -950,9 +967,12 @@ class Window(Adw.ApplicationWindow):
dialog.present(self) dialog.present(self)
entry.grab_focus() 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) 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.set_button_label("Output")
toast.connect("button-clicked", lambda *_: OutputDialog(self, *output).present(self)) toast.connect("button-clicked", lambda *_: OutputDialog(self, *output).present(self))
self.toasts.add_toast(toast) self.toasts.add_toast(toast)
@@ -1023,6 +1043,12 @@ class ProxySuiteGui(Adw.Application):
action = Gio.SimpleAction.new(name, None) action = Gio.SimpleAction.new(name, None)
action.connect("activate", callback) action.connect("activate", callback)
self.add_action(action) 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 self.hold() # the tray and notifications outlive the window
try: try:
from proxy_sni import StatusNotifierItem from proxy_sni import StatusNotifierItem
@@ -1058,6 +1084,14 @@ class ProxySuiteGui(Adw.Application):
# --- window ------------------------------------------------------------------------------ # --- 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): def present(self, tab=None):
if self.window is None: if self.window is None:
self.window = Window(self) self.window = Window(self)
@@ -1169,9 +1203,12 @@ class ProxySuiteGui(Adw.Application):
dialog.connect("response", lambda _, r: r == "run" and then()) dialog.connect("response", lambda _, r: r == "run" and then())
dialog.present(parent) dialog.present(parent)
def run_argv(self, mode, argv, win): 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.""" """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)}" 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 qr = "--qr" in argv
if qr: if qr:
argv = [a for a in argv if a != "--qr"] argv = [a for a in argv if a != "--qr"]
@@ -1181,14 +1218,14 @@ class ProxySuiteGui(Adw.Application):
dialog.present(win) dialog.present(win)
elif win is not None: elif win is not None:
win.toast(f"… {command}") 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 = [] out = []
try: try:
p = model.popen(argv) p = model.popen(argv, "pkexec" if root else None)
if dialog: 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: for line in p.stdout:
out.append(line.rstrip("\n")) out.append(line.rstrip("\n"))
if dialog: if dialog:
@@ -1197,16 +1234,20 @@ class ProxySuiteGui(Adw.Application):
except OSError as e: except OSError as e:
out.append(f"cannot run proxy-ctl: {e}") out.append(f"cannot run proxy-ctl: {e}")
status = 127 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) last = last_line(out)
text = "\n".join(out) text = "\n".join(out)
output = (command, text) 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: if win is not None:
win.last_output = output win.last_output = output
win.last_retry = retry
if dialog: if dialog:
dialog.finished(status) dialog.finished(status, retry)
if status == -signal.SIGTERM: if status == -signal.SIGTERM:
dialog.write("\x1b[2m(stopped)\x1b[0m") dialog.write("\x1b[2m(stopped)\x1b[0m")
elif status: elif status:
@@ -1218,12 +1259,14 @@ class ProxySuiteGui(Adw.Application):
win.copy_text(last, f"Copied: {last}") win.copy_text(last, f"Copied: {last}")
else: else:
message = f"{last} ({command})" if last else command 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: elif status:
# From the tray: nothing else would say it failed. # From the tray: nothing else would say it failed.
note = Gio.Notification.new(f"{command} failed") note = Gio.Notification.new(f"{command} failed")
note.set_body(last or f"exit status {status}") note.set_body(last or f"exit status {status}")
note.set_default_action("app.present") 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.send_notification(None, note)
self.reload() self.reload()
+32 -7
View File
@@ -8,6 +8,7 @@ die() cannot take a front end down.
import os import os
import re import re
import shlex import shlex
import shutil
import signal import signal
import subprocess import subprocess
import sys import sys
@@ -83,6 +84,20 @@ def needs_confirm(action, row):
return action.confirm(row) if callable(action.confirm) else action.confirm 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": "◐"} STATE_ICONS = {"active": "●", "inactive": "○", "failed": "✗", "activating": "◐", "deactivating": "◐", "reloading": "◐"}
@@ -281,7 +296,7 @@ def snapshot(states):
def status_items(states): def status_items(states):
"""(label, value, style) for the status line: style is "", "ok", "warn" or "bad".""" """(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) overall = ctl._overall_state(snapshot(states) if states else None)
items.append(("", overall["label"], {"failed": "bad", "busy": "warn", "unknown": "bad"}.get(overall["badge"], ""))) items.append(("", overall["label"], {"failed": "bad", "busy": "warn", "unknown": "bad"}.get(overall["badge"], "")))
if "proxy-suite-socks" in states: if "proxy-suite-socks" in states:
@@ -406,7 +421,7 @@ TABS = [
prompt="<tag> <url or JSON>", prompt="<tag> <url or JSON>",
), ),
Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"], confirm=True), 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("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("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"), Action("Q", "its URL as QR", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--qr"], when=ROW, mode="dialog"),
@@ -492,7 +507,8 @@ TABS = [
Tab( Tab(
"apps", "apps",
"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")], [("profile", "Profile"), ("route", "Route")],
app_rows, app_rows,
actions=[ actions=[
@@ -537,10 +553,16 @@ def _capture(argv):
return p.stdout + p.stderr return p.stdout + p.stderr
def popen(argv): def elevated(argv, via):
"""proxy-ctl with its output streamed: its own process group, so stop() takes down what it spawned too.""" """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( 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, text=True, errors="replace", start_new_session=True,
) )
@@ -550,7 +572,10 @@ def stop(proc):
try: try:
os.killpg(proc.pid, signal.SIGTERM) os.killpg(proc.pid, signal.SIGTERM)
except OSError: except OSError:
proc.terminate() try:
proc.terminate()
except OSError:
pass # running as root: not ours to signal
def _safe(fn, *args, fallback=None): def _safe(fn, *args, fallback=None):
+106 -19
View File
@@ -3,8 +3,11 @@
What it shows and does lives in proxy_model, shared with proxy-suite-gui; this is the drawing. What it shows and does lives in proxy_model, shared with proxy-suite-gui; this is the drawing.
""" """
import os
import shlex import shlex
import shutil
import signal import signal
import subprocess
from rich.text import Text from rich.text import Text
from textual import events, work from textual import events, work
@@ -51,6 +54,8 @@ GLOBAL_KEYS = [
("w", "how is a domain routed"), ("w", "how is a domain routed"),
("L", "follow all logs"), ("L", "follow all logs"),
("o", "output of the last command"), ("o", "output of the last command"),
("!", "retry what just failed as root (sudo)"),
("#", "switch to root: proxy-tui again under sudo"),
("r", "refresh now"), ("r", "refresh now"),
("?", "keys"), ("?", "keys"),
("q", "quit"), ("q", "quit"),
@@ -229,14 +234,32 @@ class Menu(Dialog):
class Output(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__() 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.proc = None # the streaming command, stopped when the dialog closes
self.text = [] # plain lines, for copying 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: def compose(self) -> ComposeResult:
with Vertical(classes="dialog output"): with Vertical(classes="dialog output"):
yield Label(self.heading, classes="dialog-title", markup=False) yield Label(self.heading, classes="dialog-title", markup=False)
@@ -247,7 +270,7 @@ class Output(Dialog):
self.text.append(text.plain) self.text.append(text.plain)
log.write(text) log.write(text)
yield log yield log
yield hint(("c copy", "copy"), ("esc close", "dismiss")) yield self.hints()
def write(self, line): def write(self, line):
if self.is_attached: if self.is_attached:
@@ -297,6 +320,8 @@ class MainScreen(Screen):
Binding("w", "app.where"), Binding("w", "app.where"),
Binding("L", "app.logs"), Binding("L", "app.logs"),
Binding("o", "app.last_output"), Binding("o", "app.last_output"),
Binding("exclamation_mark", "app.retry_root"),
Binding("number_sign", "app.switch_root"),
Binding("r", "app.reload"), Binding("r", "app.reload"),
Binding("q", "app.quit"), Binding("q", "app.quit"),
] ]
@@ -381,6 +406,7 @@ class ProxyTui(App):
self.typed = {} # prompt title -> what was last typed there self.typed = {} # prompt title -> what was last typed there
self.feedback_timer = None self.feedback_timer = None
self.last_output = None # (title, text) 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.animation_level = "none" # tab switches land at once
self.register_theme(THEME) self.register_theme(THEME)
self.theme = THEME.name self.theme = THEME.name
@@ -529,6 +555,8 @@ class ProxyTui(App):
return model.applicable(self.tabs[self.active_tab()], row) return model.applicable(self.tabs[self.active_tab()], row)
def check_action(self, action, parameters): 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. # A row action that does not apply: its key does nothing.
if action != "act" or self.screen is not self.main: if action != "act" or self.screen is not self.main:
return True return True
@@ -588,7 +616,7 @@ class ProxyTui(App):
def action_last_output(self): def action_last_output(self):
if self.last_output: 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: else:
self.feedback("Nothing has run yet.") self.feedback("Nothing has run yet.")
@@ -629,14 +657,7 @@ class ProxyTui(App):
def run_argv(self, mode, argv): def run_argv(self, mode, argv):
command = f"proxy-ctl {shlex.join(argv)}" command = f"proxy-ctl {shlex.join(argv)}"
if mode in ("suspend", "pause"): if mode in ("suspend", "pause"):
with self.suspend(): self.foreground(mode, [CTL, *argv])
ctl._run_foreground([CTL, *argv])
if mode == "pause":
try:
input("\n[enter] back to proxy-tui")
except (EOFError, KeyboardInterrupt):
pass
self.action_reload()
return return
# A wrapped QR code no longer scans: it scrolls sideways instead. # A wrapped QR code no longer scans: it scrolls sideways instead.
dialog = Output(command, wrap="--qr" not in argv) if mode == "dialog" else None 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.feedback(f"… {command}")
self.stream(command, argv, dialog, mode == "copy") 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) @work(thread=True)
def stream(self, command, argv, dialog, copy=False): def stream(self, command, argv, dialog, copy=False):
out = [] out = []
@@ -660,23 +691,77 @@ class ProxyTui(App):
except OSError as e: except OSError as e:
out.append(f"cannot run proxy-ctl: {e}") out.append(f"cannot run proxy-ctl: {e}")
status = 127 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() last = Text.from_ansi(next((line for line in reversed(out) if line.strip()), "")).plain.strip()
message = f"{last} ({command})" if last else command message = f"{last} ({command})" if last else command
self.last_output = (command, "\n".join(out)) self.last_output = (command, "\n".join(out))
if status == -signal.SIGTERM and dialog: if status == -signal.SIGTERM and dialog:
self.call_from_thread(self.feedback, f"stopped: {command}", False) self.feedback(f"stopped: {command}", False)
return return
if copy and not status and last: 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}" message = f"copied: {last}"
if status: if status:
message = f"exit {status}: {message}" message = f"exit {status}: {message}"
if dialog: 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: if len(out) > 1 and not dialog:
message += " · o: full output" message += " · o: full output"
self.call_from_thread(self.feedback, message, status == 0) self.retry = None
self.call_from_thread(self.action_reload) 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): def feedback(self, message, ok=None):
icon, style = {True: ("✓ ", "green"), False: ("✗ ", "red"), None: ("", "")}[ok] icon, style = {True: ("✓ ", "green"), False: ("✗ ", "red"), None: ("", "")}[ok]
@@ -690,4 +775,6 @@ class ProxyTui(App):
if __name__ == "__main__": 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"])
+16 -2
View File
@@ -352,7 +352,21 @@ class AutoProxyTest(EnvTest):
finally: finally:
os.chmod(self.dir, 0o755) os.chmod(self.dir, 0o755)
self.assertNotEqual(status, 0) 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): class InboundsTest(EnvTest):
@@ -568,7 +582,7 @@ class OutboundTestTest(EnvTest):
os.chmod(self.write("outbound-endpoints.json", {}), 0) os.chmod(self.write("outbound-endpoints.json", {}), 0)
status, _, err = run(ctl.cmd_outbounds, "test", "--ping") status, _, err = run(ctl.cmd_outbounds, "test", "--ping")
self.assertEqual(status, 0) 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): class ShareTest(EnvTest):
+16
View File
@@ -43,6 +43,22 @@ class ModelTest(unittest.TestCase):
self.assertEqual(items[-1], ("", "1 failed", "bad")) self.assertEqual(items[-1], ("", "1 failed", "bad"))
self.assertEqual(model.status_items({})[0], ("", "Status unavailable", "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): def test_services_skip_the_subscription_update(self):
rows = model.service_rows({"proxy-suite-socks": "active", ctl.SUBSCRIPTION_UPDATE: "inactive"}) rows = model.service_rows({"proxy-suite-socks": "active", ctl.SUBSCRIPTION_UPDATE: "inactive"})
self.assertEqual([r["unit"] for r in rows], ["proxy-suite-socks"]) self.assertEqual([r["unit"] for r in rows], ["proxy-suite-socks"])
+33
View File
@@ -2,6 +2,7 @@
"""Headless proxy-tui: arrows, the action menu and shortcuts turn into the right proxy-ctl argv.""" """Headless proxy-tui: arrows, the action menu and shortcuts turn into the right proxy-ctl argv."""
import asyncio import asyncio
import contextlib
import tempfile import tempfile
import unittest import unittest
from unittest import mock from unittest import mock
@@ -279,6 +280,38 @@ class TuiTest(unittest.TestCase):
await pilot.pause() await pilot.pause()
killpg.assert_called_once_with(4242, model.signal.SIGTERM) 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__": if __name__ == "__main__":
unittest.main() unittest.main()