fix: more hardening

This commit is contained in:
fufsob committed 2026-09-30 13:27:55 +00:00
1 parent 18a2049a1c
commit c1e4425d18
23 files changed
+929 -99

No files matched your search

+1
View File
@@ -330,6 +330,7 @@ services.proxy-suite = {
userControl = {
enable = false;
group = "proxy-suite";
groups = { };
scopes = [ ];
};
warp = {
+31
View File
@@ -9,6 +9,9 @@ Part of the [proxy-suite options reference](./index.md).
- userControl
- [enable](#services-proxy-suite-usercontrol-enable)
- [group](#services-proxy-suite-usercontrol-group)
- [groups](#services-proxy-suite-usercontrol-groups)
- `<name>`
- [scopes](#services-proxy-suite-usercontrol-groups-name-scopes)
- [scopes](#services-proxy-suite-usercontrol-scopes)
<a id="services-proxy-suite-usercontrol-enable"></a>
@@ -27,6 +30,34 @@ Group whose members can run privileged ` proxy-ctl ` commands\.
**Type:** string matching the pattern ^\[a-z_]\[a-z0-9_-]\*$\
**Default:** `"proxy-suite"`
<a id="services-proxy-suite-usercontrol-groups"></a>
## services\.proxy-suite\.userControl\.groups
More groups, each with scopes of its own, alongside ` userControl.group `\. A member gets
what all of their groups allow\. ` group ` stays the one that owns proxy-suite’s files;
these are given access to them through POSIX ACLs, so the file systems of
` /var/lib/proxy-suite ` and ` /run ` must support them (the defaults do)\.
**Type:** attribute set of (submodule)\
**Default:** `{ }`\
**Example:**
```nix
{
proxy-admins.scopes = [ ];
proxy-users.scopes = [ "perApp" "routing" ];
}
```
<a id="services-proxy-suite-usercontrol-groups-name-scopes"></a>
## services\.proxy-suite\.userControl\.groups\.\<name>\.scopes
What this group may do, as in ` userControl.scopes `\. Empty allows everything\.
**Type:** list of (one of “services”, “perApp”, “routing”, “outbounds”, “secrets”, “autoProxy”, “zapret”, “stats”, “inbounds”, “whitelistBypass”, “amneziaWg”)\
**Default:** `[ ]`
<a id="services-proxy-suite-usercontrol-scopes"></a>
## services\.proxy-suite\.userControl\.scopes
+20
View File
@@ -0,0 +1,20 @@
{ config, lib, pkgs, ... }:
{
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
outbounds = [ { tag = "my-vps"; urlFile = "/run/secrets/my-vps-url"; } ];
};
userControl = {
enable = true;
scopes = [ "routing" ];
groups = {
proxy-admins.scopes = [ ];
proxy-users.scopes = [ "perApp" "outbounds" ];
};
};
};
users.users.alice.extraGroups = [ "proxy-admins" ];
users.users.bob.extraGroups = [ "proxy-users" ];
}
+35
View File
@@ -47,6 +47,40 @@ Members of the group get the listed scopes. An empty `scopes` list grants all of
Log out and back in after joining the group. Without `userControl`, a change asks for an
admin password, or you run `proxy-ctl` with sudo.
### Several groups
`userControl.groups` adds more groups, each with scopes of its own. A member gets what all
of their groups allow:
```nix
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
outbounds = [ { tag = "my-vps"; urlFile = "/run/secrets/my-vps-url"; } ];
};
userControl = {
enable = true;
scopes = [ "routing" ];
groups = {
proxy-admins.scopes = [ ];
proxy-users.scopes = [ "perApp" "outbounds" ];
};
};
};
users.users.alice.extraGroups = [ "proxy-admins" ];
users.users.bob.extraGroups = [ "proxy-users" ];
```
`userControl.group` still owns proxy-suite's files. The other groups reach them through
POSIX ACLs, so `/var/lib/proxy-suite` and `/run` need a file system that supports ACLs. ext4,
btrfs, xfs and tmpfs all do.
The sing-box Clash API's secret stays readable by root only. Other users reach the API
through `proxy-suite-clash-api`, which decides per request. Any member can read the
outbounds and test them. Switching a selector through the API needs `routing`, and live
connections (`proxy-ctl where`) need `secrets`. Nothing else in the API is open to them.
## Runtime changes and the Nix config
| Change | Lasts |
@@ -81,6 +115,7 @@ back, `F` follows again and `q` quits.
## See also
- [`userControl.scopes`](../options/userControl.md#services-proxy-suite-usercontrol-scopes)
- [`userControl.groups`](../options/userControl.md#services-proxy-suite-usercontrol-groups)
- [`gui.enable`](../options/gui.md#services-proxy-suite-gui-enable)
- [`tui.enable`](../options/tui.md#services-proxy-suite-tui-enable)
- [The full `proxy-ctl help`](../../README.md), at the end of the README
+15 -4
View File
@@ -14,9 +14,16 @@
let
apCfg = cfg.proxy.autoProxy;
inherit ((import ./derived.nix { inherit lib cfg; }).constants) rootInSharedDirConfig;
# The autoProxy scope's group writes the directory: `proxy auto learn` queues there.
stateDirMode = if userControlAllows "autoProxy" then "0771" else "0751";
derived = import ./derived.nix { inherit lib cfg; };
inherit (derived.constants) rootInSharedDirConfig;
# The autoProxy scope's groups write the directory: `proxy auto learn` queues there. Those
# in userControl.groups through ACLs, which the group bits (the ACL mask) leave open.
stateDirMode = if derived.userControlAnyAllows "autoProxy" then "0771" else "0751";
grantAcl = pkgs.writeShellScript "proxy-suite-autoproxy-acl" (
derived.constants.grantDirAcl pkgs (lib.escapeShellArg autoProxyStateDir)
(derived.userControlExtraGroupsFor "autoProxy")
"rwX"
);
render = import ./autoproxy-render.nix {
inherit pkgs;
inherit ((import ./derived.nix { inherit lib cfg; }).constants) serviceUser ifPrivileged;
@@ -47,7 +54,8 @@ let
clashApiBlock = ''
socks_config="$(dirname "$index")/config.json"
clash_api=$(jq -r '.experimental.clash_api.external_controller // empty' "$socks_config" 2>/dev/null || true)
clash_secret=$(jq -r '.experimental.clash_api.secret // empty' "$socks_config" 2>/dev/null || true)
# Root's copy: config.json no longer holds it (start-scripts.nix).
clash_secret=$(tr -d '\r\n' 2>/dev/null < "$(dirname "$index")/clash-secret" || true)
clash_auth_header() { printf 'Authorization: Bearer %s\n' "$clash_secret"; }
'';
@@ -470,6 +478,9 @@ let
# rules/, which its group reads (autoproxy-render.nix), and nothing else.
StateDirectoryMode = stateDirMode;
UMask = "0027";
# Inside the sandbox below, which keeps a name a member left there from leading it
# anywhere else.
ExecStartPre = "${grantAcl}";
}
// lib.optionalAttrs (userControlAllows "autoProxy") { Group = cfg.userControl.group; }
# Root writes by fixed names in a directory the group writes to: nowhere else, whatever
+67 -1
View File
@@ -455,6 +455,15 @@ let
# proxy-suite-outbound-groups moves failover groups, and "failover" selection, along. Runtime
# groups can be failover too, so it runs with every Clash API; with nothing to watch it idles.
outboundGroupsWatch = proxyEnabled && clashApiEnabled;
# proxy-suite-clash-api: the Clash API for those in the groups, as their scopes allow; the
# secret itself stays root's. With listener.auth alone, userControl.group only reads.
clashBrokerEnabled =
proxyEnabled
&& clashApiEnabled
&& cfg.host.privileged
&& (userControlEnabled || localProxy.authEnabled);
clashBrokerGroups =
if userControlEnabled then userControlGroupScopes else { ${userControlCfg.group} = [ ]; };
hasStaticOutbounds = proxyCfg.outbounds != [ ];
hasSubscriptions = proxyCfg.subscriptions != [ ];
@@ -478,10 +487,32 @@ let
zapretCutoffProxyFallback =
zapretCutoffEnabled && zapretCfg.zapret2.cutoff.proxyFallback && hasAvailableOutbounds;
userControlEnabled = userControlCfg.enable;
# Whether the group holds a scope; no scopes listed means all of them.
# Whether userControl.group, which owns proxy-suite's files, holds a scope; no scopes
# listed means all of them. The groups in userControl.groups get theirs through ACLs.
userControlAllows =
scope:
userControlEnabled && (userControlCfg.scopes == [ ] || builtins.elem scope userControlCfg.scopes);
# Every group and what it may do, "none listed" spelled out as every scope.
userControlGroupScopes = lib.optionalAttrs userControlEnabled (
lib.mapAttrs (_: scopes: if scopes == [ ] then import ./options/user-control-scopes.nix else scopes)
(
lib.mapAttrs (_: g: g.scopes) userControlCfg.groups
// {
${userControlCfg.group} = userControlCfg.scopes;
}
)
);
# The groups in userControl.groups that hold a scope.
userControlExtraGroupsFor =
scope:
builtins.filter (g: g != userControlCfg.group && builtins.elem scope userControlGroupScopes.${g}) (
builtins.attrNames userControlGroupScopes
);
# Whether any group holds it.
userControlAnyAllows = scope: userControlAllows scope || userControlExtraGroupsFor scope != [ ];
userControlExtraGroups = lib.optionals userControlEnabled (
builtins.attrNames userControlCfg.groups
);
managerFlag = lib.optionalString (cfg.host.serviceManager == "systemd-user") " --user";
constants = {
inherit stateDir runtimeDir;
@@ -539,6 +570,34 @@ let
ProtectHome = true;
PrivateTmp = true;
};
# POSIX ACLs for the groups in userControl.groups, which cannot own a file the way
# userControl.group does. Shell text, for root.
# grantFileAcl: after a file's chmod (which sets the ACL mask), `perm` for each group.
grantFileAcl =
pkgs: path: groups: perm:
lib.optionalString (cfg.host.privileged && groups != [ ]) ''
${pkgs.acl}/bin/setfacl -m ${lib.concatMapStringsSep "," (g: "g:${g}:${perm}") groups} -- ${path}
'';
# grantDirAcl: a directory and all in it, for each group, and what is made in it later
# (default entries). What was granted before is taken away first, so a group dropped
# from the configuration loses access; -b keeps each file's effective bits. Nothing for
# a directory not there yet. -P: never through a symlink a member left in it; a unit
# running it keeps the rest of the file system read-only as well.
# -n: each file keeps its mask, its group bits, so a group gets no more than the
# file's own group would: nothing of a 0600 key. Recalculated, the mask would take
# `perm` whole.
grantDirAcl =
pkgs: path: groups: perm:
lib.optionalString cfg.host.privileged ''
if [ -d ${path} ]; then
${pkgs.acl}/bin/setfacl -R -P -b -- ${path}
${lib.optionalString (groups != [ ]) ''
${pkgs.acl}/bin/setfacl -R -P -n -m ${
lib.concatMapStringsSep "," (g: "g:${g}:${perm},d:g:${g}:${perm}") groups
} -- ${path}
''}
fi
'';
# Socket marks and IP_TRANSPARENT, TUN and auto_redirect, listeners below 1024, ICMP.
backendCaps = [
"net_admin"
@@ -593,6 +652,7 @@ let
'';
# Written by every backend start script; proxy-ctl reads the socks copy.
outboundInventoryFile = "${runtimeDir}/proxy-suite-socks/outbounds.json";
clashBrokerSocket = "${runtimeDir}/proxy-suite-clash/api.sock";
inboundStatsApiSocket = "${runtimeDir}/proxy-suite-inbounds/api/stats.sock";
# Mark and table sending the AmneziaWG listeners' diverted packets to the local stack,
@@ -709,6 +769,10 @@ in
userControlCfg
userControlEnabled
userControlAllows
userControlGroupScopes
userControlExtraGroupsFor
userControlAnyAllows
userControlExtraGroups
sshProxyCfg
sshProxyOutboundEnabled
sshProxyNativeOutbound
@@ -763,6 +827,8 @@ in
subscriptionTags
groupTags
outboundGroupsWatch
clashBrokerEnabled
clashBrokerGroups
hasSubscriptions
hasAvailableOutbounds
collapseNamedOutbounds
@@ -0,0 +1,15 @@
# What userControl's groups may be given (options/user-control.nix); derived.nix reads it
# to spell out "no scopes listed", which means all of them.
[
"services"
"perApp"
"routing"
"outbounds"
"secrets"
"autoProxy"
"zapret"
"stats"
"inbounds"
"whitelistBypass"
"amneziaWg"
]
+28 -15
View File
@@ -2,6 +2,8 @@
let
inherit (lib) mkOption types;
scopeType = types.enum (import ./user-control-scopes.nix);
in
{
options.services.proxy-suite.userControl = {
@@ -14,21 +16,7 @@ in
};
scopes = mkOption {
type = types.listOf (
types.enum [
"services"
"perApp"
"routing"
"outbounds"
"secrets"
"autoProxy"
"zapret"
"stats"
"inbounds"
"whitelistBypass"
"amneziaWg"
]
);
type = types.listOf scopeType;
default = [ ];
description = ''
What the group may do. Empty allows everything.
@@ -52,5 +40,30 @@ in
"routing"
];
};
groups = mkOption {
type = types.attrsOf (
types.submodule {
options.scopes = mkOption {
type = types.listOf scopeType;
default = [ ];
description = "What this group may do, as in `userControl.scopes`. Empty allows everything.";
};
}
);
default = { };
description = ''
More groups, each with scopes of its own, alongside `userControl.group`. A member gets
what all of their groups allow. `group` stays the one that owns proxy-suite's files;
these are given access to them through POSIX ACLs, so the file systems of
`/var/lib/proxy-suite` and `/run` must support them (the defaults do).
'';
example = lib.literalExpression ''
{
proxy-admins.scopes = [ ];
proxy-users.scopes = [ "perApp" "routing" ];
}
'';
};
};
}
@@ -251,6 +251,18 @@ let
(mkAssertion (cfg.userControl.scopes == [ ] || cfg.userControl.enable)
"proxy-suite: userControl.scopes is set but userControl.enable is false, so the group gets nothing"
)
(mkAssertion (cfg.userControl.groups == { } || cfg.userControl.enable)
"proxy-suite: userControl.groups is set but userControl.enable is false, so those groups get nothing"
)
(mkAssertion
(lib.all (
g:
builtins.match "[a-z_][a-z0-9_-]*" g != null
&& g != cfg.userControl.group
&& g != derived.constants.serviceUser
) (builtins.attrNames cfg.userControl.groups))
"proxy-suite: userControl.groups names must be group names (lowercase letters, digits, - and _), and neither userControl.group nor ${derived.constants.serviceUser}"
)
(requireEnabled (
cfg.warp.enable && cfg.warp.asOutbound != null
) proxyEnabled "proxy-suite: warp.asOutbound requires proxy.enable = true")
+2 -1
View File
@@ -52,7 +52,8 @@ let
builders = import ./builders.nix { inherit lib pkgs; };
polkit = import ./polkit.nix {
inherit lib pkgs userControlCfg;
inherit lib pkgs;
inherit (derived) userControlGroupScopes;
unitNames =
let
declared =
+5
View File
@@ -136,6 +136,8 @@ in
RUNTIME_OUTBOUNDS_DIR = constants.runtimeOutboundsDir;
RUNTIME_SUBS_DIR = constants.runtimeSubscriptionsDir;
USER_CONTROL_GROUP = userControlCfg.group;
# {group: [scopes]}: what proxy-suite-clash-api lets each group's members ask.
USER_CONTROL_GROUPS = builtins.toJSON ctx.clashBrokerGroups;
LOCAL_PROXY_URL = "http://${localProxy.hostPart}:${toString proxyCfg.listener.port}";
AUTOPROXY_ENABLED = flag proxyCfg.autoProxy.enable;
AUTOPROXY_STATE_DIR = constants.autoProxyStateDir;
@@ -146,6 +148,9 @@ in
SERVICE_MANAGER = constants.serviceManager;
PRIVILEGED = flag constants.privileged;
}
// lib.optionalAttrs ctx.clashBrokerEnabled {
CLASH_BROKER = constants.clashBrokerSocket;
}
// lib.optionalAttrs (constants.serviceManager == "supervisor") {
SUPERVISOR_CTL = constants.systemctl;
};
+140 -38
View File
@@ -56,6 +56,50 @@ let
) derived.proxyInbounds;
routingScripts = import ./routing-scripts.nix { inherit (context) ctx; };
# A spool directory the groups holding `scope` write to. userControl.group owns it; with
# only userControl.groups holding the scope, root does, and they get it through ACLs
# (proxy-suite-acls), which the group bits must leave open: they are the ACL mask.
spoolDirMode =
scope:
if userControlAllows scope then
"2770 root ${userControlCfg.group}"
else if derived.userControlAnyAllows scope then
"2770 root root"
else if constants.privileged then
"0700 root root"
else
"0700 - -";
# What proxy-suite-acls opens to userControl.groups: the spools made by tmpfiles, which no
# unit of their own sets up.
aclSpools =
lib.optionals proxyEnabled [
{
path = constants.runtimeOutboundsDir;
scope = "outbounds";
}
{
path = constants.runtimeSubscriptionsDir;
scope = "outbounds";
}
]
++ lib.optional derived.proxyInboundsRuntimeEnabled {
path = constants.runtimeInboundsDir;
scope = "inbounds";
}
++ lib.optional derived.awgRuntimeGlobal {
path = constants.runtimeAwgDir;
scope = "amneziaWg";
}
++ lib.optional derived.zapretCutoffEnabled {
path = "${constants.zapret2CutoffDir}/requests";
scope = "zapret";
}
++ lib.optional cfg.whitelistBypass.enable {
path = "${constants.stateDir}/whitelist-bypass";
scope = "whitelistBypass";
};
serviceUnits = import ./units.nix {
ctx = context.ctx // {
inherit routingScripts;
@@ -109,10 +153,87 @@ let
};
};
};
# The Clash API's secret is root's: members of the userControl groups reach the API through
# this, and only for what their scopes cover (proxy_ctl.py, _broker_allows).
clashBrokerUnit = lib.mkIf (cfg.enable && derived.clashBrokerEnabled) {
services.proxy-suite.internal.services.proxy-suite-clash-api = {
description = "proxy-suite - the Clash API for userControl's groups, as their scopes allow";
after = [ "proxy-suite-socks.service" ];
bindsTo = [ "proxy-suite-socks.service" ];
wantedBy = [ "proxy-suite-socks.service" ];
serviceConfig = {
ExecStart = "${control.proxyCtl}/bin/proxy-ctl proxy clash-broker";
Restart = "on-failure";
RestartSec = 5;
RuntimeDirectory = "proxy-suite-clash";
RuntimeDirectoryMode = "0755";
# Root for the secret's sake (its file is root's), with no capability at all.
CapabilityBoundingSet = [ "" ];
NoNewPrivileges = true;
PrivateTmp = true;
ProtectSystem = "strict";
ProtectHome = true;
ProtectClock = true;
ProtectControlGroups = true;
ProtectHostname = true;
ProtectKernelLogs = true;
ProtectKernelModules = true;
ProtectKernelTunables = true;
RestrictRealtime = true;
RestrictSUIDSGID = true;
LockPersonality = true;
RestrictAddressFamilies = [
"AF_UNIX"
"AF_INET"
"AF_INET6"
];
# The API is on loopback; nothing else to reach.
IPAddressAllow = [ "localhost" ];
IPAddressDeny = [ "any" ];
};
};
};
# userControl.groups cannot own the spools the way userControl.group does: POSIX ACLs let
# them in, set again on every boot and whenever the groups change (a changed unit
# restarts), so a group dropped from the configuration loses what it had. With
# userControl off too: it then only takes away what an earlier configuration granted.
aclUnit = lib.mkIf (cfg.enable && constants.privileged && aclSpools != [ ]) {
services.proxy-suite.internal.services.proxy-suite-acls = {
description = "proxy-suite - give userControl.groups their access to the runtime spools";
wantedBy = [ "multi-user.target" ];
after = [ "systemd-tmpfiles-setup.service" ];
script = lib.concatMapStrings (
spool:
constants.grantDirAcl pkgs (lib.escapeShellArg spool.path)
(derived.userControlExtraGroupsFor spool.scope)
"rwX"
) aclSpools;
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
# It walks directories the groups write to: whatever a name there comes to point
# at, nothing but the spools can change.
ProtectSystem = "strict";
ReadWritePaths = map (spool: "-${spool.path}") aclSpools;
ProtectHome = true;
PrivateTmp = true;
NoNewPrivileges = true;
CapabilityBoundingSet = [
"CAP_FOWNER"
"CAP_DAC_OVERRIDE"
"CAP_DAC_READ_SEARCH"
];
};
};
};
in
lib.mkMerge [
autoProxyUnits
outboundGroupsUnit
clashBrokerUnit
aclUnit
{
services.proxy-suite.internal = {
# The GUI's pkexec needs its setuid wrapper.
@@ -176,9 +297,9 @@ lib.mkMerge [
];
sysctl = tproxyLanSysctl;
groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) [
userControlCfg.group
];
groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) (
[ userControlCfg.group ] ++ derived.userControlExtraGroups
);
polkit.enable = lib.mkIf (cfg.enable && (userControlEnabled || cfg.gui.enable)) true;
# The GUI's "Retry as Root" and root toggle run proxy-ctl through pkexec: one
@@ -195,7 +316,7 @@ lib.mkMerge [
'')
(lib.mkIf (cfg.enable && userControlEnabled) ''
polkit.addRule(function(action, subject) {
if (!subject.isInGroup("${userControlCfg.group}")) {
if (!(${polkit.userControlPolkitMember})) {
return null;
}
@@ -217,49 +338,30 @@ lib.mkMerge [
# outbound before the proxy has ever run.
tmpfiles = lib.mkMerge [
(lib.mkIf (cfg.enable && proxyEnabled) (
map
(
dir:
"d ${dir} ${
if userControlAllows "outbounds" then
"2770 root ${userControlCfg.group}"
else if constants.privileged then
"0700 root root"
else
"0700 - -"
} -"
)
[
constants.runtimeOutboundsDir
constants.runtimeSubscriptionsDir
]
map (dir: "d ${dir} ${spoolDirMode "outbounds"} -") [
constants.runtimeOutboundsDir
constants.runtimeSubscriptionsDir
]
))
# inbounds.runtime: the users' and listeners' files hold their secrets, so the dir is
# as closed as outbounds.d, and group-writable only with the inbounds scope.
(lib.mkIf (cfg.enable && derived.proxyInboundsRuntimeEnabled) (
map
(
dir:
"d ${dir} ${
if userControlAllows "inbounds" then
"2770 root ${userControlCfg.group}"
else if constants.privileged then
"0700 root root"
else
"0700 - -"
} -"
)
[
constants.runtimeInboundsDir
"${constants.runtimeInboundsDir}/users"
"${constants.runtimeInboundsDir}/listeners"
]
map (dir: "d ${dir} ${spoolDirMode "inbounds"} -") [
constants.runtimeInboundsDir
"${constants.runtimeInboundsDir}/users"
"${constants.runtimeInboundsDir}/listeners"
]
))
# Global AmneziaWG profiles added at runtime. Listable, so the tray and TUI show
# their names to everyone; each file is 0600 (amneziawg_config.py writes it so).
(lib.mkIf (cfg.enable && derived.awgRuntimeGlobal) [
"d ${constants.runtimeAwgDir} ${
if userControlAllows "amneziaWg" then "2775 root ${userControlCfg.group}" else "0755 root root"
if userControlAllows "amneziaWg" then
"2775 root ${userControlCfg.group}"
else if derived.userControlAnyAllows "amneziaWg" then
"2775 root root"
else
"0755 root root"
} -"
])
];
+12 -5
View File
@@ -8,7 +8,8 @@
{
lib,
pkgs,
userControlCfg,
# {group: [scopes]}, every scope spelled out (derived.nix).
userControlGroupScopes,
# Declared system units, "name.service" or "name.timer"; templates as "name@".
unitNames,
}:
@@ -88,10 +89,16 @@ in
break;
}
}
// No scopes listed means all of them.
var scopes = ${builtins.toJSON userControlCfg.scopes};
if (scopes.length === 0 || scopes.indexOf(scope) !== -1) {
return polkit.Result.YES;
// Any of the subject's groups that holds the scope.
var groupScopes = ${builtins.toJSON userControlGroupScopes};
for (var group in groupScopes) {
if (groupScopes[group].indexOf(scope) !== -1 && subject.isInGroup(group)) {
return polkit.Result.YES;
}
}
'';
# Whether the subject is in any userControl group at all: the rule's first test.
userControlPolkitMember = lib.concatMapStringsSep " || " (
group: "subject.isInGroup(${builtins.toJSON group})"
) (builtins.attrNames userControlGroupScopes);
}
@@ -15,6 +15,7 @@ let
proxyInboundViaOutbounds
userControlCfg
userControlAllows
userControlExtraGroupsFor
localProxyAuth
localProxyAuthEnabled
localProxyAuthPasswordSource
@@ -150,6 +151,7 @@ let
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${linksFile}"
''}
chmod ${if userControlAllows "secrets" then "640" else "600"} "${linksFile}"
${constants.grantFileAcl pkgs ''"${linksFile}"'' (userControlExtraGroupsFor "secrets") "r"}
'';
# One file per user for the web server, plus a token index for proxy-ctl. Filled aside
@@ -173,6 +175,7 @@ let
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${subscriptionsFile}"
''}
chmod ${if userControlAllows "secrets" then "640" else "600"} "${subscriptionsFile}"
${constants.grantFileAcl pkgs ''"${subscriptionsFile}"'' (userControlExtraGroupsFor "secrets") "r"}
'';
startInbounds = pkgs.writeShellScript "proxy-suite-inbounds" ''
@@ -262,6 +265,10 @@ let
chmod 640 "$RUNTIME_DIR/config.json.tmp"
''
}
${constants.grantFileAcl pkgs ''"$RUNTIME_DIR/config.json.tmp"''
(userControlExtraGroupsFor "secrets")
"r"
}
mv "$RUNTIME_DIR/config.json.tmp" "$RUNTIME_DIR/config.json"
# The stats API's socket takes this setgid directory's group: XRay cannot chown it.
@@ -277,6 +284,13 @@ let
else
''install -d -m 2750 -o ${constants.serviceUser} -g ${constants.serviceUser} "$API_DIR"''
}
# userControl.groups with the stats scope: into the directory, and onto the socket XRay
# makes in it as its own group is (a default entry; the socket's mode caps it).
${lib.optionalString (constants.privileged && userControlExtraGroupsFor "stats" != [ ]) ''
${pkgs.acl}/bin/setfacl -m ${
lib.concatMapStringsSep "," (g: "g:${g}:rx,d:g:${g}:rwx") (userControlExtraGroupsFor "stats")
} -- "$API_DIR"
''}
${writeLinksBlock}
${writeSubscriptionsBlock}
@@ -326,6 +340,7 @@ let
echo "proxy-suite: group ${userControlCfg.group} cannot read the stats; they stay root-only" >&2
''}
chmod ${if userControlAllows "stats" then "640" else "600"} "$tmp"
${constants.grantFileAcl pkgs ''"$tmp"'' (userControlExtraGroupsFor "stats") "r"}
mv -f "$tmp" "$file"
'';
# inbounds.runtime: after proxy-ctl changes the spool. The AmneziaWG interfaces only when
+26 -17
View File
@@ -166,6 +166,11 @@ let
} > "${runtimeProxychainsConfig}"
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${runtimeProxychainsConfig}"''}
chmod 640 "${runtimeProxychainsConfig}"
# It holds the proxy's password: userControl.groups that run apps through proxychains.
${constants.grantFileAcl pkgs ''"${runtimeProxychainsConfig}"''
(ctx.userControlExtraGroupsFor "perApp")
"r"
}
'';
mkStartScript =
@@ -231,7 +236,7 @@ let
AUTOPROXY_DIR=${lib.escapeShellArg autoProxyStateDir}
# 0751: sing-box, running as ${constants.serviceUser}, reaches the rules/ inside;
# 0771 with userControl's autoProxy scope, whose group queues learn requests there.
install -d -m ${if userControlAllows "autoProxy" then "0771" else "0751"} "$AUTOPROXY_DIR"
install -d -m ${if ctx.userControlAnyAllows "autoProxy" then "0771" else "0751"} "$AUTOPROXY_DIR"
[ -s "$AUTOPROXY_DIR/state.json" ] || echo '{"domains":{},"hosts":{},"exits":{},"backlog":{}}' > "$AUTOPROXY_DIR/state.json"
# direct is always exit 0; state is keyed by tag, so shifting indices are
@@ -293,6 +298,7 @@ let
''
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$ENDPOINTS_TMP"''}
chmod 640 "$ENDPOINTS_TMP"
${constants.grantFileAcl pkgs ''"$ENDPOINTS_TMP"'' ctx.userControlExtraGroups "r"}
''
else
''chmod 600 "$ENDPOINTS_TMP"''
@@ -314,6 +320,7 @@ let
' <<< "$OUTBOUNDS_JSON" > "$SHARE_TMP")
${lib.optionalString (userControlAllows "secrets") ''${chgrp} ${userControlGroup} "$SHARE_TMP"''}
chmod ${if userControlAllows "secrets" then "640" else "600"} "$SHARE_TMP"
${constants.grantFileAcl pkgs ''"$SHARE_TMP"'' (ctx.userControlExtraGroupsFor "secrets") "r"}
mv "$SHARE_TMP" "$RUNTIME_DIR/outbound-share.json"
${lib.optionalString (!pureXrayEnabled) ''
@@ -388,22 +395,23 @@ let
''}
# The Clash API lists every connection and switches outbounds. Loopback alone lets
# every local user at it, and every web page too (sing-box allows any origin): a
# secret per start, readable where outbound-endpoints.json is.
# secret per start.
BACKEND_EXTRA_CONFIG=()
if ${jq} -e '.experimental.clash_api? != null' "$RUNTIME_DIR/config.json" >/dev/null; then
CLASH_SECRET=$(${pkgs.coreutils}/bin/od -An -tx1 -N24 /dev/urandom | ${pkgs.coreutils}/bin/tr -d ' \n')
(umask 077 && ${jq} --rawfile s <(printf '%s' "$CLASH_SECRET") '.experimental.clash_api.secret = $s' \
"$RUNTIME_DIR/config.json" > "$RUNTIME_DIR/config.json.next")
mv "$RUNTIME_DIR/config.json.next" "$RUNTIME_DIR/config.json"
# Not in config.json, which the secrets scope reads (`proxy config --raw`): the
# backend's alone, which sing-box merges in (a second -c).
(umask 077 && ${jq} -n --rawfile s <(printf '%s' "$CLASH_SECRET") '{experimental: {clash_api: {secret: $s}}}' \
> "$RUNTIME_DIR/clash-api.json.tmp")
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chown ${constants.serviceUser}:${constants.serviceUser} "$RUNTIME_DIR/clash-api.json.tmp"''}
chmod 400 "$RUNTIME_DIR/clash-api.json.tmp"
mv "$RUNTIME_DIR/clash-api.json.tmp" "$RUNTIME_DIR/clash-api.json"
BACKEND_EXTRA_CONFIG=(-c "$RUNTIME_DIR/clash-api.json")
# Root's alone where the host is privileged: userControl's groups ask
# proxy-suite-clash-api, which lets them do what their scopes cover. A rootless host
# runs as its one user anyway.
(umask 077 && printf '%s\n' "$CLASH_SECRET" > "$RUNTIME_DIR/clash-secret.tmp")
${
if userControlCfg.enable || localProxyAuthEnabled then
''
${constants.ifPrivileged ''${chgrp} ${userControlGroup} "$RUNTIME_DIR/clash-secret.tmp"''}
chmod 640 "$RUNTIME_DIR/clash-secret.tmp"
''
else
''chmod 600 "$RUNTIME_DIR/clash-secret.tmp"''
}
chmod 600 "$RUNTIME_DIR/clash-secret.tmp"
mv "$RUNTIME_DIR/clash-secret.tmp" "$RUNTIME_DIR/clash-secret"
fi
# Credentials, read by the backend running as ${constants.serviceUser}. With
@@ -423,6 +431,7 @@ let
chmod 640 "$backend_config"
''
}
${constants.grantFileAcl pkgs ''"$backend_config"'' (ctx.userControlExtraGroupsFor "secrets") "r"}
done
FAKE_IP_CACHE=$(${jq} -r '.experimental.cache_file.path? // empty' "$RUNTIME_DIR/config.json")
if [ -n "$FAKE_IP_CACHE" ]; then
@@ -452,7 +461,7 @@ let
exit "$XRAY_SIDECAR_STATUS"
fi
${runBackend} ${singBox} run -c "$RUNTIME_DIR/config.json" &
${runBackend} ${singBox} run -c "$RUNTIME_DIR/config.json" "''${BACKEND_EXTRA_CONFIG[@]}" &
SING_BOX_PID="$!"
# Either one going away breaks the outbounds: exit, and let systemd restart both.
SING_BOX_STATUS=0
@@ -460,11 +469,11 @@ let
exit "$(( SING_BOX_STATUS == 0 ? 1 : SING_BOX_STATUS ))"
fi
exec ${runBackend} ${singBox} run -c "$RUNTIME_DIR/config.json"
exec ${runBackend} ${singBox} run -c "$RUNTIME_DIR/config.json" "''${BACKEND_EXTRA_CONFIG[@]}"
''
else
''
exec ${runBackend} ${backendBin} run -c "$RUNTIME_DIR/config.json"
exec ${runBackend} ${backendBin} run -c "$RUNTIME_DIR/config.json" "''${BACKEND_EXTRA_CONFIG[@]}"
''
}
'';
+8 -2
View File
@@ -28,10 +28,16 @@ let
# Logins, calls and the links joiners take at runtime (`proxy-ctl wl auth|join|new`); the
# whitelistBypass scope's group writes them too. tmpfiles makes it before any unit has run,
# so a creator or joiner that waits on a file there can be given one.
groupAccess = privileged && derived.userControlAllows "whitelistBypass";
# Groups in userControl.groups get it through ACLs (proxy-suite-acls), which the mode must
# leave open: systemd applies it on every start.
groupAccess = privileged && derived.userControlAnyAllows "whitelistBypass";
stateDir = "${derived.constants.stateDir}/whitelist-bypass";
stateMode = if groupAccess then "0770" else "0700";
stateGroup = if groupAccess then cfg.userControl.group else serviceUser;
stateGroup =
if privileged && derived.userControlAllows "whitelistBypass" then
cfg.userControl.group
else
serviceUser;
# A runtime file the unit cannot start without, when nothing in the configuration stands in.
waitFor = file: {
unitConfig.ConditionPathExists = "%S/proxy-suite/whitelist-bypass/${file}";
+12 -2
View File
@@ -19,6 +19,8 @@ let
inherit (import ./derived.nix { inherit lib cfg; })
constants
userControlAllows
userControlAnyAllows
userControlExtraGroupsFor
zapretGlobalEnabled
;
inherit
@@ -88,9 +90,17 @@ let
mkPreStart = ''
${lib.getExe' pkgs.kmod "modprobe"} nfnetlink_queue 2>/dev/null || true
install -d -m ${
if userControlAllows "zapret" then "2775 -g ${lib.escapeShellArg cfg.userControl.group}" else "0755"
if userControlAllows "zapret" then
"2775 -g ${lib.escapeShellArg cfg.userControl.group}"
# userControl.groups only, through ACLs: the group bits (their mask) stay open.
else if userControlAnyAllows "zapret" then
"2775"
else
"0755"
} ${runtime.stateDir} ${runtime.circularStateDir}
touch ${runtime.autoHostlistFile} ${runtime.userHostlistFile} ${runtime.excludeHostlistFile}
# In this unit's sandbox: a name a member left here leads nowhere else.
${constants.grantDirAcl pkgs runtime.stateDir (userControlExtraGroupsFor "zapret") "rwX"}
${runtime.initScript} start_fw
'';
@@ -102,7 +112,7 @@ let
ExecReload = "${lib.getExe' pkgs.coreutils "kill"} -HUP $MAINPID";
Environment = runtimeEnv;
# Its own part of the state only: under the sandbox below, the rest stays read-only.
StateDirectoryMode = if userControlAllows "zapret" then "2775" else "0755";
StateDirectoryMode = if userControlAnyAllows "zapret" then "2775" else "0755";
}
# systemd gives the state directory the unit's group on every start: the group's, which
# edits the lists (as autoProxy's units do).
+8 -1
View File
@@ -15,6 +15,7 @@ let
inherit (import ../derived.nix { inherit lib cfg; })
constants
userControlAllows
userControlAnyAllows
zapretGlobalEnabled
;
z2k = zapret2Sources.z2k;
@@ -180,7 +181,13 @@ in
tmpfiles = [
"d ${dir}/requests ${
if userControlAllows "zapret" then "2770 root ${cfg.userControl.group}" else "0700 root root"
if userControlAllows "zapret" then
"2770 root ${cfg.userControl.group}"
# userControl.groups only, through ACLs (proxy-suite-acls): the mode keeps them open.
else if userControlAnyAllows "zapret" then
"2770 root root"
else
"0700 root root"
} -"
];
+12
View File
@@ -93,6 +93,18 @@ in
true
)
# listener.auth alone: the Clash API's secret stays root's, and the group that reads the
# login only reads through proxy-suite-clash-api (no scopes).
(
let
env = (mkProxyCtlDerived localProxyAuthFixture).proxyCtl.proxySuiteCheck.wrapperEnv;
in
assert localProxyAuthFixture.config.systemd.services ? proxy-suite-clash-api;
assert builtins.fromJSON env.USER_CONTROL_GROUPS == { proxy-suite = [ ]; };
assert pkgs.lib.hasInfix "chmod 600 \"$RUNTIME_DIR/clash-secret.tmp\"" localProxyAuthStartScript;
true
)
# Authenticated mixed inbound is injected at runtime.
(
assert pkgs.lib.hasInfix ''LOCAL_PROXY_PASSWORD="$(cat "'' localProxyAuthStartScript;
+1
View File
@@ -62,6 +62,7 @@ let
pkgs
evalProxySuite
baseModule
mkProxyCtlDerived
;
};
proxychainsChecks = import ./per-app-routing-proxychains.nix {
+106 -2
View File
@@ -3,6 +3,7 @@
pkgs,
evalProxySuite,
baseModule,
mkProxyCtlDerived,
}:
let
@@ -35,11 +36,32 @@ let
enable = true;
group = "vpnops";
};
# The primary group routes; proxy-admins may do anything, proxy-users what is listed.
multiGroupFixture = mkFixture {
enable = true;
scopes = [ "routing" ];
groups = {
proxy-admins.scopes = [ ];
proxy-users.scopes = [
"perApp"
"outbounds"
];
};
};
disabledFixture = mkFixture { };
scopesWithoutEnableFixture = mkFixture { scopes = [ "routing" ]; };
groupsWithoutEnableFixture = mkFixture { groups.proxy-users.scopes = [ "routing" ]; };
primaryInGroupsFixture = mkFixture {
enable = true;
groups.proxy-suite.scopes = [ "routing" ];
};
polkitConfig = fixture: fixture.config.security.polkit.extraConfig;
service = fixture: name: fixture.config.systemd.services.${name}.serviceConfig;
hasUnit = fixture: name: fixture.config.systemd.services ? ${name};
failedAssertion =
fixture: text: builtins.any (a: !a.assertion && hasInfix text a.message) fixture.config.assertions;
wrapperEnv = fixture: (mkProxyCtlDerived fixture).proxyCtl.proxySuiteCheck.wrapperEnv;
# 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.
@@ -75,7 +97,10 @@ in
# -- userControl: enabled without scopes grants every scope --
(
assert allFixture.config.users.groups ? "proxy-suite";
assert hasInfix "var scopes = [];" (polkitConfig allFixture);
# No scopes listed: every one of them, spelled out.
assert hasInfix "var groupScopes = {\"proxy-suite\":[\"services\",\"perApp\"," (
polkitConfig allFixture
);
assert hasInfix "subject.isInGroup(\"proxy-suite\")" (polkitConfig allFixture);
assert hasInfix "\"proxy-suite-zapret2-cutoff.\":\"zapret\"" (polkitConfig allFixture);
# Declared units by name: systemd asks polkit the same question, with the same unit
@@ -133,7 +158,9 @@ in
# -- userControl: a listed scope grants only itself --
(
assert hasInfix "var scopes = [\"routing\"];" (polkitConfig routingOnlyFixture);
assert hasInfix "var groupScopes = {\"proxy-suite\":[\"routing\"]};" (
polkitConfig routingOnlyFixture
);
assert rootOnlySecrets routingOnlyFixture;
assert
autoProxyGroups routingOnlyFixture == [
@@ -148,12 +175,89 @@ in
true
)
# -- userControl.groups: each group its own scopes, the files opened through ACLs --
(
let
fixture = multiGroupFixture;
polkit = polkitConfig fixture;
start = socksStart fixture;
acls = fixture.config.systemd.services.proxy-suite-acls.script;
derived = import ../../modules/proxy-suite/derived.nix {
inherit (pkgs) lib;
cfg = fixture.config.services.proxy-suite;
};
in
assert fixture.config.users.groups ? "proxy-admins";
assert fixture.config.users.groups ? "proxy-users";
assert hasInfix
"subject.isInGroup(\"proxy-admins\") || subject.isInGroup(\"proxy-suite\") || subject.isInGroup(\"proxy-users\")"
polkit;
assert hasInfix "\"proxy-suite\":[\"routing\"],\"proxy-users\":[\"perApp\",\"outbounds\"]}" polkit;
assert hasInfix "\"proxy-admins\":[\"services\",\"perApp\"," polkit;
# outbounds.d: the primary group lacks the scope, so root owns it and the mode keeps
# the ACL mask open for those that hold it.
assert builtins.elem "d /var/lib/proxy-suite/outbounds.d 2770 root root -" (
fixture.config.systemd.tmpfiles.rules
);
# -n: the mask stays each file's group bits, so a 0600 file stays closed to them.
assert hasInfix
"setfacl -R -P -n -m g:proxy-admins:rwX,d:g:proxy-admins:rwX,g:proxy-users:rwX,d:g:proxy-users:rwX -- /var/lib/proxy-suite/outbounds.d"
acls;
# What was granted before goes first: a dropped group loses its access.
assert hasInfix "setfacl -R -P -b -- /var/lib/proxy-suite/outbounds.d" acls;
assert (service fixture "proxy-suite-acls").ProtectSystem == "strict";
# autoProxy: proxy-admins only, the primary group not at all.
assert
autoProxyGroups fixture == [
null
null
null
];
assert (service fixture "proxy-suite-autoproxy").StateDirectoryMode == "0771";
assert derived.userControlExtraGroupsFor "autoProxy" == [ "proxy-admins" ];
assert pkgs.lib.hasSuffix "-proxy-suite-autoproxy-acl"
(service fixture "proxy-suite-autoproxy").ExecStartPre;
# Secrets to proxy-admins alone, still 600 for the primary group.
assert hasInfix "chmod 600 \"$SHARE_TMP\"" start;
assert hasInfix "setfacl -m g:proxy-admins:r -- \"$SHARE_TMP\"" start;
assert !(hasInfix "g:proxy-users:r -- \"$SHARE_TMP\"" start);
# The Clash API's secret stays root's; the broker answers the groups.
assert hasInfix "chmod 600 \"$RUNTIME_DIR/clash-secret.tmp\"" start;
# Nor in config.json, which the secrets scope reads: sing-box merges it in.
assert !(hasInfix ".experimental.clash_api.secret = " start);
assert hasInfix "chmod 400 \"$RUNTIME_DIR/clash-api.json.tmp\"" start;
assert hasInfix "run -c \"$RUNTIME_DIR/config.json\" \"\${BACKEND_EXTRA_CONFIG[@]}\"" start;
assert (service fixture "proxy-suite-clash-api").CapabilityBoundingSet == [ "" ];
assert
builtins.fromJSON (wrapperEnv fixture).USER_CONTROL_GROUPS == {
proxy-admins = import ../../modules/proxy-suite/options/user-control-scopes.nix;
proxy-suite = [ "routing" ];
proxy-users = [
"perApp"
"outbounds"
];
};
assert (wrapperEnv fixture).CLASH_BROKER == "/run/proxy-suite-clash/api.sock";
true
)
# -- userControl.groups: refused without enable, and never the primary group again --
(ok (failedAssertion groupsWithoutEnableFixture "userControl.groups is set"))
(ok (failedAssertion primaryInGroupsFixture "userControl.groups names must be group names"))
# -- 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 !(hasUnit disabledFixture "proxy-suite-clash-api");
# Only taking away what an earlier configuration granted.
assert hasInfix "setfacl -R -P -b -- /var/lib/proxy-suite/outbounds.d" (
disabledFixture.config.systemd.services.proxy-suite-acls.script
);
assert !(hasInfix " -m " disabledFixture.config.systemd.services.proxy-suite-acls.script);
assert !((wrapperEnv disabledFixture) ? CLASH_BROKER);
assert
autoProxyGroups disabledFixture == [
null
+250 -11
View File
@@ -291,7 +291,15 @@ def ask_group():
"""What lets a refused user in: root, or userControl's group with the scope for it."""
if not privileged():
return "check its owner and permissions"
return f"join the {env('USER_CONTROL_GROUP', 'proxy-suite')} group, or re-run with sudo"
primary = env("USER_CONTROL_GROUP", "proxy-suite")
# userControl.groups too, each with scopes of its own: whichever holds the one needed.
try:
groups = [primary] + sorted(g for g in json.loads(env("USER_CONTROL_GROUPS") or "{}") if g != primary)
except (ValueError, TypeError):
groups = [primary]
if len(groups) == 1:
return f"join the {primary} group, or re-run with sudo"
return f"join a userControl group whose scopes allow it ({', '.join(groups)}), or re-run with sudo"
def denied(path, what="read"):
@@ -1205,6 +1213,9 @@ def cmd_proxy(verb="status", *args):
# A mode stopped on purpose lifts the kill switch; one that fails leaves it up.
if action == "off" and svc_exists(KILL_SWITCH):
systemctl("stop", KILL_SWITCH)
elif verb == "clash-broker":
# proxy-suite-clash-api's ExecStart.
_clash_broker_serve()
elif verb == "auto":
cmd_proxy_auto(*args)
elif verb in ("probe", "learn", "forget", "relearn", "queue", "learned"):
@@ -1298,19 +1309,43 @@ def _local_proxy_login():
return None
def _clash(method, path, body=None, timeout=10):
"""(HTTP status, JSON body or None) from the backend's Clash API; status 0 when unreachable."""
# The API is on loopback: never through the shell's HTTP(S)_PROXY.
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
data = None if body is None else json.dumps(body).encode()
headers = {"Content-Type": "application/json"}
# The socks start script's secret for this run: root and the userControl group read it.
# Anyone else gets 401, which reads as no API.
def _clash_secret():
"""The socks start script's secret for this run: root only (the broker hands the rest out)."""
try:
with open(_runtime_file("clash-secret"), encoding="utf-8") as f:
headers["Authorization"] = f"Bearer {f.read().strip()}"
return f.read().strip()
except (OSError, UnicodeError):
pass
return None
def _clash(method, path, body=None, timeout=10):
"""(HTTP status, JSON body or None) from the backend's Clash API; status 0 when unreachable.
Root reads the secret and asks the API itself; anyone else asks proxy-suite-clash-api,
which lets a userControl group's member make the requests their scopes allow.
"""
secret = _clash_secret()
broker = env("CLASH_BROKER")
if secret is None and broker and os.path.exists(broker):
return _clash_via_broker(broker, method, path, body, timeout)
return _clash_direct(method, path, body, timeout, secret)
class _NoRedirect(urllib.request.HTTPRedirectHandler):
"""The Clash API never redirects: one that did would lead the broker past its checks."""
def redirect_request(self, *_):
return None
def _clash_direct(method, path, body, timeout, secret):
# The API is on loopback: never through the shell's HTTP(S)_PROXY.
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect)
data = None if body is None else json.dumps(body).encode()
headers = {"Content-Type": "application/json"}
# Without the secret the API answers 401, which reads as no API.
if secret is not None:
headers["Authorization"] = f"Bearer {secret}"
try:
# Building the request is part of reaching the API: an unset or malformed
# CLASH_API is "unreachable", not a traceback out of `status` or `where`.
@@ -1329,6 +1364,210 @@ def _clash(method, path, body=None, timeout=10):
return status, None
class _UnixHTTPConnection(http.client.HTTPConnection):
def __init__(self, path, timeout):
super().__init__("localhost", timeout=timeout)
self._path = path
def connect(self):
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.settimeout(self.timeout)
self.sock.connect(self._path)
def _clash_via_broker(broker, method, path, body, timeout):
conn = _UnixHTTPConnection(broker, timeout + 5)
try:
conn.request(method, path, body=None if body is None else json.dumps(body), headers={"Content-Type": "application/json"})
response = conn.getresponse()
status, raw = response.status, response.read()
except (OSError, http.client.HTTPException):
return 0, None
finally:
conn.close()
# The broker's own "not the API": unreachable, as a direct call would read.
if status == 502:
return 0, None
try:
return status, json.loads(raw) if raw else None
except ValueError:
return status, None
# --- the Clash API broker -------------------------------------------------------
#
# proxy-suite-clash-api: the Clash API's secret is root's; members of the userControl groups
# reach the API through this, and only for what their scopes cover. A bare secret would
# let any of them switch what everyone dials and see everyone's connections.
CLASH_TEST_SELECTOR = "proxy-suite-test"
CLASH_BROKER_MAX_BODY = 64 * 1024
# Any local user may connect: a caller that stalls, or opens many, holds no thread for long
# and never all of them.
CLASH_BROKER_TIMEOUT = 15
CLASH_BROKER_MAX_CLIENTS = 64
def _peer_uid(sock):
import struct
creds = sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i"))
return struct.unpack("3i", creds)[1]
def _broker_scopes(uid):
"""The scopes a caller holds, "*" for root; None when it is in no userControl group."""
if uid == 0:
return {"*"}
import grp
import pwd
try:
user = pwd.getpwuid(uid)
gids = os.getgrouplist(user.pw_name, user.pw_gid)
except (KeyError, OSError):
return None
try:
table = json.loads(env("USER_CONTROL_GROUPS") or "{}")
except ValueError:
table = {}
held = None
for gid in gids:
try:
name = grp.getgrgid(gid).gr_name
except KeyError:
continue
if isinstance(table.get(name), list):
held = (held or set()) | set(table[name])
return held
def _broker_allows(method, path, scopes):
"""Whether a caller holding `scopes` may make this request; `path` without its query.
Only what proxy-ctl asks: reads and delay tests for any member, the download test's own
selector too, switching the others with `routing`, live connections with `secrets`.
Nothing else: not closing connections, the config, the logs or the traffic stream.
"""
if "*" in scopes:
return True
parts = path.split("/")[1:] if path.startswith("/") else None
# Names as the API's router reads them: a "%2F" or "%2E%2E" in one must not turn
# /proxies/<name> into another endpoint once decoded and cleaned.
if not parts or any(not p or "/" in (u := urllib.parse.unquote(p)) or u in (".", "..") for p in parts):
return False
if method == "GET":
return (
parts == ["proxies"]
or (parts[0] == "proxies" and len(parts) == 2)
or (parts[0] in ("proxies", "group") and len(parts) == 3 and parts[2] == "delay")
or (parts == ["connections"] and "secrets" in scopes)
)
if method == "PUT" and parts[0] == "proxies" and len(parts) == 2:
return urllib.parse.unquote(parts[1]) == CLASH_TEST_SELECTOR or "routing" in scopes
return False
def _clash_broker_serve():
"""proxy-suite-clash-api's ExecStart: an HTTP server on a Unix socket in front of the API."""
path = env("CLASH_BROKER")
if not path:
die("CLASH_BROKER is not set.")
server = _clash_broker_server(path)
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
server.serve_forever()
def _clash_broker_server(path):
import http.server
import socketserver
import threading
class Handler(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.0"
timeout = CLASH_BROKER_TIMEOUT
def _reply(self, status, payload):
raw = json.dumps(payload).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def _handle(self, method):
uid = _peer_uid(self.connection)
scopes = _broker_scopes(uid)
parts = urllib.parse.urlsplit(self.path)
if scopes is None or not _broker_allows(method, parts.path, scopes):
# repr: the path is the caller's, escape sequences and all.
print(f"proxy-suite-clash-api: refused uid {uid}: {method} {parts.path!r}", file=sys.stderr)
return self._reply(403, {"message": "not allowed for your userControl scopes"})
body = None
if method == "PUT":
try:
length = int(self.headers.get("Content-Length") or 0)
except ValueError:
length = -1
if not 0 <= length <= CLASH_BROKER_MAX_BODY:
return self._reply(400, {"message": "bad request body"})
try:
body = json.loads(self.rfile.read(length) or b"null")
except ValueError:
return self._reply(400, {"message": "bad request body"})
target = parts.path + (f"?{parts.query}" if parts.query else "")
status, answer = _clash_direct(method, target, body, 30, _clash_secret())
# 502: the API itself could not be reached, which the client reads as no API.
self._reply(status or 502, answer)
def do_GET(self):
self._handle("GET")
def do_PUT(self):
self._handle("PUT")
def log_message(self, *_):
pass
class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
daemon_threads = True
slots = threading.BoundedSemaphore(CLASH_BROKER_MAX_CLIENTS)
def verify_request(self, request, client_address):
# Someone in no userControl group is closed on before sending a byte.
try:
return _broker_scopes(_peer_uid(request)) is not None
except OSError:
return False
def process_request(self, request, client_address):
# A full house holds the next one back a while (proxy-ctl alone tests 16
# outbounds at once), then lets it go.
if not self.slots.acquire(timeout=CLASH_BROKER_TIMEOUT):
self.shutdown_request(request)
return
try:
super().process_request(request, client_address)
except BaseException:
self.slots.release()
raise
def process_request_thread(self, request, client_address):
try:
super().process_request_thread(request, client_address)
finally:
self.slots.release()
try:
os.unlink(path)
except FileNotFoundError:
pass
server = Server(path, Handler)
# Anyone may connect: whom the broker answers, and with what, it decides per request.
os.chmod(path, 0o666)
return server
# --- proxy outbounds test -----------------------------------------------------
#
# ping: a TCP connect to each outbound's server, from this host. delay: the
+108
View File
@@ -7,6 +7,7 @@ import json
import os
import shutil
import socket
import stat
import sys
import tempfile
import threading
@@ -116,6 +117,107 @@ class ClashApiTest(EnvTest):
self.assertEqual(ctl._outbound_current(), "")
class ClashBrokerTest(EnvTest):
def test_what_each_scope_may_ask(self):
allows = ctl._broker_allows
member, routing, secrets = set(), {"routing"}, {"secrets"}
for method, path, scopes, expected in (
("GET", "/proxies", member, True),
("GET", "/proxies/proxy", member, True),
("GET", "/proxies/DE%20one/delay", member, True),
("GET", "/group/g/delay", member, True),
("PUT", "/proxies/proxy-suite-test", member, True),
("PUT", "/proxies/proxy", member, False),
("PUT", "/proxies/proxy", routing, True),
("GET", "/connections", member, False),
("GET", "/connections", secrets, True),
("DELETE", "/connections", secrets, False),
("PATCH", "/configs", routing, False),
("GET", "/logs", secrets, False),
("GET", "/proxies/a/b/c", member, False),
("GET", "/proxies/", member, False),
# Decoded and cleaned by the API's router, these name another endpoint.
("GET", "/proxies/%2E%2E%2Fconnections", member, False),
("GET", "/proxies/..", member, False),
("PUT", "/proxies/%2E%2E", routing, False),
("GET", "/anything", {"*"}, True),
):
with self.subTest(method=method, path=path, scopes=scopes):
self.assertEqual(allows(method, path, scopes), expected)
def test_root_reads_the_secret_everyone_else_asks_the_broker(self):
os.environ["CLASH_BROKER"] = self.write("api.sock", "")
self.patch("_clash_via_broker", lambda *a: (200, {"via": "broker"}))
self.patch("_clash_direct", lambda *a: (200, {"via": "direct"}))
self.patch("_clash_secret", lambda: None)
self.assertEqual(ctl._clash("GET", "/proxies"), (200, {"via": "broker"}))
self.patch("_clash_secret", lambda: "s")
self.assertEqual(ctl._clash("GET", "/proxies"), (200, {"via": "direct"}))
@unittest.skipIf(os.geteuid() == 0, "root holds every scope")
def test_end_to_end(self):
import grp
import http.server
try:
group = grp.getgrgid(os.getgid()).gr_name
except KeyError:
self.skipTest("no name for this group")
seen = []
class Api(http.server.BaseHTTPRequestHandler):
def _answer(self):
seen.append((self.command, self.path, self.headers.get("Authorization")))
raw = json.dumps({"path": self.path}).encode()
self.send_response(200)
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
do_GET = do_PUT = _answer
def log_message(self, *_):
pass
api = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Api)
self.addCleanup(api.server_close)
threading.Thread(target=api.serve_forever, daemon=True).start()
self.addCleanup(api.shutdown)
self.write("clash-secret", "s3cret\n")
sock = self.path("api.sock")
os.environ.update(
CLASH_API=f"http://127.0.0.1:{api.server_address[1]}",
OUTBOUND_INVENTORY_FILE=self.path("outbounds.json"),
USER_CONTROL_GROUPS=json.dumps({group: ["routing"]}),
)
self.patch("CLASH_BROKER_TIMEOUT", 1)
broker = ctl._clash_broker_server(sock)
self.addCleanup(broker.server_close)
threading.Thread(target=broker.serve_forever, daemon=True).start()
self.addCleanup(broker.shutdown)
self.assertEqual(stat.S_IMODE(os.stat(sock).st_mode), 0o666)
ask = lambda method, path, body=None: ctl._clash_via_broker(sock, method, path, body, 5) # noqa: E731
self.assertEqual(ask("GET", "/proxies/proxy/delay?url=x&timeout=1"), (200, {"path": "/proxies/proxy/delay?url=x&timeout=1"}))
self.assertEqual(ask("PUT", "/proxies/proxy", {"name": "de"})[0], 200)
with contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(ask("GET", "/connections")[0], 403)
# The secret reaches the API, never the caller; the refused request never left.
self.assertEqual([s[2] for s in seen], ["Bearer s3cret", "Bearer s3cret"])
self.assertNotIn("/connections", [s[1] for s in seen])
# One that connects and says nothing holds up no one else, and not for long.
stalled = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.addCleanup(stalled.close)
stalled.connect(sock)
self.assertEqual(ask("GET", "/proxies")[0], 200)
stalled.settimeout(5)
self.assertEqual(stalled.recv(1), b"")
# In no group at all: closed on unheard, which reads as no API.
os.environ["USER_CONTROL_GROUPS"] = json.dumps({"someone-else": []})
self.assertEqual(ask("GET", "/proxies"), (0, None))
self.assertEqual(len(seen), 3)
class WarpDevicesTest(EnvTest):
def test_every_device_or_the_one_named(self):
os.environ["WARP_DEVICES"] = json.dumps([{"tag": "warp-1", "unit": "proxy-suite-awg-warp-1"}, {"tag": "warp-2", "unit": "proxy-suite-awg-warp-2"}])
@@ -685,6 +787,12 @@ class ServiceManagerTest(EnvTest):
os.environ["PRIVILEGED"] = "0"
self.assertNotIn("sudo", ctl.ask_group())
def test_names_every_user_control_group(self):
os.environ.update(USER_CONTROL_GROUP="proxy-suite", USER_CONTROL_GROUPS=json.dumps({"proxy-suite": [], "users": ["perApp"]}))
self.assertIn("(proxy-suite, users)", ctl.ask_group())
os.environ["USER_CONTROL_GROUPS"] = json.dumps({"proxy-suite": []})
self.assertIn("join the proxy-suite group", ctl.ask_group())
class AutoProxyTest(EnvTest):
def setUp(self):