feat: runtime users and inbounds
This commit is contained in:
36 files changed
+2932
-83
No files matched your search
@@ -219,6 +219,21 @@ Changes and secrets need root or the userControl group.
|
||||
inbounds sub [user] [--qr] subscription users, or one user's URL
|
||||
inbounds stats [days] [--by user|inbound|outbound]
|
||||
traffic by user, listener or exit
|
||||
inbounds users [list] users: order, serverSource address, listeners
|
||||
(the rest below needs inbounds.runtime)
|
||||
inbounds users add <name> [--order N] [--listener <tag>]...
|
||||
add a user at runtime, with generated secrets
|
||||
inbounds users rm <name> remove a runtime user
|
||||
inbounds users order <name> <N> a runtime user's order (serverSource number)
|
||||
inbounds bind|unbind <user> <tag> put a user on a listener, or take it off
|
||||
(a runtime user, or a runtime listener)
|
||||
inbounds add <tag> <type> [--port N] [--via V] [--transport T] [--path P] [--host H]
|
||||
[--reality SNI[,SNI]] [--tls <cert>] [--alpn a,b] [--flow vision] [--method M]
|
||||
[--listen A] [--user U]... [more: see inbounds add --help]
|
||||
add a listener at runtime
|
||||
inbounds add <tag> <file.json|-> add one from JSON shaped like inbounds.listeners.<tag>
|
||||
inbounds rm <tag> remove a runtime listener
|
||||
inbounds show <tag> a runtime listener's JSON
|
||||
inbounds online who is online, and when others were last seen
|
||||
```
|
||||
<!-- proxy-ctl-help:end -->
|
||||
@@ -115,6 +115,16 @@ Part of the [proxy-suite options reference](./index.md).
|
||||
- [ipv6](#services-proxy-suite-inbounds-routing-serversource-ipv6)
|
||||
- [via](#services-proxy-suite-inbounds-routing-via)
|
||||
- [zapretDirect](#services-proxy-suite-inbounds-routing-zapretdirect)
|
||||
- runtime
|
||||
- [enable](#services-proxy-suite-inbounds-runtime-enable)
|
||||
- [fallbackDests](#services-proxy-suite-inbounds-runtime-fallbackdests)
|
||||
- [ports](#services-proxy-suite-inbounds-runtime-ports)
|
||||
- [tlsCertificates](#services-proxy-suite-inbounds-runtime-tlscertificates)
|
||||
- `<name>`
|
||||
- [certificateFile](#services-proxy-suite-inbounds-runtime-tlscertificates-name-certificatefile)
|
||||
- [keyFile](#services-proxy-suite-inbounds-runtime-tlscertificates-name-keyfile)
|
||||
- [serverName](#services-proxy-suite-inbounds-runtime-tlscertificates-name-servername)
|
||||
- [vias](#services-proxy-suite-inbounds-runtime-vias)
|
||||
- [serverAddress](#services-proxy-suite-inbounds-serveraddress)
|
||||
- [serverAliases](#services-proxy-suite-inbounds-serveraliases)
|
||||
- [serverPorts](#services-proxy-suite-inbounds-serverports)
|
||||
@@ -1086,6 +1096,93 @@ Send zapret hostlist sites direct, so this host’s zapret unblocks them\. Only
|
||||
**Type:** boolean\
|
||||
**Default:** `true`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-runtime-enable"></a>
|
||||
## services\.proxy-suite\.inbounds\.runtime\.enable
|
||||
|
||||
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\.
|
||||
|
||||
**Type:** boolean\
|
||||
**Default:** `false`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-runtime-fallbackdests"></a>
|
||||
## services\.proxy-suite\.inbounds\.runtime\.fallbackDests
|
||||
|
||||
` dest ` values a runtime listener’s fallbacks may use, such as a decoy site\. A
|
||||
fallback to a ` listener ` must name another runtime listener\.
|
||||
|
||||
**Type:** list of (16 bit unsigned integer; between 0 and 65535 (both inclusive) or string)\
|
||||
**Default:** `[ ]`\
|
||||
**Example:** `[ "127.0.0.1:8080" ]`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-runtime-ports"></a>
|
||||
## services\.proxy-suite\.inbounds\.runtime\.ports
|
||||
|
||||
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\.
|
||||
|
||||
**Type:** list of (16 bit unsigned integer; between 0 and 65535 (both inclusive) or string matching the pattern \[0-9]±\[0-9]+)\
|
||||
**Default:** `[ ]`\
|
||||
**Example:** `[ 8443 "20000-20099" ]`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-runtime-tlscertificates"></a>
|
||||
## services\.proxy-suite\.inbounds\.runtime\.tlsCertificates
|
||||
|
||||
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\.
|
||||
|
||||
**Type:** attribute set of (submodule)\
|
||||
**Default:** `{ }`\
|
||||
**Example:**
|
||||
|
||||
```nix
|
||||
{
|
||||
main = {
|
||||
certificateFile = "/var/lib/acme/vpn.example.com/fullchain.pem";
|
||||
keyFile = "/var/lib/acme/vpn.example.com/key.pem";
|
||||
};
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
<a id="services-proxy-suite-inbounds-runtime-tlscertificates-name-certificatefile"></a>
|
||||
## services\.proxy-suite\.inbounds\.runtime\.tlsCertificates\.\<name>\.certificateFile
|
||||
|
||||
File with the PEM certificate chain\.
|
||||
|
||||
**Type:** string
|
||||
|
||||
<a id="services-proxy-suite-inbounds-runtime-tlscertificates-name-keyfile"></a>
|
||||
## services\.proxy-suite\.inbounds\.runtime\.tlsCertificates\.\<name>\.keyFile
|
||||
|
||||
File with the PEM private key\.
|
||||
|
||||
**Type:** string
|
||||
|
||||
<a id="services-proxy-suite-inbounds-runtime-tlscertificates-name-servername"></a>
|
||||
## services\.proxy-suite\.inbounds\.runtime\.tlsCertificates\.\<name>\.serverName
|
||||
|
||||
SNI in share links\. ` null `: ` serverAddress `\.
|
||||
|
||||
**Type:** null or string\
|
||||
**Default:** `null`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-runtime-vias"></a>
|
||||
## services\.proxy-suite\.inbounds\.runtime\.vias
|
||||
|
||||
Exits a runtime listener may pick with ` via `, besides ` routing.via ` and “block”:
|
||||
“proxy”, “direct” or a ` proxy.outbounds ` tag, as in ` routing.via `\.
|
||||
|
||||
**Type:** list of string\
|
||||
**Default:** `[ ]`\
|
||||
**Example:** `[ "direct" ]`
|
||||
|
||||
<a id="services-proxy-suite-inbounds-serveraddress"></a>
|
||||
## services\.proxy-suite\.inbounds\.serverAddress
|
||||
|
||||
@@ -1204,7 +1301,7 @@ kept for as long as the user exists\.
|
||||
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\.
|
||||
|
||||
**Type:** null or (positive integer, meaning >0)\
|
||||
**Default:** `null`\
|
||||
|
||||
@@ -89,6 +89,13 @@ services.proxy-suite = {
|
||||
via = "proxy";
|
||||
zapretDirect = true;
|
||||
};
|
||||
runtime = {
|
||||
enable = false;
|
||||
fallbackDests = [ ];
|
||||
ports = [ ];
|
||||
tlsCertificates = { };
|
||||
vias = [ ];
|
||||
};
|
||||
serverAddress = null;
|
||||
serverAliases = [ ];
|
||||
serverPorts = [ ];
|
||||
|
||||
@@ -40,11 +40,13 @@ What the group may do\. Empty allows everything\.
|
||||
- “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
|
||||
“services”; an AmneziaWG outbound is “outbounds”\.
|
||||
|
||||
**Type:** list of (one of “services”, “perApp”, “routing”, “outbounds”, “secrets”, “autoProxy”, “zapret”, “stats”, “whitelistBypass”, “amneziaWg”)\
|
||||
**Type:** list of (one of “services”, “perApp”, “routing”, “outbounds”, “secrets”, “autoProxy”, “zapret”, “stats”, “inbounds”, “whitelistBypass”, “amneziaWg”)\
|
||||
**Default:** `[ ]`\
|
||||
**Example:** `[ "services" "routing" ]`
|
||||
@@ -0,0 +1,12 @@
|
||||
{ config, lib, pkgs, ... }:
|
||||
{
|
||||
services.proxy-suite.inbounds.runtime = {
|
||||
enable = true;
|
||||
ports = [ "20000-20099" ]; # runtime listeners bind only here; opened in the firewall
|
||||
vias = [ "direct" ]; # exits besides routing.via and "block"
|
||||
tlsCertificates.main = { # named, so a runtime listener never points at a file
|
||||
certificateFile = "/var/lib/acme/vpn.example.com/fullchain.pem";
|
||||
keyFile = "/var/lib/acme/vpn.example.com/key.pem";
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -41,6 +41,7 @@ Members of the group get the listed scopes. An empty `scopes` list grants all of
|
||||
| `amneziaWg` | `awg add` and `awg rm`: global AmneziaWG profiles, which take over the host's routes and DNS |
|
||||
| `perApp` | `apps run` with `tun`, `tproxy` and `zapret` profiles |
|
||||
| `secrets` | reading share links, subscription URLs and running configs |
|
||||
| `inbounds` | adding, removing and binding runtime inbound users and listeners, and their secrets |
|
||||
| `autoProxy`, `zapret`, `stats`, `whitelistBypass` | the matching `proxy-ctl` groups |
|
||||
|
||||
Log out and back in after joining the group. Without `userControl`, a change asks for an
|
||||
@@ -52,6 +53,7 @@ admin password, or you run `proxy-ctl` with sudo.
|
||||
|---|---|
|
||||
| `proxy outbounds add`, `proxy subs add`, `awg add` | until removed with `rm`; kept across reboots |
|
||||
| `proxy outbounds disable` | until `enable`; works on outbounds from Nix too |
|
||||
| `inbounds users add`, `inbounds add`, `inbounds bind` | until removed; kept across reboots |
|
||||
| `proxy pin` | until `unpin`; kept across reboots |
|
||||
| `proxy mode` | until the next reboot |
|
||||
| `… on` / `… off` | until the next reboot; boot state comes from the config |
|
||||
|
||||
@@ -88,6 +88,7 @@ hysteria2, vmess, …) and transports (ws, grpc, xhttp) are set per listener; se
|
||||
proxy-ctl inbounds # listeners
|
||||
proxy-ctl inbounds link vless-reality phone --qr # link as a QR code for the phone
|
||||
proxy-ctl inbounds link awg phone --config # AmneziaWG .conf
|
||||
proxy-ctl inbounds users # users: order, address, listeners
|
||||
proxy-ctl inbounds stats # traffic per user
|
||||
proxy-ctl inbounds online # who is connected
|
||||
```
|
||||
@@ -106,6 +107,43 @@ services.nginx.virtualHosts."vpn.example.com".locations."/sub/".alias =
|
||||
|
||||
Then `proxy-ctl inbounds sub phone --qr` prints that user's subscription.
|
||||
|
||||
## Add users and listeners at runtime
|
||||
|
||||
With `inbounds.runtime`, users and listeners can be added with `proxy-ctl`, the TUI or the app,
|
||||
without a rebuild. The config says what they may use: ports, exits and certificates.
|
||||
|
||||
```nix
|
||||
services.proxy-suite.inbounds.runtime = {
|
||||
enable = true;
|
||||
ports = [ "20000-20099" ]; # runtime listeners bind only here; opened in the firewall
|
||||
vias = [ "direct" ]; # exits besides routing.via and "block"
|
||||
tlsCertificates.main = { # named, so a runtime listener never points at a file
|
||||
certificateFile = "/var/lib/acme/vpn.example.com/fullchain.pem";
|
||||
keyFile = "/var/lib/acme/vpn.example.com/key.pem";
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
```sh
|
||||
proxy-ctl inbounds users add alice --listener vless-reality # secrets are generated
|
||||
proxy-ctl inbounds add friends vless --port 20001 --reality www.microsoft.com --user alice
|
||||
proxy-ctl inbounds bind phone friends # a declared user on it too
|
||||
proxy-ctl inbounds users # order, address, listeners
|
||||
proxy-ctl inbounds link friends alice --qr
|
||||
```
|
||||
|
||||
A runtime user can join any listener; a declared user only a runtime one (bind two declared
|
||||
ones in the config). Each user's `order` is its `routing.serverSource` number, as in the
|
||||
config: given with `--order` or the lowest free one, and kept. A listener takes JSON too,
|
||||
shaped like an [`inbounds.listeners`](../options/inbounds.md#services-proxy-suite-inbounds-listeners)
|
||||
entry: `proxy-ctl inbounds add friends listener.json`. It cannot name files, raw XRay JSON,
|
||||
AmneziaWG or port hopping; REALITY keys and Shadowsocks 2022 server keys are generated.
|
||||
|
||||
Every change restarts the inbounds, which drops the connections once. One that does not hold
|
||||
up is refused, and anything that stops working later (a certificate removed from the config,
|
||||
say) is left out with a warning in `proxy-ctl logs proxy-suite-inbounds` while the rest runs.
|
||||
Without root, members of `userControl.group` need the `inbounds` scope.
|
||||
|
||||
## Good to know
|
||||
|
||||
- Clients cannot reach this host's LAN or Russian sites by default
|
||||
@@ -120,5 +158,6 @@ Then `proxy-ctl inbounds sub phone --qr` prints that user's subscription.
|
||||
|
||||
- [`inbounds.listeners`](../options/inbounds.md#services-proxy-suite-inbounds-listeners)
|
||||
- [`inbounds.routing.via`](../options/inbounds.md#services-proxy-suite-inbounds-routing-via)
|
||||
- [`inbounds.runtime`](../options/inbounds.md#services-proxy-suite-inbounds-runtime-enable)
|
||||
- [`inbounds.subscriptions`](../options/inbounds.md#services-proxy-suite-inbounds-subscriptions-enable)
|
||||
- [`tor.onionService`](../options/tor.md#services-proxy-suite-tor-onionservice-enable)
|
||||
@@ -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 (
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 "";
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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) [
|
||||
|
||||
@@ -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
|
||||
;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -112,6 +112,11 @@ pkgs.testers.runNixOSTest {
|
||||
dns = [ ];
|
||||
};
|
||||
};
|
||||
# A peer added with proxy-ctl.
|
||||
runtime = {
|
||||
enable = true;
|
||||
ports = [ "9000-9001" ];
|
||||
};
|
||||
};
|
||||
};
|
||||
environment.systemPackages = [ pkgs.jq ];
|
||||
@@ -215,5 +220,18 @@ pkgs.testers.runNixOSTest {
|
||||
server.wait_for_unit("proxy-suite-inbounds.service")
|
||||
assert server.succeed("jq -S .users /var/lib/proxy-suite/awg-inbounds/roam/state.json") == before
|
||||
through_server(alice, timeout=90)
|
||||
|
||||
with subtest("a runtime user becomes a peer, and only its listener's interfaces restart"):
|
||||
server.succeed("proxy-ctl inbounds users add ring --listener roam")
|
||||
server.wait_until_succeeds("awg show awgi-roam peers | wc -l | grep -qx 3", timeout=30)
|
||||
server.succeed("jq -e '.users.ring.publicKey' /var/lib/proxy-suite/awg-inbounds/roam/state.json")
|
||||
server.succeed("proxy-ctl inbounds link roam ring --config | grep -q '^PrivateKey'")
|
||||
# A change that leaves the peers alone restarts only XRay.
|
||||
since = server.succeed("systemctl show -p ActiveEnterTimestampMonotonic --value proxy-suite-inbounds-awg.service").strip()
|
||||
server.succeed("proxy-ctl inbounds users order ring 9")
|
||||
assert server.succeed("systemctl show -p ActiveEnterTimestampMonotonic --value proxy-suite-inbounds-awg.service").strip() == since
|
||||
server.succeed("proxy-ctl inbounds users rm ring")
|
||||
server.wait_until_succeeds("awg show awgi-roam peers | wc -l | grep -qx 2", timeout=30)
|
||||
server.succeed("jq -e '.users.ring == null' /var/lib/proxy-suite/awg-inbounds/roam/state.json")
|
||||
'';
|
||||
}
|
||||
@@ -63,6 +63,11 @@ pkgs.testers.runNixOSTest {
|
||||
method = "2022-blake3-aes-128-gcm";
|
||||
users = [ "ss-user" ];
|
||||
};
|
||||
# Users and listeners proxy-ctl adds below.
|
||||
runtime = {
|
||||
enable = true;
|
||||
ports = [ "9000-9010" ];
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
@@ -159,5 +164,38 @@ pkgs.testers.runNixOSTest {
|
||||
with subtest("a listener keeps serving after a restart"):
|
||||
server.succeed("systemctl restart proxy-suite-inbounds.service")
|
||||
server.wait_for_open_port(8443)
|
||||
|
||||
with subtest("runtime users and listeners"):
|
||||
cfg = "/run/proxy-suite-inbounds/config.json"
|
||||
server.succeed("proxy-ctl inbounds users add friend --listener vless-in")
|
||||
server.succeed(f"jq -e '.inbounds[] | select(.tag == \"vless-in\") | .settings.clients | map(.email) == [\"tester\", \"friend\"]' {cfg}")
|
||||
server.succeed("proxy-ctl inbounds add rt vless --port 9001 --user friend --user tester")
|
||||
server.wait_for_open_port(9001)
|
||||
server.succeed("proxy-ctl inbounds users | grep friend | grep -q rt")
|
||||
# Refused, and nothing else disturbed.
|
||||
server.fail("proxy-ctl inbounds add far vless --port 30000 --user friend")
|
||||
server.fail("proxy-ctl inbounds bind tester vless-in")
|
||||
server.succeed("test ! -e /var/lib/proxy-suite/inbounds.d/listeners/far.json")
|
||||
# The runtime user's link works from the client, as a runtime outbound there. XRay
|
||||
# refuses plain VLESS to a public IP, so it dials the private one.
|
||||
link = server.succeed("proxy-ctl inbounds link rt friend").strip()
|
||||
assert link.startswith("vless://") and ":9001" in link, link
|
||||
link = link.replace("${serverAddress}", "${serverPrivateAddress}")
|
||||
client.succeed(f"proxy-ctl proxy outbounds add rt-out '{link}'")
|
||||
client.succeed("proxy-ctl proxy pin rt-out")
|
||||
client.wait_until_succeeds(
|
||||
"curl -sS --fail --max-time 20 --proxy socks5h://127.0.0.1:1080"
|
||||
f" http://{'${serverAddress}'}/ | grep -q served-from-origin",
|
||||
timeout=60,
|
||||
)
|
||||
# A spool file that no longer holds up is left out; the declared listeners stay.
|
||||
server.succeed("echo '{' > /var/lib/proxy-suite/inbounds.d/listeners/rt.json")
|
||||
server.succeed("systemctl start proxy-suite-inbounds-reload.service")
|
||||
server.wait_for_open_port(8443)
|
||||
server.succeed(f"jq -e '[.inbounds[].tag] | index(\"rt\") == null' {cfg}")
|
||||
server.succeed("journalctl -u proxy-suite-inbounds | grep -q \"ignoring runtime listener 'rt'\"")
|
||||
server.succeed("rm /var/lib/proxy-suite/inbounds.d/listeners/rt.json")
|
||||
server.succeed("proxy-ctl inbounds users rm friend")
|
||||
server.succeed(f"jq -e '.inbounds[] | select(.tag == \"vless-in\") | .settings.clients | map(.email) == [\"tester\"]' {cfg}")
|
||||
'';
|
||||
}
|
||||
@@ -211,6 +211,46 @@ let
|
||||
lib.recursiveUpdate selfSourceInbounds { routing.serverSource.ipv4 = "10.78.0.5/24"; }
|
||||
);
|
||||
|
||||
# inbounds.runtime: the rules runtime listeners join are marked, the runtime users'
|
||||
# serverSource rules have their anchors, and the rest of the system is ready for them.
|
||||
runtimeInbounds = selfSourceInbounds // {
|
||||
runtime = {
|
||||
enable = true;
|
||||
ports = [
|
||||
9443
|
||||
"20000-20010"
|
||||
];
|
||||
vias = [ "direct" ];
|
||||
};
|
||||
};
|
||||
runtimeFixture = mkInbounds runtimeInbounds;
|
||||
runtimeConfig = mkInboundsConfig runtimeFixture;
|
||||
runtimeSpec = mkInboundsSpec runtimeFixture;
|
||||
hasFailed =
|
||||
fixture: message:
|
||||
builtins.any (a: !a.assertion && lib.hasInfix message a.message) fixture.config.assertions;
|
||||
# Only this module's: a fixture has no root file system or boot loader.
|
||||
failedMessages =
|
||||
fixture:
|
||||
builtins.filter (lib.hasPrefix "proxy-suite:") (
|
||||
map (a: a.message) (builtins.filter (a: !a.assertion) fixture.config.assertions)
|
||||
);
|
||||
# A listener meant only for runtime users, and nothing but runtime listeners.
|
||||
runtimeOnlyFixture = mkInbounds {
|
||||
serverAddress = "vpn.example.com";
|
||||
runtime = {
|
||||
enable = true;
|
||||
ports = [ "20000-20010" ];
|
||||
};
|
||||
listeners.waiting = realityListener // {
|
||||
users = [ ];
|
||||
};
|
||||
};
|
||||
runtimeClashFixture = mkInbounds (
|
||||
lib.recursiveUpdate runtimeInbounds { runtime.ports = [ "400-500" ]; }
|
||||
);
|
||||
runtimeNoPortsFixture = mkInbounds (runtimeInbounds // { runtime.enable = true; });
|
||||
|
||||
unguardedFixture = mkInbounds {
|
||||
routing = {
|
||||
blockRu = false;
|
||||
@@ -995,6 +1035,118 @@ let
|
||||
) badSelfSourceFixture.config.assertions;
|
||||
true
|
||||
)
|
||||
# The declared users are in the spec without inbounds.runtime too, for `inbounds users`.
|
||||
(
|
||||
let
|
||||
spec = mkInboundsSpec selfSourceFixture;
|
||||
in
|
||||
assert spec.runtime == null;
|
||||
assert
|
||||
builtins.attrNames spec.users == [
|
||||
"a"
|
||||
"alice"
|
||||
"anon"
|
||||
"b"
|
||||
"bob"
|
||||
"far"
|
||||
"h3"
|
||||
"hy2"
|
||||
"laptop"
|
||||
"phone"
|
||||
"second"
|
||||
"ss"
|
||||
"user"
|
||||
"ws"
|
||||
];
|
||||
assert
|
||||
(builtins.head spec.serverSource.declared) == {
|
||||
name = "bob";
|
||||
number = 1;
|
||||
};
|
||||
true
|
||||
)
|
||||
# Without inbounds.runtime nothing is marked for it.
|
||||
(ok (!builtins.any (rule: rule ? _members || rule ? _anchor) selfSourceConfig.routing.rules))
|
||||
(
|
||||
let
|
||||
rules = runtimeConfig.routing.rules;
|
||||
anchors = builtins.filter (rule: rule ? _anchor) rules;
|
||||
tags = ruleTags runtimeConfig;
|
||||
at = tag: lib.lists.findFirstIndex (t: t == tag) null tags;
|
||||
anchorAt = name: lib.lists.findFirstIndex (rule: (rule._anchor or null) == name) null rules;
|
||||
startScript = (import ./read-generated.nix).readDerivation (service runtimeFixture)
|
||||
.serviceConfig.ExecStart;
|
||||
fw = runtimeFixture.config.networking.firewall;
|
||||
in
|
||||
assert
|
||||
map (rule: rule._anchor) anchors == [
|
||||
"selfIp"
|
||||
"selfName"
|
||||
];
|
||||
# Each after the declared users' own, before the host's.
|
||||
assert anchorAt "selfIp" > at "inbound-server-address-self-ip4-6";
|
||||
assert anchorAt "selfIp" < at "inbound-server-address-direct-ip";
|
||||
assert anchorAt "selfName" > at "inbound-server-address-self-6";
|
||||
assert anchorAt "selfName" < at "inbound-server-address-direct";
|
||||
assert (builtins.head anchors).ip4 == [ "203.0.113.10" ];
|
||||
assert (builtins.head anchors).port == "8443,443,9443,20000-20010";
|
||||
assert
|
||||
(ruleByTag runtimeConfig "inbound-server-address-direct")._members == { notVia = [ "block" ]; };
|
||||
# A guard for every exit a runtime listener may take, even with nobody on it yet.
|
||||
assert (ruleByTag runtimeConfig "inbound-server-address-sniffed-direct").inboundTag == [ ];
|
||||
assert
|
||||
(ruleByTag runtimeConfig "inbound-server-address-sniffed-direct")._members == {
|
||||
via = [ "direct" ];
|
||||
};
|
||||
assert !builtins.elem "inbound-server-address-sniffed-block" tags;
|
||||
assert
|
||||
runtimeSpec.runtime.vias == [
|
||||
"proxy"
|
||||
"direct"
|
||||
"block"
|
||||
];
|
||||
assert
|
||||
runtimeSpec.serverSource.declared == [
|
||||
{
|
||||
name = "bob";
|
||||
number = 1;
|
||||
}
|
||||
{
|
||||
name = "alice";
|
||||
number = 5;
|
||||
}
|
||||
{
|
||||
name = "anon";
|
||||
number = 6;
|
||||
}
|
||||
];
|
||||
assert runtimeSpec.runtime.spool == "/var/lib/proxy-suite/inbounds.d";
|
||||
assert !(runtimeSpec.runtime.listenerDefaults ? users);
|
||||
assert runtimeSpec.runtime.listenerDefaults.port == 443;
|
||||
assert
|
||||
runtimeSpec.runtime.selfFinalRules
|
||||
== (builtins.head (builtins.filter (ob: ob.tag == "direct-self4-1") runtimeConfig.outbounds))
|
||||
.settings.finalRules;
|
||||
assert builtins.elem 9443 fw.allowedTCPPorts && builtins.elem 9443 fw.allowedUDPPorts;
|
||||
assert
|
||||
fw.allowedTCPPortRanges == [
|
||||
{
|
||||
from = 20000;
|
||||
to = 20010;
|
||||
}
|
||||
];
|
||||
assert lib.hasInfix "--template" startScript;
|
||||
assert runtimeFixture.config.systemd.services ? proxy-suite-inbounds-reload;
|
||||
assert builtins.elem "d /var/lib/proxy-suite/inbounds.d 0700 root root -"
|
||||
runtimeFixture.config.systemd.tmpfiles.rules;
|
||||
assert !(selfSourceFixture.config.systemd.services ? proxy-suite-inbounds-reload);
|
||||
true
|
||||
)
|
||||
(ok (failedMessages runtimeOnlyFixture == [ ]))
|
||||
(ok (
|
||||
hasFailed runtimeClashFixture "inbounds.runtime.ports cover a port a declared listener or proxy-suite itself uses (443)"
|
||||
))
|
||||
(ok (hasFailed runtimeNoPortsFixture "inbounds.runtime.enable needs inbounds.runtime.ports"))
|
||||
(ok ((ruleByTag aliasedConfig "inbound-server-address-direct").port == "443,993,7882-7885"))
|
||||
(ok ((ruleByTag aliasedConfig "inbound-server-address-direct-ip").port == "443,993,7882-7885"))
|
||||
(ok ((ruleByTag aliasedConfig "inbound-server-address-direct-ip").outboundTag == "direct"))
|
||||
|
||||
@@ -62,6 +62,11 @@ pkgs.lib.mapAttrs mkPythonCheck {
|
||||
file = "${scripts}/test-awg-inbound.py";
|
||||
env = withPath scripts;
|
||||
};
|
||||
# inbounds.runtime: the spool, its fences, the merge and the rules it expands.
|
||||
inbound-runtime = {
|
||||
file = "${scripts}/test-inbound-runtime.py";
|
||||
env = withPath scripts;
|
||||
};
|
||||
# The NFQWS_OPT rewrites the zapret v1 package build applies.
|
||||
patch-zapret-config = {
|
||||
file = "${scripts}/test-patch-zapret-config.py";
|
||||
@@ -76,6 +81,7 @@ pkgs.lib.mapAttrs mkPythonCheck {
|
||||
# `awg add` and AmneziaWG outbounds hand their configs to it.
|
||||
env = singBox // {
|
||||
AWG_CONFIG_TOOL = "${scripts}/amneziawg_config.py";
|
||||
INBOUNDS_RUNTIME_TOOL = "${scripts}/inbound_runtime.py";
|
||||
};
|
||||
};
|
||||
# proxy-suitectl, nix-on-droid's service manager: real processes restarted, timed and stopped.
|
||||
|
||||
+167
-3
@@ -138,6 +138,21 @@ Changes and secrets need root or the userControl group.
|
||||
inbounds sub [user] [--qr] subscription users, or one user's URL
|
||||
inbounds stats [days] [--by user|inbound|outbound]
|
||||
traffic by user, listener or exit
|
||||
inbounds users [list] users: order, serverSource address, listeners
|
||||
(the rest below needs inbounds.runtime)
|
||||
inbounds users add <name> [--order N] [--listener <tag>]...
|
||||
add a user at runtime, with generated secrets
|
||||
inbounds users rm <name> remove a runtime user
|
||||
inbounds users order <name> <N> a runtime user's order (serverSource number)
|
||||
inbounds bind|unbind <user> <tag> put a user on a listener, or take it off
|
||||
(a runtime user, or a runtime listener)
|
||||
inbounds add <tag> <type> [--port N] [--via V] [--transport T] [--path P] [--host H]
|
||||
[--reality SNI[,SNI]] [--tls <cert>] [--alpn a,b] [--flow vision] [--method M]
|
||||
[--listen A] [--user U]... [more: see inbounds add --help]
|
||||
add a listener at runtime
|
||||
inbounds add <tag> <file.json|-> add one from JSON shaped like inbounds.listeners.<tag>
|
||||
inbounds rm <tag> remove a runtime listener
|
||||
inbounds show <tag> a runtime listener's JSON
|
||||
inbounds online who is online, and when others were last seen
|
||||
"""
|
||||
|
||||
@@ -149,6 +164,33 @@ ROUTE_MODE_LABELS = {
|
||||
"all-bypass": "All Bypass (override)",
|
||||
}
|
||||
|
||||
# `inbounds add`: the listener types and flags scripts/inbound_runtime.py takes.
|
||||
INBOUND_TYPES = ("vless", "vmess", "trojan", "hysteria2", "shadowsocks", "socks", "http")
|
||||
INBOUND_ADD_FLAGS = {
|
||||
"--port": "port, from inbounds.runtime.ports",
|
||||
"--listen": "listening address (default ::)",
|
||||
"--via": "where its traffic exits",
|
||||
"--transport": "raw, ws, grpc, httpupgrade or xhttp",
|
||||
"--path": "ws, httpupgrade or xhttp path",
|
||||
"--host": "expected Host header",
|
||||
"--mode": "xhttp mode",
|
||||
"--service-name": "gRPC service name",
|
||||
"--reality": "REALITY server names, comma-separated",
|
||||
"--reality-dest": "REALITY dest host:port",
|
||||
"--short-id": "REALITY short ID",
|
||||
"--tls": "a certificate from inbounds.runtime.tlsCertificates",
|
||||
"--alpn": "ALPN, comma-separated",
|
||||
"--sni": "SNI in share links",
|
||||
"--flow": "vless flow (vision)",
|
||||
"--method": "shadowsocks cipher",
|
||||
"--share-port": "port in share links",
|
||||
"--share-address": "address in share links",
|
||||
"--order": "position in links and subscriptions",
|
||||
"--masquerade": "hysteria2: site shown to anything else",
|
||||
"--salamander": "hysteria2: Salamander obfuscation",
|
||||
"--user": "a user it accepts",
|
||||
}
|
||||
|
||||
# A hostname: it lands in root-owned files and then in URLs.
|
||||
HOSTNAME = re.compile(r"[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
|
||||
|
||||
@@ -690,9 +732,31 @@ COMPLETE = {
|
||||
"sub": "subscription users, or one user's URL",
|
||||
"stats": "traffic per user, listener or exit",
|
||||
"online": "who is connected now",
|
||||
"users": "users, and adding them at runtime",
|
||||
"bind": "put a user on a listener",
|
||||
"unbind": "take a user off a listener",
|
||||
"add": "add a listener at runtime",
|
||||
"rm": "remove a runtime listener",
|
||||
"show": "a runtime listener's JSON",
|
||||
}
|
||||
},
|
||||
"inbounds stats": {"flags": {"--by": "user, inbound or outbound"}},
|
||||
"inbounds users": {
|
||||
"words": {
|
||||
"list": "users, their order, address and listeners",
|
||||
"add": "add a user at runtime",
|
||||
"rm": "remove a runtime user",
|
||||
"order": "set a runtime user's order",
|
||||
}
|
||||
},
|
||||
"inbounds users add": {"flags": {"--order": "its serverSource number", "--listener": "a listener to put it on"}},
|
||||
"inbounds users rm": {"args": lambda: _inbound_runtime_names("users", "runtime")},
|
||||
"inbounds users order": {"args": lambda: _inbound_runtime_names("users", "runtime")},
|
||||
"inbounds bind": {"args": lambda: {**_inbound_runtime_names("users"), **_inbound_runtime_names("listeners")}, "repeat": True},
|
||||
"inbounds unbind": {"args": lambda: {**_inbound_runtime_names("users"), **_inbound_runtime_names("listeners")}, "repeat": True},
|
||||
"inbounds add": {"args": lambda: {t: "" for t in INBOUND_TYPES}, "repeat": True, "flags": INBOUND_ADD_FLAGS},
|
||||
"inbounds rm": {"args": lambda: _inbound_runtime_names("listeners", "runtime")},
|
||||
"inbounds show": {"args": lambda: _inbound_runtime_names("listeners", "runtime")},
|
||||
"inbounds link": {
|
||||
"args": _inbound_link_choices,
|
||||
"flags": {
|
||||
@@ -3720,15 +3784,115 @@ def _inbound_subscriptions(*args):
|
||||
print("Set inbounds.subscriptions.baseUrl to get a URL instead of a path.", file=sys.stderr)
|
||||
|
||||
|
||||
# --- runtime inbound users and listeners ---------------------------------------
|
||||
#
|
||||
# inbounds.runtime: users/<name>.json and listeners/<tag>.json in a spool the "inbounds" scope
|
||||
# may write. scripts/inbound_runtime.py checks and writes them, with what the spec allows;
|
||||
# the reload unit restarts the inbounds, which merge them in when they start.
|
||||
|
||||
def _inbound_runtime(*args, stdin=None, quiet=False, listing=False):
|
||||
"""scripts/inbound_runtime.py with the spec: its output, or its complaint as ours.
|
||||
|
||||
listing: a read, which works without inbounds.runtime (the declared users and listeners).
|
||||
"""
|
||||
if not (listing and env("INBOUNDS_ENABLED") == "1") and env("INBOUNDS_RUNTIME_ENABLED") != "1":
|
||||
die("Runtime inbound users and listeners are not enabled in this configuration (inbounds.runtime.enable).")
|
||||
argv = [sys.executable, env("INBOUNDS_RUNTIME_TOOL"), "--spec", env("INBOUNDS_SPEC_FILE"), "--xray", env("INBOUNDS_XRAY", "xray"), *args]
|
||||
try:
|
||||
p = subprocess.run(argv, input=stdin, capture_output=True, text=True)
|
||||
except OSError as e:
|
||||
die(f"Cannot run {argv[1]}: {e}")
|
||||
if p.returncode and not quiet:
|
||||
message = p.stderr.strip() or f"{argv[1]} exited with {p.returncode}"
|
||||
die(f"{message} - {ask_group()}." if p.returncode == 77 else message)
|
||||
if not quiet and p.stderr:
|
||||
sys.stderr.write(p.stderr)
|
||||
return p.returncode, p.stdout
|
||||
|
||||
|
||||
def _inbound_runtime_rows(kind):
|
||||
"""Users or listeners, declared and runtime, as the tool lists them; [] when it cannot."""
|
||||
if env("INBOUNDS_ENABLED") != "1":
|
||||
return []
|
||||
status, out = _inbound_runtime(kind, "--json", quiet=True, listing=True)
|
||||
try:
|
||||
rows = json.loads(out) if not status else []
|
||||
except ValueError:
|
||||
rows = []
|
||||
return rows if isinstance(rows, list) else []
|
||||
|
||||
|
||||
def _inbound_runtime_names(kind, source=""):
|
||||
key = "name" if kind == "users" else "tag"
|
||||
return {_s(r[key]): _s(r.get("source") or "") for r in _inbound_runtime_rows(kind) if not source or r.get("source") == source}
|
||||
|
||||
|
||||
def _inbound_runtime_change(*args, stdin=None):
|
||||
"""A change to the spool, then the reload that applies it, then what it left out."""
|
||||
_, out = _inbound_runtime(*args, stdin=stdin)
|
||||
sys.stdout.write(out)
|
||||
if systemctl("start", "proxy-suite-inbounds-reload.service")[0]:
|
||||
die("Saved, but applying it failed - see: proxy-ctl logs proxy-suite-inbounds-reload")
|
||||
p = subprocess.run(
|
||||
[sys.executable, env("INBOUNDS_RUNTIME_TOOL"), "--spec", env("INBOUNDS_SPEC_FILE"), "check"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
for line in lines(p.stderr):
|
||||
print(f"warning: {line}", file=sys.stderr)
|
||||
|
||||
|
||||
def _inbound_users(verb="list", *args):
|
||||
if verb in ("list", "--json"):
|
||||
sys.stdout.write(_inbound_runtime("users", *(["--json"] if "--json" in (verb, *args) else []), listing=True)[1])
|
||||
elif verb == "add" and args:
|
||||
_inbound_runtime_change("users", "add", *args)
|
||||
elif verb == "rm" and len(args) == 1:
|
||||
_inbound_runtime_change("users", "rm", *args)
|
||||
elif verb == "order" and len(args) == 2:
|
||||
_inbound_runtime_change("users", "order", *args)
|
||||
else:
|
||||
usage("inbounds users [list] | add <name> [--order N] [--listener <tag>]... | rm <name> | order <name> <N>")
|
||||
|
||||
|
||||
def cmd_inbounds(verb="list", *args):
|
||||
require_enabled("INBOUNDS_ENABLED", "inbounds")
|
||||
if verb == "users":
|
||||
_inbound_users(*args)
|
||||
return
|
||||
if verb in ("bind", "unbind"):
|
||||
if len(args) != 2:
|
||||
usage(f"inbounds {verb} <user> <tag>")
|
||||
_inbound_runtime_change(verb, *args)
|
||||
return
|
||||
if verb == "add":
|
||||
if "--help" in args or "-h" in args:
|
||||
sys.stdout.write(_inbound_runtime("add", "--help")[1])
|
||||
return
|
||||
if len(args) < 2:
|
||||
usage("inbounds add <tag> <type> [flags] | <tag> <file.json|->")
|
||||
_inbound_runtime_change("add", *args, stdin=sys.stdin.read() if args[1:2] == ("-",) else None)
|
||||
return
|
||||
if verb == "rm":
|
||||
if len(args) != 1:
|
||||
usage("inbounds rm <tag>")
|
||||
_inbound_runtime_change("rm", *args)
|
||||
return
|
||||
if verb == "show":
|
||||
if len(args) != 1:
|
||||
usage("inbounds show <tag>")
|
||||
sys.stdout.write(_inbound_runtime("show", *args)[1])
|
||||
return
|
||||
if verb == "list":
|
||||
state = svc_state("proxy-suite-inbounds")
|
||||
row = " {:<24} {:<16} {:<14} {:<8} {}"
|
||||
print(row.format("TAG", "USER", "TYPE", "PORT", "STATE"))
|
||||
# Which listeners were added at runtime, when they can be.
|
||||
sources = _inbound_runtime_names("listeners") if env("INBOUNDS_RUNTIME_ENABLED") == "1" else {}
|
||||
row = " {:<24} {:<16} {:<14} {:<8} {:<8}" + (" {}" if sources else "")
|
||||
print(row.format("TAG", "USER", "TYPE", "PORT", "STATE", "SOURCE").rstrip())
|
||||
for x in _inbound_links():
|
||||
kind = _s(x.get("type")) + (" (onion)" if x.get("variant") == "onion" else "")
|
||||
print(row.format(_s(x.get("tag")), _s(x.get("user")), kind, _s(x.get("port")), state))
|
||||
tag = _s(x.get("tag"))
|
||||
print(row.format(tag, _s(x.get("user")), kind, _s(x.get("port")), state, sources.get(tag, "nix")).rstrip())
|
||||
elif verb in ("link", "qr"):
|
||||
rest = [a for a in args if not a.startswith("--")]
|
||||
if not rest:
|
||||
|
||||
@@ -28,7 +28,7 @@ def _die(message, status=1):
|
||||
|
||||
|
||||
# Clash API calls and systemctl spawns that several readers repeat within one load.
|
||||
MEMOIZED = ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_timer_next_run", "svc_state", "_wl")
|
||||
MEMOIZED = ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_timer_next_run", "svc_state", "_wl", "_inbound_runtime_rows")
|
||||
# proxy_ctl as the CLI has it, before the patching below: its own tests put these back.
|
||||
CLI_FUNCTIONS = {name: getattr(ctl, name) for name in ("die", *MEMOIZED)}
|
||||
|
||||
@@ -396,17 +396,50 @@ def inbound_rows(_):
|
||||
# so a per-listener row could only repeat the same verdict once per listener. The
|
||||
# "who is online" action shows it once per user, which is the shape the data has.
|
||||
# A listener behind the onion service has a second row, for its .onion link.
|
||||
sources = ctl._inbound_runtime_names("listeners")
|
||||
return [
|
||||
{
|
||||
# The TUI titles its menu with the key: no trailing "/" for the plain link.
|
||||
"key": "/".join(ctl._s(x.get(k)) for k in ("tag", "user", "variant") if x.get(k)),
|
||||
**{k: ctl._s(x.get(k) or "") for k in ("tag", "user", "type", "port", "variant")},
|
||||
**({"type": f"{ctl._s(x.get('type') or '')} (onion)"} if x.get("variant") == "onion" else {}),
|
||||
"source": sources.get(ctl._s(x.get("tag")), "nix"),
|
||||
}
|
||||
for x in ctl._inbound_links()
|
||||
]
|
||||
|
||||
|
||||
def inbound_user_rows(_):
|
||||
"""Inbound users as `inbounds users` lists them: the declared ones, and with
|
||||
inbounds.runtime the runtime ones too."""
|
||||
return [
|
||||
{
|
||||
"key": ctl._s(u.get("name")),
|
||||
"name": ctl._s(u.get("name")),
|
||||
"order": ctl._s(u.get("order") if u.get("order") is not None else ""),
|
||||
"address": ctl._s(u.get("address") or ""),
|
||||
"source": ctl._s(u.get("source") or ""),
|
||||
"listeners": ",".join(ctl._s(t) for t in u.get("listeners") or []),
|
||||
"problems": "; ".join(ctl._s(p) for p in u.get("problems") or []),
|
||||
}
|
||||
for u in ctl._inbound_runtime_rows("users")
|
||||
]
|
||||
|
||||
|
||||
def _inbounds_runtime():
|
||||
return ctl.env("INBOUNDS_RUNTIME_ENABLED") == "1"
|
||||
|
||||
|
||||
def _runtime_row(row):
|
||||
return row.get("source") == "runtime"
|
||||
|
||||
|
||||
def _user_add_argv(text):
|
||||
words = shlex.split(text)
|
||||
order = ["--order", words[1]] if len(words) > 1 else []
|
||||
return ["inbounds", "users", "add", *words[:1], *order, *(a for t in words[2:] for a in ("--listener", t))]
|
||||
|
||||
|
||||
def app_rows(_):
|
||||
return [
|
||||
{"key": ctl._s(p.get("name")), "profile": ctl._s(p.get("name")), "route": ctl._s(p.get("route"))}
|
||||
@@ -753,6 +786,36 @@ TABS = [
|
||||
Action("I", "traffic per inbound", lambda r, *_: ["inbounds", "stats", "--by", "inbound"], mode="dialog"),
|
||||
Action("O", "traffic per exit", lambda r, *_: ["inbounds", "stats", "--by", "outbound"], mode="dialog"),
|
||||
Action("n", "who is online", lambda r, *_: ["inbounds", "online"], mode="dialog"),
|
||||
Action(
|
||||
"a",
|
||||
"add a listener…",
|
||||
lambda r, t, _: ["inbounds", "add", *shlex.split(t)],
|
||||
prompt="<tag> <type> [--port N] [--reality SNI] [--tls <cert>] [--user U]... - e.g. friends vless --port 20001 --reality www.microsoft.com",
|
||||
offered=_inbounds_runtime,
|
||||
),
|
||||
Action("d", "remove this listener", lambda r, *_: ["inbounds", "rm", r["tag"]], when=_runtime_row, confirm=True, offered=_inbounds_runtime),
|
||||
Action("b", "bind a user to it…", lambda r, t, _: ["inbounds", "bind", t.strip(), r["tag"]], when=ROW, prompt="<user>", offered=_inbounds_runtime),
|
||||
Action("u", "unbind a user from it…", lambda r, t, _: ["inbounds", "unbind", t.strip(), r["tag"]], when=ROW, prompt="<user>", offered=_inbounds_runtime),
|
||||
],
|
||||
),
|
||||
Tab(
|
||||
"inbound-users",
|
||||
"Users",
|
||||
_enabled("INBOUNDS_ENABLED"),
|
||||
[("name", "User"), ("order", "Order"), ("address", "Address"), ("source", "Source"), ("listeners", "Listeners"), ("problems", "Problems")],
|
||||
inbound_user_rows,
|
||||
summary=lambda: (
|
||||
"Runtime users get generated secrets; a change restarts the inbounds, which drops every connection once."
|
||||
if _inbounds_runtime()
|
||||
else "Users from the configuration. inbounds.runtime would let you add and bind them here."
|
||||
),
|
||||
actions=[
|
||||
Action("n", "add a user…", lambda r, t, _: _user_add_argv(t), prompt="<name> [order] [listener]... - e.g. alice 7 vless-in", offered=_inbounds_runtime),
|
||||
Action("d", "remove this user", lambda r, *_: ["inbounds", "users", "rm", r["name"]], when=_runtime_row, confirm=True, offered=_inbounds_runtime),
|
||||
Action("e", "set its order…", lambda r, t, _: ["inbounds", "users", "order", r["name"], t.strip()], when=_runtime_row, prompt="<order>", offered=_inbounds_runtime),
|
||||
Action("b", "bind it to a listener…", lambda r, t, _: ["inbounds", "bind", r["name"], t.strip()], when=ROW, prompt="<listener>", offered=_inbounds_runtime),
|
||||
Action("u", "unbind it from a listener…", lambda r, t, _: ["inbounds", "unbind", r["name"], t.strip()], when=ROW, prompt="<listener>", offered=_inbounds_runtime),
|
||||
Action("t", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"),
|
||||
],
|
||||
),
|
||||
Tab(
|
||||
|
||||
@@ -1157,6 +1157,103 @@ class OutboundTestTest(EnvTest):
|
||||
self.assertIn("proxy-suite group, or re-run with sudo", err)
|
||||
|
||||
|
||||
class InboundRuntimeTest(EnvTest):
|
||||
"""inbounds.runtime through proxy-ctl: the tool does the work, proxy-ctl reloads after."""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
tool = os.environ.get("INBOUNDS_RUNTIME_TOOL")
|
||||
if not tool:
|
||||
self.skipTest("INBOUNDS_RUNTIME_TOOL is not set")
|
||||
spool = self.path("inbounds.d")
|
||||
os.makedirs(spool)
|
||||
spec = {
|
||||
"serverAddress": "vpn.example.com",
|
||||
"shareLinks": True,
|
||||
"users": {"bob": {"order": 1, "uuid": "11111111-1111-4111-8111-111111111111"}, "idle": {"order": None}},
|
||||
"serverSource": {"ipv4": None, "ipv6": None, "declared": []},
|
||||
"listeners": [
|
||||
{"tag": "vless-in", "type": "vless", "port": 443, "order": 1000, "via": "proxy", "listen": "::",
|
||||
"users": [{"name": "bob", "uuid": "11111111-1111-4111-8111-111111111111"}]},
|
||||
],
|
||||
"runtime": {
|
||||
"spool": spool,
|
||||
"ports": ["20000-20010"],
|
||||
"vias": ["proxy", "block"],
|
||||
"defaultVia": "proxy",
|
||||
"fallbackDests": [],
|
||||
"tlsCertificates": {},
|
||||
"listenerDefaults": {
|
||||
"address": "::", "acceptProxyProtocol": False, "fallbacks": [], "flow": None, "order": 1000, "port": 443,
|
||||
"method": "2022-blake3-aes-128-gcm", "serverPassword": None, "sharePort": None, "shareAddress": None,
|
||||
"hysteria": {"masquerade": None, "salamander": {"enable": False, "password": None}},
|
||||
"reality": {"enable": False, "dest": "www.microsoft.com:443", "serverNames": [], "privateKey": None,
|
||||
"publicKey": None, "shortIds": [""], "xver": 0},
|
||||
"tls": {"enable": False, "alpn": None, "serverName": None},
|
||||
"transport": {"type": "raw", "path": "/", "host": None, "mode": None, "serviceName": "", "trustedXForwardedFor": []},
|
||||
},
|
||||
},
|
||||
}
|
||||
os.environ.update(
|
||||
INBOUNDS_ENABLED="1",
|
||||
INBOUNDS_RUNTIME_ENABLED="1",
|
||||
INBOUNDS_SPEC_FILE=self.write("spec.json", spec),
|
||||
)
|
||||
self.started = []
|
||||
|
||||
def systemctl(*args, **kw):
|
||||
self.started.append(args)
|
||||
return 0, ""
|
||||
|
||||
self.patch("systemctl", systemctl)
|
||||
|
||||
def test_users_and_listeners(self):
|
||||
out = ok(ctl.cmd_inbounds, "users", "add", "alice", "--listener", "vless-in")
|
||||
self.assertEqual(out, "Added user alice (order 2) on vless-in\n")
|
||||
self.assertEqual(self.started, [("start", "proxy-suite-inbounds-reload.service")])
|
||||
out = ok(ctl.cmd_inbounds, "add", "friends", "vless", "--port", "20001", "--user", "alice")
|
||||
self.assertIn("Added listener friends", out)
|
||||
rows = {r["name"]: r for r in json.loads(ok(ctl.cmd_inbounds, "users", "--json"))}
|
||||
self.assertEqual(rows["alice"]["listeners"], ["friends", "vless-in"])
|
||||
self.assertEqual(rows["bob"]["source"], "nix")
|
||||
self.assertEqual(ctl._inbound_runtime_names("listeners", "runtime"), {"friends": "runtime"})
|
||||
status, _, err = run(ctl.cmd_inbounds, "bind", "bob", "vless-in")
|
||||
self.assertEqual(status, 1)
|
||||
self.assertIn("declared in the configuration", err)
|
||||
# A refusal changes nothing, so nothing is reloaded.
|
||||
self.assertEqual(len(self.started), 2)
|
||||
ok(ctl.cmd_inbounds, "rm", "friends")
|
||||
self.assertIn("vless-in", ok(ctl.cmd_inbounds, "users"))
|
||||
|
||||
def test_bad_listener_is_refused(self):
|
||||
status, _, err = run(ctl.cmd_inbounds, "add", "far", "vless", "--port", "30000")
|
||||
self.assertEqual(status, 1)
|
||||
self.assertIn("not in inbounds.runtime.ports", err)
|
||||
self.assertEqual(self.started, [])
|
||||
|
||||
def test_off(self):
|
||||
os.environ["INBOUNDS_RUNTIME_ENABLED"] = "0"
|
||||
spec = ctl.read_json(os.environ["INBOUNDS_SPEC_FILE"])
|
||||
spec["runtime"] = None
|
||||
os.environ["INBOUNDS_SPEC_FILE"] = self.write("spec-off.json", spec)
|
||||
status, _, err = run(ctl.cmd_inbounds, "users", "add", "alice")
|
||||
self.assertEqual(status, 1)
|
||||
self.assertIn("inbounds.runtime.enable", err)
|
||||
# The declared users are still listed, on a listener or not.
|
||||
rows = {r["name"]: r for r in ctl._inbound_runtime_rows("users")}
|
||||
self.assertEqual(rows["bob"]["listeners"], ["vless-in"])
|
||||
self.assertEqual(rows["idle"]["listeners"], [])
|
||||
self.assertIn("idle", ok(ctl.cmd_inbounds, "users"))
|
||||
os.environ["INBOUNDS_ENABLED"] = "0"
|
||||
self.assertEqual(ctl._inbound_runtime_rows("users"), [])
|
||||
|
||||
def test_completion(self):
|
||||
ok(ctl.cmd_inbounds, "users", "add", "alice")
|
||||
self.assertIn("alice", ctl._complete_tree("inbounds", "users", "rm", ""))
|
||||
self.assertNotIn("bob", ctl._complete_tree("inbounds", "users", "rm", ""))
|
||||
self.assertIn("--reality", ctl._complete_tree("inbounds", "add", "x", "vless", ""))
|
||||
|
||||
|
||||
class ShareTest(EnvTest):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
|
||||
@@ -103,6 +103,37 @@ class ModelTest(unittest.TestCase):
|
||||
self.assertTrue(actions["k"].when(awg) and actions["K"].when(awg) and actions["J"].when(vless))
|
||||
self.assertFalse(actions["k"].when(vless) or actions["K"].when(vless) or actions["J"].when(awg))
|
||||
|
||||
def test_runtime_inbound_users_and_listeners(self):
|
||||
users = next(t for t in model.TABS if t.id == "inbound-users")
|
||||
inbounds = next(t for t in model.TABS if t.id == "inbounds")
|
||||
with mock.patch.dict(os.environ, {"INBOUNDS_ENABLED": "1", "INBOUNDS_RUNTIME_ENABLED": "0"}):
|
||||
# Listed from the configuration; nothing to change them with.
|
||||
self.assertTrue(users.available({}))
|
||||
self.assertEqual([a.key for a in users.actions if model.offered(a)], ["t"])
|
||||
self.assertNotIn("a", [a.key for a in inbounds.actions if model.offered(a)])
|
||||
with mock.patch.dict(os.environ, {"INBOUNDS_ENABLED": "0"}):
|
||||
self.assertFalse(users.available({}))
|
||||
with mock.patch.dict(os.environ, {"INBOUNDS_ENABLED": "1", "INBOUNDS_RUNTIME_ENABLED": "1"}):
|
||||
self.assertTrue(users.available({}))
|
||||
rows = [{"name": "bob", "source": "nix", "order": 1, "address": "10.78.0.1", "listeners": ["in"], "problems": []},
|
||||
{"name": "alice", "source": "runtime", "order": 4, "address": "", "listeners": [], "problems": ["no listeners"]}]
|
||||
with mock.patch.object(ctl, "_inbound_runtime_rows", lambda kind: rows):
|
||||
bob, alice = model.inbound_user_rows({})
|
||||
self.assertEqual((bob["listeners"], alice["problems"]), ("in", "no listeners"))
|
||||
actions = {a.key: a for a in users.actions}
|
||||
self.assertEqual(actions["n"].argv(None, "carol 7 in ws", {}),
|
||||
["inbounds", "users", "add", "carol", "--order", "7", "--listener", "in", "--listener", "ws"])
|
||||
self.assertEqual(actions["n"].argv(None, "carol", {}), ["inbounds", "users", "add", "carol"])
|
||||
self.assertEqual([a.key for a in model.applicable(users, bob)], ["n", "b", "u", "t"])
|
||||
self.assertEqual(actions["e"].argv(alice, " 9 ", {}), ["inbounds", "users", "order", "alice", "9"])
|
||||
self.assertEqual(actions["b"].argv(alice, "in", {}), ["inbounds", "bind", "alice", "in"])
|
||||
actions = {a.key: a for a in inbounds.actions}
|
||||
row = {"key": "friends/alice", "tag": "friends", "user": "alice", "type": "vless", "port": "20001", "source": "runtime"}
|
||||
self.assertEqual(actions["a"].argv(None, "friends vless --port 20001", {}), ["inbounds", "add", "friends", "vless", "--port", "20001"])
|
||||
self.assertEqual(actions["d"].argv(row), ["inbounds", "rm", "friends"])
|
||||
self.assertFalse(actions["d"].when({**row, "source": "nix"}))
|
||||
self.assertEqual(actions["b"].argv(row, "bob", {}), ["inbounds", "bind", "bob", "friends"])
|
||||
|
||||
def test_inbound_rows_carry_no_presence(self):
|
||||
"""XRay keys the online map by user, not by inbound, so a per-listener row
|
||||
could only repeat one verdict per listener; it must not claim to have one."""
|
||||
|
||||
@@ -21,6 +21,7 @@ import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import inbound_runtime
|
||||
from amneziawg_config import (
|
||||
ConfigError,
|
||||
_apply_awg3_mtu_default,
|
||||
@@ -359,9 +360,21 @@ def prepare(spec: dict, awg_binary: str, runtime_dir: str) -> list[dict]:
|
||||
"implementation": transport_implementation(config),
|
||||
}
|
||||
)
|
||||
# Who is on which interface now: inbound_runtime.py's check tells from it whether a
|
||||
# runtime change needs these interfaces restarted too.
|
||||
write_private(os.path.join(runtime_dir, "users.json"), json.dumps(awg_users(spec)) + "\n")
|
||||
return prepared
|
||||
|
||||
|
||||
def awg_users(spec: dict) -> dict[str, list[str]]:
|
||||
"""Each AmneziaWG listener's users, by tag."""
|
||||
return {
|
||||
listener["tag"]: sorted(user["name"] for user in listener["users"])
|
||||
for listener in spec["listeners"]
|
||||
if listener.get("type") == "amneziawg"
|
||||
}
|
||||
|
||||
|
||||
def peer_names(spec: dict) -> dict[str, dict]:
|
||||
"""By interface: the listener's tag and its users' names by public key."""
|
||||
result: dict[str, dict] = {}
|
||||
@@ -431,6 +444,8 @@ def main() -> int:
|
||||
with open(args.spec, encoding="utf-8") as handle:
|
||||
spec = json.load(handle)
|
||||
try:
|
||||
# Runtime users on AmneziaWG listeners are peers like the declared ones.
|
||||
spec, _, _ = inbound_runtime.merge(spec)
|
||||
if args.command == "prepare":
|
||||
# One line per listener, for the start script to read.
|
||||
for entry in prepare(spec, args.awg, args.runtime_dir):
|
||||
|
||||
@@ -5,6 +5,7 @@ import argparse
|
||||
import json
|
||||
import sys
|
||||
|
||||
import inbound_runtime
|
||||
from proxy_inbound import build_inbounds
|
||||
|
||||
|
||||
@@ -25,6 +26,11 @@ def main() -> None:
|
||||
dest="onion_address",
|
||||
help="the onion service's address, for a second set of links to its listeners",
|
||||
)
|
||||
ap.add_argument(
|
||||
"--template",
|
||||
help="the XRay config template: with inbounds.runtime, the result also carries its "
|
||||
"routing rules with the runtime listeners and users in",
|
||||
)
|
||||
args = ap.parse_args()
|
||||
|
||||
with open(args.spec, encoding="utf-8") as handle:
|
||||
@@ -36,7 +42,14 @@ def main() -> None:
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
spec, runtime, warnings = inbound_runtime.merge(spec, check_ports=True)
|
||||
for warning in warnings:
|
||||
print(f"proxy-suite: warning: {warning}", file=sys.stderr)
|
||||
result = build_inbounds(spec, server_address, args.onion_address)
|
||||
if args.template and spec.get("runtime"):
|
||||
with open(args.template, encoding="utf-8") as handle:
|
||||
template = json.load(handle)
|
||||
result.update(inbound_runtime.routing(spec, runtime, template["routing"]["rules"]))
|
||||
except (ValueError, OSError) as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,405 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import base64
|
||||
import contextlib
|
||||
import copy
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
import inbound_runtime as rt
|
||||
|
||||
# What config.nix renders as runtime.listenerDefaults: the option with nothing set.
|
||||
LISTENER_DEFAULTS = {
|
||||
"acceptProxyProtocol": False,
|
||||
"address": "::",
|
||||
"fallbacks": [],
|
||||
"flow": None,
|
||||
"hysteria": {"masquerade": None, "portHopping": None, "salamander": {"enable": False, "password": None, "passwordFile": None}},
|
||||
"method": "2022-blake3-aes-128-gcm",
|
||||
"order": 1000,
|
||||
"port": 443,
|
||||
"reality": {
|
||||
"dest": "www.microsoft.com:443",
|
||||
"enable": False,
|
||||
"privateKey": None,
|
||||
"privateKeyFile": None,
|
||||
"publicKey": None,
|
||||
"serverNames": [],
|
||||
"shortIds": [""],
|
||||
"xver": 0,
|
||||
},
|
||||
"serverPassword": None,
|
||||
"serverPasswordFile": None,
|
||||
"shareAddress": None,
|
||||
"sharePort": None,
|
||||
"tls": {"alpn": None, "certificateFile": None, "enable": False, "keyFile": None, "serverName": None},
|
||||
"transport": {"host": None, "mode": None, "path": "/", "serviceName": "", "trustedXForwardedFor": [], "type": "raw"},
|
||||
"type": None,
|
||||
"via": None,
|
||||
}
|
||||
|
||||
|
||||
def declared_user(name, **fields):
|
||||
user = {
|
||||
"name": name,
|
||||
"order": None,
|
||||
"uuid": None,
|
||||
"uuidFile": None,
|
||||
"password": None,
|
||||
"passwordFile": None,
|
||||
"publicKey": None,
|
||||
"privateKeyFile": None,
|
||||
"presharedKeyFile": None,
|
||||
"address": None,
|
||||
}
|
||||
user.update(fields)
|
||||
return user
|
||||
|
||||
|
||||
def declared_listener(tag, users, **fields):
|
||||
listener = copy.deepcopy(LISTENER_DEFAULTS)
|
||||
listener.pop("address")
|
||||
listener.update({"tag": tag, "type": "vless", "listen": "::", "via": "proxy", "users": users, "front": None,
|
||||
"xrayJson": None, "jsonFile": None, "salamanderStateFile": f"/tmp/{tag}"})
|
||||
listener.update(fields)
|
||||
return listener
|
||||
|
||||
|
||||
BOB = declared_user("bob", order=1, uuid="11111111-1111-4111-8111-111111111111")
|
||||
ANON = declared_user("anon", uuid="22222222-2222-4222-8222-222222222222")
|
||||
SS = declared_user("ss", password="c2VydmVyLWtleS0xNmJ5dGU=")
|
||||
|
||||
|
||||
def make_spec(spool, **runtime):
|
||||
spec = {
|
||||
"serverAddress": "vpn.example.com",
|
||||
"shareLinks": True,
|
||||
"users": {u["name"]: {k: v for k, v in u.items() if k != "name"} for u in (BOB, ANON, SS)},
|
||||
"serverSource": {"ipv4": "10.78.0.0/24", "ipv6": "fd78::/64",
|
||||
"declared": [{"name": "bob", "number": 1}, {"name": "anon", "number": 2}, {"name": "ss", "number": 3}]},
|
||||
"listeners": [
|
||||
declared_listener("vless-in", [BOB, ANON], order=1000),
|
||||
declared_listener("ss-in", [SS], type="shadowsocks", port=8388, method="aes-128-gcm"),
|
||||
declared_listener("awg", [], type="amneziawg", port=51820),
|
||||
],
|
||||
"runtime": {
|
||||
"spool": spool,
|
||||
"ports": [8443, "20000-20010"],
|
||||
"vias": ["proxy", "direct", "block"],
|
||||
"defaultVia": "proxy",
|
||||
"fallbackDests": ["127.0.0.1:8080"],
|
||||
"tlsCertificates": {"main": {"certificateFile": "/run/cert", "keyFile": "/run/key", "serverName": None}},
|
||||
"selfFinalRules": [{"action": "block", "ip": ["geoip:private"]}],
|
||||
"salamanderStateDir": "/tmp/salamander",
|
||||
"listenerDefaults": LISTENER_DEFAULTS,
|
||||
},
|
||||
}
|
||||
spec["runtime"].update(runtime)
|
||||
return spec
|
||||
|
||||
|
||||
class RuntimeTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.spool = os.path.join(self.tmp.name, "spool")
|
||||
os.makedirs(self.spool)
|
||||
self.spec = make_spec(self.spool)
|
||||
# `xray x25519` as XRay 26 prints it.
|
||||
self.xray = os.path.join(self.tmp.name, "xray")
|
||||
with open(self.xray, "w", encoding="utf-8") as f:
|
||||
f.write("#!/bin/sh\necho 'PrivateKey: private-x'\necho 'Password (PublicKey): public-x'\necho 'Hash32: h'\n")
|
||||
os.chmod(self.xray, 0o755)
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def state(self):
|
||||
return rt.load_spool(self.spool)[0]
|
||||
|
||||
def write(self, kind, name, entry):
|
||||
rt.write_entry(self.spool, kind, name, entry)
|
||||
|
||||
def add_listener(self, tag, **entry):
|
||||
return rt.cmd_add(self.spec, self.spool, tag, entry, self.xray)
|
||||
|
||||
# --- users -------------------------------------------------------------------
|
||||
|
||||
def test_user_orders_go_around_declared_numbers(self):
|
||||
rt.cmd_users_add(self.spec, self.spool, "alice", None, ["vless-in"])
|
||||
rt.cmd_users_add(self.spec, self.spool, "carol", 9, [])
|
||||
users = self.state()["users"]
|
||||
self.assertEqual(users["alice"]["order"], 4) # bob 1, anon 2, ss 3
|
||||
self.assertEqual(users["carol"]["order"], 9)
|
||||
self.assertRegex(users["alice"]["uuid"], r"^[0-9a-f-]{36}$")
|
||||
self.assertTrue(users["alice"]["password"])
|
||||
with self.assertRaisesRegex(rt.RuntimeError_, "declared user 'anon'"):
|
||||
rt.cmd_users_add(self.spec, self.spool, "dave", 2, [])
|
||||
with self.assertRaisesRegex(rt.RuntimeError_, "runtime user 'carol'"):
|
||||
rt.cmd_users_order(self.spec, self.spool, "alice", 9)
|
||||
with self.assertRaisesRegex(rt.RuntimeError_, "declared user"):
|
||||
rt.cmd_users_add(self.spec, self.spool, "bob", None, [])
|
||||
with self.assertRaisesRegex(rt.RuntimeError_, "Unknown listener"):
|
||||
rt.cmd_users_add(self.spec, self.spool, "erin", None, ["nope"])
|
||||
with self.assertRaisesRegex(rt.RuntimeError_, "Invalid user name"):
|
||||
rt.cmd_users_add(self.spec, self.spool, "a b", None, [])
|
||||
rt.cmd_users_order(self.spec, self.spool, "alice", 12)
|
||||
self.assertEqual(self.state()["users"]["alice"]["order"], 12)
|
||||
|
||||
def test_runtime_users_join_declared_listeners(self):
|
||||
rt.cmd_users_add(self.spec, self.spool, "alice", None, ["vless-in", "awg"])
|
||||
merged, result, warnings = rt.merge(self.spec)
|
||||
by_tag = {l["tag"]: l for l in merged["listeners"]}
|
||||
self.assertEqual([u["name"] for u in by_tag["vless-in"]["users"]], ["bob", "anon", "alice"])
|
||||
# An AmneziaWG listener takes it as a peer, its keys and address left to awg_inbound.py.
|
||||
self.assertEqual([u["name"] for u in by_tag["awg"]["users"]], ["alice"])
|
||||
self.assertIsNone(by_tag["awg"]["users"][0]["address"])
|
||||
self.assertEqual(result["users"], ["alice"])
|
||||
self.assertEqual(result["selfSources"][0]["ipv4"], "10.78.0.4")
|
||||
self.assertEqual(result["selfSources"][0]["ipv6"], "fd78::4")
|
||||
self.assertEqual(warnings, [])
|
||||
|
||||
def test_a_second_user_on_a_plain_shadowsocks_listener_is_refused(self):
|
||||
with self.assertRaisesRegex(rt.RuntimeError_, "2022-blake3-aes method"):
|
||||
rt.cmd_users_add(self.spec, self.spool, "alice", None, ["ss-in"])
|
||||
self.assertEqual(self.state()["users"], {})
|
||||
|
||||
def test_shadowsocks_2022_keys_fit_the_method(self):
|
||||
rt.cmd_users_add(self.spec, self.spool, "alice", None, [])
|
||||
self.add_listener("ss2", type="shadowsocks", port=20003, method="2022-blake3-aes-128-gcm", users=["alice"])
|
||||
entry = self.state()["listeners"]["ss2"]
|
||||
self.assertEqual(len(base64.b64decode(entry["serverPassword"])), 16)
|
||||
merged, _, _ = rt.merge(self.spec)
|
||||
alice = next(l for l in merged["listeners"] if l["tag"] == "ss2")["users"][0]
|
||||
self.assertEqual(len(base64.b64decode(alice["password"])), 16)
|
||||
self.assertNotEqual(alice["password"], self.state()["users"]["alice"]["password"])
|
||||
|
||||
def test_a_taken_order_moves_the_runtime_user_with_a_warning(self):
|
||||
# Written by hand, or the configuration gave the number to a declared user since.
|
||||
self.write("users", "zed", {"order": 1, "uuid": "33333333-3333-4333-8333-333333333333", "password": "p", "listeners": ["vless-in"]})
|
||||
_, result, warnings = rt.merge(self.spec)
|
||||
self.assertEqual(result["selfSources"][0]["number"], 4)
|
||||
self.assertTrue(any("order 1 is taken; using 4" in w for w in warnings))
|
||||
|
||||
def test_bind_writes_the_runtime_side(self):
|
||||
rt.cmd_users_add(self.spec, self.spool, "alice", None, [])
|
||||
self.add_listener("friends", type="vless", port=20001)
|
||||
rt.cmd_bind(self.spec, self.spool, "alice", "vless-in", True)
|
||||
rt.cmd_bind(self.spec, self.spool, "bob", "friends", True)
|
||||
state = self.state()
|
||||
self.assertEqual(state["users"]["alice"]["listeners"], ["vless-in"])
|
||||
self.assertEqual(state["listeners"]["friends"]["users"], ["bob"])
|
||||
with self.assertRaisesRegex(rt.RuntimeError_, "Both bob and vless-in are declared"):
|
||||
rt.cmd_bind(self.spec, self.spool, "bob", "vless-in", True)
|
||||
rt.cmd_bind(self.spec, self.spool, "bob", "friends", False)
|
||||
self.assertEqual(self.state()["listeners"]["friends"]["users"], [])
|
||||
with self.assertRaisesRegex(rt.RuntimeError_, "not bound"):
|
||||
rt.cmd_bind(self.spec, self.spool, "bob", "friends", False)
|
||||
# A declared user without the secret the protocol needs.
|
||||
self.add_listener("tro", type="trojan", port=20002, tls={"enable": True, "certificate": "main"})
|
||||
with self.assertRaisesRegex(rt.RuntimeError_, "no password"):
|
||||
rt.cmd_bind(self.spec, self.spool, "bob", "tro", True)
|
||||
|
||||
def test_removing_takes_the_bindings_along(self):
|
||||
rt.cmd_users_add(self.spec, self.spool, "alice", None, [])
|
||||
self.add_listener("friends", type="vless", port=20001, users=["alice", "bob"])
|
||||
rt.cmd_bind(self.spec, self.spool, "alice", "friends", True)
|
||||
rt.cmd_users_rm(self.spec, self.spool, "alice")
|
||||
self.assertEqual(self.state()["listeners"]["friends"]["users"], ["bob"])
|
||||
rt.cmd_users_add(self.spec, self.spool, "carol", None, ["friends", "vless-in"])
|
||||
rt.cmd_rm(self.spec, self.spool, "friends")
|
||||
self.assertEqual(self.state()["users"]["carol"]["listeners"], ["vless-in"])
|
||||
with self.assertRaisesRegex(rt.RuntimeError_, "declared in the configuration"):
|
||||
rt.cmd_rm(self.spec, self.spool, "vless-in")
|
||||
with self.assertRaisesRegex(rt.RuntimeError_, "declared in the configuration"):
|
||||
rt.cmd_users_rm(self.spec, self.spool, "bob")
|
||||
|
||||
# --- listeners ---------------------------------------------------------------
|
||||
|
||||
def test_reality_listener_gets_generated_keys(self):
|
||||
args = rt.main.__globals__["argparse"].Namespace(
|
||||
port=20001, listen=None, via=None, share_port=None, share_address=None, order=None, method=None,
|
||||
flow="vision", transport=None, path=None, host=None, mode=None, service_name=None, tls=None, alpn=None,
|
||||
sni=None, reality="www.example.com,example.com", reality_dest=None, short_id=None, masquerade=None,
|
||||
salamander=False, user=["bob"],
|
||||
)
|
||||
entry = rt.listener_from_flags("vless", args)
|
||||
self.assertEqual(entry["reality"]["dest"], "www.example.com:443")
|
||||
self.assertEqual(entry["flow"], "xtls-rprx-vision")
|
||||
rt.cmd_add(self.spec, self.spool, "friends", entry, self.xray)
|
||||
saved = self.state()["listeners"]["friends"]
|
||||
self.assertEqual((saved["reality"]["privateKey"], saved["reality"]["publicKey"]), ("private-x", "public-x"))
|
||||
self.assertRegex(saved["reality"]["shortIds"][0], r"^[0-9a-f]{8}$")
|
||||
merged, result, _ = rt.merge(self.spec)
|
||||
friends = next(l for l in merged["listeners"] if l["tag"] == "friends")
|
||||
self.assertEqual(friends["listen"], "::")
|
||||
self.assertEqual(friends["via"], "proxy")
|
||||
self.assertTrue(friends["runtime"])
|
||||
self.assertEqual(result["listeners"], ["friends"])
|
||||
|
||||
def test_fences(self):
|
||||
cases = [
|
||||
({"type": "vless", "port": 30000}, "not in inbounds.runtime.ports"),
|
||||
({"type": "vless", "port": 443}, "not in inbounds.runtime.ports"),
|
||||
({"type": "vless", "port": 20001, "via": "elsewhere"}, "via 'elsewhere'"),
|
||||
({"type": "trojan", "port": 20001}, "TLS needs tls.certificate"),
|
||||
({"type": "trojan", "port": 20001, "tls": {"enable": True, "certificate": "other"}}, "'other' is not in"),
|
||||
({"type": "vless", "port": 20001, "tls": {"certificateFile": "/etc/shadow"}}, "not something a runtime entry can set"),
|
||||
({"type": "vless", "port": 20001, "xrayJson": {}}, "not something a runtime entry can set"),
|
||||
({"type": "amneziawg", "port": 20001}, "type: invalid value"),
|
||||
({"type": "hysteria2", "port": 20001, "hysteria": {"portHopping": "1-2"}}, "not something"),
|
||||
({"type": "vless", "port": 20001, "fallbacks": [{"dest": 22}]}, "not in inbounds.runtime.fallbackDests"),
|
||||
({"type": "vless", "port": 20001, "fallbacks": [{"listener": "vless-in"}]}, "must be another runtime listener"),
|
||||
({"type": "vless", "port": 20001, "flow": "xtls-rprx-vision", "transport": {"type": "ws"}}, "flow is only valid"),
|
||||
({"type": "vmess", "port": 20001, "reality": {"enable": True, "serverNames": ["a.com"]}}, "reality only for vless"),
|
||||
]
|
||||
for entry, message in cases:
|
||||
with self.subTest(entry=entry), self.assertRaisesRegex(rt.RuntimeError_, message):
|
||||
self.add_listener("x", **entry)
|
||||
self.assertEqual(self.state()["listeners"], {})
|
||||
with self.assertRaisesRegex(rt.RuntimeError_, "declared in the configuration"):
|
||||
self.add_listener("vless-in", type="vless", port=20001)
|
||||
self.add_listener("a", type="vless", port=20001)
|
||||
with self.assertRaisesRegex(rt.RuntimeError_, "taken by another listener"):
|
||||
self.add_listener("b", type="vless", port=20001)
|
||||
|
||||
def test_fallback_to_a_runtime_listener(self):
|
||||
self.add_listener("ws", type="vless", port=20002, address="127.0.0.1", transport={"type": "ws", "path": "/ws"}, users=["bob"])
|
||||
self.add_listener("front", type="vless", port=8443, tls={"enable": True, "certificate": "main"},
|
||||
fallbacks=[{"path": "/ws", "listener": "ws"}, {"dest": "127.0.0.1:8080"}], users=["bob"])
|
||||
merged, _, warnings = rt.merge(self.spec)
|
||||
self.assertEqual(warnings, [])
|
||||
by_tag = {l["tag"]: l for l in merged["listeners"]}
|
||||
self.assertEqual(by_tag["front"]["fallbacks"][0], {"name": None, "alpn": None, "path": "/ws", "dest": "127.0.0.1:20002", "xver": 2})
|
||||
self.assertEqual(by_tag["ws"]["front"]["port"], 8443)
|
||||
self.assertEqual(by_tag["front"]["tls"]["certificateFile"], "/run/cert")
|
||||
with self.assertRaisesRegex(rt.RuntimeError_, "already the fallback listener"):
|
||||
self.add_listener("front2", type="vless", port=20003, fallbacks=[{"path": "/ws", "listener": "ws"}], users=["bob"])
|
||||
|
||||
def test_listener_without_users_waits(self):
|
||||
self.add_listener("empty", type="vless", port=20001)
|
||||
merged, result, warnings = rt.merge(self.spec)
|
||||
self.assertNotIn("empty", [l["tag"] for l in merged["listeners"]])
|
||||
self.assertTrue(any("'empty' has no users yet" in w for w in warnings))
|
||||
# AmneziaWG listeners run with no peers.
|
||||
self.assertIn("awg", [l["tag"] for l in merged["listeners"]])
|
||||
|
||||
# --- the spool ---------------------------------------------------------------
|
||||
|
||||
def test_bad_spool_entries_are_left_out(self):
|
||||
os.makedirs(os.path.join(self.spool, "users"))
|
||||
target = os.path.join(self.tmp.name, "secret.json")
|
||||
with open(target, "w", encoding="utf-8") as f:
|
||||
f.write(json.dumps({"order": 5, "uuid": "44444444-4444-4444-8444-444444444444", "password": "p", "listeners": []}))
|
||||
os.symlink(target, os.path.join(self.spool, "users", "link.json"))
|
||||
with open(os.path.join(self.spool, "users", "broken.json"), "w", encoding="utf-8") as f:
|
||||
f.write("{")
|
||||
os.mkfifo(os.path.join(self.spool, "users", "fifo.json"))
|
||||
self.write("users", "noorder", {"uuid": "44444444-4444-4444-8444-444444444444", "password": "p"})
|
||||
state, warnings = rt.load_spool(self.spool)
|
||||
self.assertEqual(sorted(state["users"]), ["noorder"])
|
||||
self.assertEqual(len(warnings), 3)
|
||||
_, result, more = rt.merge_state(self.spec, state)
|
||||
self.assertIn(("user", "noorder"), result["problems"])
|
||||
|
||||
def test_entries_are_group_readable_only(self):
|
||||
self.write("users", "alice", {"order": 5})
|
||||
mode = stat.S_IMODE(os.stat(os.path.join(self.spool, "users", "alice.json")).st_mode)
|
||||
self.assertEqual(mode & 0o027, 0)
|
||||
|
||||
# --- routing -----------------------------------------------------------------
|
||||
|
||||
def test_expand_rules(self):
|
||||
exception = {"notVia": ["block"]}
|
||||
rules = [
|
||||
{"ruleTag": "inbound-block-private", "ip": ["geoip:private"], "outboundTag": "block"},
|
||||
{"ruleTag": "inbound-server-address-self-ip4-1", "user": ["bob"], "inboundTag": ["vless-in"], "_members": exception},
|
||||
{"_anchor": "selfIp", "inboundTag": ["vless-in"], "port": "443,20000-20010", "ip4": ["203.0.113.10"], "ip6": [], "_members": exception},
|
||||
{"ruleTag": "inbound-server-address-sniffed-direct", "inboundTag": [], "_members": {"via": ["direct"]}},
|
||||
{"ruleTag": "inbound-server-address-sniffed-proxy", "inboundTag": ["vless-in"], "_members": {"via": ["proxy"]}},
|
||||
{"_anchor": "selfName", "inboundTag": ["vless-in"], "port": "443", "domain": ["full:vpn.example.com"], "_members": exception},
|
||||
{"ruleTag": "inbound-final", "outboundTag": "proxy"},
|
||||
]
|
||||
listeners = [{"tag": "friends", "via": "proxy"}, {"tag": "out", "via": "direct"}, {"tag": "shut", "via": "block"}]
|
||||
sources = [{"email": "alice", "number": 4, "id": "4", "ipv4": "10.78.0.4", "ipv6": None}]
|
||||
expanded = rt.expand_rules(rules, listeners, sources, "proxy")
|
||||
tags = [r.get("ruleTag") for r in expanded]
|
||||
self.assertEqual(tags, [
|
||||
"inbound-block-private",
|
||||
"inbound-server-address-self-ip4-1",
|
||||
"inbound-server-address-self-ip4-4",
|
||||
"inbound-server-address-sniffed-direct",
|
||||
"inbound-server-address-sniffed-proxy",
|
||||
"inbound-server-address-self-4",
|
||||
"inbound-via-out",
|
||||
"inbound-via-shut",
|
||||
"inbound-final",
|
||||
])
|
||||
by_tag = {r.get("ruleTag"): r for r in expanded}
|
||||
self.assertEqual(by_tag["inbound-server-address-self-ip4-4"]["inboundTag"], ["vless-in", "friends", "out"])
|
||||
self.assertEqual(by_tag["inbound-server-address-self-ip4-4"]["outboundTag"], "direct-self4-4")
|
||||
self.assertEqual(by_tag["inbound-server-address-self-ip4-4"]["user"], ["alice"])
|
||||
self.assertEqual(by_tag["inbound-server-address-sniffed-direct"]["inboundTag"], ["out"])
|
||||
self.assertEqual(by_tag["inbound-server-address-self-4"]["domain"], ["full:vpn.example.com"])
|
||||
self.assertFalse(any("_members" in r or "_anchor" in r for r in expanded))
|
||||
# Nobody on direct: its guard goes.
|
||||
again = rt.expand_rules(rules, listeners[:1], [], "proxy")
|
||||
self.assertNotIn("inbound-server-address-sniffed-direct", [r.get("ruleTag") for r in again])
|
||||
|
||||
def test_self_outbounds(self):
|
||||
outbounds = rt.self_outbounds([{"email": "a", "number": 4, "id": "4", "ipv4": "10.78.0.4", "ipv6": "fd78::4"}], [{"action": "block"}])
|
||||
self.assertEqual([o["tag"] for o in outbounds], ["direct-self4-4", "direct-self6-4"])
|
||||
self.assertEqual(outbounds[1]["settings"]["domainStrategy"], "UseIPv6")
|
||||
|
||||
# --- the command line --------------------------------------------------------
|
||||
|
||||
def run_main(self, *argv, stdin=None):
|
||||
spec_path = os.path.join(self.tmp.name, "spec.json")
|
||||
with open(spec_path, "w", encoding="utf-8") as f:
|
||||
json.dump(self.spec, f)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
status = rt.main(["--spec", spec_path, "--xray", self.xray, *argv])
|
||||
return status, out.getvalue(), err.getvalue()
|
||||
|
||||
def test_main(self):
|
||||
status, out, _ = self.run_main("users", "add", "alice", "--listener", "vless-in")
|
||||
self.assertEqual((status, out), (0, "Added user alice (order 4) on vless-in\n"))
|
||||
status, out, _ = self.run_main("add", "hy", "hysteria2", "--port", "20005", "--tls", "main", "--salamander", "--user", "alice")
|
||||
self.assertEqual(status, 0, out)
|
||||
status, out, _ = self.run_main("users", "--json")
|
||||
rows = {r["name"]: r for r in json.loads(out)}
|
||||
self.assertEqual(rows["alice"]["listeners"], ["hy", "vless-in"]) # in listing order
|
||||
self.assertEqual(rows["alice"]["address"], "10.78.0.4")
|
||||
self.assertEqual(rows["anon"]["order"], 2)
|
||||
status, _, err = self.run_main("users", "add", "alice")
|
||||
self.assertEqual(status, 1)
|
||||
self.assertIn("already exists", err)
|
||||
status, out, _ = self.run_main("show", "hy")
|
||||
self.assertTrue(json.loads(out)["hysteria"]["salamander"]["enable"])
|
||||
|
||||
def test_check_names_the_awg_unit_when_its_peers_change(self):
|
||||
users = os.path.join(self.tmp.name, "users.json")
|
||||
with open(users, "w", encoding="utf-8") as f:
|
||||
json.dump({"awg": []}, f)
|
||||
self.assertEqual(self.run_main("check", "--awg-users", users)[1], "")
|
||||
rt.cmd_users_add(self.spec, self.spool, "alice", None, ["awg"])
|
||||
self.assertEqual(self.run_main("check", "--awg-users", users)[1], "proxy-suite-inbounds-awg.service\n")
|
||||
|
||||
def test_no_write_access(self):
|
||||
os.chmod(self.spool, 0o500)
|
||||
try:
|
||||
if os.access(self.spool, os.W_OK):
|
||||
self.skipTest("running as root")
|
||||
status, _, err = self.run_main("users", "add", "alice")
|
||||
self.assertEqual(status, 77)
|
||||
self.assertIn("Cannot write", err)
|
||||
finally:
|
||||
os.chmod(self.spool, 0o700)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user