refactor: users single-point

This commit is contained in:
fufsob committed 2026-09-29 05:39:33 +00:00
1 parent c8b9b3de46
commit a4752049ef
35 files changed
+1009 -381

No files matched your search

@@ -16,6 +16,62 @@ let
localProxyAddress = derived.localProxy.host;
# Checked on the address actually dialed, so a name resolving private is caught too
# (routing's geoip:private sees only literal IPs under AsIs). Explicit either way:
# XRay's own default blocks private for vless/vmess/trojan/shadowsocks only, which
# left socks/http open and ignored blockPrivate = false.
directFinalRules =
if derived.proxyInboundsCfg.routing.blockPrivate then
[
{
action = "block";
ip = [ "geoip:private" ];
}
]
else
[ { action = "allow"; } ];
# inbounds.routing.serverSource: a user's connections to this host, from the user's own
# address on the dummy interface. Only ever to this host: its listed IPs where there are
# some, and never somewhere private.
serverIps =
builtins.filter
(a: !lib.hasPrefix "domain:" a && (lib.hasInfix ":" a || builtins.match "[0-9.]+" a != null))
(
lib.optional (derived.proxyInboundsCfg.serverAddress != null) derived.proxyInboundsCfg.serverAddress
++ derived.proxyInboundsCfg.serverAliases
);
selfFinalRules =
if serverIps != [ ] then
[
{
action = "allow";
ip = serverIps;
}
{ action = "block"; }
]
else
[
{
action = "block";
ip = [ "geoip:private" ];
}
];
mkSelfOutbound = family: address: id: {
protocol = "freedom";
tag = "direct-self${family}-${id}";
sendThrough = address;
settings = {
domainStrategy = if family == "4" then "UseIPv4" else "UseIPv6";
finalRules = selfFinalRules;
};
};
selfOutbounds = lib.concatMap (
s:
lib.optional (s.ipv4 != null) (mkSelfOutbound "4" s.ipv4 s.id)
++ lib.optional (s.ipv6 != null) (mkSelfOutbound "6" s.ipv6 s.id)
) derived.proxyInboundsSelfSources;
# The client stack's SOCKS listener; credentials are injected at start.
localProxyOutbound = lib.optional proxyInboundsNeedLocalProxy {
protocol = "socks";
@@ -72,31 +128,21 @@ in
};
};
outbounds = localProxyOutbound ++ [
{
protocol = "freedom";
tag = "direct";
# Checked on the address actually dialed, so a name resolving private is caught too
# (routing's geoip:private sees only literal IPs under AsIs). Explicit either way:
# XRay's own default blocks private for vless/vmess/trojan/shadowsocks only, which
# left socks/http open and ignored blockPrivate = false.
settings.finalRules =
if derived.proxyInboundsCfg.routing.blockPrivate then
[
{
action = "block";
ip = [ "geoip:private" ];
}
]
else
[ { action = "allow"; } ];
}
{
protocol = "blackhole";
tag = "block";
settings = { };
}
];
outbounds =
localProxyOutbound
++ [
{
protocol = "freedom";
tag = "direct";
settings.finalRules = directFinalRules;
}
{
protocol = "blackhole";
tag = "block";
settings = { };
}
]
++ selfOutbounds;
routing = {
# AsIs where sing-box dials: resolving here made every new site wait on a
+7 -1
View File
@@ -26,7 +26,13 @@ let
inboundRules = import ./rules/proxy-inbounds.nix {
inherit lib;
inherit (derived) proxyInboundsCfg proxyInbounds proxyInboundsRouteOnion;
inherit (derived)
proxyInboundsCfg
proxyInbounds
proxyInboundsRouteOnion
proxyInboundsResolveInSingBox
proxyInboundsSelfSources
;
inherit (rules) zapretDirectRules;
};
+54
View File
@@ -181,6 +181,58 @@ let
}) proxyInboundsCfg.listeners
);
# inbounds.routing.serverSource: an address per inbound user (by XRay's email, the user's
# name), which XRay sends that user's connections to this host from.
proxyInboundsServerSource = proxyInboundsCfg.routing.serverSource;
proxyInboundsSelfSources =
let
src = proxyInboundsServerSource;
# The users XRay's listeners accept (by name, XRay's email): numbered by their order,
# the rest after the highest order, by name.
names = lib.unique (
lib.concatMap (ib: map (user: user.name) ib.listener.users) (
builtins.filter (ib: ib.listener.type != "amneziawg") proxyInbounds
)
);
orderOf = name: proxyInboundsCfg.users.${name}.order;
ordered = builtins.filter (name: orderOf name != null) names;
highest = lib.foldl lib.max 0 (map orderOf ordered);
numbered =
map (name: {
email = name;
number = orderOf name;
}) ordered
++ lib.imap1 (i: name: {
email = name;
number = highest + i;
}) (lib.sort lib.lessThan (builtins.filter (name: orderOf name == null) names));
octets =
cidr:
map lib.toInt (lib.take 4 (builtins.match "([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)/[0-9]+" cidr));
v4Int = cidr: lib.foldl (acc: o: acc * 256 + o) 0 (octets cidr);
v4String =
n:
lib.concatMapStringsSep "." (shift: toString (lib.mod (n / shift) 256)) [
16777216
65536
256
1
];
v6Prefix = cidr: builtins.head (lib.splitString "/" cidr);
in
lib.optionals (src.ipv4 != null || src.ipv6 != null) (
map (
{ email, number }:
{
inherit email number;
id = toString number;
ipv4 = if src.ipv4 == null then null else v4String (v4Int src.ipv4 + number);
ipv6 =
if src.ipv6 == null then null else "${v6Prefix src.ipv6}${lib.toLower (lib.toHexString number)}";
}
) (lib.sort (a: b: a.number < b.number) numbered)
);
# .onion names from clients go to the local proxy, whose rule hands them to Tor, whatever
# the listener's via. AmneziaWG listeners never pass XRay's routing.
proxyInboundsRouteOnion =
@@ -606,6 +658,8 @@ in
proxyInboundsRouteOnion
proxyInboundsNeedLocalProxy
proxyInboundsResolveInSingBox
proxyInboundsServerSource
proxyInboundsSelfSources
proxyInboundsGuardPrivate
proxyInboundsGuardStrategy
proxyInboundViaTags
+78 -4
View File
@@ -1,4 +1,9 @@
{ lib, proxySuiteUpstream, ... }:
{
config,
lib,
proxySuiteUpstream,
...
}:
let
inherit (lib)
@@ -108,19 +113,88 @@ in
blockRu = bool true ''Block Russian destinations (geosite "category-ru", geoip "ru").'';
blockPrivate = bool true "Block private and loopback addresses, so clients cannot reach this host's LAN or local services.";
zapretDirect = bool true "Send zapret hostlist sites direct, so this host's zapret unblocks them. Only for the default `via`.";
zapretDirect = bool true "Send zapret hostlist sites direct, so this host's zapret unblocks them. Only for the default `via`. With a direct listener or the XRay backend, only by IP: XRay matches names by what a client puts in its handshake, whatever address it connects to.";
# Consumed in derived.nix (the addresses), rules/proxy-inbounds.nix and the inbounds'
# start script (the interface).
serverSource = {
ipv4 = mkOption {
type = types.nullOr (types.strMatching "([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}");
default = null;
example = "10.78.0.0/24";
description = ''
Range each inbound user gets an address from, for the connections they make to this
host itself (`serverAddress`, `serverAliases`, `serverPorts`). Otherwise those come
from this host's own address, and its services (mail, the web server, their rate
limits and bans) see every user as one. They see neither the users' real addresses.
The addresses sit on a dummy interface and reach nothing but this host. Pick a range
nothing here routes or trusts. Users are numbered by their `order`, then name, from
the range's second address: set `order` to keep each user's address as users come
and go.
'';
};
ipv6 = mkOption {
type = types.nullOr (types.strMatching "[0-9a-fA-F:]*::/[0-9]{1,3}");
default = null;
example = "fd78:78:78::/64";
description = ''
The same for IPv6: a prefix written with "::", such as a ULA /64. Needed as well when
`serverAliases` lists an IPv6 address, which is otherwise dialed from this host's own.
'';
};
interface = mkOption {
type = types.strMatching "[a-zA-Z0-9_-]{1,15}";
default = "ps-self";
description = "Dummy interface the `serverSource` addresses are put on.";
};
};
};
users = mkOption {
type = types.attrsOf (types.submodule t.userModule);
default = { };
description = ''
Inbound users, by name, which listeners accept by naming them in their `users`. Each
listener takes the secret its protocol wants: `uuid`/`uuidFile` for vless and vmess,
`password`/`passwordFile` for the others, the keys for AmneziaWG.
'';
example = literalExpression ''
{
phone = {
order = 1;
uuidFile = "/run/secrets/proxy-inbound-uuid";
};
laptop.order = 2;
}
'';
};
listeners = mkOption {
type = types.attrsOf t.inboundType;
default = { };
description = "Server listeners, by tag.";
# Each named user becomes the user, with their name: nothing past the options sees names.
apply = lib.mapAttrs (
tag: listener:
listener
// {
users = map (
name:
(config.services.proxy-suite.inbounds.users.${name}
or (throw "proxy-suite: inbounds listener '${tag}' names user '${name}', which inbounds.users does not define")
)
// {
inherit name;
}
) listener.users;
}
);
example = literalExpression ''
{
vless-reality = {
type = "vless";
port = 443;
users = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ];
users = [ "phone" ];
flow = "xtls-rprx-vision";
reality = {
enable = true;
@@ -134,7 +208,7 @@ in
home = {
type = "amneziawg";
port = 51820;
users = [ { name = "phone"; } { name = "laptop"; } ];
users = [ "phone" "laptop" ];
amneziaWg.mode = "lan";
};
}
+22 -10
View File
@@ -5,13 +5,20 @@ let
inherit (import ./amnezia-wg.nix { inherit lib; }) obfuscationType;
inherit (import ../lib.nix { inherit lib; }) nullStr;
userType = types.submodule {
# One inbound user, in `inbounds.users` under their name (shown in share links, subscriptions
# and stats); listeners name the ones they accept.
userModule = {
options = {
name = mkOption {
type = types.str;
default = "";
description = "User name, shown in share links, subscriptions and stats.";
example = "phone";
order = mkOption {
type = types.nullOr types.ints.positive;
default = null;
description = ''
The user's number, for good: their `inbounds.routing.serverSource` addresses are
that many past the start of each range (5: 10.78.0.5 in 10.78.0.0/24). Users
without one follow the highest number given, by name, and move when users are
added before them. Unique.
'';
example = 1;
};
uuid = nullStr "UUID (vless, vmess). Ends up in the Nix store; prefer `uuidFile`." "b831381d-6324-4d53-ad4f-8cda48b30811";
uuidFile = nullStr "File with the UUID." "/run/secrets/proxy-inbound-uuid";
@@ -382,10 +389,15 @@ let
};
users = mkOption {
type = types.listOf userType;
# Resolved to the users themselves, with their name, by the listeners option's apply
# (options/inbounds.nix): everything past the options reads full users.
type = types.listOf (types.strMatching "[^[:space:]]+");
default = [ ];
description = "Accepted users.";
example = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ];
description = "Accepted users, by their names in `inbounds.users`.";
example = [
"phone"
"laptop"
];
};
flow = mkOption {
@@ -500,5 +512,5 @@ let
);
in
{
inherit inboundType;
inherit inboundType userModule;
}
@@ -106,7 +106,7 @@ in
type = types.package;
default = proxySuiteUpstream.whitelist-bypass;
defaultText = lib.literalMD "proxy-suite's `whitelist-bypass` (`pkgs/whitelist-bypass.nix`)";
description = "whitelist-bypass package.";
description = "whitelist-bypass package. It must take the call link and the proxy password from WB_LINK and WB_UPSTREAM_PASS, as `pkgs/whitelist-bypass.nix` patches it to.";
};
joiners = mkOption {
+87 -8
View File
@@ -5,6 +5,8 @@
proxyInboundsCfg,
proxyInbounds,
proxyInboundsRouteOnion,
proxyInboundsResolveInSingBox,
proxyInboundsSelfSources,
zapretDirectRules,
}:
@@ -74,15 +76,83 @@ let
inherit ruleTag;
${field} = items;
inboundTag = exceptionInboundTags;
port = lib.concatMapStringsSep "," toString serverAddressPorts;
port = serverPortList;
outboundTag = "direct";
};
serverAddressRule =
mkServerAddressRule "inbound-server-address-direct" "domain" (
map (name: if isSuffix name then name else "full:${name}") serverNames
# Sniffing is routeOnly (proxy_inbound.py): a name rule also matches a connection to an IP
# whose TLS SNI or HTTP Host carries that name, and "direct" then dials the IP, from this
# host's own address. Any client could reach any address past routing.via that way by
# naming this host (or a zapret site) in its handshake. So before a name rule sends
# anything direct, a connection to an IP it would match goes where it would have gone
# without the name rule: its listener's via. Under AsIs an ip condition matches only
# connections to an IP. Under IPOnDemand it resolves names as well, so there it only works
# after the IP rules, which a name resolving to this host matches first.
anyIp = [
"0.0.0.0/0"
"::/0"
];
mkSniffGuard =
ruleTag: domains: inbounds: extra:
lib.mapAttrsToList (
via: ibs:
{
type = "field";
ruleTag = "${ruleTag}-${via}";
domain = domains;
ip = anyIp;
inboundTag = map (ib: ib.tag) ibs;
outboundTag = via;
}
// extra
) (lib.groupBy (ib: ib.via) inbounds);
serverNameDomains = map (name: if isSuffix name then name else "full:${name}") serverNames;
serverPortList = lib.concatMapStringsSep "," toString serverAddressPorts;
# inbounds.routing.serverSource: each user's connections to this host leave from the
# user's own address (the "direct-self" outbounds, config-templates/proxy-inbounds.nix),
# ahead of the rules that dial them from this host's. A name is dialed over the family the
# user has an address in.
serverIps4 = builtins.filter (ip: !lib.hasInfix ":" ip) serverIps;
serverIps6 = builtins.filter (lib.hasInfix ":") serverIps;
mkSelfRule =
ruleTag: field: items: source: outboundTag:
lib.optional (items != [ ] && exceptionInboundTags != [ ]) {
type = "field";
ruleTag = "${ruleTag}-${source.id}";
${field} = items;
user = [ source.email ];
inboundTag = exceptionInboundTags;
port = serverPortList;
inherit outboundTag;
};
selfIpRules = lib.concatMap (
s:
lib.optionals (s.ipv4 != null) (
mkSelfRule "inbound-server-address-self-ip4" "ip" serverIps4 s "direct-self4-${s.id}"
)
++ mkServerAddressRule "inbound-server-address-direct-ip" "ip" serverIps;
++ lib.optionals (s.ipv6 != null) (
mkSelfRule "inbound-server-address-self-ip6" "ip" serverIps6 s "direct-self6-${s.id}"
)
) proxyInboundsSelfSources;
selfNameRules = lib.concatMap (
s:
mkSelfRule "inbound-server-address-self" "domain" serverNameDomains s (
if s.ipv4 != null then "direct-self4-${s.id}" else "direct-self6-${s.id}"
)
) proxyInboundsSelfSources;
serverNameGuarded = proxyInboundsResolveInSingBox || serverIps != [ ];
serverAddressRule =
selfIpRules
++ mkServerAddressRule "inbound-server-address-direct-ip" "ip" serverIps
++ lib.optionals (serverNames != [ ] && serverNameGuarded && exceptionInboundTags != [ ]) (
mkSniffGuard "inbound-server-address-sniffed" serverNameDomains (builtins.filter (
ib: ib.via != "block"
) proxyInbounds) { port = serverPortList; }
)
++ lib.optionals (serverNames != [ ] && serverNameGuarded) selfNameRules
++ mkServerAddressRule "inbound-server-address-direct" "domain" serverNameDomains;
blockRuRules = lib.optionals proxyInboundsCfg.routing.blockRu [
{
@@ -144,11 +214,18 @@ let
outboundTag = "direct";
};
zapretDomains = map (domain: "domain:${domain}") zapretDirectRules.domains;
# Under IPOnDemand the guard would take every zapret name too: the domain rule stays off.
zapretRules =
mkZapretRule "inbound-zapret-direct-domain" "domain" (
map (domain: "domain:${domain}") zapretDirectRules.domains
mkZapretRule "inbound-zapret-direct-ip" "ip" zapretDirectRules.ips
++ lib.optionals (zapretDirectEnabled && zapretDomains != [ ] && proxyInboundsResolveInSingBox) (
mkSniffGuard "inbound-zapret-sniffed" zapretDomains (builtins.filter (
ib: builtins.elem ib.tag defaultInboundTags
) proxyInbounds) { }
)
++ mkZapretRule "inbound-zapret-direct-ip" "ip" zapretDirectRules.ips;
++ lib.optionals proxyInboundsResolveInSingBox (
mkZapretRule "inbound-zapret-direct-domain" "domain" zapretDomains
);
overrideRules = map (ib: {
type = "field";
@@ -179,4 +256,6 @@ let
in
{
inherit xrayInboundRules;
# Names of this host sent direct with no guard (IPOnDemand, and no IP aliases): a warning.
unguardedServerNames = lib.optionals (!serverNameGuarded) serverNames;
}
+28 -3
View File
@@ -185,6 +185,34 @@ let
(mkAssertion (!(cfg.warp.enable && cfg.warp.asOutbound != null && cfg.warp.asAmneziaWg))
"proxy-suite: warp.asOutbound and warp.asAmneziaWg share one WARP key and would knock each other off; enable one"
)
# inbounds.routing.serverSource: a dummy interface, and an address per user in each range.
(
let
src = cfg.inbounds.routing.serverSource;
highest = lib.foldl lib.max 0 (map (s: s.number) derived.proxyInboundsSelfSources);
v4 = builtins.match "([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)/([0-9]+)" src.ipv4;
v4Prefix = lib.toInt (lib.last v4);
v4Int = lib.foldl (acc: o: acc * 256 + lib.toInt o) 0 (lib.take 4 v4);
v4Size = lib.foldl (acc: _: acc * 2) 1 (lib.range 1 (32 - v4Prefix));
in
mkAssertion
(
src.ipv4 == null
|| (v4Prefix >= 8 && v4Prefix <= 30 && lib.mod v4Int v4Size == 0 && highest + 2 <= v4Size)
)
"proxy-suite: inbounds.routing.serverSource.ipv4 must be a network address (host bits zero), /8 to /30, with room for user number ${toString highest}"
)
# A user's order is their serverSource number: two would share an address.
(uniqueValues true (builtins.filter (order: order != null) (
lib.mapAttrsToList (_: user: user.order) cfg.inbounds.users
)) "proxy-suite: inbounds.users must each have a distinct order")
(mkAssertion (
cfg.inbounds.routing.serverSource.ipv6 == null
|| lib.toInt (lib.last (lib.splitString "/" cfg.inbounds.routing.serverSource.ipv6)) <= 112
) "proxy-suite: inbounds.routing.serverSource.ipv6 must be a prefix of /112 or shorter")
(mkAssertion (derived.proxyInboundsSelfSources == [ ] || cfg.host.privileged)
"proxy-suite: inbounds.routing.serverSource needs a system install: it puts addresses on a dummy interface"
)
# Daemon configs are readable by the service group; users must not share it.
(mkAssertion (cfg.userControl.group != derived.constants.serviceUser)
"proxy-suite: userControl.group must not be ${derived.constants.serviceUser}, the group that can read backend configs"
@@ -845,9 +873,6 @@ let
];
in
lib.optionals (proxyInboundsEnabled && l.type == "amneziawg") [
(mkAssertion (lib.all (user: user.name != "")
l.users
) "${prefix}: AmneziaWG users each need a name, which their keys and address are kept under")
(mkAssertion (builtins.stringLength awg.interfaceName <= 15)
"${prefix}: amneziaWg.interfaceName '${awg.interfaceName}' is longer than the kernel's 15 characters"
)
+26
View File
@@ -270,6 +270,32 @@ lib.mkMerge [
"proxy-suite: proxy.listener.address is ${proxyCfg.listener.address} without listener.auth:"
+ " anyone who reaches the port uses your outbounds; set listener.auth, or keep it off the"
+ " firewall's allowed ports"
)
# rules/proxy-inbounds.nix guards the names of this host only where XRay leaves names
# unresolved, or where IP aliases catch a name that resolves here first.
++
lib.optional
(
proxyInboundsEnabled
&& !derived.proxyInboundsResolveInSingBox
# Only a listener whose traffic is not direct anyway loses anything by it.
&& lib.any (
ib:
!builtins.elem ib.via [
"direct"
"block"
]
) derived.proxyInbounds
&& (cfg.inbounds.serverAddress != null || cfg.inbounds.serverAliases != [ ])
&& lib.all (a: lib.hasPrefix "domain:" a || builtins.match "[0-9.]+|.*:.*" a == null) (
lib.optional (cfg.inbounds.serverAddress != null) cfg.inbounds.serverAddress
++ cfg.inbounds.serverAliases
)
)
(
"proxy-suite: with a direct listener or the XRay backend, list this host's IPs in"
+ " inbounds.serverAliases: without them a client can name this host in its TLS handshake"
+ " while connecting to any other address, which XRay then dials direct, from this host"
);
}
@@ -25,6 +25,7 @@ let
buildOutboundPy
proxyInboundsFile
proxyInboundsSpecFile
proxyInboundsSelfSources
builders
constants
;
@@ -33,6 +34,22 @@ let
subscriptionsFile = "${runtimeDir}/subscriptions.json";
subsCfg = proxyInboundsCfg.subscriptions;
xray = "${proxyInboundsCfg.package}/bin/xray";
# inbounds.routing.serverSource: the users' own addresses toward this host, on a dummy
# interface. Reached through lo like any local address; nothing routes out from them.
ip = "${pkgs.iproute2}/bin/ip";
selfInterface = lib.escapeShellArg proxyInboundsCfg.routing.serverSource.interface;
selfInterfaceDown = "${ip} link del ${selfInterface} 2>/dev/null || true";
selfInterfaceUp = lib.optionalString (proxyInboundsSelfSources != [ ]) ''
${selfInterfaceDown}
${ip} link add ${selfInterface} type dummy
${ip} link set ${selfInterface} up
${lib.concatMapStrings (
s:
lib.optionalString (s.ipv4 != null) "${ip} addr add ${s.ipv4}/32 dev ${selfInterface}\n"
+ lib.optionalString (s.ipv6 != null) "${ip} -6 addr add ${s.ipv6}/128 dev ${selfInterface} nodad\n"
) proxyInboundsSelfSources}
'';
# Only listeners, and for AmneziaWG listeners transparent sockets (IP_TRANSPARENT).
runXray = constants.runAsServiceUser pkgs (
[ "net_bind_service" ] ++ lib.optional (proxyInboundsAwg != [ ]) "net_admin"
@@ -242,6 +259,7 @@ let
${writeLinksBlock}
${writeSubscriptionsBlock}
${selfInterfaceUp}
exec ${runXray} ${xray} run -c "$RUNTIME_DIR/config.json"
'';
@@ -288,10 +306,16 @@ let
chmod ${if userControlAllows "stats" then "640" else "600"} "$tmp"
mv -f "$tmp" "$file"
'';
stopInboundsInterface =
if proxyInboundsSelfSources == [ ] then
null
else
pkgs.writeShellScript "proxy-suite-inbounds" selfInterfaceDown;
in
{
inherit
startInbounds
stopInboundsInterface
collectInboundStats
linksFile
subscriptionsFile
+2 -1
View File
@@ -168,7 +168,7 @@ let
inherit (startScripts) startSocks startTun startPerAppTun;
proxyInboundsScripts = import ./proxy-inbounds-scripts.nix { ctx = sctx; };
inherit (proxyInboundsScripts) startInbounds collectInboundStats;
inherit (proxyInboundsScripts) startInbounds stopInboundsInterface collectInboundStats;
proxyInboundsLinksFile = proxyInboundsScripts.linksFile;
proxyInboundsSubscriptionsFile = proxyInboundsScripts.subscriptionsFile;
@@ -204,6 +204,7 @@ in
startTun
startPerAppTun
startInbounds
stopInboundsInterface
collectInboundStats
;
inherit
+2
View File
@@ -118,6 +118,8 @@ let
++ lib.optional torOnionEnabled "proxy-suite-tor.service";
wantedBy = [ "multi-user.target" ];
execStart = scripts.startInbounds;
# inbounds.routing.serverSource's dummy interface.
execStopPost = scripts.stopInboundsInterface;
runtimeDirectory = serviceNames.inbounds;
# The collector's file.
stateDirectory = "proxy-suite";
+29 -9
View File
@@ -27,10 +27,21 @@ let
withProxyAuth = viaProxy && derived.localProxy.authEnabled;
bridgesEnabled = t.bridges.lines != [ ] || t.bridges.file != null;
# Members of userControl.group may use the control socket for `proxy-ctl tor
# status|newnym`, so Tor runs with that group on a system install: Tor refuses a
# group-writable socket whose directory is owned by any group but its own.
controlGroup = privileged && derived.userControlAllows "services";
# The control socket is Tor's own (and root's): with it, one can publish any loopback
# port as an onion service, point Tor at another upstream, or read the proxy password
# from its config. userControl's group asks for a new identity through
# proxy-suite-tor-newnym instead.
controlSocket = derived.constants.torControlSocket;
newnymScript = pkgs.writeShellScript "proxy-suite-tor-newnym" ''
set -euo pipefail
reply=$(printf 'AUTHENTICATE\r\nSIGNAL NEWNYM\r\nQUIT\r\n' \
| ${pkgs.socat}/bin/socat -t 5 - UNIX-CONNECT:${lib.escapeShellArg controlSocket})
# One "250 OK" each for AUTHENTICATE and SIGNAL.
if [ "$(${pkgs.gnugrep}/bin/grep -c '^250 OK' <<< "$reply")" -lt 2 ]; then
printf 'Tor refused: %s\n' "$reply" >&2
exit 1
fi
'';
# An onion service port per listener: its share port, forwarded to where XRay listens.
onionTarget =
@@ -68,7 +79,6 @@ let
"TransPort 0"
"NATDPort 0"
"CookieAuthentication 0"
"ControlSocketsGroupWritable 1"
]
++ lib.optional t.clientOnly "ClientOnly 1"
++ (if t.asOutbound then [ "SocksPort 127.0.0.1:${toString t.socksPort}" ] else [ "SocksPort 0" ])
@@ -103,9 +113,7 @@ let
umask 0077
torrc="$RUNTIME_DIRECTORY/torrc"
${pkgs.coreutils}/bin/mkdir -p -m ${
if controlGroup then "0750" else "0700"
} "$RUNTIME_DIRECTORY/control"
${pkgs.coreutils}/bin/mkdir -p -m 0700 "$RUNTIME_DIRECTORY/control"
{
cat <<'TORRC'
${staticConfig}
@@ -161,7 +169,19 @@ in
RestartSec = 5;
LimitNOFILE = 65536;
}
// lib.optionalAttrs controlGroup { Group = cfg.userControl.group; }
// lib.optionalAttrs onionKeyEnabled { ExecStartPre = onionKeyScript; };
};
# `proxy-ctl tor newnym` for userControl's group ("services" scope), which cannot open
# the control socket. Root.
services.proxy-suite.internal.services.proxy-suite-tor-newnym = lib.mkIf privileged {
description = "proxy-suite - new Tor circuits for new connections";
after = [ "proxy-suite-tor.service" ];
# Only a running Tor: this never starts one.
unitConfig.Requisite = [ "proxy-suite-tor.service" ];
serviceConfig = {
Type = "oneshot";
ExecStart = newnymScript;
};
};
}
+16 -16
View File
@@ -12,17 +12,10 @@ let
inherit (derived.constants) unprivilegedServiceConfig privileged serviceUser;
inherit (derived.localProxy) auth;
# Every flag that takes the call, joiner and creator alike.
linkFlag = {
wbstream = "--room";
dion = "--room";
bitrix = "--room";
telemost = "--tm-link";
vk = "--vk-link";
};
joinerLinkFlag = linkFlag // {
bitrix = "--link";
};
# A file in the state directory, which the whitelistBypass scope's group writes to: a
# regular file only, never through a symlink, which could name the backend's config
# (the daemon reads it) and have its credentials on a command line.
readState = file: "${pkgs.coreutils}/bin/dd if=${file} iflag=nofollow,nonblock status=none";
passwordSource =
if auth.passwordFile != null then
@@ -59,6 +52,9 @@ let
StateDirectory = "proxy-suite/whitelist-bypass";
StateDirectoryMode = stateMode;
}
# The group writes the state directory: whatever a name there points at, the daemon
# writes nowhere else.
// lib.optionalAttrs privileged { ProtectSystem = "strict"; }
// lib.optionalAttrs groupAccess { Group = stateGroup; }
// serviceConfig;
};
@@ -72,9 +68,10 @@ let
set -euo pipefail
join="$STATE_DIRECTORY/${j.tag}.join"
${lib.optionalString (j.linkFile != null) ''[ -e "$join" ] || join="$CREDENTIALS_DIRECTORY/link"''}
link=$(tr -d '[:space:]' < "$join")
exec ${w.package}/bin/headless-${j.platform}-joiner \
${joinerLinkFlag.${j.platform}} "$link" --socks-port ${toString j.port}
# The link from the environment (pkgs/whitelist-bypass.nix): argv is public.
WB_LINK=$(${readState ''"$join"''} | tr -d '[:space:]')
export WB_LINK
exec ${w.package}/bin/headless-${j.platform}-joiner --socks-port ${toString j.port}
'';
LoadCredential = lib.optional (j.linkFile != null) "link:${j.linkFile}";
}
@@ -91,6 +88,8 @@ let
set -euo pipefail
cookies="$STATE_DIRECTORY/${name}.cookies.json"
links="$STATE_DIRECTORY/${name}.link"
# The creator opens it by name: not through a symlink the group left there.
if [ -L "$cookies" ]; then rm -f -- "$cookies"; fi
${lib.optionalString (c.cookiesFile != null) ''
[ -e "$cookies" ] || install -m 600 "$CREDENTIALS_DIRECTORY/cookies" "$cookies"
''}
@@ -99,9 +98,10 @@ let
if c.linkFile != null then
''link=$(tr -d '[:space:]' < "$CREDENTIALS_DIRECTORY/link")''
else
''link=$(tail -n 1 "$links" 2>/dev/null || true)''
"link=$(${readState ''"$links"''} 2>/dev/null | tail -n 1 || true)"
}
[ -z "$link" ] || args+=(${linkFlag.${c.platform}} "$link")
# From the environment (pkgs/whitelist-bypass.nix): argv is public.
export WB_LINK="$link"
${lib.optionalString viaProxy ''
args+=(--upstream-socks ${derived.localProxy.hostPart}:${toString cfg.proxy.listener.port})
''}${lib.optionalString withProxyAuth ''
+7 -2
View File
@@ -101,7 +101,12 @@ let
Type = "notify";
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";
}
# systemd gives the state directory the unit's group on every start: the group's, which
# edits the lists (as autoProxy's units do).
// lib.optionalAttrs (userControlAllows "zapret") { Group = cfg.userControl.group; }
# nfqws2 runs as root and writes its lists in a directory the zapret scope's group
# writes to as well.
// constants.rootInSharedDirConfig;
@@ -136,7 +141,7 @@ in
wantedBy = [ "multi-user.target" ];
preStart = mkPreStart;
runtimeDirectory = "proxy-suite-zapret";
stateDirectory = "proxy-suite";
stateDirectory = "proxy-suite/zapret2";
execStart = "${runtime.daemonScript}";
execStopPost = "${runtime.initScript} stop_fw";
extraServiceConfig = daemonConfig (
@@ -156,7 +161,7 @@ in
conflicts = perAppConflicts ++ awgServiceNames;
preStart = mkPreStart;
runtimeDirectory = "proxy-suite-per-app-zapret";
stateDirectory = "proxy-suite";
stateDirectory = "proxy-suite/zapret2";
execStart = "${runtime.daemonScript}";
execStartPre = "${perAppZapretMarkUpScript}";
execStopPost = [