feat/wip/fix: add inbounds support, fix ssh-proxy

This commit is contained in:
fufsob committed 2026-09-09 16:38:52 +00:00
1 parent ea7916dffb
commit 2a319d1f88
39 files changed
+5093 -48

No files matched your search

@@ -0,0 +1,71 @@
# Build-time XRay configuration template for the server-side inbound service.
# Inbounds and proxy outbounds are both injected at service start time, so no
# credential reaches the Nix store.
{
lib,
derived,
inboundRules,
mkDnsServer,
}:
let
inherit (derived) proxyCfg proxyInboundsCfg proxyInboundsNeedLocalProxy;
# Relaying goes through the client stack's SOCKS listener rather than a second
# copy of the outbound machinery, so the inbound service always follows the
# currently selected outbound. Connect over loopback when the listener is on a
# wildcard address.
localProxyAddress =
if builtins.elem proxyCfg.listenAddress [
"0.0.0.0"
"::"
""
] then
"127.0.0.1"
else
proxyCfg.listenAddress;
# Credentials, when the local proxy has them, are injected at start time.
localProxyOutbound = lib.optional proxyInboundsNeedLocalProxy {
protocol = "socks";
tag = "proxy";
settings = {
servers = [
{
address = localProxyAddress;
port = proxyCfg.port;
}
];
};
};
in
{
log.loglevel = "warning";
dns.servers = [
(mkDnsServer "remote" proxyCfg.dns.remote)
(mkDnsServer "local" proxyCfg.dns.local)
];
# Filled in at start time from the listener spec.
inbounds = [ ];
outbounds = localProxyOutbound ++ [
{
protocol = "freedom";
tag = "direct";
settings = { };
}
{
protocol = "blackhole";
tag = "block";
settings = { };
}
];
routing = {
domainStrategy = "IPIfNonMatch";
domainMatcher = "hybrid";
rules = inboundRules.xrayInboundRules;
};
}
@@ -256,6 +256,10 @@ let
// lib.optionalAttrs enableTunFakeDns { fakedns = fakeDnsPools; };
in
{
# Reused by the server-side inbound template, which builds a different config
# shape out of the same backend primitives.
inherit mkDnsServer;
tproxy = mkConfig {
enableMixed = true;
enableTProxy = true;
+43
View File
@@ -24,6 +24,41 @@ let
;
};
inboundRules = import ./rules/proxy-inbounds.nix {
inherit lib;
inherit (derived) proxyInboundsCfg proxyInbounds;
inherit (rules) zapretDirectRules;
};
proxyInboundsTemplate = import ./config-templates/proxy-inbounds.nix {
inherit lib derived inboundRules;
inherit (xrayTemplates) mkDnsServer;
};
# Listener specification handed to build-inbound.py at service start. Secrets
# appear here only as paths; the script reads them at runtime.
proxyInboundsSpec = {
serverAddress = derived.proxyInboundsCfg.serverAddress;
shareLinks = derived.proxyInboundsCfg.shareLinks;
listeners = map (ib: {
inherit (ib) tag;
inherit (ib.listener)
type
port
sharePort
users
flow
method
transport
tls
reality
xrayJson
jsonFile
;
listen = ib.listener.listenAddress;
}) derived.proxyInbounds;
};
selectedTemplates = if derived.pureXrayEnabled then xrayTemplates else singBoxTemplates;
routeModeRules =
if derived.pureXrayEnabled then rules.xrayRouteModeRules else rules.singBoxRouteModeRules;
@@ -40,6 +75,12 @@ let
routeModeRulesFile = pkgs.writeText "proxy-suite-route-mode-rules.json" (
builtins.toJSON routeModeRules
);
proxyInboundsFile = pkgs.writeText "proxy-suite-inbounds-template.json" (
builtins.toJSON proxyInboundsTemplate
);
proxyInboundsSpecFile = pkgs.writeText "proxy-suite-inbounds-spec.json" (
builtins.toJSON proxyInboundsSpec
);
in
{
inherit
@@ -47,5 +88,7 @@ in
tunFile
perAppTunFile
routeModeRulesFile
proxyInboundsFile
proxyInboundsSpecFile
;
}
+6 -1
View File
@@ -13,6 +13,7 @@ let
cfg = config.services.proxy-suite;
packages = import ../../pkgs/default.nix { inherit pkgs; };
nftr = import ./nftables.nix { inherit lib pkgs cfg; };
derived = import ./derived.nix { inherit lib cfg; };
in
{
imports = [
@@ -52,6 +53,8 @@ in
tunFile
perAppTunFile
routeModeRulesFile
proxyInboundsFile
proxyInboundsSpecFile
;
inherit (nftr)
nftablesRulesFile
@@ -86,7 +89,9 @@ in
}
))
(lib.mkIf cfg.sshProxy.enable (
# SingBox dials SSH natively, so it needs no OpenSSH unit. XRay has no SSH
# outbound, and a standalone tunnel has no backend at all, so both keep it.
(lib.mkIf derived.sshProxyUnitEnabled (
import ./ssh-proxy.nix {
inherit
lib
+70
View File
@@ -39,6 +39,61 @@ let
sshProxyCfg = cfg.sshProxy;
sshProxyOutboundTag = "ssh-proxy";
sshProxyOutboundEnabled = sshProxyCfg.enable && sshProxyCfg.asOutbound;
# Only sing-box has a native `ssh` outbound. XRay has none, so it keeps the
# OpenSSH `ssh -D` unit and its local SOCKS listener -- as does a standalone
# tunnel that is not wired in as an outbound at all.
sshProxyNativeOutbound = sshProxyOutboundEnabled && !pureXrayEnabled;
sshProxyUnitEnabled = sshProxyCfg.enable && !sshProxyNativeOutbound;
proxyInboundsCfg = cfg.proxyInbounds;
proxyInboundsEnabled = proxyInboundsCfg.enable;
# Listener attrset flattened to a list with `via` resolved against the
# tree-wide default. Everything downstream (rules, spec, firewall) uses this.
proxyInbounds = lib.mapAttrsToList (tag: listener: {
inherit tag listener;
via = if listener.via == null then proxyInboundsCfg.via else listener.via;
}) proxyInboundsCfg.listeners;
# "direct" and "block" are self-contained; "proxy" chains through the client
# stack's local SOCKS listener, so it needs the client side to be running.
proxyInboundsNeedLocalProxy = lib.any (ib: ib.via == "proxy") proxyInbounds;
# Any other via names a static outbound, which is rendered into the inbound
# service's own config so it stays pinned regardless of the client's
# selection. Only referenced outbounds are built, so an unused (or
# sing-box-only) one never has to be XRay-representable.
proxyInboundViaTags = lib.unique (
builtins.filter (via: !builtins.elem via builtinTags) (map (ib: ib.via) proxyInbounds)
);
proxyInboundViaOutbounds = builtins.filter (
ob: builtins.elem ob.tag proxyInboundViaTags
) proxyCfg.outbounds;
proxyInboundUdpTypes = [
"shadowsocks"
"socks"
];
proxyInboundPorts = lib.unique (map (ib: ib.listener.port) proxyInbounds);
# A loopback-bound listener is reached through something else on this host (an
# nginx vhost, say), so opening its port would expose the endpoint that
# arrangement exists to hide.
proxyInboundsPublic = builtins.filter (
ib:
!builtins.elem ib.listener.listenAddress [
"127.0.0.1"
"::1"
]
) proxyInbounds;
proxyInboundFirewallPorts = lib.unique (map (ib: ib.listener.port) proxyInboundsPublic);
# A raw-JSON listener could serve anything, so open both protocols for it.
proxyInboundFirewallUdpPorts = lib.unique (
map (ib: ib.listener.port) (
builtins.filter (
ib: ib.listener.type == null || builtins.elem ib.listener.type proxyInboundUdpTypes
) proxyInboundsPublic
)
);
selectionMode = proxyCfg.selection;
builtinTags = [
@@ -81,6 +136,9 @@ let
};
};
# Subscription tags are deliberately not accepted: they only exist at runtime.
invalidInboundViaTargets = builtins.filter (tag: !builtins.elem tag outboundTags) proxyInboundViaTags;
invalidRoutingTargets = lib.unique (
map (rule: rule.outbound) (
builtins.filter (
@@ -113,6 +171,18 @@ in
sshProxyCfg
sshProxyOutboundTag
sshProxyOutboundEnabled
sshProxyNativeOutbound
sshProxyUnitEnabled
proxyInboundsCfg
proxyInboundsEnabled
proxyInbounds
proxyInboundsNeedLocalProxy
proxyInboundViaTags
proxyInboundViaOutbounds
invalidInboundViaTargets
proxyInboundPorts
proxyInboundFirewallPorts
proxyInboundFirewallUdpPorts
constants
selectionMode
builtinTags
+1
View File
@@ -4,6 +4,7 @@
imports = [
./other.nix
./ssh-proxy.nix
./proxy-inbounds.nix
./amnezia-wg.nix
./legacy-sing-box.nix
./sing-box.nix
@@ -0,0 +1,172 @@
# Server-side proxy inbound options.
{ lib, pkgs, ... }:
let
inherit (lib)
literalExpression
mkEnableOption
mkOption
types
;
inboundTypes = import ./types/proxy-inbounds.nix { inherit lib; };
in
{
options.services.proxy-suite.proxyInbounds = {
enable = mkEnableOption "server-side proxy inbounds (accept connections from outside)";
package = mkOption {
type = types.package;
default = pkgs.xray;
defaultText = literalExpression "pkgs.xray";
example = literalExpression "pkgs.xray";
description = ''
XRay package serving the inbounds.
This is independent of proxy.xray.package: the inbound service always
runs XRay, whichever backend the client side uses, and works with
proxy.enable = false.
'';
};
serverAddress = mkOption {
type = types.nullOr (types.strMatching "[^[:space:]]+");
default = null;
description = ''
Public hostname or address clients connect to. Used for generated share
links only; it does not affect what the listeners bind.
Leave null to detect the machine's uplink IPv4 address at service start
time. Set it explicitly when the server is behind NAT or reached by a
domain name.
'';
example = "vpn.example.com";
};
openFirewall = mkOption {
type = types.bool;
default = true;
description = ''
Add every listener port to networking.firewall. Disable to manage the
firewall yourself.
'';
example = false;
};
shareLinks = mkOption {
type = types.bool;
default = true;
description = ''
Write client share links to /run/proxy-suite-inbounds/links.json at
service start, for `proxy-ctl inbounds link` and
`proxy-ctl inbounds qr`.
The file is readable by root and the userControl group only, because
the links carry the listener credentials.
'';
example = false;
};
via = mkOption {
type = types.str;
default = "proxy";
description = ''
Default egress for traffic arriving on the inbounds. Individual
listeners can override it with their own via option, which is how two
listeners can leave through two different servers.
- "proxy": chain out through the local proxy stack, so the machine
relays rather than exits. Requires proxy.enable. The inbound service
hands traffic to the SOCKS listener on proxy.listenAddress, so it
follows whatever the client side is currently doing: the selected
outbound, subscriptions, urltest, and `proxy-ctl select` all apply,
with no second copy of that machinery.
- A proxy.outbounds tag: pin this traffic to that specific server,
independently of what the client side has selected. The outbound is
built into the inbound service's own config, so it must be one XRay
can represent (a url/urlFile entry, or xrayJson). Subscription
proxies cannot be named here, because their tags only exist at
runtime; use "proxy" to reach those.
- "direct": leave from this machine, making it a plain exit node. Needs
no client-side proxy configuration at all.
- "block": drop the traffic.
'';
example = "direct";
};
zapretDirect = mkOption {
type = types.bool;
default = true;
description = ''
Route zapret's hostlist domains and IPs to the direct outbound instead
of through the proxy, so this host's own zapret unblocks them for
inbound clients.
Has no effect unless zapret.enable and zapret.syncDirectRouting are on:
the rules are built from the same hostlists that already feed
routing.direct on the client side, so they are empty when zapret is not
running here.
On by default because a zapret host is by definition inside the filtered
network, and paying for a proxy hop to reach something zapret already
unblocks locally is pure latency. Only applies to listeners using the
default via; an explicit per-listener via still wins.
'';
example = false;
};
blockRu = mkOption {
type = types.bool;
default = true;
description = ''
Send traffic destined for Russian domains and IP ranges
("category-ru" geosite, "ru" geoip) to the block outbound.
On by default: a relay whose whole point is leaving the RKN-filtered
network has no reason to carry traffic back into it, and it keeps the
server out of the way of domestic services that geo-check.
'';
example = false;
};
blockPrivate = mkOption {
type = types.bool;
default = true;
description = ''
Send traffic destined for private and loopback addresses to the block
outbound.
On by default: without it, anyone holding an inbound credential can
reach the server's LAN, its localhost services, and the local proxy
ports of proxy-suite itself.
'';
example = false;
};
listeners = mkOption {
type = types.attrsOf inboundTypes.inboundType;
default = { };
description = ''
Named inbound listeners. The attribute name becomes the inbound tag
used in routing rules and in `proxy-ctl inbounds`.
'';
example = literalExpression ''
{
vless-reality = {
type = "vless";
port = 443;
users = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ];
flow = "xtls-rprx-vision";
reality = {
enable = true;
dest = "www.microsoft.com:443";
serverNames = [ "www.microsoft.com" ];
privateKeyFile = "/run/secrets/proxy-inbound-reality-key";
publicKey = "jNXH...";
shortIds = [ "0123abcd" ];
};
};
}
'';
};
};
}
+106 -5
View File
@@ -23,6 +23,9 @@ in
description = ''
Unix user for the systemd SSH proxy service. Leave unset to use
systemd's default user.
OpenSSH path only: ignored when a SingBox or hybrid backend dials SSH
natively and no separate unit is created.
'';
example = "proxy";
};
@@ -46,14 +49,24 @@ in
listenAddress = mkOption {
type = types.strMatching "[^[:space:]]+";
default = "127.0.0.1";
description = "Local address for the SSH-created SOCKS5 listener.";
description = ''
Local address for the SSH-created SOCKS5 listener.
OpenSSH path only: a SingBox or hybrid backend dials SSH natively and
creates no local listener.
'';
example = "127.0.0.1";
};
listenPort = mkOption {
type = types.port;
default = 1091;
description = "Local port for the SSH-created SOCKS5 listener.";
description = ''
Local port for the SSH-created SOCKS5 listener.
OpenSSH path only: a SingBox or hybrid backend dials SSH natively and
creates no local listener.
'';
example = 1091;
};
@@ -72,10 +85,85 @@ in
default = null;
description = ''
Optional runtime path to the known-hosts file passed to OpenSSH.
OpenSSH path only. A SingBox or hybrid backend verifies host keys with
sshProxy.hostKey instead.
'';
example = "/run/secrets/proxy-suite-ssh-known-hosts";
};
hostKey = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Accepted SSH host public keys, in `authorized_keys` one-line form.
Used by the sing-box backend, which verifies host keys by value rather
than against a known-hosts file.
List **every** key the server offers, not just one. The host key
algorithm is negotiated, so pinning a single key fails the handshake
outright whenever the server picks a different algorithm. Get the full
set with `ssh-keyscan -p PORT HOST`, or from an existing known-hosts
entry with `ssh-keygen -F '[HOST]:PORT'`.
Leaving this empty accepts **any** host key, which allows a
machine-in-the-middle on the tunnel. Set it whenever sshProxy.asOutbound
is used with a SingBox or hybrid backend.
Ignored by the XRay backend and by a standalone tunnel, which use
knownHostsFile and strictHostKeyChecking instead.
'';
example = [ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI..." ];
};
hostKeyFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a known-hosts file to read the accepted host keys from,
instead of listing them inline in sshProxy.hostKey. Every key recorded
there for `host:sshPort` is accepted, so a single known-hosts file stays
the one source of truth. Hashed known-hosts files work.
Read when the service starts, not at evaluation time, so the file never
enters the Nix store. Set either this or sshProxy.hostKey; if both are
set the file wins.
Used by the sing-box backend. The XRay backend and a standalone tunnel
pass knownHostsFile to OpenSSH instead.
'';
example = "/root/.ssh/known_hosts";
};
domainStrategy = mkOption {
type = types.nullOr (
types.enum [
"prefer_ipv4"
"prefer_ipv6"
"ipv4_only"
"ipv6_only"
]
);
default = null;
description = ''
Resolve destination domains locally before sending them through the
SSH SOCKS5 proxy, so the remote SSH server never has to resolve them.
Null preserves the backend's default behavior.
Only applies to the XRay backend, which reaches the tunnel through the
local SOCKS5 listener and maps this onto the outbound's
`sockopt.domainStrategy`. SingBox and hybrid backends dial SSH natively
and resolve destinations themselves, so this option is ignored there.
Note that local resolution hands the remote server an address chosen by
*this* machine's DNS. For anycast or geo-steered CDNs that address can
be unreachable from the remote network, which surfaces as connection
timeouts rather than as a DNS error. Prefer fixing DNS on the remote
server if you have access to it.
'';
example = "prefer_ipv4";
};
strictHostKeyChecking = mkOption {
type = types.enum [
"yes"
@@ -86,6 +174,9 @@ in
description = ''
OpenSSH host-key verification policy. Use "yes" with pinned
knownHostsFile contents for strict verification.
OpenSSH path only. A SingBox or hybrid backend verifies host keys with
sshProxy.hostKey instead.
'';
example = "yes";
};
@@ -96,6 +187,10 @@ in
description = ''
Additional arguments passed to OpenSSH before the destination.
This can be used for options such as jump hosts or agent forwarding.
OpenSSH path only: ignored when a SingBox or hybrid backend dials SSH
natively. Keepalive, connect-timeout and restart behavior are already
set by the module, so they do not need to be repeated here.
'';
example = [
"-o"
@@ -107,9 +202,15 @@ in
type = types.bool;
default = false;
description = ''
Add the local SSH SOCKS5 listener as a proxy-suite outbound tagged
"ssh-proxy". Requires proxy.enable and an active SingBox or XRay
backend.
Add the SSH tunnel as a proxy-suite outbound tagged "ssh-proxy".
Requires proxy.enable and an active SingBox or XRay backend.
How the tunnel is built depends on the backend. SingBox and hybrid
backends dial SSH natively, with no systemd unit and no local SOCKS5
listener. XRay has no SSH outbound, so it keeps the OpenSSH `ssh -D`
unit and proxies through its local SOCKS5 listener. With
asOutbound = false the OpenSSH unit is always used, since the tunnel is
then a standalone listener the backends know nothing about.
'';
example = true;
};
@@ -0,0 +1,432 @@
# Server-side inbound listener option type definitions.
{ lib }:
let
inherit (lib) mkOption types;
userType = types.submodule {
options = {
name = mkOption {
type = types.str;
default = "";
description = ''
Optional label for this account. Used as the share-link fragment so
clients show a readable server name, and as the XRay user email.
'';
example = "phone";
};
uuid = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Literal UUID for vless/vmess accounts.
This value is embedded in the Nix store. Prefer uuidFile for real
credentials.
Set exactly one of uuid or uuidFile for vless and vmess listeners.
'';
example = "b831381d-6324-4d53-ad4f-8cda48b30811";
};
uuidFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing the account UUID.
Intended for use with secret managers (sops-nix, agenix, etc.).
The file is read at service start time and never lands in the Nix store.
'';
example = "/run/secrets/proxy-inbound-uuid";
};
password = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Literal password for trojan, shadowsocks, socks, and http listeners.
This value is embedded in the Nix store. Prefer passwordFile for real
credentials.
'';
example = "hunter2";
};
passwordFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing the account password.
The file is read at service start time and never lands in the Nix store.
'';
example = "/run/secrets/proxy-inbound-password";
};
};
};
transportType = types.submodule {
options = {
type = mkOption {
type = types.enum [
"raw"
"ws"
"grpc"
"httpupgrade"
"xhttp"
];
default = "raw";
description = ''
Stream transport for this listener. "raw" is plain TCP and is what
REALITY setups normally use.
'';
example = "ws";
};
path = mkOption {
type = types.str;
default = "/";
description = ''
Request path for the "ws", "httpupgrade", and "xhttp" transports.
Ignored by the other transports.
'';
example = "/download";
};
host = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Expected Host header for the "ws", "httpupgrade", and "xhttp"
transports. Leave null to accept any host.
'';
example = "cdn.example.com";
};
mode = mkOption {
type = types.nullOr (
types.enum [
"auto"
"packet-up"
"stream-up"
"stream-one"
]
);
default = null;
description = ''
Transfer mode for the "xhttp" transport. Ignored by the others.
Leave null for XRay's own default, which lets the client choose.
Behind an HTTP/1.1 reverse proxy, "packet-up" is the mode that works:
"stream-one" needs a full-duplex HTTP/2 path from the client all the
way to the listener, which a proxy speaking HTTP/1.1 upstream cannot
provide.
'';
example = "packet-up";
};
serviceName = mkOption {
type = types.str;
default = "";
description = ''
gRPC service name for the "grpc" transport. Ignored otherwise.
'';
example = "GunService";
};
};
};
tlsType = types.submodule {
options = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
Terminate TLS on this listener. Mutually exclusive with reality.
Always on for trojan listeners regardless of this setting.
'';
example = true;
};
certificateFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to the PEM certificate chain. Compose with
security.acme to keep it renewed.
'';
example = "/var/lib/acme/example.com/fullchain.pem";
};
keyFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to the PEM private key matching certificateFile.
'';
example = "/var/lib/acme/example.com/key.pem";
};
serverName = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
SNI advertised in generated share links. Defaults to
proxyInbounds.serverAddress when unset.
'';
example = "example.com";
};
};
};
realityType = types.submodule {
options = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
Enable REALITY on this listener. Mutually exclusive with tls.enable.
'';
example = true;
};
dest = mkOption {
type = types.str;
default = "www.microsoft.com:443";
description = ''
Real TLS server that unauthenticated probes are proxied to. Must be a
host:port that serves TLS 1.3 with HTTP/2.
'';
example = "www.microsoft.com:443";
};
serverNames = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
SNI values accepted by this listener. These must be names the dest
server actually serves. The first entry is used in share links.
'';
example = [ "www.microsoft.com" ];
};
privateKeyFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to the REALITY x25519 private key, as produced by
`xray x25519`. Read at service start time; never lands in the Nix
store.
'';
example = "/run/secrets/proxy-inbound-reality-key";
};
privateKey = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Literal REALITY x25519 private key.
This value is embedded in the Nix store. Prefer privateKeyFile.
'';
example = "gG1Yz...";
};
publicKey = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
REALITY x25519 public key matching privateKeyFile, as printed
alongside it by `xray x25519`. Not a secret: clients need it, and it
is what generated share links carry as `pbk`.
Required when proxyInbounds.shareLinks is enabled.
'';
example = "jNXH...";
};
shortIds = mkOption {
type = types.listOf types.str;
default = [ "" ];
description = ''
Accepted REALITY short IDs (hex, up to 16 characters). The default
accepts the empty short ID. The first entry is used in share links.
'';
example = [ "0123abcd" ];
};
};
};
inboundType = types.submodule {
options = {
type = mkOption {
type = types.nullOr (types.enum [
"vless"
"vmess"
"trojan"
"shadowsocks"
"socks"
"http"
]);
default = null;
description = ''
Proxy protocol served by this listener.
Set exactly one of type, xrayJson, or jsonFile for each listener.
'';
example = "vless";
};
port = mkOption {
type = types.port;
default = 443;
description = ''
Port this listener binds. Opened in the firewall automatically unless
proxyInbounds.openFirewall is disabled.
'';
example = 443;
};
sharePort = mkOption {
type = types.nullOr types.port;
default = null;
description = ''
Port generated share links advertise, for when clients do not reach
this listener on the port it binds. Set it when something in front of
it owns the public port: an nginx vhost proxying to a loopback bind,
a container port mapping, a DNAT rule.
Leave null to advertise port.
'';
example = 443;
};
listenAddress = mkOption {
type = types.strMatching "[^[:space:]]+";
default = "::";
description = ''
Address this listener binds. The default accepts both IPv4 and IPv6
connections from anywhere.
'';
example = "0.0.0.0";
};
via = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Egress for traffic arriving on this listener: "proxy" (out through
the local proxy stack, following its current selection), a
proxy.outbounds tag (pinned to that specific server), "direct" (out
from this machine), or "block".
Give two listeners two different tags to have them leave through two
different servers.
Leave null to inherit proxyInbounds.via.
'';
example = "nl-vps";
};
users = mkOption {
type = types.listOf userType;
default = [ ];
description = ''
Accounts accepted by this listener. vless and vmess use uuid/uuidFile;
trojan, shadowsocks, socks, and http use password/passwordFile.
A share link is generated for the first user of each listener.
'';
example = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ];
};
flow = mkOption {
type = types.nullOr (types.enum [ "xtls-rprx-vision" ]);
default = null;
description = ''
VLESS flow control. "xtls-rprx-vision" is the usual pairing with
REALITY on the "raw" transport; it is not valid over ws, grpc,
httpupgrade, or xhttp.
'';
example = "xtls-rprx-vision";
};
method = mkOption {
type = types.str;
default = "2022-blake3-aes-128-gcm";
description = ''
Shadowsocks cipher. Ignored by other protocols.
The 2022 ciphers require a base64 pre-shared key of the matching
length as the password, not a passphrase.
'';
example = "aes-128-gcm";
};
transport = mkOption {
type = transportType;
default = { };
description = ''
Stream transport settings for this listener.
'';
};
tls = mkOption {
type = tlsType;
default = { };
description = ''
TLS termination settings for this listener. Mutually exclusive with
reality.
'';
};
reality = mkOption {
type = realityType;
default = { };
description = ''
REALITY settings for this listener. Mutually exclusive with tls.
'';
};
xrayJson = mkOption {
type = types.nullOr types.attrs;
default = null;
description = ''
Raw XRay inbound configuration as a Nix attribute set, for protocols
or options the typed fields do not cover. Embedded into the config at
build time, so avoid putting credentials here; use jsonFile instead.
The tag field is overridden by the listener name.
Set exactly one of type, xrayJson, or jsonFile for each listener.
'';
example = {
protocol = "dokodemo-door";
settings = {
address = "127.0.0.1";
port = 8080;
};
};
};
jsonFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing a complete XRay inbound object as
JSON. Read at service start time, so the whole inbound including its
credentials can be rendered by a secret manager and never lands in
the Nix store. The tag field is overridden by the listener name.
No share link is generated for listeners defined this way.
Set exactly one of type, xrayJson, or jsonFile for each listener.
'';
example = "/run/secrets/proxy-inbound-vless.json";
};
};
};
in
{
inherit inboundType;
}
@@ -103,6 +103,14 @@ let
[ ];
in
{
# The zapret-derived portion on its own. proxyInbounds routes these to the
# direct outbound so the host's own zapret handles the DPI bypass for inbound
# clients, instead of paying for a proxy hop it does not need.
zapretDirect = {
domains = zapretDirectDomains;
ips = zapretDirectIps;
};
direct = {
domains = lib.unique (r.direct.domains ++ zapretDirectDomains);
ips = lib.unique (r.direct.ips ++ zapretDirectIps);
+2
View File
@@ -19,6 +19,7 @@ let
;
};
inherit (zapretDirect) direct;
zapretDirectRules = zapretDirect.zapretDirect;
customRuleCategory =
outbound:
@@ -105,6 +106,7 @@ in
{
inherit
direct
zapretDirectRules
geositeRuleSets
geoIPRuleSets
singBoxRoutingRules
@@ -0,0 +1,124 @@
# XRay routing rules for the server-side inbound service.
#
# Deliberately separate from the client ruleset: inbound traffic belongs to
# somebody else's session, so it is not subject to routing.rules, route-mode
# overrides, or the DNS-hijack machinery the client config needs.
#
# The "proxy" outbound here is the local client stack's SOCKS listener, so
# anything the client decides (selected outbound, urltest, route-mode) applies
# to relayed traffic without being reimplemented.
{
lib,
proxyInboundsCfg,
proxyInbounds,
zapretDirectRules,
}:
let
defaultVia = proxyInboundsCfg.via;
# Listeners that follow the tree-wide default need no rule of their own; the
# final rule already sends them there.
overrideInbounds = builtins.filter (ib: ib.via != defaultVia) proxyInbounds;
defaultInboundTags = map (ib: ib.tag) (builtins.filter (ib: ib.via == defaultVia) proxyInbounds);
blockPrivateRule = lib.optional proxyInboundsCfg.blockPrivate {
type = "field";
ruleTag = "inbound-block-private";
ip = [ "geoip:private" ];
outboundTag = "block";
};
# A relay must not blackhole the address clients dial to reach it. Without
# this, a server on a .ru domain (or a .ru IP) blocks itself under blockRu:
# anyone connected through the host cannot open the very site the listeners
# are hidden behind, and a blackholed connection reads as a refusal rather
# than as a rule. Placed after blockPrivate so a NATed serverAddress cannot
# be used to reach the LAN.
#
# It may be given in either form, and geoip:ru catches a literal IP just as
# geosite catches the name. An IPv6 literal is the only form carrying a colon;
# a bare name cannot.
serverAddressIsIp =
let
addr = proxyInboundsCfg.serverAddress;
in
addr != null
&& (lib.hasInfix ":" addr || builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+" addr != null);
serverAddressRule = lib.optional (proxyInboundsCfg.serverAddress != null) (
{
type = "field";
ruleTag = "inbound-server-address-direct";
outboundTag = "direct";
}
// (
if serverAddressIsIp then
{ ip = [ proxyInboundsCfg.serverAddress ]; }
else
{ domain = [ "full:${proxyInboundsCfg.serverAddress}" ]; }
)
);
blockRuRules = lib.optionals proxyInboundsCfg.blockRu [
{
type = "field";
ruleTag = "inbound-block-ru-domain";
domain = [ "geosite:category-ru" ];
outboundTag = "block";
}
{
type = "field";
ruleTag = "inbound-block-ru-ip";
ip = [ "geoip:ru" ];
outboundTag = "block";
}
];
# Only meaningful when the default egress leaves through a proxy: zapret works
# on traffic this host emits itself, so destinations it can already unblock
# are better left direct than sent through a proxy hop. Scoped to the
# listeners on the default egress, so an explicit per-listener `via` wins.
zapretDirectEnabled =
proxyInboundsCfg.zapretDirect
&& defaultInboundTags != [ ]
&& !builtins.elem defaultVia [
"direct"
"block"
];
mkZapretRule =
ruleTag: field: items:
lib.optional (zapretDirectEnabled && items != [ ]) {
type = "field";
inherit ruleTag;
${field} = items;
inboundTag = defaultInboundTags;
outboundTag = "direct";
};
zapretRules =
mkZapretRule "inbound-zapret-direct-domain" "domain" (
map (domain: "domain:${domain}") zapretDirectRules.domains
)
++ mkZapretRule "inbound-zapret-direct-ip" "ip" zapretDirectRules.ips;
overrideRules = map (ib: {
type = "field";
ruleTag = "inbound-via-${ib.tag}";
inboundTag = [ ib.tag ];
outboundTag = ib.via;
}) overrideInbounds;
finalRule = {
type = "field";
ruleTag = "inbound-final";
network = "tcp,udp";
outboundTag = defaultVia;
};
xrayInboundRules = blockPrivateRule ++ serverAddressRule ++ blockRuRules ++ zapretRules ++ overrideRules ++ [ finalRule ];
in
{
inherit xrayInboundRules;
}
+129
View File
@@ -82,6 +82,12 @@ let
(mkAssertion (
!cfg.sshProxy.enable || (cfg.sshProxy.user != null && cfg.sshProxy.host != null)
) "proxy-suite: sshProxy.user and sshProxy.host are required when sshProxy.enable = true")
# SingBox dials SSH itself and verifies host keys by value, with no
# knownHostsFile and no trust-on-first-use fallback. An empty list accepts
# any host key, so refuse rather than silently downgrade the tunnel.
(mkAssertion (
!derived.sshProxyNativeOutbound || cfg.sshProxy.hostKey != [ ] || cfg.sshProxy.hostKeyFile != null
) "proxy-suite: sshProxy.hostKey or sshProxy.hostKeyFile is required when sshProxy.asOutbound = true with a SingBox or hybrid backend, because SingBox verifies host keys by value and an empty list accepts any key. Point hostKeyFile at a known-hosts file, or list every key from `ssh-keyscan -p <sshPort> <host>` in hostKey -- the host key algorithm is negotiated, so a single pinned key fails the handshake when the server picks another algorithm.")
(mkAssertion (!proxyEnabled || invalidRoutingTargets == [ ])
"proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}"
)
@@ -208,6 +214,128 @@ let
) "proxy-suite: outbound '${ob.tag}': backend = \"sing-box\" requires proxy.singBox.enable = true")
]) proxyCfg.outbounds;
proxyInboundsCfg = derived.proxyInboundsCfg;
proxyInboundsEnabled = derived.proxyInboundsEnabled;
proxyInbounds = derived.proxyInbounds;
proxyInboundsNeedLocalProxy = proxyInboundsEnabled && derived.proxyInboundsNeedLocalProxy;
# A pinned outbound is rendered by the XRay renderer inside the inbound
# service, so a sing-box-only definition cannot serve as one.
singBoxOnlyPinnedTags = map (ob: ob.tag) (
builtins.filter (
ob: ob.singBoxJson != null || ob.json != null
) derived.proxyInboundViaOutbounds
);
proxyInboundAssertions =
[
(mkAssertion (!proxyInboundsEnabled || derived.invalidInboundViaTargets == [ ])
"proxy-suite: proxyInbounds via targets are not defined in proxy.outbounds: ${lib.concatStringsSep ", " derived.invalidInboundViaTargets}. Subscription proxies cannot be named here because their tags only exist at runtime; use via = \"proxy\" to reach those."
)
(mkAssertion (!proxyInboundsEnabled || singBoxOnlyPinnedTags == [ ])
"proxy-suite: proxyInbounds via targets a sing-box-only outbound: ${lib.concatStringsSep ", " singBoxOnlyPinnedTags}. The inbound service runs XRay, so a pinned outbound needs url, urlFile, or xrayJson."
)
(requireEnabled (proxyInboundsEnabled && derived.proxyInboundViaTags != [ ]) proxyEnabled
"proxy-suite: proxyInbounds pins a listener to a proxy.outbounds tag, which requires proxy.enable = true"
)
(requireEnabled proxyInboundsEnabled (proxyInbounds != [ ])
"proxy-suite: proxyInbounds.enable requires at least one entry in proxyInbounds.listeners"
)
(requireEnabled proxyInboundsNeedLocalProxy proxyEnabled
"proxy-suite: proxyInbounds.via = \"proxy\" relays through the local proxy stack, which requires proxy.enable = true. Use via = \"direct\" for a plain exit node."
)
(requireEnabled proxyInboundsNeedLocalProxy derived.hasAvailableOutbounds
"proxy-suite: proxyInbounds.via = \"proxy\" relays through the local proxy stack, so at least one proxy.outbounds or proxy.subscriptions entry is required"
)
(uniqueValues proxyInboundsEnabled (map (ib: ib.listener.port) proxyInbounds)
"proxy-suite: proxyInbounds.listeners must each use a distinct port"
)
(mkAssertion
(
!proxyInboundsEnabled
|| !proxyEnabled
|| !builtins.elem proxyCfg.port derived.proxyInboundPorts
)
"proxy-suite: a proxyInbounds listener port collides with proxy.port (${toString proxyCfg.port})"
)
(mkAssertion
(
!proxyInboundsEnabled
|| !globalTproxy.enable
|| !builtins.elem globalTproxy.port derived.proxyInboundPorts
)
"proxy-suite: a proxyInbounds listener port collides with proxy.tproxy.port (${toString globalTproxy.port})"
)
]
++ lib.concatMap (
ib:
let
l = ib.listener;
prefix = "proxy-suite: proxyInbounds listener '${ib.tag}'";
firstUser = if l.users == [ ] then null else builtins.head l.users;
needsUuid = builtins.elem l.type [
"vless"
"vmess"
];
needsPassword = builtins.elem l.type [
"trojan"
"shadowsocks"
"socks"
"http"
];
tlsTerminated = l.tls.enable || l.type == "trojan";
in
[
(exactlyOneOf proxyInboundsEnabled [
l.type
l.xrayJson
l.jsonFile
] "${prefix}: set exactly one of type, xrayJson, or jsonFile")
(mkAssertion (
!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")
(exactlyOneOf (proxyInboundsEnabled && needsUuid && firstUser != null) [
firstUser.uuid
firstUser.uuidFile
] "${prefix}: ${toString l.type} users need exactly one of uuid or uuidFile")
(exactlyOneOf (proxyInboundsEnabled && needsPassword && firstUser != null) [
firstUser.password
firstUser.passwordFile
] "${prefix}: ${toString l.type} users need exactly one of password or passwordFile")
(exactlyOneOf (proxyInboundsEnabled && l.reality.enable) [
l.reality.privateKey
l.reality.privateKeyFile
] "${prefix}: reality needs exactly one of privateKey or privateKeyFile")
(mkAssertion (
!proxyInboundsEnabled || !l.reality.enable || l.reality.serverNames != [ ]
) "${prefix}: reality.serverNames must not be empty")
(requireAvailable (proxyInboundsEnabled && l.reality.enable && proxyInboundsCfg.shareLinks)
(l.reality.publicKey != null)
"${prefix}: reality.publicKey is required to generate share links. Run `xray x25519` to print it alongside the private key, or set proxyInbounds.shareLinks = false."
)
(mkAssertion
(
!proxyInboundsEnabled
|| !tlsTerminated
|| l.reality.enable
|| (l.tls.certificateFile != null && l.tls.keyFile != null)
)
"${prefix}: TLS termination needs both tls.certificateFile and tls.keyFile"
)
(mkAssertion
(
!proxyInboundsEnabled
|| l.flow == null
|| (l.type == "vless" && l.transport.type == "raw")
)
"${prefix}: flow is only valid on a vless listener with transport.type = \"raw\""
)
]
) proxyInbounds;
subscriptionAssertions = lib.concatMap (sub: [
(exactlyOneOf proxyEnabled [
sub.urlFile
@@ -464,6 +592,7 @@ featureAssertions
++ localProxyAuthAssertions
++ secretAssertions
++ outboundAssertions
++ proxyInboundAssertions
++ subscriptionAssertions
++ collisionAssertions
++ positiveNumberAssertions
+23
View File
@@ -8,6 +8,8 @@
tunFile,
perAppTunFile,
routeModeRulesFile,
proxyInboundsFile,
proxyInboundsSpecFile,
perAppTunChainFile,
perAppTproxyRulesFile,
perAppZapretRulesFile,
@@ -44,6 +46,12 @@ let
hasSubscriptions
sshProxyCfg
sshProxyOutboundEnabled
sshProxyUnitEnabled
proxyInboundsCfg
proxyInboundsEnabled
proxyInboundsNeedLocalProxy
proxyInboundViaOutbounds
userControlEnabled
;
# Tool paths – defined once here and passed into sub-modules as needed.
@@ -64,8 +72,11 @@ let
proxySuiteScriptsDir = ../../../scripts;
parserScriptsPythonPath = proxySuiteScriptsDir;
buildOutboundPy = "${proxySuiteScriptsDir}/build-outbound.py";
buildInboundPy = "${proxySuiteScriptsDir}/build-inbound.py";
fetchSubscriptionPy = "${proxySuiteScriptsDir}/fetch-subscription.py";
builders = import ./builders.nix { inherit lib pkgs; };
polkit = import ./polkit.nix {
inherit lib cfg userControlCfg;
};
@@ -95,6 +106,7 @@ let
xray
parserScriptsPythonPath
buildOutboundPy
buildInboundPy
fetchSubscriptionPy
;
inherit
@@ -102,6 +114,15 @@ let
tunFile
perAppTunFile
routeModeRulesFile
proxyInboundsFile
proxyInboundsSpecFile
;
inherit
proxyInboundsCfg
proxyInboundsNeedLocalProxy
proxyInboundViaOutbounds
userControlEnabled
builders
;
};
@@ -144,6 +165,8 @@ let
;
inherit (scripts) subscriptionTagsFile subscriptionCacheDir;
inherit (scripts) routeModeStateFile;
inherit proxyInboundsEnabled;
inherit (scripts) proxyInboundsLinksFile;
inherit amneziaWgProfileNamesFile;
inherit (perAppRouting)
perAppRoutingProfilesFile
+4
View File
@@ -15,6 +15,8 @@
proxychainsQuietArg,
routeModeStateFile,
amneziaWgProfileNamesFile,
proxyInboundsEnabled,
proxyInboundsLinksFile,
}:
{
proxyCtl = packages.mkProxyCtl {
@@ -35,5 +37,7 @@
perAppRoutingTunEnabled = if perAppRoutingTun.enable then "1" else "0";
perAppRoutingTproxyEnabled = if perAppRoutingTproxy.enable then "1" else "0";
perAppRoutingZapretEnabled = if perAppZapretCfg.enable then "1" else "0";
inboundsEnabled = if proxyInboundsEnabled then "1" else "0";
inboundsLinksFile = proxyInboundsLinksFile;
};
}
+18
View File
@@ -9,6 +9,8 @@
tunFile,
perAppTunFile,
routeModeRulesFile,
proxyInboundsFile,
proxyInboundsSpecFile,
nftablesRulesFile,
perAppTproxyRulesFile,
perAppZapretRulesFile,
@@ -28,6 +30,8 @@ let
tunFile
perAppTunFile
routeModeRulesFile
proxyInboundsFile
proxyInboundsSpecFile
perAppTunChainFile
perAppTproxyRulesFile
perAppZapretRulesFile
@@ -61,6 +65,11 @@ let
perAppZapretEnabled
hasSubscriptions
sshProxyOutboundEnabled
sshProxyUnitEnabled
proxyInboundsEnabled
proxyInboundsNeedLocalProxy
proxyInboundFirewallPorts
proxyInboundFirewallUdpPorts
outboundTags
effectiveOutboundTags
subscriptionTags
@@ -99,6 +108,9 @@ let
perAppZapretEnabled
hasSubscriptions
sshProxyOutboundEnabled
sshProxyUnitEnabled
proxyInboundsEnabled
proxyInboundsNeedLocalProxy
scripts
perAppRouting
routingScripts
@@ -124,6 +136,12 @@ in
|| perAppZapretEnabled
) (lib.mkDefault true);
# Inbound listeners are reached from outside, so their ports have to be open.
networking.firewall = lib.mkIf (proxyInboundsEnabled && cfg.proxyInbounds.openFirewall) {
allowedTCPPorts = proxyInboundFirewallPorts;
allowedUDPPorts = proxyInboundFirewallUdpPorts;
};
users.groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) {
"${userControlCfg.group}" = { };
};
@@ -0,0 +1,142 @@
# Startup script for the server-side inbound service.
#
# Much smaller than the client start script: no route-mode, no TUN/TProxy, no
# hybrid sidecar. It renders the listeners (reading their secrets), merges them
# into the build-time template, and hands the result to XRay.
{
lib,
pkgs,
proxyCfg,
proxyInboundsCfg,
proxyInboundsNeedLocalProxy,
proxyInboundViaOutbounds,
userControlCfg,
userControlEnabled,
localProxyAuth,
localProxyAuthEnabled,
localProxyAuthPasswordSource,
jq,
python3,
parserScriptsPythonPath,
buildInboundPy,
buildOutboundPy,
proxyInboundsFile,
proxyInboundsSpecFile,
builders,
}:
let
runtimeDir = "/run/proxy-suite-inbounds";
linksFile = "${runtimeDir}/links.json";
# This service's own package, not the client backend's.
xray = "${proxyInboundsCfg.package}/bin/xray";
# Only the local proxy needs credentials injected; the listeners' own secrets
# are resolved by build-inbound.py.
needsLocalProxyAuth = proxyInboundsNeedLocalProxy && localProxyAuthEnabled;
serverAddressBlock =
if proxyInboundsCfg.serverAddress != null then
''SERVER_ADDRESS=${lib.escapeShellArg proxyInboundsCfg.serverAddress}''
else if proxyInboundsCfg.shareLinks then
''
${builders.mkDefaultUplinkIPv4Source {
ip = "${pkgs.iproute2}/bin/ip";
awk = "${pkgs.gawk}/bin/awk";
errorMessage = "proxy-suite: could not determine this host's uplink address for inbound share links; set proxyInbounds.serverAddress";
}}
SERVER_ADDRESS="$uplink_addr"
''
else
''SERVER_ADDRESS=""'';
# Outbounds a listener pins itself to with `via = "<tag>"`. Rendered here, at
# start time, so a urlFile's contents stay out of the Nix store. Subscriptions
# are deliberately not duplicated into this service: their cache is refreshed
# for the client backend only, and `via = "proxy"` already reaches them.
mkViaOutboundBlock =
ob:
let
urlSource =
if ob.urlFile != null then
ob.urlFile
else if ob.url != null then
pkgs.writeText "proxy-suite-inbound-via-url-${ob.tag}" ob.url
else
null;
in
if urlSource == null then
''
# via outbound: ${ob.tag} (static xray json)
OB_JSON=$(cat ${
pkgs.writeText "proxy-suite-inbound-via-${ob.tag}.json" (
builtins.toJSON (ob.xrayJson // { inherit (ob) tag; })
)
})
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
''
else
''
# via outbound: ${ob.tag}
URL=$(cat ${lib.escapeShellArg urlSource})
OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} \
--backend xray --tag ${lib.escapeShellArg ob.tag})
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
'';
viaOutboundsBlock = lib.concatMapStrings mkViaOutboundBlock proxyInboundViaOutbounds;
# Share links carry the listener credentials, so they are no more public than
# the config itself.
writeLinksBlock = lib.optionalString proxyInboundsCfg.shareLinks ''
${jq} -c '.links' <<< "$RENDERED" > "${linksFile}"
${lib.optionalString userControlEnabled ''
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${linksFile}"
''}
chmod ${if userControlEnabled then "640" else "600"} "${linksFile}"
'';
startInbounds = pkgs.writeShellScript "proxy-suite-start-inbounds" ''
set -euo pipefail
umask 077
RUNTIME_DIR="${runtimeDir}"
mkdir -p "$RUNTIME_DIR"
${serverAddressBlock}
RENDERED=$(PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildInboundPy} \
--spec ${proxyInboundsSpecFile} \
--server-address "$SERVER_ADDRESS")
INBOUNDS_JSON=$(${jq} -c '.inbounds' <<< "$RENDERED")
OUTBOUNDS_JSON='[]'
${viaOutboundsBlock}
${lib.optionalString needsLocalProxyAuth ''
LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")"
''}
${jq} \
--argjson ibs "$INBOUNDS_JSON" \
--argjson obs "$OUTBOUNDS_JSON" \
--argjson auth_enabled ${if needsLocalProxyAuth then "true" else "false"} \
--arg user ${if needsLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \
--arg password ${if needsLocalProxyAuth then "\"$LOCAL_PROXY_PASSWORD\"" else "''"} \
'.inbounds = $ibs
| .outbounds = $obs + .outbounds
| if $auth_enabled then
(.outbounds[] | select(.tag == "proxy") | .settings.servers[0].users)
= [{user:$user,pass:$password}]
else . end' \
${proxyInboundsFile} > "$RUNTIME_DIR/config.json"
chmod 600 "$RUNTIME_DIR/config.json"
${writeLinksBlock}
exec ${xray} run -c "$RUNTIME_DIR/config.json"
'';
in
{
inherit startInbounds linksFile;
}
@@ -22,6 +22,15 @@
let
sshProxyTag = "ssh-proxy";
# sing-box domain-strategy names mapped onto XRay's sockopt.domainStrategy.
# XRay's "UseIPv4v6" means "IPv4 first, fall back to IPv6", i.e. prefer_ipv4.
xrayDomainStrategies = {
prefer_ipv4 = "UseIPv4v6";
prefer_ipv6 = "UseIPv6v4";
ipv4_only = "UseIPv4";
ipv6_only = "UseIPv6";
};
rawOutboundJson =
ob: tag: routingMark:
let
@@ -169,16 +178,33 @@ let
mkSshProxyOutboundBlock =
routingMark:
let
# sing-box dials SSH itself, so there is no OpenSSH unit and no local
# SOCKS5 hop. It resolves destinations natively, which is why this shape
# takes no domainStrategy.
singBoxOutbound = {
type = "socks";
type = "ssh";
tag = sshProxyTag;
server = sshProxyCfg.listenAddress;
server_port = sshProxyCfg.listenPort;
version = "5";
server = sshProxyCfg.host;
server_port = sshProxyCfg.sshPort;
user = sshProxyCfg.user;
}
// lib.optionalAttrs (sshProxyCfg.identityFile != null) {
private_key_path = sshProxyCfg.identityFile;
}
// lib.optionalAttrs (sshProxyCfg.hostKey != [ ]) {
host_key = sshProxyCfg.hostKey;
}
// lib.optionalAttrs (routingMark != null) {
routing_mark = routingMark;
};
# XRay has no SSH outbound, so it proxies through the listener the
# OpenSSH unit creates. sockopt.domainStrategy is what makes XRay resolve
# destinations here instead of handing the domain to the remote sshd.
xraySockopt =
lib.optionalAttrs (routingMark != null) { mark = routingMark; }
// lib.optionalAttrs (sshProxyCfg.domainStrategy != null) {
domainStrategy = xrayDomainStrategies.${sshProxyCfg.domainStrategy};
};
xrayOutbound = {
protocol = "socks";
tag = sshProxyTag;
@@ -187,23 +213,45 @@ let
port = sshProxyCfg.listenPort;
};
}
// lib.optionalAttrs (routingMark != null) {
streamSettings.sockopt.mark = routingMark;
// lib.optionalAttrs (xraySockopt != { }) {
streamSettings.sockopt = xraySockopt;
};
outbound = if pureXrayEnabled then xrayOutbound else singBoxOutbound;
outboundJson = builtins.toJSON outbound;
jsonFile = pkgs.writeText "proxy-suite-ob-ssh-proxy-${backend}.json" outboundJson;
# Host keys come from a known-hosts file at start time so the file stays
# out of the Nix store. ssh-keygen -F also resolves hashed entries.
knownHostsTarget =
if sshProxyCfg.sshPort == 22 then
sshProxyCfg.host
else
"[${sshProxyCfg.host}]:${toString sshProxyCfg.sshPort}";
hostKeyFileBlock =
lib.optionalString (!pureXrayEnabled && sshProxyCfg.hostKeyFile != null)
''
SSH_HOST_KEYS=$(${pkgs.openssh}/bin/ssh-keygen -F ${lib.escapeShellArg knownHostsTarget} \
-f ${lib.escapeShellArg sshProxyCfg.hostKeyFile} \
| ${jq} -R -s '[splits("\n")] | map(select(length > 0 and (startswith("#") | not))) | map(sub("^\\S+\\s+"; ""))')
if [ "$(${jq} 'length' <<< "$SSH_HOST_KEYS")" -eq 0 ]; then
echo "proxy-suite: no host keys for ${knownHostsTarget} in ${sshProxyCfg.hostKeyFile}" >&2
exit 1
fi
OB_JSON=$(${jq} --argjson hk "$SSH_HOST_KEYS" '.host_key = $hk' <<< "$OB_JSON")
'';
in
if hybridEnabled then
''
# outbound: ${sshProxyTag} (SSH SOCKS5)
# outbound: ${sshProxyTag} (${if pureXrayEnabled then "OpenSSH SOCKS5 listener" else "native SSH"})
OB_JSON=$(cat "${jsonFile}")
${hostKeyFileBlock}
_proxy_suite_add_sing_box_ob "$OB_JSON"
''
else
''
# outbound: ${sshProxyTag} (SSH SOCKS5)
# outbound: ${sshProxyTag} (${if pureXrayEnabled then "OpenSSH SOCKS5 listener" else "native SSH"})
OB_JSON=$(cat "${jsonFile}")
${hostKeyFileBlock}
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
'';
+36 -1
View File
@@ -26,6 +26,14 @@
tunFile,
perAppTunFile,
routeModeRulesFile,
proxyInboundsCfg,
proxyInboundsNeedLocalProxy,
proxyInboundViaOutbounds,
userControlEnabled,
buildInboundPy,
proxyInboundsFile,
proxyInboundsSpecFile,
builders,
}:
let
@@ -157,6 +165,32 @@ let
};
inherit (startScripts) startSocks startTun startPerAppTun;
proxyInboundsScripts = import ./proxy-inbounds-scripts.nix {
inherit
lib
pkgs
proxyCfg
proxyInboundsCfg
proxyInboundsNeedLocalProxy
proxyInboundViaOutbounds
userControlCfg
userControlEnabled
localProxyAuth
localProxyAuthEnabled
localProxyAuthPasswordSource
jq
python3
parserScriptsPythonPath
buildInboundPy
buildOutboundPy
proxyInboundsFile
proxyInboundsSpecFile
builders
;
};
inherit (proxyInboundsScripts) startInbounds;
proxyInboundsLinksFile = proxyInboundsScripts.linksFile;
controlScripts = import ./control-scripts.nix {
inherit
lib
@@ -175,8 +209,9 @@ let
in
{
inherit startSocks startTun startPerAppTun;
inherit startSocks startTun startPerAppTun startInbounds;
inherit
proxyInboundsLinksFile
routeModeStateFile
setRouteModeScript
subscriptionUpdateScript
+32 -2
View File
@@ -13,6 +13,9 @@
perAppZapretEnabled,
hasSubscriptions,
sshProxyOutboundEnabled,
sshProxyUnitEnabled,
proxyInboundsEnabled,
proxyInboundsNeedLocalProxy,
scripts,
perAppRouting,
routingScripts,
@@ -41,6 +44,7 @@ let
perAppTproxy = "proxy-suite-per-app-tproxy";
perAppZapret = "proxy-suite-per-app-zapret";
subscriptionUpdate = "proxy-suite-subscription-update";
inbounds = "proxy-suite-inbounds";
};
backendDescription =
@@ -61,17 +65,43 @@ let
name = serviceNames.socks;
value = mkRestartingService {
description = "${backendDescription} proxy client (SOCKS + TProxy-ready)";
# Only the XRay backend proxies through the OpenSSH unit's listener;
# SingBox dials SSH inside its own process and needs no ordering.
after = [
"network-online.target"
]
++ lib.optional sshProxyOutboundEnabled "proxy-suite-ssh-proxy.service";
wants = [ "network-online.target" ];
++ lib.optional (sshProxyOutboundEnabled && sshProxyUnitEnabled) "proxy-suite-ssh-proxy.service";
wants = [
"network-online.target"
]
++ lib.optional (sshProxyOutboundEnabled && sshProxyUnitEnabled) "proxy-suite-ssh-proxy.service";
wantedBy = [ "multi-user.target" ];
execStart = scripts.startSocks;
runtimeDirectory = serviceNames.socks;
stateDirectory = "proxy-suite";
};
}
{
enable = proxyInboundsEnabled;
name = serviceNames.inbounds;
value = mkRestartingService {
description = "XRay server inbounds (accept connections from outside)";
after = [
"network-online.target"
]
# Relayed traffic leaves through the client stack's SOCKS listener, so
# start after it. Not `requires`: the listeners should keep serving
# direct-routed traffic even if the client stack is down.
++ lib.optional proxyInboundsNeedLocalProxy "${serviceNames.socks}.service";
wants = [
"network-online.target"
]
++ lib.optional proxyInboundsNeedLocalProxy "${serviceNames.socks}.service";
wantedBy = [ "multi-user.target" ];
execStart = scripts.startInbounds;
runtimeDirectory = serviceNames.inbounds;
};
}
{
enable = proxyEnabled && globalTproxy.enable;
name = serviceNames.tproxy;
+11 -1
View File
@@ -16,6 +16,9 @@ let
-N
-o BatchMode=yes
-o ExitOnForwardFailure=yes
-o ServerAliveInterval=15
-o ServerAliveCountMax=3
-o ConnectTimeout=10
-o StrictHostKeyChecking=${lib.escapeShellArg s.strictHostKeyChecking}
-D ${lib.escapeShellArg "${s.listenAddress}:${toString s.listenPort}"}
)
@@ -34,10 +37,17 @@ in
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
# Restart=always plus a server that refuses connections would otherwise hit
# the default 5-starts-in-10s limit and stay failed.
startLimitIntervalSec = 0;
serviceConfig = {
ExecStart = startScript;
Restart = "on-failure";
# `ssh -N` exits 0 when the server closes the connection cleanly, which
# under on-failure left the tunnel down for good.
Restart = "always";
RestartSec = 5;
# One fd per forwarded channel; the 1024 default is low for a relay.
LimitNOFILE = 65536;
}
// lib.optionalAttrs (s.serviceUser != null) {
User = s.serviceUser;