feat: runtime users and inbounds

This commit is contained in:
fufsob committed 2026-09-29 08:11:29 +00:00
1 parent a4752049ef
commit 9bbffe24b4
36 files changed
+2932 -83

No files matched your search

+3 -1
View File
@@ -225,7 +225,9 @@ let
# the main table by rule instead, which the kernel checks before it picks the source.
repliesTable = profile: "proxy-suite-awg-${profile.interfaceName}";
serverUdpPorts = lib.unique (
map toString (awgCfg.serverUdpPorts ++ derived.proxyInboundFirewallUdpPorts)
map toString (
awgCfg.serverUdpPorts ++ derived.proxyInboundFirewallUdpPorts ++ derived.proxyInboundRuntimePorts
)
++ cfg.host.openUdpPorts
);
serverUdpRulesDown = ''
@@ -32,38 +32,14 @@ let
[ { 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" ];
}
];
# address on the dummy interface. inbound_runtime.py makes the runtime users' the same way.
mkSelfOutbound = family: address: id: {
protocol = "freedom";
tag = "direct-self${family}-${id}";
sendThrough = address;
settings = {
domainStrategy = if family == "4" then "UseIPv4" else "UseIPv6";
finalRules = selfFinalRules;
finalRules = inboundRules.selfFinalRules;
};
};
selfOutbounds = lib.concatMap (
+53 -1
View File
@@ -32,6 +32,9 @@ let
proxyInboundsRouteOnion
proxyInboundsResolveInSingBox
proxyInboundsSelfSources
proxyInboundsRuntimeEnabled
proxyInboundsRuntimeVias
proxyInboundRuntimePorts
;
inherit (rules) zapretDirectRules;
};
@@ -67,9 +70,57 @@ let
}
);
# A listener with nothing set: what inbound_runtime.py fills a runtime listener's JSON in
# with, so its defaults are the option's. Not the AmneziaWG part, which runtime listeners
# cannot have, nor what the JSON must not set.
listenerDefaults =
builtins.removeAttrs
(lib.evalModules {
modules = [
{
options.listener = lib.mkOption {
type = (import ./options/types.nix { inherit lib; }).inboundType;
default = { };
};
}
];
}).config.listener
[
"amneziaWg"
"users"
"xrayJson"
"jsonFile"
];
# inbounds.runtime, for inbound_runtime.py: where the spool is and what it may use.
runtimeSpec =
let
rt = derived.proxyInboundsCfg.runtime;
in
{
spool = derived.constants.runtimeInboundsDir;
inherit (rt) ports fallbackDests tlsCertificates;
vias = derived.proxyInboundsRuntimeVias;
defaultVia = derived.proxyInboundsCfg.routing.via;
inherit (inboundRules) selfFinalRules;
salamanderStateDir = "${cfg.host.stateDir}/inbounds";
inherit listenerDefaults;
};
# Listener specification handed to build-inbound.py at service start. Secrets
# appear here only as paths; the script reads them at runtime.
proxyInboundsSpec = {
runtime = if derived.proxyInboundsRuntimeEnabled then runtimeSpec else null;
# Every declared user, on a listener or not, and their serverSource numbers: what
# `proxy-ctl inbounds users` lists, and what runtime users go around. Secrets as paths.
users = derived.proxyInboundsCfg.users;
serverSource = {
inherit (derived.proxyInboundsCfg.routing.serverSource) ipv4 ipv6;
declared = map (s: {
name = s.email;
inherit (s) number;
}) derived.proxyInboundsSelfSources;
};
serverAddress = derived.proxyInboundsCfg.serverAddress;
shareLinks = derived.proxyInboundsCfg.shareLinks;
# Listeners the onion service carries, which get a second set of links to it.
@@ -77,8 +128,9 @@ let
listeners = map (
ib:
{
inherit (ib) tag;
inherit (ib) tag via;
inherit (ib.listener)
order
type
port
sharePort
+37 -4
View File
@@ -181,6 +181,15 @@ let
}) proxyInboundsCfg.listeners
);
# inbounds.runtime: listeners added with proxy-ctl may exit by these, so everything built
# per exit (rules, outbounds, the local proxy, name resolution) is there for them too.
proxyInboundsRuntimeEnabled = proxyInboundsEnabled && proxyInboundsCfg.runtime.enable;
proxyInboundsRuntimeVias = lib.optionals proxyInboundsRuntimeEnabled (
lib.unique ([ proxyInboundsCfg.routing.via ] ++ proxyInboundsCfg.runtime.vias ++ [ "block" ])
);
# Every exit a listener has or may get.
proxyInboundsVias = map (ib: ib.via) proxyInbounds ++ proxyInboundsRuntimeVias;
# 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;
@@ -236,12 +245,16 @@ let
# .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 =
torRouteOnion && lib.any (ib: ib.via != "block" && ib.listener.type != "amneziawg") proxyInbounds;
torRouteOnion
&& (
lib.any (ib: ib.via != "block" && ib.listener.type != "amneziawg") proxyInbounds
|| proxyInboundsRuntimeEnabled
);
# Whether any listener or inbounds.routing.proxy exception relays through the local SOCKS
# listener.
proxyInboundsNeedLocalProxy =
lib.any (ib: ib.via == "proxy") proxyInbounds
builtins.elem "proxy" proxyInboundsVias
|| proxyInboundsRouteOnion
|| lib.any (field: proxyInboundsCfg.routing.proxy.${field} != [ ]) [
"domains"
@@ -251,7 +264,7 @@ let
];
# Names pass unresolved unless XRay dials itself (a direct listener, or pure XRay).
proxyInboundsResolveInSingBox = !pureXrayEnabled && !lib.any (ib: ib.via == "direct") proxyInbounds;
proxyInboundsResolveInSingBox = !pureXrayEnabled && !builtins.elem "direct" proxyInboundsVias;
# Even when XRay resolves (a direct listener), it hands sing-box the name, which sing-box
# looks up again: guard there too.
@@ -269,7 +282,7 @@ let
# Other vias name static outbounds, rendered into the inbound service's own config.
proxyInboundViaTags = lib.unique (
builtins.filter (via: !builtins.elem via builtinTags) (map (ib: ib.via) proxyInbounds)
builtins.filter (via: !builtins.elem via builtinTags) proxyInboundsVias
);
# The pinned outbounds and every hop they chain through, which the inbound service renders
# too. A hop that is not a static outbound (a subscription entry, warp) has no tag here.
@@ -351,6 +364,19 @@ let
) proxyInboundsPublic
)
);
# inbounds.runtime.ports, both protocols: what a runtime listener serves is not known here.
proxyInboundRuntimePorts = lib.optionals (proxyInboundsRuntimeEnabled) proxyInboundsCfg.runtime.ports;
proxyInboundRuntimeSinglePorts = builtins.filter builtins.isInt proxyInboundRuntimePorts;
proxyInboundRuntimePortRanges = map (
range:
let
bounds = map lib.toInt (lib.splitString "-" range);
in
{
from = builtins.elemAt bounds 0;
to = builtins.elemAt bounds 1;
}
) (builtins.filter builtins.isString proxyInboundRuntimePorts);
# A raw-JSON listener could serve anything, so open both protocols for it.
proxyInboundFirewallUdpPorts = lib.unique (
map (ib: ib.listener.port) (
@@ -492,6 +518,8 @@ let
pinnedOutboundFile = "${stateDir}/pinned-outbound";
runtimeOutboundsDir = "${stateDir}/outbounds.d";
runtimeSubscriptionsDir = "${stateDir}/subscriptions.d";
# inbounds.runtime: users/<name>.json and listeners/<tag>.json (scripts/inbound_runtime.py).
runtimeInboundsDir = "${stateDir}/inbounds.d";
# Shell function for the scripts that read those spools as root. $1 a file: in a spool,
# a regular file only, and never through a symlink, which would hand over any file root
# can read (a share link or an error message then shows it), nor a FIFO, which would
@@ -653,6 +681,11 @@ in
proxyInboundsCfg
proxyInboundsEnabled
proxyInbounds
proxyInboundsRuntimeEnabled
proxyInboundsRuntimeVias
proxyInboundRuntimePorts
proxyInboundRuntimeSinglePorts
proxyInboundRuntimePortRanges
proxyInboundsAwg
proxyInboundIsUdpOnly
proxyInboundsRouteOnion
+2
View File
@@ -66,6 +66,8 @@ in
networking.firewall = {
allowedTCPPorts = forward internal.firewall.allowedTCPPorts;
allowedUDPPorts = forward internal.firewall.allowedUDPPorts;
allowedTCPPortRanges = forward internal.firewall.allowedTCPPortRanges;
allowedUDPPortRanges = forward internal.firewall.allowedUDPPortRanges;
extraReversePathFilterRules = forward internal.firewall.extraReversePathFilterRules;
extraInputRules = forward internal.firewall.extraInputRules;
trustedInterfaces = forward internal.firewall.trustedInterfaces;
+3
View File
@@ -74,6 +74,9 @@ in
firewall = {
allowedTCPPorts = internalOption (types.listOf types.port) [ ];
allowedUDPPorts = internalOption (types.listOf types.port) [ ];
# { from; to; }, as networking.firewall takes them.
allowedTCPPortRanges = internalOption (types.listOf (types.attrsOf types.port)) [ ];
allowedUDPPortRanges = internalOption (types.listOf (types.attrsOf types.port)) [ ];
extraReversePathFilterRules = internalOption types.lines "";
# nftables firewall only: iptables has no such hook.
extraInputRules = internalOption types.lines "";
+85
View File
@@ -150,6 +150,91 @@ in
};
};
# Consumed by scripts/inbound_runtime.py, which merges the spool into the spec at start,
# and by proxy-ctl, which writes the spool.
runtime = {
enable = mkEnableOption "" // {
description = ''
Users and listeners added at runtime with `proxy-ctl inbounds users add` and
`inbounds add`, kept in `inbounds.d` in the state directory. Runtime users can be
bound to any listener; declared users to runtime listeners only. A change restarts
the inbounds, which drops every connection once. Anything a runtime listener could
reach beyond its port is declared here: its ports, certificates, exits and
fallbacks. Members of `userControl.group` need the "inbounds" scope.
'';
};
ports = mkOption {
type = types.listOf (types.either types.port (types.strMatching "[0-9]+-[0-9]+"));
default = [ ];
description = ''
Ports runtime listeners may use, on any address: single ports and "from-to" ranges.
Opened in the firewall (TCP and UDP) with `openFirewall`, and reachable through the
tunnel like the listeners' own. Keep them clear of the declared listeners and of
other services here.
'';
example = [
8443
"20000-20099"
];
};
vias = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Exits a runtime listener may pick with `via`, besides `routing.via` and "block":
"proxy", "direct" or a `proxy.outbounds` tag, as in `routing.via`.
'';
example = [ "direct" ];
};
tlsCertificates = mkOption {
type = types.attrsOf (
types.submodule {
options = {
certificateFile = mkOption {
type = types.str;
description = "File with the PEM certificate chain.";
};
keyFile = mkOption {
type = types.str;
description = "File with the PEM private key.";
};
serverName = mkOption {
type = types.nullOr types.str;
default = null;
description = "SNI in share links. `null`: `serverAddress`.";
};
};
}
);
default = { };
description = ''
Certificates a runtime listener with TLS (trojan, hysteria2, `tls.enable`) may use,
by name: it names one in `tls.certificate` (`--tls <name>`), never a file.
'';
example = literalExpression ''
{
main = {
certificateFile = "/var/lib/acme/vpn.example.com/fullchain.pem";
keyFile = "/var/lib/acme/vpn.example.com/key.pem";
};
}
'';
};
fallbackDests = mkOption {
type = types.listOf (types.either types.port types.str);
default = [ ];
description = ''
`dest` values a runtime listener's fallbacks may use, such as a decoy site. A
fallback to a `listener` must name another runtime listener.
'';
example = [ "127.0.0.1:8080" ];
};
};
users = mkOption {
type = types.attrsOf (types.submodule t.userModule);
default = { };
@@ -16,7 +16,7 @@ let
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.
added before them. Unique. Runtime users (`inbounds.runtime`) go around these numbers.
'';
example = 1;
};
@@ -24,6 +24,7 @@ in
"autoProxy"
"zapret"
"stats"
"inbounds"
"whitelistBypass"
"amneziaWg"
]
@@ -39,6 +40,8 @@ in
- "autoProxy": see and change what autoProxy learned.
- "zapret": change zapret2's learned sites, and `zapret cutoff probe`.
- "stats": `inbounds stats`.
- "inbounds": add, remove and bind runtime inbound users and listeners
(`inbounds.runtime`), and read the secrets they are given.
- "whitelistBypass": everything under `proxy-ctl wl`.
- "amneziaWg": add and remove global AmneziaWG profiles (`proxy-ctl awg add`, `awg rm`).
A global profile takes over the host's routes and DNS. Starting and stopping one is
+93 -32
View File
@@ -7,12 +7,26 @@
proxyInboundsRouteOnion,
proxyInboundsResolveInSingBox,
proxyInboundsSelfSources,
proxyInboundsRuntimeEnabled,
proxyInboundsRuntimeVias,
proxyInboundRuntimePorts,
zapretDirectRules,
}:
let
defaultVia = proxyInboundsCfg.routing.via;
# inbounds.runtime: the start script (inbound_runtime.py) adds the runtime listeners' tags
# to every rule marked with the listeners it is for, by their via, and drops the marked
# rules no listener is left in. So with runtime listeners possible, a rule stays even
# while no declared listener is in it. "_anchor" rules are where the runtime users'
# serverSource rules go; they are replaced whether or not there are any.
runtime = proxyInboundsRuntimeEnabled;
mark = members: rule: rule // lib.optionalAttrs runtime { _members = members; };
forException = mark { notVia = [ "block" ]; };
forDefault = mark { via = [ defaultVia ]; };
any = tags: tags != [ ] || runtime;
# Listeners on the default egress are covered by the final rule.
overrideInbounds = builtins.filter (ib: ib.via != defaultVia) proxyInbounds;
defaultInboundTags = map (ib: ib.tag) (builtins.filter (ib: ib.via == defaultVia) proxyInbounds);
@@ -22,7 +36,7 @@ let
# Only Tor reaches .onion: to the local proxy, whose own rule sends it there. First, so no
# IP rule before it has XRay look the name up, which would leak it to a resolver.
onionRule = lib.optional proxyInboundsRouteOnion {
onionRule = lib.optional proxyInboundsRouteOnion (forException {
type = "field";
ruleTag = "inbound-tor-onion";
domain = [ "domain:onion" ];
@@ -30,7 +44,7 @@ let
builtins.filter (ib: ib.via != "block" && ib.listener.type != "amneziawg") proxyInbounds
);
outboundTag = "proxy";
};
});
blockPrivateRule = lib.optional proxyInboundsCfg.routing.blockPrivate {
type = "field";
@@ -66,19 +80,20 @@ let
443
]
++ proxyInboundsCfg.serverPorts
++ proxyInboundRuntimePorts
);
# Names and IPs in rules of their own: XRay ANDs the fields of one rule.
mkServerAddressRule =
ruleTag: field: items:
lib.optional (items != [ ] && exceptionInboundTags != [ ]) {
lib.optional (items != [ ] && any exceptionInboundTags) (forException {
type = "field";
inherit ruleTag;
${field} = items;
inboundTag = exceptionInboundTags;
port = serverPortList;
outboundTag = "direct";
};
});
# 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
@@ -92,20 +107,25 @@ let
"0.0.0.0/0"
"::/0"
];
# One rule per via; runtimeVias get theirs even with no declared listener on them.
mkSniffGuard =
ruleTag: domains: inbounds: extra:
ruleTag: domains: inbounds: runtimeVias: 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);
mark { via = [ via ]; } (
{
type = "field";
ruleTag = "${ruleTag}-${via}";
domain = domains;
ip = anyIp;
inboundTag = map (ib: ib.tag) ibs;
outboundTag = via;
}
// extra
)
) (lib.genAttrs (lib.optionals runtime runtimeVias) (_: [ ]) // lib.groupBy (ib: ib.via) inbounds);
# Where a runtime listener that is not blocked may exit.
runtimeOpenVias = builtins.filter (via: via != "block") proxyInboundsRuntimeVias;
serverNameDomains = map (name: if isSuffix name then name else "full:${name}") serverNames;
serverPortList = lib.concatMapStringsSep "," toString serverAddressPorts;
@@ -118,7 +138,7 @@ let
serverIps6 = builtins.filter (lib.hasInfix ":") serverIps;
mkSelfRule =
ruleTag: field: items: source: outboundTag:
lib.optional (items != [ ] && exceptionInboundTags != [ ]) {
lib.optional (items != [ ] && any exceptionInboundTags) (forException {
type = "field";
ruleTag = "${ruleTag}-${source.id}";
${field} = items;
@@ -126,7 +146,7 @@ let
inboundTag = exceptionInboundTags;
port = serverPortList;
inherit outboundTag;
};
});
selfIpRules = lib.concatMap (
s:
lib.optionals (s.ipv4 != null) (
@@ -142,16 +162,40 @@ let
if s.ipv4 != null then "direct-self4-${s.id}" else "direct-self6-${s.id}"
)
) proxyInboundsSelfSources;
# The runtime users' rules, as the declared users' are made: inbound_runtime.py numbers
# them and makes one of each per user from these.
serverSourceOn =
proxyInboundsCfg.routing.serverSource.ipv4 != null
|| proxyInboundsCfg.routing.serverSource.ipv6 != null;
mkSelfAnchor =
anchor: fields:
lib.optional (runtime && serverSourceOn) (
forException (
{
_anchor = anchor;
ruleTag = "inbound-runtime-anchor-${anchor}";
inboundTag = exceptionInboundTags;
port = serverPortList;
}
// fields
)
);
serverNameGuarded = proxyInboundsResolveInSingBox || serverIps != [ ];
serverAddressRule =
selfIpRules
++ mkSelfAnchor "selfIp" {
ip4 = serverIps4;
ip6 = serverIps6;
}
++ mkServerAddressRule "inbound-server-address-direct-ip" "ip" serverIps
++ lib.optionals (serverNames != [ ] && serverNameGuarded && exceptionInboundTags != [ ]) (
++ lib.optionals (serverNames != [ ] && serverNameGuarded && any exceptionInboundTags) (
mkSniffGuard "inbound-server-address-sniffed" serverNameDomains (builtins.filter (
ib: ib.via != "block"
) proxyInbounds) { port = serverPortList; }
) proxyInbounds) runtimeOpenVias { port = serverPortList; }
)
++ lib.optionals (serverNames != [ ] && serverNameGuarded) (
selfNameRules ++ mkSelfAnchor "selfName" { domain = serverNameDomains; }
)
++ lib.optionals (serverNames != [ ] && serverNameGuarded) selfNameRules
++ mkServerAddressRule "inbound-server-address-direct" "domain" serverNameDomains;
blockRuRules = lib.optionals proxyInboundsCfg.routing.blockRu [
@@ -173,8 +217,8 @@ let
proxyDomainRule =
lib.optional
(exceptionInboundTags != [ ] && (inboundProxy.domains != [ ] || inboundProxy.geosites != [ ]))
{
(any exceptionInboundTags && (inboundProxy.domains != [ ] || inboundProxy.geosites != [ ]))
(forException {
type = "field";
ruleTag = "inbound-proxy-domain";
domain =
@@ -182,23 +226,22 @@ let
++ map (name: "geosite:${name}") inboundProxy.geosites;
inboundTag = exceptionInboundTags;
outboundTag = "proxy";
};
});
proxyIpRule =
lib.optional
(exceptionInboundTags != [ ] && (inboundProxy.ips != [ ] || inboundProxy.geoips != [ ]))
{
lib.optional (any exceptionInboundTags && (inboundProxy.ips != [ ] || inboundProxy.geoips != [ ]))
(forException {
type = "field";
ruleTag = "inbound-proxy-ip";
ip = inboundProxy.ips ++ map (name: "geoip:${name}") inboundProxy.geoips;
inboundTag = exceptionInboundTags;
outboundTag = "proxy";
};
});
# Only when the default egress is a proxy, and only for its listeners.
zapretDirectEnabled =
proxyInboundsCfg.routing.zapretDirect
&& defaultInboundTags != [ ]
&& any defaultInboundTags
&& !builtins.elem defaultVia [
"direct"
"block"
@@ -206,13 +249,13 @@ let
mkZapretRule =
ruleTag: field: items:
lib.optional (zapretDirectEnabled && items != [ ]) {
lib.optional (zapretDirectEnabled && items != [ ]) (forDefault {
type = "field";
inherit ruleTag;
${field} = items;
inboundTag = defaultInboundTags;
outboundTag = "direct";
};
});
zapretDomains = map (domain: "domain:${domain}") zapretDirectRules.domains;
# Under IPOnDemand the guard would take every zapret name too: the domain rule stays off.
@@ -221,7 +264,7 @@ let
++ lib.optionals (zapretDirectEnabled && zapretDomains != [ ] && proxyInboundsResolveInSingBox) (
mkSniffGuard "inbound-zapret-sniffed" zapretDomains (builtins.filter (
ib: builtins.elem ib.tag defaultInboundTags
) proxyInbounds) { }
) proxyInbounds) [ defaultVia ] { }
)
++ lib.optionals proxyInboundsResolveInSingBox (
mkZapretRule "inbound-zapret-direct-domain" "domain" zapretDomains
@@ -253,9 +296,27 @@ let
++ zapretRules
++ overrideRules
++ [ finalRule ];
# The serverSource outbounds' own last word: only ever to this host, its listed IPs where
# there are some, and never somewhere private.
selfFinalRules =
if serverIps != [ ] then
[
{
action = "allow";
ip = serverIps;
}
{ action = "block"; }
]
else
[
{
action = "block";
ip = [ "geoip:private" ];
}
];
in
{
inherit xrayInboundRules;
inherit xrayInboundRules selfFinalRules;
# Names of this host sent direct with no guard (IPOnDemand, and no IP aliases): a warning.
unguardedServerNames = lib.optionals (!serverNameGuarded) serverNames;
}
+54 -6
View File
@@ -210,7 +210,19 @@ let
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)
(mkAssertion
(
(
derived.proxyInboundsSelfSources == [ ]
&& !(
derived.proxyInboundsRuntimeEnabled
&& (
cfg.inbounds.routing.serverSource.ipv4 != null || cfg.inbounds.routing.serverSource.ipv6 != null
)
)
)
|| 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.
@@ -447,6 +459,11 @@ let
builtins.filter (ob: ob.singBoxJson != null) derived.proxyInboundViaOutbounds
);
inRuntimePorts =
port:
builtins.elem port derived.proxyInboundRuntimeSinglePorts
|| lib.any (range: range.from <= port && port <= range.to) derived.proxyInboundRuntimePortRanges;
proxyInboundAssertions = [
(mkAssertion (!proxyInboundsEnabled || derived.invalidInboundViaTargets == [ ])
"proxy-suite: inbounds via targets, or the hops they chain through, are not defined in proxy.outbounds: ${lib.concatStringsSep ", " derived.invalidInboundViaTargets}. Subscription proxies, warp, tor, ssh-proxy and AmneziaWG outbounds cannot be named here because the inbound service does not run them; use via = \"proxy\" to reach those."
@@ -457,9 +474,40 @@ let
(requireEnabled (proxyInboundsEnabled && derived.proxyInboundViaTags != [ ]) proxyEnabled
"proxy-suite: inbounds pins a listener to a proxy.outbounds tag, which requires proxy.enable = true"
)
(requireEnabled proxyInboundsEnabled (
proxyInbounds != [ ]
) "proxy-suite: inbounds.enable requires at least one entry in inbounds.listeners")
(requireEnabled proxyInboundsEnabled (proxyInbounds != [ ] || derived.proxyInboundsRuntimeEnabled)
"proxy-suite: inbounds.enable requires at least one entry in inbounds.listeners, or inbounds.runtime.enable"
)
# Runtime listeners bind only there: clear of what is bound here already.
(mkAssertion
(
!derived.proxyInboundsRuntimeEnabled
|| !lib.any inRuntimePorts (
derived.proxyInboundPorts
++ reservedLoopbackPorts
++ lib.optional proxyEnabled proxyCfg.listener.port
++ lib.optional globalTproxy.enable globalTproxy.port
)
)
"proxy-suite: inbounds.runtime.ports cover a port a declared listener or proxy-suite itself uses (${
lib.concatMapStringsSep ", " toString (
builtins.filter inRuntimePorts (
derived.proxyInboundPorts
++ reservedLoopbackPorts
++ lib.optional proxyEnabled proxyCfg.listener.port
++ lib.optional globalTproxy.enable globalTproxy.port
)
)
})"
)
(mkAssertion (
!derived.proxyInboundsRuntimeEnabled
|| lib.all (
range: range.from >= 1 && range.from <= range.to && range.to <= 65535
) derived.proxyInboundRuntimePortRanges
) "proxy-suite: inbounds.runtime.ports ranges must be \"from-to\" within 1-65535, from <= to")
(mkAssertion (!derived.proxyInboundsRuntimeEnabled || derived.proxyInboundRuntimePorts != [ ])
"proxy-suite: inbounds.runtime.enable needs inbounds.runtime.ports, the ports runtime listeners may use"
)
(requireEnabled proxyInboundsNeedLocalProxy proxyEnabled
"proxy-suite: inbounds.routing.via = \"proxy\" relays through the local proxy stack, which requires proxy.enable = true. Use via = \"direct\" for a plain exit node."
)
@@ -553,8 +601,8 @@ let
!proxyInboundsEnabled || !(l.tls.enable && l.reality.enable)
) "${prefix}: tls.enable and reality.enable are mutually exclusive")
(mkAssertion (
!proxyInboundsEnabled || l.type == null || l.users != [ ]
) "${prefix}: at least one entry in users is required")
!proxyInboundsEnabled || l.type == null || l.users != [ ] || derived.proxyInboundsRuntimeEnabled
) "${prefix}: at least one entry in users is required (or inbounds.runtime, to add them there)")
# XRay refuses to start on a repeated email, which is the user's name.
(uniqueValues (proxyInboundsEnabled && l.type != null) (builtins.filter (n: n != "") (
map (user: user.name) l.users
+7
View File
@@ -21,6 +21,8 @@ let
userControlCfg
proxyInboundsCfg
proxyInboundsEnabled
proxyInboundsRuntimeEnabled
proxyInboundsSpecFile
amneziaWgProfileNamesFile
awgRuntimeGlobal
awgRuntimeOutbounds
@@ -111,6 +113,11 @@ in
INBOUNDS_SUBS_FILE = proxyInboundsSubscriptionsFile;
INBOUNDS_SUB_BASE_URL =
if proxyInboundsSubscriptionsBaseUrl == null then "" else proxyInboundsSubscriptionsBaseUrl;
# inbounds.runtime: the users and listeners proxy-ctl adds go through this tool, which
# reads what it may use from the spec.
INBOUNDS_RUNTIME_ENABLED = flag proxyInboundsRuntimeEnabled;
INBOUNDS_RUNTIME_TOOL = "${proxySuiteScriptsDir}/inbound_runtime.py";
INBOUNDS_SPEC_FILE = "${proxyInboundsSpecFile}";
# Only the system-wide instance reads the site lists; per-app zapret handles all traffic.
ZAPRET_AUTO_ENABLED = flag (zapretEngine == "zapret2" && zapretGlobalEnabled);
ZAPRET_STATE_DIR = constants.zapret2StateDir;
+31 -2
View File
@@ -117,9 +117,17 @@ lib.mkMerge [
# Inbound listeners are reached from outside, so their ports have to be open.
firewall = lib.mkMerge [
(lib.mkIf (proxyInboundsEnabled && cfg.inbounds.openFirewall) {
allowedTCPPorts = proxyInboundFirewallPorts;
allowedUDPPorts = proxyInboundFirewallUdpPorts;
allowedTCPPorts = proxyInboundFirewallPorts ++ derived.proxyInboundRuntimeSinglePorts;
allowedUDPPorts = proxyInboundFirewallUdpPorts ++ derived.proxyInboundRuntimeSinglePorts;
})
# Only the NixOS adapter forwards ranges.
(lib.mkIf
(proxyInboundsEnabled && cfg.inbounds.openFirewall && derived.proxyInboundRuntimePortRanges != [ ])
{
allowedTCPPortRanges = derived.proxyInboundRuntimePortRanges;
allowedUDPPortRanges = derived.proxyInboundRuntimePortRanges;
}
)
# Gateway clients' diverted packets reach input with their original destination, and
# carry a mark whose table has no route back. Only those: the LAN is not trusted.
(lib.mkIf (tproxyLanSysctl != { }) (
@@ -194,6 +202,27 @@ lib.mkMerge [
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"
]
))
# 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) [
+1
View File
@@ -29,6 +29,7 @@ let
"proxy-suite-autoproxy-learn." = "autoProxy";
"proxy-suite-zapret2-cutoff." = "zapret";
"proxy-suite-inbound-stats." = "stats";
"proxy-suite-inbounds-reload." = "inbounds";
"proxy-suite-wb-" = "whitelistBypass";
};
templates = lib.filter (lib.hasSuffix "@") unitNames;
@@ -26,6 +26,7 @@ let
proxyInboundsFile
proxyInboundsSpecFile
proxyInboundsSelfSources
proxyInboundsRuntimeEnabled
builders
constants
;
@@ -40,7 +41,12 @@ let
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 != [ ]) ''
serverSource = proxyInboundsCfg.routing.serverSource;
# With inbounds.runtime, runtime users may get addresses too, whatever the declared have.
selfInterfaceWanted =
proxyInboundsSelfSources != [ ]
|| (proxyInboundsRuntimeEnabled && (serverSource.ipv4 != null || serverSource.ipv6 != null));
selfInterfaceUp = lib.optionalString selfInterfaceWanted ''
${selfInterfaceDown}
${ip} link add ${selfInterface} type dummy
${ip} link set ${selfInterface} up
@@ -49,6 +55,14 @@ let
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}
${lib.optionalString proxyInboundsRuntimeEnabled ''
while IFS=$'\t' read -r family address; do
case "$family" in
4) ${ip} addr add "$address/32" dev ${selfInterface} ;;
6) ${ip} -6 addr add "$address/128" dev ${selfInterface} nodad ;;
esac
done < <(${jq} -r '.selfAddresses[]? | (select(.ipv4) | "4\t\(.ipv4)"), (select(.ipv6) | "6\t\(.ipv6)")' <<< "$RENDERED")
''}
'';
# Only listeners, and for AmneziaWG listeners transparent sockets (IP_TRANSPARENT).
runXray = constants.runAsServiceUser pkgs (
@@ -173,7 +187,7 @@ let
RENDERED=$(PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildInboundPy} \
--spec ${proxyInboundsSpecFile} \
--server-address "$SERVER_ADDRESS" \
--onion-address "$ONION_ADDRESS")
--onion-address "$ONION_ADDRESS"${lib.optionalString proxyInboundsRuntimeEnabled " \\\n --template ${proxyInboundsFile}"})
INBOUNDS_JSON=$(${jq} -c '.inbounds' <<< "$RENDERED")
@@ -184,6 +198,8 @@ let
LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")"
''}
# With inbounds.runtime, the routing rules are build-inbound.py's: the template's with the
# runtime listeners and users in. Their serverSource outbounds come with them.
${jq} \
--slurpfile ibs <(printf '%s' "$INBOUNDS_JSON") \
--slurpfile obs <(printf '%s' "$OUTBOUNDS_JSON") \
@@ -195,8 +211,14 @@ let
else
"--arg password ''"
} \
--argjson runtime ${if proxyInboundsRuntimeEnabled then "true" else "false"} \
--slurpfile rendered <(printf '%s' "$RENDERED") \
'.inbounds += $ibs[0]
| .outbounds = $obs[0] + .outbounds
| if $runtime then
.routing.rules = $rendered[0].rules
| .outbounds += $rendered[0].selfOutbounds
else . end
| if $auth_enabled then
(.outbounds[] | select(.tag == "proxy") | .settings.servers[0].users)
= [{user:$user,pass:$password}]
@@ -306,8 +328,22 @@ let
chmod ${if userControlAllows "stats" then "640" else "600"} "$tmp"
mv -f "$tmp" "$file"
'';
# inbounds.runtime: after proxy-ctl changes the spool. The AmneziaWG interfaces only when
# their peers changed: restarting them cuts off every one of their clients for a moment.
reloadInbounds = pkgs.writeShellScript "proxy-suite-inbounds" ''
set -euo pipefail
restart=$(PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${parserScriptsPythonPath}/inbound_runtime.py \
--spec ${proxyInboundsSpecFile} check${
lib.optionalString (
proxyInboundsAwg != [ ]
) " --awg-users ${constants.runtimeDir}/proxy-suite-inbounds-awg/users.json"
})
# shellcheck disable=SC2086
${constants.systemctl} try-restart $restart proxy-suite-inbounds.service
'';
stopInboundsInterface =
if proxyInboundsSelfSources == [ ] then
if !selfInterfaceWanted then
null
else
pkgs.writeShellScript "proxy-suite-inbounds" selfInterfaceDown;
@@ -317,6 +353,7 @@ in
startInbounds
stopInboundsInterface
collectInboundStats
reloadInbounds
linksFile
subscriptionsFile
;
+7 -1
View File
@@ -168,7 +168,12 @@ let
inherit (startScripts) startSocks startTun startPerAppTun;
proxyInboundsScripts = import ./proxy-inbounds-scripts.nix { ctx = sctx; };
inherit (proxyInboundsScripts) startInbounds stopInboundsInterface collectInboundStats;
inherit (proxyInboundsScripts)
startInbounds
stopInboundsInterface
collectInboundStats
reloadInbounds
;
proxyInboundsLinksFile = proxyInboundsScripts.linksFile;
proxyInboundsSubscriptionsFile = proxyInboundsScripts.subscriptionsFile;
@@ -206,6 +211,7 @@ in
startInbounds
stopInboundsInterface
collectInboundStats
reloadInbounds
;
inherit
proxyInboundsLinksFile
+11
View File
@@ -22,6 +22,7 @@ let
torOnionEnabled
whitelistBypassJoiners
proxyInboundsEnabled
proxyInboundsRuntimeEnabled
proxyInboundsNeedLocalProxy
scripts
perAppRouting
@@ -129,6 +130,16 @@ let
};
};
}
{
enable = proxyInboundsRuntimeEnabled;
name = "proxy-suite-inbounds-reload";
value = mkOneshotService {
description = "Apply proxy-suite inbound users and listeners added at runtime";
execStart = scripts.reloadInbounds;
stateDirectory = "proxy-suite";
extraServiceConfig.RemainAfterExit = false;
};
}
{
enable = proxyInboundsEnabled;
name = serviceNames.inboundStats;