feat: allow using suite on non-nixos systems

This commit is contained in:
FUFSoB committed 2026-09-17 13:27:08 +05:00
1 parent e852bef400
commit 3b568bb54e
63 files changed
+3572 -523

No files matched your search

+54 -2
View File
@@ -1,6 +1,6 @@
# proxy-suite-flake
Declarative proxy stack for NixOS, on either side of the connection: as a client that routes this host's traffic through outbounds, as a server that accepts clients on its own inbounds, or both at once. Configure it in Nix, rebuild, and it runs as systemd services.
Declarative proxy stack for NixOS, on either side of the connection: as a client that routes this host's traffic through outbounds, as a server that accepts clients on its own inbounds, or both at once. Configure it in Nix, rebuild, and it runs as systemd services. It also runs on other Linux distributions (through system-manager or home-manager) and on Android (through Nix-on-Droid): see [Other hosts](#other-hosts).
> [!IMPORTANT]
> This project is for study and research purposes only: learning how proxies, tunnels and traffic routing work. It comes with no warranty, and the authors are not responsible for how it is used.
@@ -85,7 +85,7 @@ services.proxy-suite = {
profiles.work.vpnFile = "/run/secrets/work-amnezia.vpn";
# An outbound tagged "de" instead: the proxy binds to its interface, which gets no routes.
profiles.de = {
asOutbound = "interface"; # or "singBox": plain WireGuard inside sing-box
asOutbound = "interface"; # or "userspace" (no root), or "singBox" (plain WireGuard)
configFile = "/run/secrets/de-amneziawg.conf";
};
};
@@ -106,6 +106,58 @@ services.proxy-suite = {
};
```
### Other hosts
The same options work outside NixOS. Pick the module for the host; everything the host cannot do fails evaluation with a message naming the option.
| | NixOS | system-manager | home-manager | Nix-on-Droid |
|---|:-:|:-:|:-:|:-:|
| Runs as | root, systemd | root, systemd | user, `systemd --user` | user, `proxy-suitectl` |
| Local SOCKS/HTTP proxy, subscriptions, selection, route modes | ✓ | ✓ | ✓ | ✓ |
| Per-app proxychains | ✓ | ✓ | ✓ | ✓ |
| Server inbounds, share links, stats | ✓ | ✓ | ports ≥ 1024 | ports ≥ 1024 |
| tg-ws-proxy, SSH proxy, WARP as a sing-box outbound | ✓ | ✓ | ✓ | ✓ |
| AmneziaWG `asOutbound = "userspace"` | ✓ | ✓ | ✓ | ✓ |
| Global TUN/TProxy, per-app TUN/TProxy/zapret, zapret, AmneziaWG interfaces | ✓ | ✓ | ✗ | ✗ |
| `userControl`, polkit | ✓ | ✓ | not needed | not needed |
| GUI | ✓ | ✓ | ✓ | ✗ (`proxy-ctl`, `proxy-tui`) |
Rootless hosts get the local proxy only: nothing captures the rest of the host's traffic, so point applications at `127.0.0.1:1080` (or run them through `proxy-ctl apps run`).
#### system-manager (other distributions, as root)
```nix
# with github:numtide/system-manager
modules = [ inputs.proxy-suite.systemManagerModules.default ];
```
- Units, service users and the polkit rules (`/etc/polkit-1/rules.d/50-proxy-suite.rules`) are installed like on NixOS; the GUI's user unit goes to `/etc/systemd/user`. The service users come from `users.users`, so system-manager needs its user management.
- The host's firewall is left alone: open the inbound ports yourself. TUN, TProxy and zapret load their own nftables tables, which needs `nf_tables`, `nfnetlink_queue` and `tun` in the host kernel.
- AmneziaWG runs on its userspace implementation (`amneziaWg.kernelModulePackage` must stay `null`). DNS pushed by a VPN profile goes through `resolvectl` under systemd-resolved, `openresolv` otherwise.
#### home-manager (any Linux, no root)
```nix
# homeConfigurations.<name> = home-manager.lib.homeManagerConfiguration { ... }
modules = [ inputs.proxy-suite.homeManagerModules.default ];
```
- Units run in the user's systemd manager: `systemctl --user status proxy-suite-socks`. They stop at logout unless lingering is on: `loginctl enable-linger $USER`.
- State lives in `$XDG_STATE_HOME/proxy-suite`, runtime files in `$XDG_CACHE_HOME/proxy-suite/run`.
#### Nix-on-Droid (Android, no root)
```nix
# nixOnDroidConfigurations.default = nix-on-droid.lib.nixOnDroidConfiguration { ... }
modules = [ inputs.proxy-suite.nixOnDroidModules.default ];
```
- Android has no systemd, so `nix-on-droid switch` hands the units to `proxy-suitectl`, a small supervisor that understands the parts of systemd units proxy-suite uses (restarts, dependencies, timers, path watches). `proxy-ctl` talks to it for you; directly, `proxy-suitectl status`, `proxy-suitectl restart proxy-suite-socks` and `proxy-suitectl journal -u 'proxy-suite-*' -f` work much like `systemctl` and `journalctl`.
- Android gives the app no boot hook. The services start on `nix-on-droid switch`, and, with `services.proxy-suite.nixOnDroid.startWithSession` (on by default), whenever a Nix-on-Droid shell opens; `proxy-suitectl boot` starts them by hand.
- Android stops background apps: acquire Nix-on-Droid's wake lock from its notification and exempt the app from battery optimisation, or the services die with the terminal.
- Inbounds are reachable from the local network on ports from 1024 up; zapret is not available (on Android it needs a VPN app).
- An AmneziaWG `userspace` outbound resolves an `Endpoint` hostname through the system resolver; give it as an IP address where that resolver is itself blocked.
---
## Options
+21 -1
View File
@@ -64,6 +64,7 @@ Part of the [proxy-suite options reference](./index.md).
- [vpnFile](#services-proxy-suite-amneziawg-profiles-name-vpnfile)
- [toolsPackage](#services-proxy-suite-amneziawg-toolspackage)
- [userspacePackage](#services-proxy-suite-amneziawg-userspacepackage)
- [wireproxyPackage](#services-proxy-suite-amneziawg-wireproxypackage)
<a id="services-proxy-suite-amneziawg-enable"></a>
## services\.proxy-suite\.amneziaWg\.enable
@@ -141,13 +142,18 @@ always runs, leaves the host’s routes and resolver alone, and is not listed by
- “singBox”: a WireGuard endpoint in its own sing-box process, reached as a loopback SOCKS
hop\. sing-box speaks plain WireGuard: AmneziaWG obfuscation is dropped with a warning\.
- “userspace”: the same hop served by wireproxy on AmneziaWG’s userspace implementation, so
obfuscation works\. It needs no interface or root: the only AmneziaWG mode on
home-manager and nix-on-droid\. A declared or profile ListenPort is used as is\. An
Endpoint hostname resolves through the system resolver: give an address where that
resolver cannot reach the name\.
- “interface”: the AmneziaWG interface comes up without routes (Table = off), and the
outbound binds to it, so obfuscation works\. With the sing-box backend its DNS goes
through the interface too (proxy\.dns\.remote); XRay resolves as usual\.
Either way the tunnel itself reaches the peer over the uplink, past TUN and TProxy\.
*Type:*
null or one of “singBox”, “interface”
null or one of “singBox”, “userspace”, “interface”
*Default:*
@@ -912,3 +918,17 @@ package
```nix
<derivation amneziawg-go-3.1.20260828>
```
<a id="services-proxy-suite-amneziawg-wireproxypackage"></a>
## services\.proxy-suite\.amneziaWg\.wireproxyPackage
wireproxy build with AWG 3\.1 and FwMark, which runs profiles with asOutbound = “userspace”\.
*Type:*
package
*Default:*
```nix
<derivation wireproxy-awg-1.0.18>
```
+1
View File
@@ -29,6 +29,7 @@ services.proxy-suite = {
profiles = { };
toolsPackage = pkgs.amneziawg-tools;
userspacePackage = pkgs.amneziawg-go;
wireproxyPackage = pkgs.wireproxy-awg;
};
enable = false;
geodata = {
+3 -1
View File
@@ -55,11 +55,13 @@ Add WARP as an outbound tagged “warp”\.
endpoint on 127\.0\.0\.1:18538, as the proxy-suite-daemon user\. The tunnel starts again on a
new source port when WARP does not answer within 15 seconds of a start, or misses three
probes later on, unless the uplink itself is down\.
- “userspace”: an AmneziaWG profile named “warp” with asOutbound = “userspace”, which honours
the AmneziaWG lines of the profile without an interface or root\. Requires amneziaWg\.enable\.
- “interface”: an AmneziaWG profile named “warp” with asOutbound = “interface”, which honours
the AmneziaWG lines of the profile\. Requires amneziaWg\.enable\.
*Type:*
null or one of “singBox”, “interface”
null or one of “singBox”, “userspace”, “interface”
*Default:*
+17 -1
View File
@@ -32,7 +32,7 @@
];
forAll = nixpkgs.lib.genAttrs systems;
pkgsFor = system: import nixpkgs { inherit system; };
proxySuiteModule = import ./modules/proxy-suite {
proxySuiteModules = import ./modules/proxy-suite {
inherit
zapret
nixpkgs
@@ -40,6 +40,7 @@
z2k
;
};
proxySuiteModule = proxySuiteModules.nixos;
mkOptionsDoc = import ./nix/options-doc.nix {
inherit nixpkgs pkgsFor proxySuiteModule;
};
@@ -59,6 +60,18 @@
# A single-user VPS: VLESS REALITY, TLS and WS inbounds, ACME and SSH. Includes default.
nixosModules.server = import ./deploy/server-module.nix { inherit proxySuiteModule; };
# Rootless, in the user's systemd manager: the local proxy, inbounds on ports from 1024
# up, and what else needs no root.
homeManagerModules.default = proxySuiteModules.homeManager;
# For numtide/system-manager on other distributions: everything NixOS has, with the
# firewall and kernel modules left to the host.
systemManagerModules.default = proxySuiteModules.systemManager;
# nix-on-droid, where proxy-suitectl supervises the services: what home-manager gets,
# without the GUI.
nixOnDroidModules.default = proxySuiteModules.nixOnDroid;
# Re-export zapret standalone for users who want just that.
nixosModules.zapret = zapret.nixosModules.default;
@@ -72,6 +85,7 @@
mkProxyCtl
mkTgWsProxy
tg-ws-proxy
wireproxy-awg
zapret2
;
# Replaced by Proxy Suite GUI, which mkProxyCtl builds as `.gui`.
@@ -119,6 +133,7 @@
amneziawg-tools
amneziawg-go
tg-ws-proxy
wireproxy-awg
zapret2
;
xray = import ./pkgs/xray.nix { inherit pkgs; };
@@ -166,6 +181,7 @@
system
nixpkgs
proxySuiteModule
proxySuiteModules
zapret
;
generatedOptionsDoc = mkOptionsDoc system;
+32 -16
View File
@@ -1,6 +1,5 @@
# Native AmneziaWG client profile services.
{
config,
lib,
pkgs,
cfg,
@@ -12,7 +11,15 @@ let
profiles = awgCfg.profiles;
profileNames = builtins.attrNames profiles;
globalProfileNames = builtins.attrNames derived.awgGlobalProfiles;
singBoxOutbounds = builtins.filter (ob: ob.kind == "singBox") derived.awgOutbounds;
# Profiles behind a loopback SOCKS hop, in a tunnel unit rather than awg-quick.
tunnelOutbounds = derived.awgTunnelOutbounds;
interfaceProfiles = lib.filterAttrs (
_: profile:
!builtins.elem profile.asOutbound [
"singBox"
"userspace"
]
) profiles;
serviceName = name: "proxy-suite-awg-${name}";
globalServiceNames = map serviceName globalProfileNames;
allProfileConflicts =
@@ -172,7 +179,7 @@ let
| ${pkgs.gnugrep}/bin/grep -F " wg-quick-${profile.interfaceName}" \
| while read -r _ family table; do nft delete table "$family" "$table" 2>/dev/null || true; done
fi
${config.networking.resolvconf.package}/bin/resolvconf -d "${profile.interfaceName}" -f 2>/dev/null || true
${cfg.host.resolvconfPackage}/bin/resolvconf -d "${profile.interfaceName}" -f 2>/dev/null || true
${pkgs.iproute2}/bin/ip link delete dev ${lib.escapeShellArg profile.interfaceName} 2>/dev/null || true
}
trap cleanup ERR
@@ -255,8 +262,8 @@ let
pkgs.iproute2
pkgs.iputils
pkgs.kmod
config.networking.firewall.package
config.networking.resolvconf.package
cfg.host.firewallPackage
cfg.host.resolvconfPackage
];
serviceConfig = {
Type = "oneshot";
@@ -286,7 +293,7 @@ let
};
};
mkSingBoxService =
mkTunnelService =
ob:
let
profile = profiles.${ob.name};
@@ -294,8 +301,16 @@ let
mkTunnel {
description = "proxy-suite AmneziaWG tunnel behind the ${ob.name} outbound";
unit = serviceName ob.name;
engine = ob.kind;
inherit (ob) tag tunnelPort directPort;
profile = ''
${lib.optionalString (profile.configFile != null) ''
# It may not exist yet: WARP's appears once proxy-suite-warp has registered.
if [ ! -s ${lib.escapeShellArg profile.configFile} ]; then
echo "proxy-suite: waiting for the AmneziaWG profile at ${profile.configFile}" >&2
until [ -s ${lib.escapeShellArg profile.configFile} ]; do sleep 5; done
fi
''}
profile="$RUNTIME_DIRECTORY/profile.conf"
${prepareCommand profile ''"$profile"''}
'';
@@ -424,28 +439,29 @@ let
globalAutostartCount = builtins.length autostartProfiles + (if cfg.proxy.autostart != null then 1 else 0);
in
{
environment.systemPackages = [
services.proxy-suite.internal.packages = [
awgCfg.toolsPackage
awgCfg.userspacePackage
];
]
++ lib.optional (builtins.any (ob: ob.kind == "userspace") tunnelOutbounds) awgCfg.wireproxyPackage;
boot.extraModulePackages = lib.optionals (awgCfg.kernelModulePackage != null) [
services.proxy-suite.internal.kernelModulePackages = lib.optionals (awgCfg.kernelModulePackage != null) [
awgCfg.kernelModulePackage
];
# Replies to the proxy's sockets come in on an interface the host has no route through.
networking.firewall.extraReversePathFilterRules = lib.concatMapStrings (ob: ''
services.proxy-suite.internal.firewall.extraReversePathFilterRules = lib.concatMapStrings (ob: ''
iifname "${ob.interface}" accept
'') derived.awgInterfaceOutbounds;
systemd.services = lib.mkMerge [
(lib.mapAttrs' (name: profile: lib.nameValuePair (serviceName name) (mkService name profile)) (
lib.filterAttrs (_: profile: profile.asOutbound != "singBox") profiles
))
services.proxy-suite.internal.services = lib.mkMerge [
(lib.mapAttrs' (
name: profile: lib.nameValuePair (serviceName name) (mkService name profile)
) interfaceProfiles)
(lib.mapAttrs' (
name: profile: lib.nameValuePair "${serviceName name}-watchdog" (mkWatchdog name profile)
) (lib.filterAttrs (_: profile: profile.asOutbound != "singBox") profiles))
(lib.listToAttrs (map (ob: lib.nameValuePair (serviceName ob.name) (mkSingBoxService ob)) singBoxOutbounds))
) interfaceProfiles)
(lib.listToAttrs (map (ob: lib.nameValuePair (serviceName ob.name) (mkTunnelService ob)) tunnelOutbounds))
(lib.mkIf cfg.proxy.tun.enable {
proxy-suite-tun.conflicts = map (name: "${name}.service") globalServiceNames;
})
+6 -2
View File
@@ -4,7 +4,11 @@
# because sing-box refuses to start when a local rule-set path is missing, so
# every file it will be told about must exist first; the prober needs it to
# publish what it learns, which sing-box then picks up without a restart.
{ pkgs, serviceUser }:
{
pkgs,
serviceUser,
ifPrivileged,
}:
pkgs.writeShellScript "proxy-suite-autoproxy" ''
set -euo pipefail
@@ -21,7 +25,7 @@ pkgs.writeShellScript "proxy-suite-autoproxy" ''
# files: that takes read on it, not just the search the state dir grants.
# Asserted on every render, since StateDirectory= re-owns the tree when the
# units' Group= changes.
install -d -m 0750 -g ${serviceUser} "$(dirname "$path")"
install -d -m 0750 ${ifPrivileged "-g ${serviceUser} "}"$(dirname "$path")"
# Written aside and renamed into place: sing-box reloads on rename (as well
# as on in-place writes), and it never reads a half-written file.
jq -c --arg t "$tag" '
+11 -9
View File
@@ -7,6 +7,8 @@
cfg,
proxyCtl,
autoProxyStateDir,
runtimeDir,
journalctl,
userControlAllows,
}:
@@ -16,7 +18,7 @@ let
stateDirMode = if userControlAllows "autoProxy" then "0771" else "0751";
render = import ./autoproxy-render.nix {
inherit pkgs;
inherit ((import ./derived.nix { inherit lib cfg; }).constants) serviceUser;
inherit ((import ./derived.nix { inherit lib cfg; }).constants) serviceUser ifPrivileged;
};
jqFile =
path:
@@ -52,7 +54,7 @@ let
set -euo pipefail
export PATH=${bin}
state_dir=''${AUTOPROXY_STATE_DIR:-${lib.escapeShellArg autoProxyStateDir}}
index=''${PROBE_EXITS_FILE:-/run/proxy-suite-socks/probe-exits.json}
index=''${PROBE_EXITS_FILE:-${runtimeDir}/proxy-suite-socks/probe-exits.json}
${clashApiBlock}
if [ -z "$clash_api" ]; then
echo "sing-box has no Clash API (selection = \"first\"?); nothing to sample"
@@ -81,7 +83,7 @@ let
# Overridable to rehearse a run against a scratch copy; the units never set them.
state_dir=''${AUTOPROXY_STATE_DIR:-${lib.escapeShellArg autoProxyStateDir}}
export PROBE_EXITS_FILE=''${PROBE_EXITS_FILE:-/run/proxy-suite-socks/probe-exits.json}
export PROBE_EXITS_FILE=''${PROBE_EXITS_FILE:-${runtimeDir}/proxy-suite-socks/probe-exits.json}
index=$PROBE_EXITS_FILE
state="$state_dir/state.json"
requests="$state_dir/requests"
@@ -273,7 +275,7 @@ let
last=$(jq -r '.lastRun // 0' "$state")
if [ "$last" -gt 0 ]; then since="@$last"; else since="-${apCfg.interval}"; fi
dialled=$(
journalctl -u proxy-suite-inbounds --since "$since" --no-pager -o cat 2>/dev/null |
${journalctl} -u proxy-suite-inbounds --since "$since" --no-pager -o cat 2>/dev/null |
sed -n 's/.* accepted tcp:\([a-zA-Z0-9._-]*\):[0-9]*.*/\1/p' |
grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' |
${lib.optionalString (excludePattern != "") "grep -vE '(^|\\.)(${excludePattern})$' |"}
@@ -442,13 +444,13 @@ let
};
in
{
systemd.services.proxy-suite-autoproxy =
services.proxy-suite.internal.services.proxy-suite-autoproxy =
mkUnit "proxy-suite - find the exit that reaches each destination, and remember it" "";
systemd.services.proxy-suite-autoproxy-learn =
services.proxy-suite.internal.services.proxy-suite-autoproxy-learn =
mkUnit "proxy-suite - probe the destinations asked for with proxy-ctl proxy auto learn" " --requests-only";
systemd.services.proxy-suite-autoproxy-sample = lib.mkIf (apCfg.slowBelowKiBps > 0) {
services.proxy-suite.internal.services.proxy-suite-autoproxy-sample = lib.mkIf (apCfg.slowBelowKiBps > 0) {
description = "proxy-suite - watch live transfers for destinations that crawl directly";
after = [ "proxy-suite-socks.service" ];
serviceConfig = {
@@ -458,7 +460,7 @@ in
// stateDirConfig;
};
systemd.timers.proxy-suite-autoproxy-sample = lib.mkIf (apCfg.slowBelowKiBps > 0) {
services.proxy-suite.internal.timers.proxy-suite-autoproxy-sample = lib.mkIf (apCfg.slowBelowKiBps > 0) {
description = "proxy-suite autoProxy transfer sampling";
wantedBy = [ "timers.target" ];
timerConfig = {
@@ -468,7 +470,7 @@ in
};
};
systemd.timers.proxy-suite-autoproxy = {
services.proxy-suite.internal.timers.proxy-suite-autoproxy = {
description = "proxy-suite autoProxy probe schedule";
wantedBy = [ "timers.target" ];
timerConfig = {
@@ -212,10 +212,12 @@ let
});
in
{
# The local proxy, ready for TProxy. A rootless host can neither take transparent
# connections nor mark sockets: there it is the SOCKS/HTTP listener alone.
tproxy = mkConfig {
enableMixed = true;
enableTProxy = true;
useOutboundRoutingMark = true;
enableTProxy = constants.privileged;
useOutboundRoutingMark = constants.privileged;
xrayDnsBridgePort = xrayDnsBridgePorts.socks;
};
@@ -264,10 +264,11 @@ in
# shape out of the same backend primitives.
inherit mkDnsServer;
# As sing-box's: without TProxy and marks on a rootless host.
tproxy = mkConfig {
enableMixed = true;
enableTProxy = true;
useOutboundRoutingMark = true;
enableTProxy = constants.privileged;
useOutboundRoutingMark = constants.privileged;
};
tun = mkConfig {
+173
View File
@@ -0,0 +1,173 @@
# The host-neutral part of proxy-suite: options, generated configs and scripts, and
# the services to run, declared under services.proxy-suite.internal for a host adapter
# (./hosts) to install.
{
zapret,
nixpkgs,
nfqws2-keenetic,
z2k,
}:
{
config,
lib,
pkgs,
...
}:
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 = [
./options
];
config = lib.mkMerge [
{
# xray and sing-box default to this flake's own nixpkgs (redirect it
# with inputs.nixpkgs.follows), not the system's: a stable release lags
# both by months, and current xray needs a newer Go than stable ships.
_module.args.proxySuiteUpstream =
let
upstream = nixpkgs.legacyPackages.${pkgs.stdenv.hostPlatform.system};
in
{
xray = import ../../pkgs/xray.nix { pkgs = upstream; };
# AWG 3.1 userspace; its kernel module has to match the system's kernel instead.
amneziaWg = import ../../pkgs/amneziawg.nix { pkgs = upstream; };
inherit (upstream) sing-box;
};
}
(lib.mkIf cfg.enable (
let
rules = import ./rules.nix {
inherit
lib
pkgs
cfg
zapret
;
};
configs = import ./config.nix {
inherit
lib
pkgs
cfg
rules
;
};
in
lib.mkMerge [
(import ./service {
inherit
lib
pkgs
packages
cfg
;
inherit (configs)
tproxyFile
tunFile
perAppTunFile
routeModeRulesFile
proxyInboundsFile
proxyInboundsSpecFile
;
inherit (nftr)
nftablesRulesFile
perAppTproxyRulesFile
perAppZapretRulesFile
perAppTunChainFile
ip
nft
;
})
(lib.mkIf
(
cfg.zapret.engine == "zapret-discord-youtube"
&& (cfg.zapret.enable || cfg.perAppRouting.zapret.enable)
)
(
import ./zapret.nix {
inherit
lib
pkgs
cfg
zapret
;
inherit (nftr) perAppZapretRulesFile nft;
}
)
)
(lib.mkIf (cfg.zapret.engine == "zapret2" && (cfg.zapret.enable || cfg.perAppRouting.zapret.enable))
(
import ./zapret2.nix {
inherit
lib
pkgs
cfg
packages
;
inherit (nftr) perAppZapretRulesFile nft;
zapret2Sources = { inherit nfqws2-keenetic z2k; };
}
)
)
(lib.mkIf cfg.tgWsProxy.enable (
(import ./tg-ws-proxy.nix {
inherit
lib
pkgs
packages
cfg
derived
;
}).config
))
# 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
pkgs
cfg
derived
;
}
))
(lib.mkIf cfg.warp.enable (
import ./warp.nix {
inherit
lib
pkgs
cfg
derived
;
}
))
(lib.mkIf cfg.amneziaWg.enable (
import ./amnezia-wg.nix {
inherit
lib
pkgs
cfg
derived
;
}
))
]
))
];
}
+14 -189
View File
@@ -1,195 +1,20 @@
# Factory function – receives the zapret flake and this flake's own nixpkgs,
# returns a NixOS module. This lets consumers add a single flake input and get
# everything transitively.
{
zapret,
nixpkgs,
nfqws2-keenetic,
z2k,
}:
{
config,
options,
lib,
pkgs,
...
}:
# Factory: receives the zapret flake and this flake's own nixpkgs, and returns the
# proxy-suite module for each supported host. Consumers add a single flake input and
# get everything transitively.
inputs:
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; };
# Scripts share one store name per block, and journald names a unit's output
# after its ExecStart basename; tag each unit with its own name instead.
unitsWithOwnSyslogIdentifier = lib.mkOption {
type = lib.types.attrsOf (
lib.types.submodule (
{ name, ... }:
{
config.serviceConfig.SyslogIdentifier = lib.mkIf (lib.hasPrefix "proxy-suite-" name) (
lib.mkDefault (lib.removeSuffix "@" name)
);
}
)
);
core = import ./core.nix inputs;
forHost = adapter: {
imports = [
core
adapter
];
};
in
{
imports = [
./options
];
options.systemd.services = unitsWithOwnSyslogIdentifier;
options.systemd.user.services = unitsWithOwnSyslogIdentifier;
config = lib.mkMerge [
{
# xray and sing-box default to this flake's own nixpkgs (redirect it
# with inputs.nixpkgs.follows), not the system's: a stable release lags
# both by months, and current xray needs a newer Go than stable ships.
_module.args.proxySuiteUpstream =
let
upstream = nixpkgs.legacyPackages.${pkgs.stdenv.hostPlatform.system};
in
{
xray = import ../../pkgs/xray.nix { pkgs = upstream; };
# AWG 3.1 userspace; its kernel module has to match the system's kernel instead.
amneziaWg = import ../../pkgs/amneziawg.nix { pkgs = upstream; };
inherit (upstream) sing-box;
};
}
(lib.mkIf cfg.enable (
let
rules = import ./rules.nix {
inherit
lib
pkgs
cfg
zapret
;
};
configs = import ./config.nix {
inherit
lib
pkgs
cfg
rules
;
};
in
lib.mkMerge [
(import ./service {
inherit
config
options
lib
pkgs
packages
cfg
;
inherit (configs)
tproxyFile
tunFile
perAppTunFile
routeModeRulesFile
proxyInboundsFile
proxyInboundsSpecFile
;
inherit (nftr)
nftablesRulesFile
perAppTproxyRulesFile
perAppZapretRulesFile
perAppTunChainFile
ip
nft
;
})
(lib.mkIf
(
cfg.zapret.engine == "zapret-discord-youtube"
&& (cfg.zapret.enable || cfg.perAppRouting.zapret.enable)
)
(
import ./zapret.nix {
inherit
lib
pkgs
cfg
zapret
;
inherit (nftr) perAppZapretRulesFile nft;
}
)
)
(lib.mkIf (cfg.zapret.engine == "zapret2" && (cfg.zapret.enable || cfg.perAppRouting.zapret.enable))
(
import ./zapret2.nix {
inherit
lib
pkgs
cfg
packages
;
inherit (nftr) perAppZapretRulesFile nft;
zapret2Sources = { inherit nfqws2-keenetic z2k; };
}
)
)
(lib.mkIf cfg.tgWsProxy.enable (
(import ./tg-ws-proxy.nix {
inherit
lib
pkgs
packages
cfg
derived
;
}).config
))
# 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
pkgs
cfg
derived
;
}
))
(lib.mkIf cfg.warp.enable (
import ./warp.nix {
inherit
lib
pkgs
cfg
derived
;
}
))
(lib.mkIf cfg.amneziaWg.enable (
import ./amnezia-wg.nix {
inherit
config
lib
pkgs
cfg
derived
;
}
))
]
))
];
nixos = forHost ./hosts/nixos.nix;
homeManager = forHost ./hosts/home-manager.nix;
systemManager = forHost ./hosts/system-manager.nix;
nixOnDroid = forHost ./hosts/nix-on-droid.nix;
}
+36 -19
View File
@@ -5,6 +5,8 @@
let
proxyCfg = cfg.proxy;
# Host paths: /var/lib/proxy-suite and /run on a system install.
inherit (cfg.host) stateDir runtimeDir;
singBoxCfg = proxyCfg // {
enable = singBoxEnabled;
package = proxyCfg.singBox.package;
@@ -38,20 +40,17 @@ let
# Without a configFile, proxy-suite-warp registers with wgcf into its state dir.
autoRegister = cfg.warp.enable && cfg.warp.configFile == null;
profilePath =
if cfg.warp.configFile != null then
cfg.warp.configFile
else
"/var/lib/proxy-suite/warp/wgcf-profile.conf";
if cfg.warp.configFile != null then cfg.warp.configFile else "${stateDir}/warp/wgcf-profile.conf";
# Loopback SOCKS listener of proxy-suite-warp-tunnel, which the "warp" outbound dials.
tunnelPort = 18538;
# Its "direct-in" listener, which tells a blocked WARP from a dead uplink.
directPort = 18539;
};
warpOutboundTag = "warp";
# The sing-box tunnel; asOutbound = "interface" comes in through the AmneziaWG profile list.
# The sing-box tunnel; "userspace" and "interface" come in through the AmneziaWG profile list.
warpOutboundEnabled = warpCfg.enable && warpCfg.asOutbound == "singBox";
# Two ports per "singBox" AmneziaWG outbound, above the autoProxy prober's own
# Two ports per "singBox" or "userspace" AmneziaWG outbound, above the autoProxy prober's own
# listeners (proxy.autoProxy.probeBasePort, 18540 by default, one per exit):
# both bind loopback, so an overlap leaves whichever unit starts second dead.
awgTunnelBasePort = 18600;
@@ -69,12 +68,15 @@ let
tag = name;
kind = profile.asOutbound;
interface = profile.interfaceName;
# Loopback listeners of a "singBox" tunnel, as warpCfg.tunnelPort/directPort.
# Loopback listeners of a "singBox" or "userspace" tunnel, as warpCfg.tunnelPort/directPort
# (only sing-box listens on directPort).
tunnelPort = awgTunnelBasePort + 2 * index;
directPort = awgTunnelBasePort + 1 + 2 * index;
}
) (builtins.filter (name: awgProfiles.${name}.asOutbound != null) (builtins.attrNames awgProfiles));
awgInterfaceOutbounds = builtins.filter (ob: ob.kind == "interface") awgOutbounds;
# Profiles run behind a loopback SOCKS hop rather than an interface.
awgTunnelOutbounds = builtins.filter (ob: ob.kind != "interface") awgOutbounds;
proxyInboundsCfg = cfg.inbounds;
proxyInboundsEnabled = proxyInboundsCfg.enable;
@@ -202,19 +204,33 @@ let
userControlAllows =
scope:
userControlEnabled && (userControlCfg.scopes == [ ] || builtins.elem scope userControlCfg.scopes);
managerFlag = lib.optionalString (cfg.host.serviceManager == "systemd-user") " --user";
constants = {
inherit stateDir runtimeDir;
inherit (cfg.host) privileged serviceManager;
# Daemons (sing-box, XRay, the WARP tunnel, OpenSSH, tg-ws-proxy, wgcf) run as this
# user. Its group is not the userControl group: backend configs hold credentials. Start
# scripts still read secrets and program routing as root, then exec the daemon through
# runAsServiceUser with only the capabilities it needs.
# On a rootless host everything already runs as the user: no service user, and
# nothing to hand files over to it.
serviceUser = "proxy-suite-daemon";
# Shell text that only matters when the services run as root.
ifPrivileged = lib.optionalString cfg.host.privileged;
# The commands scripts manage units and read their logs with: the units live in the
# user's manager on a home-manager host, and in proxy-suitectl on nix-on-droid.
systemctl = cfg.host.systemctl + managerFlag;
journalctl = cfg.host.journalctl + managerFlag;
runAsServiceUser =
pkgs: caps:
let
keep = lib.concatMapStrings (cap: ",+${cap}") caps;
in
"${pkgs.util-linux}/bin/setpriv --reuid=proxy-suite-daemon --regid=proxy-suite-daemon --clear-groups"
+ " --inh-caps=-all${keep} --ambient-caps=-all${keep} --bounding-set=-all${keep} --no-new-privs --";
lib.optionalString cfg.host.privileged (
"${pkgs.util-linux}/bin/setpriv --reuid=proxy-suite-daemon --regid=proxy-suite-daemon --clear-groups"
+ " --inh-caps=-all${keep} --ambient-caps=-all${keep} --bounding-set=-all${keep} --no-new-privs --"
);
# The same for a unit that needs no root at all; "+" ExecStartPre/ExecStopPost
# commands still run privileged.
unprivilegedServiceConfig =
@@ -222,7 +238,7 @@ let
let
systemdCaps = map (cap: "CAP_${lib.toUpper cap}") caps;
in
{
lib.optionalAttrs cfg.host.privileged {
User = "proxy-suite-daemon";
Group = "proxy-suite-daemon";
AmbientCapabilities = systemdCaps;
@@ -244,8 +260,8 @@ let
"net_raw"
];
zapret2StateDir = "/var/lib/proxy-suite/zapret2";
zapret2CutoffDir = "/var/lib/proxy-suite/zapret2/cutoff";
zapret2StateDir = "${stateDir}/zapret2";
zapret2CutoffDir = "${stateDir}/zapret2/cutoff";
# Conntrack bit on the cutoff probe's own connections, which zapret2 leaves alone.
zapret2CutoffProbeCtMark = 33554432; # 0x2000000
@@ -257,23 +273,23 @@ let
zapret2 = 300;
};
autoProxyStateDir = "/var/lib/proxy-suite/autoproxy";
autoProxyStateDir = "${stateDir}/autoproxy";
# Runtime outbound control. The spool dirs hold one proxy URL per file and are
# group-writable when userControl is on, so proxy-ctl edits them without sudo;
# the pin outlives a reboot, unlike the per-boot route-mode override.
pinnedOutboundFile = "/var/lib/proxy-suite/pinned-outbound";
runtimeOutboundsDir = "/var/lib/proxy-suite/outbounds.d";
runtimeSubscriptionsDir = "/var/lib/proxy-suite/subscriptions.d";
pinnedOutboundFile = "${stateDir}/pinned-outbound";
runtimeOutboundsDir = "${stateDir}/outbounds.d";
runtimeSubscriptionsDir = "${stateDir}/subscriptions.d";
# Written by every backend start script; proxy-ctl reads the socks copy.
outboundInventoryFile = "/run/proxy-suite-socks/outbounds.json";
outboundInventoryFile = "${runtimeDir}/proxy-suite-socks/outbounds.json";
inboundStatsApiPort = 18536;
# sing-box's fake IP caches, one per TUN config; the start script hands it to the backend.
fakeIpCacheDir = "/var/lib/proxy-suite/fakeip";
fakeIpCacheDir = "${stateDir}/fakeip";
# Loopback listener behind the selector `proxy-ctl proxy outbounds test` switches.
outboundTestPort = 18537;
inboundStatsFile = "/var/lib/proxy-suite/inbound-stats.json";
inboundStatsFile = "${stateDir}/inbound-stats.json";
# sing-box DNS server resolving through an "interface" AmneziaWG outbound.
awgDnsServerTag = tag: "awg-dns-${tag}";
@@ -360,6 +376,7 @@ in
awgGlobalProfiles
awgOutbounds
awgInterfaceOutbounds
awgTunnelOutbounds
proxyInboundsCfg
proxyInboundsEnabled
proxyInbounds
+30
View File
@@ -0,0 +1,30 @@
# Shared by the adapters whose host runs NixOS's own systemd unit options (NixOS,
# system-manager).
{ lib }:
rec {
# Only what the core set: an internal option's default would add a definition of its
# own. Definitions are forwarded rather than values, so priorities nested inside them
# (mkDefault in a unit, say) still meet the rest of the host's.
forwardWith =
wrap: option:
lib.mkIf (option.highestPrio < (lib.mkOptionDefault null).priority) (
lib.mkMerge (map wrap option.definitions)
);
forward = forwardWith lib.id;
# Scripts share one store name per block, and journald names a unit's output
# after its ExecStart basename; tag each unit with its own name instead.
unitsWithOwnSyslogIdentifier = lib.mkOption {
type = lib.types.attrsOf (
lib.types.submodule (
{ name, ... }:
{
config.serviceConfig.SyslogIdentifier = lib.mkIf (lib.hasPrefix "proxy-suite-" name) (
lib.mkDefault (lib.removeSuffix "@" name)
);
}
)
);
};
}
@@ -0,0 +1,64 @@
# home-manager: the services run rootless in the user's systemd manager, rendered into
# home-manager's INI form by ./user-units.nix.
{
config,
options,
lib,
pkgs,
...
}:
let
cfg = config.services.proxy-suite;
host = cfg.host;
internal = cfg.internal;
inherit
(import ./user-units.nix {
inherit lib pkgs;
inherit (host) runtimeDir;
stateDir = dirOf host.stateDir;
})
toService
toTimer
toPath
;
enabled = lib.filterAttrs (_: unit: unit.enable);
in
{
config = lib.mkMerge [
{
services.proxy-suite.host = {
kind = "home-manager";
privileged = false;
serviceManager = "systemd-user";
stateDir = lib.mkDefault "${config.xdg.stateHome}/proxy-suite";
# A literal path the scripts and proxy-ctl can share: the user's runtime
# directory is only known once the manager runs. Point it at /run/user/UID to
# have it cleared on reboot.
runtimeDir = lib.mkDefault "${config.xdg.cacheHome}/proxy-suite/run";
};
}
(lib.mkIf cfg.enable (
lib.mkMerge [
{
systemd.user.services = lib.mapAttrs toService (
enabled (internal.services // internal.userServices)
);
systemd.user.timers = lib.mapAttrs toTimer (enabled internal.timers);
systemd.user.paths = lib.mapAttrs toPath (enabled internal.paths);
home.packages = lib.mkMerge [
(lib.mkBefore internal.earlyPackages)
internal.packages
];
}
(lib.optionalAttrs (options.systemd.user ? tmpfiles) {
systemd.user.tmpfiles.rules = internal.tmpfiles;
})
]
))
];
}
+123
View File
@@ -0,0 +1,123 @@
# nix-on-droid: no systemd and no root. The units run under proxy-suitectl, a small
# supervisor that reads them, rendered as for a user manager, from a manifest the
# activation links into place; proxy-ctl and the scripts talk to it in systemctl's words.
{
config,
lib,
pkgs,
...
}:
let
cfg = config.services.proxy-suite;
host = cfg.host;
internal = cfg.internal;
home = config.user.home;
inherit
(import ./user-units.nix {
inherit lib pkgs;
inherit (host) runtimeDir;
stateDir = dirOf host.stateDir;
hostPath = "${home}/.nix-profile/bin";
})
toService
toTimer
toPath
;
enabled = lib.filterAttrs (_: unit: unit.enable);
supervisorDir = "${host.runtimeDir}/proxy-suite-supervisor";
# Outside the store, so proxy-suitectl stays the same from one generation to the next.
manifestLink = "${host.stateDir}/supervisor/manifest.json";
manifest = pkgs.writeText "proxy-suite-units.json" (
builtins.toJSON {
services = lib.mapAttrs toService (enabled (internal.services // internal.userServices));
timers = lib.mapAttrs toTimer (enabled internal.timers);
paths = lib.mapAttrs toPath (enabled internal.paths);
inherit (internal) tmpfiles;
}
);
suitectl = import ../../../pkgs/proxy-suite-supervisor.nix { inherit lib pkgs; } {
inherit supervisorDir;
manifest = manifestLink;
inherit (host) runtimeDir;
stateDir = dirOf host.stateDir;
};
suitectlBin = "${suitectl}/bin/proxy-suitectl";
# Once per session tree: nested shells find it exported.
sessionStart = ''
if [ -z "''${__PROXY_SUITE_SESSION:-}" ]; then
export __PROXY_SUITE_SESSION=1
( ${suitectlBin} ensure >/dev/null 2>&1 & )
fi
'';
in
{
options.services.proxy-suite.nixOnDroid.startWithSession = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Start the services when a Nix-on-Droid shell opens, if they are not running yet.
Android offers the app no boot hook, so without this they only start on
`nix-on-droid switch` or `proxy-suitectl boot`. Android may still stop them in
the background: keep the app's wake lock on and exempt it from battery optimisation.
'';
};
config = lib.mkMerge [
{
services.proxy-suite.host = {
kind = "nix-on-droid";
privileged = false;
serviceManager = "supervisor";
stateDir = lib.mkDefault "${home}/.local/state/proxy-suite";
runtimeDir = lib.mkDefault "${home}/.cache/proxy-suite/run";
systemctl = suitectlBin;
journalctl = "${suitectlBin} journal";
enableIPv6 = true;
# Android's kernel, resolver and firewall are not the app's to change.
kernelPackages = null;
firewallPackage = null;
resolvconfPackage = null;
};
}
(lib.mkIf cfg.enable {
assertions = [
{
assertion = !cfg.gui.enable;
message = "proxy-suite: the GUI needs a desktop session, which a nix-on-droid host does not have; use proxy-ctl or proxy-tui";
}
];
environment.packages = internal.earlyPackages ++ internal.packages ++ [ suitectl ];
build.activationAfter.proxySuite = ''
$DRY_RUN_CMD mkdir -p ${lib.escapeShellArg (dirOf manifestLink)}
$DRY_RUN_CMD ln -sfn ${manifest} ${lib.escapeShellArg manifestLink}
# Starts the supervisor, or restarts what changed under a running one.
if ! $DRY_RUN_CMD ${suitectlBin} boot; then
warnEcho "proxy-suite: some units did not start; see proxy-ctl status"
fi
'';
environment.etc = lib.mkIf cfg.nixOnDroid.startWithSession {
"profile".text = lib.mkAfter sessionStart;
"zshenv".text = lib.mkAfter sessionStart;
};
})
(lib.mkIf (!cfg.enable) {
# Disabled since the last generation: nothing should keep running.
build.activationAfter.proxySuite = ''
if [ -S ${lib.escapeShellArg "${supervisorDir}/control.sock"} ]; then
$DRY_RUN_CMD ${suitectlBin} shutdown || true
fi
'';
})
];
}
+75
View File
@@ -0,0 +1,75 @@
# NixOS: the core's declarations become NixOS settings as they are.
{
config,
options,
lib,
...
}:
let
cfg = config.services.proxy-suite;
internal = options.services.proxy-suite.internal;
inherit (import ./common.nix { inherit lib; })
forwardWith
forward
unitsWithOwnSyslogIdentifier
;
in
{
options.systemd.services = unitsWithOwnSyslogIdentifier;
options.systemd.user.services = unitsWithOwnSyslogIdentifier;
config = lib.mkMerge [
{
services.proxy-suite.host = {
kind = "nixos";
privileged = true;
serviceManager = "systemd";
inherit (config.networking) enableIPv6;
inherit (config.boot) kernelPackages;
firewallPackage = config.networking.firewall.package;
resolvconfPackage = config.networking.resolvconf.package;
};
}
(lib.mkIf cfg.enable {
systemd.services = forward internal.services;
systemd.user.services = forward internal.userServices;
systemd.timers = forward internal.timers;
systemd.paths = forward internal.paths;
systemd.tmpfiles.rules = forward internal.tmpfiles;
environment.systemPackages = lib.mkMerge [
(forwardWith lib.mkBefore internal.earlyPackages)
(forward internal.packages)
];
users.users = lib.genAttrs cfg.internal.systemUsers (name: {
isSystemUser = true;
group = name;
description = "proxy-suite daemons";
});
users.groups = lib.genAttrs (cfg.internal.systemUsers ++ cfg.internal.groups) (_: { });
security.polkit.enable = lib.mkIf cfg.internal.polkit.enable true;
security.polkit.extraConfig = forwardWith lib.mkAfter internal.polkit.rules;
networking.nftables.enable = lib.mkIf cfg.internal.nftables (lib.mkDefault true);
networking.firewall = {
allowedTCPPorts = forward internal.firewall.allowedTCPPorts;
allowedUDPPorts = forward internal.firewall.allowedUDPPorts;
extraReversePathFilterRules = forward internal.firewall.extraReversePathFilterRules;
};
boot.extraModulePackages = forward internal.kernelModulePackages;
})
# Off by default since nixpkgs 26.11, and always there before, where the option does
# not exist.
(lib.optionalAttrs (options.security.polkit ? enablePkexecWrapper) {
security.polkit.enablePkexecWrapper = lib.mkIf (
cfg.enable && cfg.internal.polkit.pkexecWrapper
) true;
})
];
}
@@ -0,0 +1,118 @@
# system-manager (numtide/system-manager): root services on another distribution. Its
# systemd options are NixOS's own, so units are forwarded as on NixOS; what it lacks
# (user units, polkit, nftables, the firewall, kernel modules) is written to /etc or
# left to the host.
{
config,
options,
lib,
pkgs,
...
}:
let
cfg = config.services.proxy-suite;
internal = options.services.proxy-suite.internal;
inherit (import ./common.nix { inherit lib; })
forwardWith
forward
unitsWithOwnSyslogIdentifier
;
# For the user manager each session runs: units go to /etc/systemd/user, which it reads
# alongside the distribution's own.
userUnits = import ./user-units.nix {
inherit lib pkgs;
runtimeDir = "%t";
stateDir = "%S";
# The GUI escalates through the distribution's setuid pkexec.
hostPath = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
};
toINI = lib.generators.toINI { listsAsDuplicateKeys = true; };
userServiceFiles = lib.concatMapAttrs (
name: unit:
let
fileName = "${name}.service";
rendered = userUnits.toService name unit;
file = pkgs.writeText fileName (toINI rendered);
link = target: lib.nameValuePair "systemd/user/${target}/${fileName}" { source = file; };
in
{
"systemd/user/${fileName}".source = file;
}
// lib.listToAttrs (
map (target: link "${target}.wants") (rendered.Install.WantedBy or [ ])
++ map (target: link "${target}.requires") (rendered.Install.RequiredBy or [ ])
)
) (lib.filterAttrs (_: unit: unit.enable) cfg.internal.userServices);
# awg-quick pushes DNS through resolvconf: resolvectl stands in for it where
# systemd-resolved owns resolv.conf, openresolv everywhere else.
resolvconf = pkgs.writeShellScriptBin "resolvconf" ''
if [ -d /run/systemd/resolve ]; then
exec -a resolvconf ${pkgs.systemd}/bin/resolvectl "$@"
fi
exec ${pkgs.openresolv}/bin/resolvconf "$@"
'';
in
{
options.systemd.services = unitsWithOwnSyslogIdentifier;
config = lib.mkMerge [
{
services.proxy-suite.host = {
kind = "system-manager";
privileged = true;
serviceManager = "systemd";
inherit (config.networking) enableIPv6;
# The host's kernel is not Nix's to extend: AmneziaWG runs in userspace.
kernelPackages = null;
firewallPackage = pkgs.nftables;
resolvconfPackage = resolvconf;
};
}
(lib.mkIf cfg.enable {
assertions = [
{
assertion = cfg.internal.kernelModulePackages == [ ];
message = "proxy-suite: system-manager cannot load kernel modules from Nix; leave amneziaWg.kernelModulePackage at null";
}
];
systemd.services = forward internal.services;
systemd.timers = forward internal.timers;
systemd.paths = forward internal.paths;
systemd.tmpfiles.rules = forward internal.tmpfiles;
environment.systemPackages = lib.mkMerge [
(forwardWith lib.mkBefore internal.earlyPackages)
(forward internal.packages)
];
environment.etc = lib.mkMerge [
userServiceFiles
# Read by polkit 0.106 and later; the distribution runs the daemon. The rules
# go through the host's setuid pkexec: nothing here needs a wrapper.
(lib.mkIf cfg.internal.polkit.enable {
"polkit-1/rules.d/50-proxy-suite.rules".text = cfg.internal.polkit.rules;
})
];
users.users = lib.genAttrs cfg.internal.systemUsers (name: {
isSystemUser = true;
group = name;
description = "proxy-suite daemons";
});
users.groups = lib.genAttrs (cfg.internal.systemUsers ++ cfg.internal.groups) (_: { });
# Only reported: system-manager leaves the host firewall alone. The routing modes
# load their own nftables tables, and the distribution's loose reverse-path filter
# already lets AmneziaWG replies in.
networking.firewall = {
allowedTCPPorts = forward internal.firewall.allowedTCPPorts;
allowedUDPPorts = forward internal.firewall.allowedUDPPorts;
};
})
];
}
+217
View File
@@ -0,0 +1,217 @@
# Renders the core's systemd-shaped units into a user manager's INI sections
# ({ Unit, Service, Install }), with what only NixOS's unit options provide spelled out:
# the directories systemd would create and the PATH NixOS would set. runtimeDir and
# stateDir are the bases of RuntimeDirectory= and StateDirectory= (specifiers allowed);
# hostPath ends every PATH, for the host's own setuid binaries.
{
lib,
pkgs,
runtimeDir,
stateDir,
hostPath ? null,
}:
let
# The user manager has none of the system targets; the default target stands in for
# multi-user.target.
systemTargets = [
"network.target"
"network-online.target"
"nss-lookup.target"
"sysinit.target"
];
userTargets = {
"multi-user.target" = "default.target";
};
toUserUnits =
units: lib.unique (map (unit: userTargets.${unit} or unit) (lib.subtractLists systemTargets units));
# Identity, capabilities and sandboxing: a user manager can apply them only partly
# (and ProtectHome would hide the state directory), and the core sets none of them
# for a rootless host itself.
systemOnlyKeys = [
"User"
"Group"
"DynamicUser"
"SupplementaryGroups"
"AmbientCapabilities"
"CapabilityBoundingSet"
"PrivateTmp"
"PrivateDevices"
"ProtectSystem"
"ProtectHome"
"ProtectClock"
"ProtectHostname"
"ProtectKernelModules"
"ProtectKernelLogs"
"ProtectKernelTunables"
"ProtectControlGroups"
"RestrictSUIDSGID"
"RestrictRealtime"
"LockPersonality"
"ReadWritePaths"
"ReadOnlyPaths"
# Rendered below against runtimeDir and stateDir: a user manager resolves them
# against XDG directories, which need not be where the core looks.
"RuntimeDirectory"
"RuntimeDirectoryMode"
"StateDirectory"
"StateDirectoryMode"
];
# home-manager takes plain values only.
iniValue =
value:
if lib.isList value then
map iniValue value
else if lib.isBool value || lib.isInt value then
value
else
toString value;
iniSection = section: lib.mapAttrs (_: iniValue) (lib.filterAttrs (_: v: v != null) section);
# As NixOS's service `path` default.
defaultPath = with pkgs; [
coreutils
findutils
gnugrep
gnused
systemd
];
# As NixOS: "@" is not allowed in a store path name.
jobScript =
name: text: pkgs.writeShellScript (lib.replaceStrings [ "@" ] [ "_" ] name) "set -e\n${text}";
dirsScript = pkgs.writeShellScript "proxy-suite-dirs" ''
while (( $# )); do
${pkgs.coreutils}/bin/install -d -m "$1" -- "$2"
shift 2
done
'';
removeDirsScript = pkgs.writeShellScript "proxy-suite-remove-dirs" ''
${pkgs.coreutils}/bin/rm -rf -- "$@"
'';
directories =
serviceConfig: key: base:
map (dir: {
path = "${base}/${dir}";
mode = serviceConfig."${key}Mode" or "0755";
}) (lib.concatMap (lib.splitString " ") (lib.toList (serviceConfig.${key} or [ ])));
unitSection =
unit:
iniSection (
{
Description = unit.description;
}
// lib.filterAttrs (_: v: v != [ ]) {
After = toUserUnits unit.after;
Before = toUserUnits unit.before;
Wants = toUserUnits unit.wants;
Requires = toUserUnits unit.requires;
BindsTo = toUserUnits unit.bindsTo;
PartOf = toUserUnits unit.partOf;
Conflicts = toUserUnits unit.conflicts;
}
// lib.optionalAttrs (unit.startLimitIntervalSec != null) {
StartLimitIntervalSec = unit.startLimitIntervalSec;
}
// unit.unitConfig
);
installSection =
unit:
lib.filterAttrs (_: v: v != [ ]) {
WantedBy = toUserUnits unit.wantedBy;
RequiredBy = toUserUnits unit.requiredBy;
};
withInstall =
unit: attrs:
attrs
// lib.optionalAttrs (installSection unit != { }) {
Install = installSection unit;
};
toService =
name: unit:
let
sc = unit.serviceConfig;
runtimeDirs = directories sc "RuntimeDirectory" runtimeDir;
stateDirs = directories sc "StateDirectory" stateDir;
dirs = runtimeDirs ++ stateDirs;
joinPaths = ds: lib.concatMapStringsSep ":" (d: d.path) ds;
# Paths go on the command line, where systemd expands specifiers such as %t.
commandLine =
script: args: lib.concatStringsSep " " ([ "${script}" ] ++ map (arg: ''"${arg}"'') args);
makeDirs = commandLine dirsScript (
lib.concatMap (d: [
d.mode
d.path
]) dirs
);
removeRuntimeDirs = commandLine removeDirsScript (map (d: d.path) runtimeDirs);
path = unit.path ++ defaultPath;
environment = {
PATH = lib.concatStringsSep ":" (
[
(lib.makeBinPath path)
(lib.makeSearchPathOutput "bin" "sbin" path)
]
++ lib.optional (hostPath != null) hostPath
);
}
// lib.optionalAttrs (runtimeDirs != [ ]) { RUNTIME_DIRECTORY = joinPaths runtimeDirs; }
// lib.optionalAttrs (stateDirs != [ ]) { STATE_DIRECTORY = joinPaths stateDirs; }
// lib.filterAttrs (_: v: v != null) unit.environment;
optionalScript = suffix: text: lib.optional (text != "") (jobScript "${name}-${suffix}" text);
in
withInstall unit {
Unit = unitSection unit;
Service = iniSection (
builtins.removeAttrs sc systemOnlyKeys
// lib.optionalAttrs (sc ? WorkingDirectory && !lib.hasPrefix "-" sc.WorkingDirectory) {
# Created by the first ExecStartPre, which already runs in it.
WorkingDirectory = "-${sc.WorkingDirectory}";
}
// lib.filterAttrs (_: v: v != [ ]) {
Environment =
lib.mapAttrsToList (n: v: builtins.toJSON "${n}=${toString v}") environment
++ lib.toList (sc.Environment or [ ]);
ExecStartPre =
lib.optional (dirs != [ ]) makeDirs
++ optionalScript "pre-start" unit.preStart
++ lib.toList (sc.ExecStartPre or [ ]);
ExecStart = optionalScript "start" unit.script ++ lib.toList (sc.ExecStart or [ ]);
ExecStartPost = optionalScript "post-start" unit.postStart ++ lib.toList (sc.ExecStartPost or [ ]);
ExecStop = optionalScript "pre-stop" unit.preStop ++ lib.toList (sc.ExecStop or [ ]);
ExecStopPost =
optionalScript "post-stop" unit.postStop
++ lib.toList (sc.ExecStopPost or [ ])
++ lib.optional (runtimeDirs != [ ]) removeRuntimeDirs;
}
);
};
toTimer =
_: unit:
withInstall unit {
Unit = unitSection unit;
Timer = iniSection unit.timerConfig;
};
toPath =
_: unit:
withInstall unit {
Unit = unitSection unit;
Path = iniSection unit.pathConfig;
};
in
{
inherit toService toTimer toPath;
}
+11 -1
View File
@@ -30,9 +30,19 @@ in
description = "AWG 3.1 userspace implementation used when the kernel interface is unavailable.";
};
wireproxyPackage = mkOption {
type = types.package;
default = awgPackages.wireproxy;
description = "wireproxy build with AWG 3.1 and FwMark, which runs profiles with asOutbound = \"userspace\".";
};
kernelModulePackage = mkOption {
type = types.nullOr types.package;
default = awgPackages.kernelModule config.boot.kernelPackages;
default =
let
kernelPackages = config.services.proxy-suite.host.kernelPackages;
in
if kernelPackages == null then null else awgPackages.kernelModule kernelPackages;
description = "AWG 3.1 kernel module package. Set null to use userspace-only fallback.";
};
+1
View File
@@ -21,6 +21,7 @@
./tray.nix
./tui.nix
./user-control.nix
./host.nix
];
options.services.proxy-suite.enable = lib.mkEnableOption "proxy-suite";
+74
View File
@@ -0,0 +1,74 @@
# What the host adapter (modules/proxy-suite/hosts/*.nix) tells the core about the
# host, and what the core hands back for the adapter to turn into host settings.
# Nothing here is user-facing.
{ lib, pkgs, ... }:
let
inherit (lib) mkOption types;
unitType = import ./types/unit.nix { inherit lib; };
internalOption =
type: default:
mkOption {
inherit type default;
internal = true;
visible = false;
};
units = internalOption (types.attrsOf unitType) { };
in
{
options.services.proxy-suite.host = {
kind = internalOption (types.enum [
"nixos"
"system-manager"
"home-manager"
"nix-on-droid"
]) "nixos";
# Whether the services run as root and may program routing, firewalls and interfaces.
privileged = internalOption types.bool true;
# Persistent state; units name the proxy-suite subdirectory of their host's state dir.
stateDir = internalOption types.str "/var/lib/proxy-suite";
# Parent of the per-unit runtime directories (proxy-suite-socks, …).
runtimeDir = internalOption types.str "/run";
# Which manager runs the units: proxy-ctl and the control scripts talk to it.
serviceManager = internalOption (types.enum [
"systemd"
"systemd-user"
"supervisor"
]) "systemd";
# The commands that manage the units and show their logs, without a --user of their own.
systemctl = internalOption types.str "${pkgs.systemd}/bin/systemctl";
journalctl = internalOption types.str "journalctl";
# Host facts a few option defaults read.
enableIPv6 = internalOption types.bool true;
kernelPackages = internalOption (types.nullOr types.raw) null;
firewallPackage = internalOption (types.nullOr types.package) null;
resolvconfPackage = internalOption (types.nullOr types.package) null;
};
options.services.proxy-suite.internal = {
# systemd-shaped unit declarations; the adapter installs or converts them.
services = units;
userServices = units;
timers = units;
paths = units;
tmpfiles = internalOption (types.listOf types.str) [ ];
packages = internalOption (types.listOf types.package) [ ];
# Ahead of the host's own packages (zapret's binaries shadow same-named ones).
earlyPackages = internalOption (types.listOf types.package) [ ];
systemUsers = internalOption (types.listOf types.str) [ ];
groups = internalOption (types.listOf types.str) [ ];
polkit = {
enable = internalOption types.bool false;
pkexecWrapper = internalOption types.bool false;
rules = internalOption types.lines "";
};
nftables = internalOption types.bool false;
firewall = {
allowedTCPPorts = internalOption (types.listOf types.port) [ ];
allowedUDPPorts = internalOption (types.listOf types.port) [ ];
extraReversePathFilterRules = internalOption types.lines "";
};
kernelModulePackages = internalOption (types.listOf types.package) [ ];
};
}
+1 -1
View File
@@ -49,7 +49,7 @@ in
ipv6 = mkOption {
type = types.bool;
default = config.networking.enableIPv6;
default = config.services.proxy-suite.host.enableIPv6;
defaultText = literalExpression "config.networking.enableIPv6";
description = ''
Carry IPv6 in the transparent modes: TProxy through a second listener on ::1, the TUNs
@@ -273,6 +273,7 @@ let
type = types.nullOr (
types.enum [
"singBox"
"userspace"
"interface"
]
);
@@ -283,6 +284,11 @@ let
`proxy-ctl awg`. Requires proxy.enable.
- "singBox": a WireGuard endpoint in its own sing-box process, reached as a loopback SOCKS
hop. sing-box speaks plain WireGuard: AmneziaWG obfuscation is dropped with a warning.
- "userspace": the same hop served by wireproxy on AmneziaWG's userspace implementation, so
obfuscation works. It needs no interface or root: the only AmneziaWG mode on
home-manager and nix-on-droid. A declared or profile ListenPort is used as is. An
Endpoint hostname resolves through the system resolver: give an address where that
resolver cannot reach the name.
- "interface": the AmneziaWG interface comes up without routes (Table = off), and the
outbound binds to it, so obfuscation works. With the sing-box backend its DNS goes
through the interface too (proxy.dns.remote); XRay resolves as usual.
@@ -0,0 +1,84 @@
# The subset of NixOS's systemd unit options proxy-suite declares units with, merged
# the same way, so hosts without NixOS's systemd module can read them back.
{ lib }:
let
inherit (lib) mkOption types;
# As nixos/lib/systemd-lib.nix: lists concatenate, anything else must agree.
unitOption = lib.mkOptionType {
name = "systemd option";
merge =
loc: defs:
let
defs' = lib.filterOverrides defs;
in
if lib.any (def: lib.isList def.value) defs' then
lib.concatMap (def: lib.toList def.value) defs'
else
lib.mergeEqualOption loc defs';
};
list = mkOption {
type = types.listOf types.str;
default = [ ];
};
lines = mkOption {
type = types.lines;
default = "";
};
section = mkOption {
type = types.attrsOf unitOption;
default = { };
};
in
types.submodule {
options = {
enable = mkOption {
type = types.bool;
default = true;
};
description = mkOption {
type = types.str;
default = "";
};
after = list;
before = list;
wants = list;
requires = list;
bindsTo = list;
partOf = list;
conflicts = list;
wantedBy = list;
requiredBy = list;
path = mkOption {
type = types.listOf (types.either types.package types.str);
default = [ ];
};
environment = mkOption {
type = types.attrsOf (
types.nullOr (
types.oneOf [
types.str
types.path
types.package
]
)
);
default = { };
};
script = lines;
preStart = lines;
postStart = lines;
preStop = lines;
postStop = lines;
startLimitIntervalSec = mkOption {
type = types.nullOr types.int;
default = null;
};
unitConfig = section;
serviceConfig = section;
timerConfig = section;
pathConfig = section;
};
}
+3
View File
@@ -39,6 +39,7 @@ in
type = types.nullOr (
types.enum [
"singBox"
"userspace"
"interface"
]
);
@@ -49,6 +50,8 @@ in
endpoint on 127.0.0.1:18538, as the proxy-suite-daemon user. The tunnel starts again on a
new source port when WARP does not answer within 15 seconds of a start, or misses three
probes later on, unless the uplink itself is down.
- "userspace": an AmneziaWG profile named "warp" with asOutbound = "userspace", which honours
the AmneziaWG lines of the profile without an interface or root. Requires amneziaWg.enable.
- "interface": an AmneziaWG profile named "warp" with asOutbound = "interface", which honours
the AmneziaWG lines of the profile. Requires amneziaWg.enable.
'';
+64 -4
View File
@@ -71,7 +71,66 @@ let
++ lib.concatMap (ob: [
ob.tunnelPort
ob.directPort
]) (builtins.filter (ob: ob.kind == "singBox") derived.awgOutbounds);
]) derived.awgTunnelOutbounds;
# A rootless host (home-manager, nix-on-droid) runs everything as the user: nothing
# that programs routing, firewalls or interfaces, and no privileged ports.
rootless = !constants.privileged;
hostKind = cfg.host.kind;
rootlessForbids =
used: feature:
mkAssertion (
!(rootless && used)
) "proxy-suite: ${feature} needs root, which services on a ${hostKind} host do not have";
rootlessPorts =
lib.optional proxyEnabled {
name = "proxy.listener.port";
port = proxyCfg.listener.port;
}
++ lib.optional tgWsProxyCfg.enable {
name = "tgWsProxy.listener.port";
port = tgWsProxyCfg.listener.port;
}
++ lib.optional cfg.sshProxy.enable {
name = "sshProxy.listener.port";
port = cfg.sshProxy.listener.port;
}
++ lib.optionals cfg.inbounds.enable (
lib.mapAttrsToList (name: listener: {
name = "inbounds.listeners.${name}.port";
inherit (listener) port;
}) cfg.inbounds.listeners
);
rootlessAssertions = [
(rootlessForbids (proxyEnabled && globalTun.enable) "proxy.tun")
(rootlessForbids (proxyEnabled && globalTproxy.enable) "proxy.tproxy")
(rootlessForbids (perAppRoutingCfg.enable && perAppRoutingTun.enable) "perAppRouting.tun")
(rootlessForbids (perAppRoutingCfg.enable && perAppRoutingTproxy.enable) "perAppRouting.tproxy")
(rootlessForbids perAppZapretCfg.enable "perAppRouting.zapret")
(rootlessForbids zapretCfg.enable "zapret")
(rootlessForbids (
derived.awgGlobalProfiles != { } || derived.awgInterfaceOutbounds != [ ]
) ''an AmneziaWG interface (a global profile, or asOutbound = "interface"; use "userspace")'')
(mkAssertion (!(rootless && cfg.userControl.enable))
"proxy-suite: userControl has nothing to grant on a ${hostKind} host, whose services already belong to the user"
)
(mkAssertion
(
!(
rootless
&& cfg.sshProxy.enable
&& cfg.sshProxy.serviceUser != null
&& cfg.sshProxy.serviceUser != constants.serviceUser
)
)
"proxy-suite: sshProxy.serviceUser cannot switch users on a ${hostKind} host; leave it at its default"
)
]
++ map (
item:
mkAssertion (!(rootless && item.port < 1024))
"proxy-suite: ${item.name} = ${toString item.port} is a privileged port, which services on a ${hostKind} host cannot bind; pick one from 1024 up"
) rootlessPorts;
featureAssertions = [
# Declaring no outbound at all is legal: they can be added at runtime with
@@ -108,8 +167,8 @@ let
"proxy-suite: warp.asOutbound requires proxy.enable = true"
)
(requireEnabled (
cfg.warp.enable && cfg.warp.asOutbound == "interface"
) cfg.amneziaWg.enable ''proxy-suite: warp.asOutbound = "interface" requires amneziaWg.enable = true'')
cfg.warp.enable && builtins.elem cfg.warp.asOutbound [ "userspace" "interface" ]
) cfg.amneziaWg.enable ''proxy-suite: warp.asOutbound = "${toString cfg.warp.asOutbound}" requires amneziaWg.enable = true'')
(requireEnabled (
cfg.warp.enable && cfg.warp.asAmneziaWg
) cfg.amneziaWg.enable "proxy-suite: warp.asAmneziaWg requires amneziaWg.enable = true")
@@ -730,7 +789,8 @@ let
}
];
in
featureAssertions
rootlessAssertions
++ featureAssertions
++ perAppRoutingAssertions
++ localProxyAuthAssertions
++ secretAssertions
@@ -12,10 +12,10 @@
mkSubscriptionFetchBlock,
runtimeSubscriptionsFetchBlock,
jq,
systemctl,
}:
let
systemctl = "${pkgs.systemd}/bin/systemctl";
curl = "${pkgs.curl}/bin/curl";
restartActiveBlock = lib.concatMapStrings (svc: ''
+3
View File
@@ -63,6 +63,9 @@
if proxyInboundsSubscriptionsBaseUrl == null then "" else proxyInboundsSubscriptionsBaseUrl;
autoProxyEnabled = if proxyCfg.autoProxy.enable then "1" else "0";
autoProxyStateDir = constants.autoProxyStateDir;
inherit (constants) stateDir runtimeDir serviceManager;
privileged = if constants.privileged then "1" else "0";
supervisorCtl = if constants.serviceManager == "supervisor" then constants.systemctl else "";
singBox = "${singBoxCfg.package}/bin/sing-box";
localProxyUrl = "http://${
if proxyCfg.listener.address == "0.0.0.0" then "127.0.0.1" else proxyCfg.listener.address
+92 -98
View File
@@ -1,7 +1,6 @@
# Assembles proxy-suite systemd services from the sub-modules.
# Assembles proxy-suite services from the sub-modules, as host-neutral declarations
# under services.proxy-suite.internal (see ../hosts).
{
config,
options,
lib,
pkgs,
packages,
@@ -130,60 +129,51 @@ let
import ../autoproxy.nix {
inherit lib pkgs cfg;
inherit (control) proxyCtl;
inherit (constants) autoProxyStateDir;
inherit (constants) autoProxyStateDir runtimeDir journalctl;
inherit userControlAllows;
}
);
in
lib.mkMerge [
autoProxyUnits
# The GUI's pkexec needs its setuid wrapper, off by default since nixpkgs 26.11 (and
# always there before, where the option does not exist).
(lib.optionalAttrs (options.security.polkit ? enablePkexecWrapper) {
security.polkit.enablePkexecWrapper = lib.mkIf (cfg.enable && cfg.gui.enable) true;
})
{
# See constants.serviceUser.
users.users.${constants.serviceUser} = {
isSystemUser = true;
group = constants.serviceUser;
description = "proxy-suite daemons";
};
users.groups.${constants.serviceUser} = { };
}
{
environment.systemPackages = [
control.proxyCtl
]
++ lib.optional cfg.tui.enable control.proxyCtl.tui
++ lib.optional cfg.gui.enable control.proxyCtl.gui;
services.proxy-suite.internal = {
# The GUI's pkexec needs its setuid wrapper.
polkit.pkexecWrapper = lib.mkIf (cfg.enable && cfg.gui.enable) true;
# See constants.serviceUser.
systemUsers = [ constants.serviceUser ];
# nftables must be on for transparent routing backends. Global TUN uses
# SingBox auto_redirect programs an `inet sing-box` nftables table.
networking.nftables.enable = lib.mkIf (
globalTun.enable
|| globalTproxy.enable
|| perAppRoutingTun.enable
|| perAppRoutingTproxy.enable
|| perAppZapretEnabled
) (lib.mkDefault true);
packages = [
control.proxyCtl
]
++ lib.optional cfg.tui.enable control.proxyCtl.tui
++ lib.optional cfg.gui.enable control.proxyCtl.gui;
# Inbound listeners are reached from outside, so their ports have to be open.
networking.firewall = lib.mkIf (proxyInboundsEnabled && cfg.inbounds.openFirewall) {
allowedTCPPorts = proxyInboundFirewallPorts;
allowedUDPPorts = proxyInboundFirewallUdpPorts;
};
# nftables must be on for transparent routing backends. Global TUN uses
# SingBox auto_redirect programs an `inet sing-box` nftables table.
nftables = lib.mkIf (
globalTun.enable
|| globalTproxy.enable
|| perAppRoutingTun.enable
|| perAppRoutingTproxy.enable
|| perAppZapretEnabled
) true;
users.groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) {
"${userControlCfg.group}" = { };
};
# Inbound listeners are reached from outside, so their ports have to be open.
firewall = lib.mkIf (proxyInboundsEnabled && cfg.inbounds.openFirewall) {
allowedTCPPorts = proxyInboundFirewallPorts;
allowedUDPPorts = proxyInboundFirewallUdpPorts;
};
security.polkit.enable = lib.mkIf (cfg.enable && (userControlEnabled || cfg.gui.enable)) true;
# The GUI's "Retry as Root" and root toggle run proxy-ctl through pkexec: one
# admin password then covers the next few minutes, as sudo's does in the TUI.
security.polkit.extraConfig = lib.mkMerge [
(lib.mkIf (cfg.enable && cfg.gui.enable) (
lib.mkAfter ''
groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) [
userControlCfg.group
];
polkit.enable = lib.mkIf (cfg.enable && (userControlEnabled || cfg.gui.enable)) true;
# The GUI's "Retry as Root" and root toggle run proxy-ctl through pkexec: one
# admin password then covers the next few minutes, as sudo's does in the TUI.
polkit.rules = lib.mkMerge [
(lib.mkIf (cfg.enable && cfg.gui.enable) ''
polkit.addRule(function(action, subject) {
if (action.id === "org.freedesktop.policykit.exec" &&
action.lookup("program") === "${control.proxyCtl}/bin/proxy-ctl") {
@@ -191,10 +181,8 @@ lib.mkMerge [
}
return null;
});
''
))
(lib.mkIf (cfg.enable && userControlEnabled) (
lib.mkAfter ''
'')
(lib.mkIf (cfg.enable && userControlEnabled) ''
polkit.addRule(function(action, subject) {
if (!subject.isInGroup("${userControlCfg.group}")) {
return null;
@@ -209,50 +197,60 @@ lib.mkMerge [
return null;
});
''
))
];
'')
];
# Spool dirs for outbounds and subscriptions added at runtime. Setgid so the
# files proxy-ctl drops here inherit the group; without the outbounds scope
# only root writes them. tmpfiles rather than the start scripts, so the group can add an
# outbound before the proxy has ever run.
systemd.tmpfiles.rules = lib.mkIf (cfg.enable && proxyEnabled) (
map
(
dir:
"d ${dir} ${
if userControlAllows "outbounds" then "2770 root ${userControlCfg.group}" else "0700 root root"
} -"
)
[
constants.runtimeOutboundsDir
constants.runtimeSubscriptionsDir
]
);
# Spool dirs for outbounds and subscriptions added at runtime. Setgid so the
# files proxy-ctl drops here inherit the group; without the outbounds scope
# only root writes them. tmpfiles rather than the start scripts, so the group can add an
# outbound before the proxy has ever run.
tmpfiles = lib.mkIf (cfg.enable && proxyEnabled) (
map
(
dir:
"d ${dir} ${
if userControlAllows "outbounds" then
"2770 root ${userControlCfg.group}"
else if constants.privileged then
"0700 root root"
else
"0700 - -"
} -"
)
[
constants.runtimeOutboundsDir
constants.runtimeSubscriptionsDir
]
);
systemd.user.services = lib.mkMerge [
(mkNamedUnits userServiceEntries)
(lib.mkIf (cfg.gui.enable && cfg.gui.autostart) {
# Starts hidden in the tray with every graphical session.
proxy-suite-gui = {
description = "Proxy Suite GUI (tray icon)";
wantedBy = [ "graphical-session.target" ];
partOf = [ "graphical-session.target" ];
after = [ "graphical-session.target" ];
unitConfig.ConditionEnvironment = [
"|WAYLAND_DISPLAY"
"|DISPLAY"
];
serviceConfig = {
ExecStart = "${control.proxyCtl.gui}/bin/proxy-suite-gui --hidden";
Restart = "on-failure";
RestartSec = 3;
userServices = lib.mkMerge [
(mkNamedUnits userServiceEntries)
(lib.mkIf (cfg.gui.enable && cfg.gui.autostart) {
# Starts hidden in the tray with every graphical session.
proxy-suite-gui = {
description = "Proxy Suite GUI (tray icon)";
wantedBy = [ "graphical-session.target" ];
partOf = [ "graphical-session.target" ];
after = [ "graphical-session.target" ];
unitConfig.ConditionEnvironment = [
"|WAYLAND_DISPLAY"
"|DISPLAY"
];
serviceConfig = {
ExecStart = "${control.proxyCtl.gui}/bin/proxy-suite-gui --hidden";
Restart = "on-failure";
RestartSec = 3;
};
};
};
})
];
})
];
services = mkNamedUnits systemServiceEntries;
timers = mkNamedUnits timerEntries;
};
}
{
assertions = import ../service-assertions.nix {
inherit lib cfg derived;
tgWsProxyCfg = cfg.tgWsProxy;
@@ -276,10 +274,6 @@ lib.mkMerge [
"proxy-suite: no outbounds or subscriptions are declared; the proxy will not start"
+ " until one is added with `proxy-ctl proxy outbounds add`"
);
systemd.services = mkNamedUnits systemServiceEntries;
systemd.timers = mkNamedUnits timerEntries;
}
# A certificate or key XRay cannot read is copied in at start (proxy-inbounds-scripts.nix),
@@ -298,20 +292,20 @@ lib.mkMerge [
);
in
lib.mkIf (cfg.enable && proxyInboundsEnabled && certFiles != [ ]) {
systemd.paths.proxy-suite-inbounds-certs = {
services.proxy-suite.internal.paths.proxy-suite-inbounds-certs = {
description = "proxy-suite - watch the inbounds' TLS certificates for renewals";
wantedBy = [ "paths.target" ];
pathConfig.PathChanged = certFiles;
};
systemd.services.proxy-suite-inbounds-certs = {
services.proxy-suite.internal.services.proxy-suite-inbounds-certs = {
description = "proxy-suite - restart the inbounds onto a renewed certificate";
serviceConfig.Type = "oneshot";
script = ''
# XRay reloads the files it reads itself; only copies go stale.
[ -d /run/proxy-suite-inbounds/tls ] || exit 0
[ -d ${constants.runtimeDir}/proxy-suite-inbounds/tls ] || exit 0
# A renewal writes the chain and the key one after the other.
sleep 10
${pkgs.systemd}/bin/systemctl try-restart proxy-suite-inbounds.service
${constants.systemctl} try-restart proxy-suite-inbounds.service
'';
};
}
@@ -32,6 +32,7 @@ let
perAppZapretSliceName = "proxy-suite-per-app-zapret.slice";
profiles = import ./per-app-routing/profiles.nix {
inherit (constants) runtimeDir;
inherit
lib
pkgs
@@ -7,6 +7,7 @@
perAppRoutingTun,
perAppRoutingTproxy,
perAppZapretCfg,
runtimeDir,
}:
let
@@ -55,7 +56,7 @@ let
proxychainsConfigFile =
if localProxyAuthEnabled then
"/run/proxy-suite-socks/proxychains.conf"
"${runtimeDir}/proxy-suite-socks/proxychains.conf"
else
pkgs.writeText "proxy-suite-per-app" ''
strict_chain
@@ -24,7 +24,7 @@
}:
let
runtimeDir = "/run/proxy-suite-inbounds";
runtimeDir = "${constants.runtimeDir}/proxy-suite-inbounds";
linksFile = "${runtimeDir}/links.json";
subscriptionsFile = "${runtimeDir}/subscriptions.json";
subsCfg = proxyInboundsCfg.subscriptions;
@@ -108,8 +108,9 @@ let
printf '%s' "$body" > "$SUB_DIR.new/$token"
done
chmod -R u=rwX,g=rX,o= "$SUB_DIR.new"
${pkgs.coreutils}/bin/chgrp -R ${lib.escapeShellArg subsCfg.group} "$SUB_DIR.new" ||
echo "proxy-suite: group ${subsCfg.group} cannot be given the subscriptions; they stay root-only" >&2
${constants.ifPrivileged ''
${pkgs.coreutils}/bin/chgrp -R ${lib.escapeShellArg subsCfg.group} "$SUB_DIR.new" ||
echo "proxy-suite: group ${subsCfg.group} cannot be given the subscriptions; they stay root-only" >&2''}
rm -rf "$SUB_DIR"
mv "$SUB_DIR.new" "$SUB_DIR"
${jq} -c '[.subscriptions[] | {user, token}]' <<< "$RENDERED" > "${subscriptionsFile}"
@@ -163,10 +164,10 @@ let
while IFS= read -r source; do
[ -n "$source" ] || continue
if ! ${runXray} ${pkgs.coreutils}/bin/test -r "$source"; then
[ -d "$CERT_DIR" ] || install -d -m 0750 -g ${constants.serviceUser} "$CERT_DIR"
[ -d "$CERT_DIR" ] || install -d -m 0750 ${constants.ifPrivileged "-g ${constants.serviceUser} "}"$CERT_DIR"
index=$((index + 1))
copy="$CERT_DIR/$index-$(basename "$source")"
install -m 0640 -g ${constants.serviceUser} "$source" "$copy"
install -m 0640 ${constants.ifPrivileged "-g ${constants.serviceUser} "}"$source" "$copy"
echo "proxy-suite: ${constants.serviceUser} cannot read $source; XRay uses a copy until the next restart" >&2
${jq} --arg from "$source" --arg to "$copy" '
(.inbounds[].streamSettings.tlsSettings.certificates[]? | (.certificateFile, .keyFile)
@@ -187,7 +188,7 @@ let
''
else
''
${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$RUNTIME_DIR/config.json.tmp"
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$RUNTIME_DIR/config.json.tmp"''}
chmod 640 "$RUNTIME_DIR/config.json.tmp"
''
}
@@ -25,13 +25,13 @@ lib.optionalString hybridEnabled ''
local batch
batch=$(${jq} -c \
--argjson base "$XRAY_SIDECAR_NEXT_PORT" \
--argjson mark ${toString xraySidecarRoutingMark} '
--argjson mark ${if xraySidecarRoutingMark == null then "null" else toString xraySidecarRoutingMark} '
to_entries | map(
($base + .key) as $port
| ("proxy-suite-xray-" + ($port | tostring)) as $auth
| .value.tag as $tag
| {outbound: (.value
| .streamSettings.sockopt.mark = $mark
${lib.optionalString (xraySidecarRoutingMark != null) "| .streamSettings.sockopt.mark = $mark"}
| .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")),
inbound: {tag: ($tag + "-inbound"), listen: "127.0.0.1", port: $port, protocol: "socks",
settings: {auth: "password", udp: true, accounts: [{user: $auth, pass: $auth}]}},
@@ -160,7 +160,9 @@ let
}
_proxy_suite_parse_xray_url() {
${parse "--backend xray" " --routing-mark ${toString xraySidecarRoutingMark}"}
${parse "--backend xray" (
lib.optionalString (xraySidecarRoutingMark != null) " --routing-mark ${toString xraySidecarRoutingMark}"
)}
}
''
else
@@ -331,7 +333,7 @@ let
# sing-box opens the key as ${constants.serviceUser}, which cannot read a key in a
# home directory: it gets a copy only root and its group can read.
SSH_IDENTITY="$RUNTIME_DIR/ssh-identity"
install -m 0640 -g ${constants.serviceUser} ${lib.escapeShellArg sshProxyCfg.identityFile} "$SSH_IDENTITY"
install -m 0640 ${constants.ifPrivileged "-g ${constants.serviceUser} "}${lib.escapeShellArg sshProxyCfg.identityFile} "$SSH_IDENTITY"
OB_JSON=$(${jq} --arg key "$SSH_IDENTITY" '.private_key_path = $key' <<< "$OB_JSON")
''}
${hostKeyFileBlock}
@@ -357,7 +359,7 @@ let
_proxy_suite_record_tag_source ${lib.escapeShellArg outbound.tag} ${source}
'';
# WARP and "singBox" AmneziaWG profiles run in a tunnel unit, which restarts them when the
# WARP and "singBox" or "userspace" AmneziaWG profiles run in a tunnel unit, which restarts them when the
# handshake stops being answered. Every backend reaches it as a loopback SOCKS hop.
mkTunnelOutboundBlock =
unit: source: tag: port:
@@ -10,6 +10,7 @@
hybridEnabled,
mainBackend,
backend,
stateDir,
runtimeSubscriptionsDir,
jq,
python3,
@@ -21,7 +22,7 @@
let
subscriptionBackend = if hybridEnabled then "hybrid" else mainBackend;
subscriptionBackendArg = "--backend ${subscriptionBackend}";
subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/${backend}";
subscriptionCacheDir = "${stateDir}/subscriptions/${backend}";
mkSubscriptionUrlSource =
sub:
+6 -4
View File
@@ -56,7 +56,7 @@ let
pkgs.writeText "proxy-suite-core" localProxyAuth.password
else
null;
routeModeStateFile = "/run/proxy-suite/route-mode";
routeModeStateFile = "${constants.runtimeDir}/proxy-suite/route-mode";
inherit (constants)
pinnedOutboundFile
runtimeOutboundsDir
@@ -64,9 +64,9 @@ let
outboundInventoryFile
;
clashApi = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}";
xrayLoglevelFile = "/run/proxy-suite/xray-loglevel";
runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf";
xraySidecarRoutingMark = globalTproxy.proxyMark;
xrayLoglevelFile = "${constants.runtimeDir}/proxy-suite/xray-loglevel";
runtimeProxychainsConfig = "${constants.runtimeDir}/proxy-suite-socks/proxychains.conf";
xraySidecarRoutingMark = if constants.privileged then globalTproxy.proxyMark else null;
routingMarkJq =
routingMark:
@@ -78,6 +78,7 @@ let
" | .routing_mark = ${toString routingMark}";
subscriptionScripts = import ./script-blocks/subscriptions.nix {
inherit (constants) stateDir;
inherit
lib
pkgs
@@ -220,6 +221,7 @@ let
proxyInboundsSubscriptionsFile = proxyInboundsScripts.subscriptionsFile;
controlScripts = import ./control-scripts.nix {
inherit (constants) systemctl;
inherit
lib
pkgs
+10 -9
View File
@@ -42,7 +42,7 @@ let
autoProxyRender = import ../autoproxy-render.nix {
inherit pkgs;
inherit (constants) serviceUser;
inherit (constants) serviceUser ifPrivileged;
};
runBackend = constants.runAsServiceUser pkgs constants.backendCaps;
userControlGroup = lib.escapeShellArg userControlCfg.group;
@@ -136,7 +136,7 @@ let
${lib.escapeShellArg localProxyAuth.username} \
"$LOCAL_PROXY_PASSWORD"
} > "${runtimeProxychainsConfig}"
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${runtimeProxychainsConfig}"
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${runtimeProxychainsConfig}"''}
chmod 640 "${runtimeProxychainsConfig}"
'';
@@ -258,7 +258,7 @@ let
${
if userControlCfg.enable || localProxyAuthEnabled then
''
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$ENDPOINTS_TMP"
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$ENDPOINTS_TMP"''}
chmod 640 "$ENDPOINTS_TMP"
''
else
@@ -358,14 +358,14 @@ let
''
else
''
${chgrp} ${constants.serviceUser} "$backend_config"
${constants.ifPrivileged ''${chgrp} ${constants.serviceUser} "$backend_config"''}
chmod 640 "$backend_config"
''
}
done
FAKE_IP_CACHE=$(${jq} -r '.experimental.cache_file.path? // empty' "$RUNTIME_DIR/config.json")
if [ -n "$FAKE_IP_CACHE" ]; then
install -d -m 0700 -o ${constants.serviceUser} -g ${constants.serviceUser} "$(dirname "$FAKE_IP_CACHE")"
install -d -m 0700 ${constants.ifPrivileged "-o ${constants.serviceUser} -g ${constants.serviceUser} "}"$(dirname "$FAKE_IP_CACHE")"
fi
${
@@ -409,9 +409,10 @@ let
'';
startSocks = mkStartScript {
runtimeDir = "/run/proxy-suite-socks";
runtimeDir = "${constants.runtimeDir}/proxy-suite-socks";
configFile = tproxyFile;
routingMark = globalTproxy.proxyMark;
# Rootless hosts cannot set SO_MARK, and have no TProxy rules to escape anyway.
routingMark = if constants.privileged then globalTproxy.proxyMark else null;
enableLocalProxyAuth = localProxyAuthEnabled;
# TProxy takes the system resolver's own upstream queries too, so a proxy server's name
# has to resolve inside XRay, as under the TUN.
@@ -425,7 +426,7 @@ let
};
startTun = mkStartScript {
runtimeDir = "/run/proxy-suite-tun";
runtimeDir = "${constants.runtimeDir}/proxy-suite-tun";
configFile = tunFile;
routingMark = if pureXrayEnabled then globalTproxy.proxyMark else null;
xrayTunDnsRuntime = pureXrayEnabled;
@@ -436,7 +437,7 @@ let
};
startPerAppTun = mkStartScript {
runtimeDir = "/run/proxy-suite-per-app-tun";
runtimeDir = "${constants.runtimeDir}/proxy-suite-per-app-tun";
configFile = perAppTunFile;
routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null;
xrayTunDnsRuntime = pureXrayEnabled;
+1 -1
View File
@@ -40,7 +40,7 @@ let
'';
in
{
systemd.services.proxy-suite-ssh-proxy = {
services.proxy-suite.internal.services.proxy-suite-ssh-proxy = {
description = "SSH dynamic SOCKS5 proxy";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
+1 -1
View File
@@ -88,7 +88,7 @@ in
# For the checks: ExecStartPre/ExecStopPost carry these behind "+".
inherit bypassUpScript bypassDownScript;
config.systemd.services.proxy-suite-tg-ws-proxy = {
config.services.proxy-suite.internal.services.proxy-suite-tg-ws-proxy = {
description = "Telegram MTProto WebSocket proxy";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
+9 -5
View File
@@ -86,16 +86,20 @@ let
'';
inherit (import ./wg-tunnel.nix { inherit lib pkgs cfg derived; }) mkTunnel;
viaAmneziaWg = builtins.elem w.asOutbound [
"userspace"
"interface"
];
in
{
services.proxy-suite.amneziaWg.profiles = lib.mkIf (w.asAmneziaWg || w.asOutbound == "interface") {
services.proxy-suite.amneziaWg.profiles = lib.mkIf (w.asAmneziaWg || viaAmneziaWg) {
warp = {
configFile = w.profilePath;
asOutbound = lib.mkIf (w.asOutbound == "interface") "interface";
asOutbound = lib.mkIf viaAmneziaWg w.asOutbound;
};
};
systemd.services = lib.mkMerge [
services.proxy-suite.internal.services = lib.mkMerge [
(lib.mkIf (w.asOutbound == "singBox") {
proxy-suite-warp-tunnel = mkTunnel {
description = "proxy-suite - Cloudflare WARP tunnel behind the warp outbound";
@@ -129,7 +133,7 @@ in
RestartSec = 30;
StateDirectory = "proxy-suite/warp";
StateDirectoryMode = "0700";
WorkingDirectory = "/var/lib/proxy-suite/warp";
WorkingDirectory = "${derived.constants.stateDir}/warp";
UMask = "0077";
LoadCredential = lib.optional (cfg.proxy.enable && withProxyAuth) "proxy-password:${passwordSource}";
ExecStart = registerScript;
@@ -137,7 +141,7 @@ in
};
# Only pulls registration in: a simple unit gives the profile no ordering guarantee.
proxy-suite-awg-warp = lib.mkIf (w.asAmneziaWg || w.asOutbound == "interface") {
proxy-suite-awg-warp = lib.mkIf (w.asAmneziaWg || viaAmneziaWg) {
wants = [ "proxy-suite-warp.service" ];
};
})
+89 -38
View File
@@ -1,6 +1,6 @@
# A WireGuard profile as a sing-box endpoint in its own process, behind a loopback SOCKS
# listener the proxy outbound dials: the WARP tunnel and AmneziaWG profiles with
# asOutbound = "singBox".
# A WireGuard profile in its own process, behind a loopback SOCKS listener the proxy
# outbound dials: the WARP tunnel and AmneziaWG profiles with asOutbound = "singBox"
# (a sing-box endpoint) or "userspace" (wireproxy, which keeps AmneziaWG's obfuscation).
{
lib,
pkgs,
@@ -9,7 +9,7 @@
}:
let
inherit (derived.constants) serviceUser runAsServiceUser;
inherit (derived.constants) serviceUser runAsServiceUser ifPrivileged;
scriptsDir = builtins.path {
name = "proxy-suite-scripts";
path = ../../scripts;
@@ -24,74 +24,75 @@ let
server = upstream.address;
server_port = upstream.port;
};
mark = cfg.proxy.tproxy.proxyMark;
# Past TUN and TProxy. Setting a mark takes CAP_NET_ADMIN, which a rootless host lacks,
# and has nothing to capture its traffic anyway.
mark = if cfg.host.privileged then cfg.proxy.tproxy.proxyMark else null;
probe = port: url: ''
${pkgs.curl}/bin/curl -s --noproxy "" -x socks5h://127.0.0.1:${toString port} -m "$timeout" \
-o /dev/null ${url}'';
# Some lines drop a share of fresh handshakes for good, and sing-box retries on the same
# source port forever. A new process binds a new port, so the watchdog exits when the peer
# stops answering and systemd starts the tunnel again. A healthy handshake takes a fraction
# of a second, so a start gets 15 seconds; a running tunnel gets three misses. The
# "direct-in" listener reaches Cloudflare through the uplink with the backend's mark (not
# urlTest.url, which is picked to be blocked here): when that fails too, the tunnel could
# not work from a new port either.
# Some lines drop a share of fresh handshakes for good, and both engines retry on the
# same source port forever. A new process binds a new port, so the watchdog exits when
# the peer stops answering and the service manager starts the tunnel again. A healthy
# handshake takes a fraction of a second, so a start gets 15 seconds; a running tunnel
# gets three misses. sing-box's "direct-in" listener reaches Cloudflare through the uplink
# with the backend's mark (not urlTest.url, which is picked to be blocked here): when that
# fails too, the tunnel could not work from a new port either. wireproxy has no such
# listener (directPort = null), so it is restarted either way.
mkWatchdog =
{
tag,
command,
tunnelPort,
directPort,
}:
pkgs.writeShellScript "proxy-suite-wg-tunnel" ''
set -uo pipefail
${cfg.proxy.singBox.package}/bin/sing-box run -c "$RUNTIME_DIRECTORY/config.json" &
singbox=$!
${command} &
tunnel=$!
healthy=0
failures=0
uplink_down=0
since=0
while sleep $(( healthy ? 10 : 2 )); do
kill -0 "$singbox" 2>/dev/null || { wait "$singbox"; exit 1; }
kill -0 "$tunnel" 2>/dev/null || { wait "$tunnel"; exit 1; }
timeout=$(( healthy ? 10 : 4 ))
if ${probe tunnelPort "-f ${lib.escapeShellArg cfg.proxy.urlTest.url}"}; then
(( healthy )) || echo "proxy-suite: ${tag} is answering" >&2
healthy=1 failures=0 uplink_down=0
continue
fi
if ! ${probe directPort "https://1.1.1.1/cdn-cgi/trace"}; then
(( uplink_down )) || echo "proxy-suite: the uplink is down; waiting for it before judging ${tag}" >&2
uplink_down=1 failures=0 since=$SECONDS
continue
fi
${lib.optionalString (directPort != null) ''
if ! ${probe directPort "https://1.1.1.1/cdn-cgi/trace"}; then
(( uplink_down )) || echo "proxy-suite: the uplink is down; waiting for it before judging ${tag}" >&2
uplink_down=1 failures=0 since=$SECONDS
continue
fi
''}
uplink_down=0
if (( healthy ? ++failures >= 3 : SECONDS - since >= 15 )); then
echo "proxy-suite: ${tag} is not answering; restarting the tunnel on a new source port" >&2
kill "$singbox"
wait "$singbox"
kill "$tunnel"
wait "$tunnel"
exit 1
fi
done
'';
# `profile` is a shell snippet, run as root, that sets $profile to the WireGuard .conf.
mkTunnel =
markArg = flag: lib.optionalString (mark != null) " ${flag} ${toString mark}";
# The profile is a secret, so it is converted at start, by root on a privileged host,
# rather than baked into the store; the engine itself runs as ${serviceUser}.
singBoxEngine =
{
description,
unit,
tag,
profile,
tunnelPort,
directPort,
}:
let
tunnelScript = pkgs.writeShellScript "proxy-suite-wg-tunnel" ''
set -euo pipefail
${profile}
# The profile is a secret, so it is converted here, as root, rather than baked into
# the store; sing-box itself runs as ${serviceUser}.
endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag ${tag} --routing-mark ${toString mark} < "$profile")
{
convert = ''
endpoint=$(${pkgs.python3}/bin/python3 ${scriptsDir}/warp_outbound.py --tag ${tag}${markArg "--routing-mark"} < "$profile")
(umask 027 && ${pkgs.jq}/bin/jq -n --argjson ep "$endpoint" '{
log: {level: "warn"},
dns: {servers: [
@@ -107,12 +108,62 @@ let
{type: "socks", tag: "socks-in", listen: "127.0.0.1", listen_port: ${toString tunnelPort}},
{type: "socks", tag: "direct-in", listen: "127.0.0.1", listen_port: ${toString directPort}}
],
outbounds: [{type: "direct", tag: "direct", routing_mark: ${toString mark}}],
outbounds: [{type: "direct", tag: "direct"${
lib.optionalString (mark != null) ", routing_mark: ${toString mark}"
}}],
endpoints: [$ep + {domain_resolver: "local"}]
}' > "$RUNTIME_DIRECTORY/config.json")
${pkgs.coreutils}/bin/chgrp ${serviceUser} "$RUNTIME_DIRECTORY" "$RUNTIME_DIRECTORY/config.json"
'';
config = "config.json";
command = ''${cfg.proxy.singBox.package}/bin/sing-box run -c "$RUNTIME_DIRECTORY/config.json"'';
inherit directPort;
};
exec ${runAsServiceUser pkgs [ "net_admin" ]} ${mkWatchdog { inherit tag tunnelPort directPort; }}
wireproxyEngine =
{ tunnelPort, ... }:
{
convert = ''
${pkgs.python3}/bin/python3 ${scriptsDir}/amneziawg_config.py --config "$profile" \
--output "$RUNTIME_DIRECTORY/wireproxy.conf" \
--wireproxy 127.0.0.1:${toString tunnelPort}${markArg "--outbound-fwmark"}
'';
config = "wireproxy.conf";
command = ''${cfg.amneziaWg.wireproxyPackage}/bin/wireproxy -c "$RUNTIME_DIRECTORY/wireproxy.conf"'';
directPort = null;
};
# `profile` is a shell snippet, run as root on a privileged host, that sets $profile to
# the WireGuard .conf. `engine` is "singBox" or "userspace"; only sing-box uses directPort.
mkTunnel =
{
description,
unit,
tag,
profile,
tunnelPort,
directPort ? null,
engine ? "singBox",
}:
let
chosen = (if engine == "userspace" then wireproxyEngine else singBoxEngine) {
inherit tag tunnelPort directPort;
};
tunnelScript = pkgs.writeShellScript "proxy-suite-wg-tunnel" ''
set -euo pipefail
${profile}
${chosen.convert}
${ifPrivileged ''
${pkgs.coreutils}/bin/chgrp ${serviceUser} "$RUNTIME_DIRECTORY" "$RUNTIME_DIRECTORY/${chosen.config}"
${pkgs.coreutils}/bin/chmod g+r "$RUNTIME_DIRECTORY/${chosen.config}"
''}
exec ${runAsServiceUser pkgs [ "net_admin" ]} ${
mkWatchdog {
inherit tag tunnelPort;
inherit (chosen) command directPort;
}
}
'';
in
{
+38 -34
View File
@@ -79,46 +79,50 @@ in
{
assertions = zapretPackages.assertions;
environment.systemPackages = lib.mkBefore (
services.proxy-suite.internal.earlyPackages = (
lib.optionals zapretCfg.enable [ globalZapretPackage ]
++ lib.optionals perAppZapretCfg.enable [ perAppZapretPackage ]
);
systemd.services.proxy-suite-zapret = lib.mkIf zapretCfg.enable (mkOneshotService {
description = "zapret DPI bypass";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = awgServiceNames;
wantedBy = [ "multi-user.target" ];
preStart = zapretCommonPreStart globalZapretPackage;
runtimeDirectory = "proxy-suite-zapret";
execStart = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret start";
execStop = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
extraServiceConfig = {
ExecReload = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret restart";
Environment = globalZapretEnv;
};
});
services.proxy-suite.internal.services.proxy-suite-zapret =
lib.mkIf zapretCfg.enable
(mkOneshotService {
description = "zapret DPI bypass";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = awgServiceNames;
wantedBy = [ "multi-user.target" ];
preStart = zapretCommonPreStart globalZapretPackage;
runtimeDirectory = "proxy-suite-zapret";
execStart = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret start";
execStop = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
extraServiceConfig = {
ExecReload = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret restart";
Environment = globalZapretEnv;
};
});
systemd.services.proxy-suite-per-app-zapret = lib.mkIf perAppZapretCfg.enable (mkOneshotService {
description = "proxy-suite per-app-routing zapret backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
]
++ awgServiceNames;
preStart = zapretCommonPreStart perAppZapretPackage;
runtimeDirectory = "proxy-suite-per-app-zapret";
execStart = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret start";
execStop = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
execStartPre = "${perAppZapretMarkUpScript}";
execStopPost = "${perAppZapretMarkDownScript}";
extraServiceConfig.Environment = perAppZapretEnv;
});
services.proxy-suite.internal.services.proxy-suite-per-app-zapret =
lib.mkIf perAppZapretCfg.enable
(mkOneshotService {
description = "proxy-suite per-app-routing zapret backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
]
++ awgServiceNames;
preStart = zapretCommonPreStart perAppZapretPackage;
runtimeDirectory = "proxy-suite-per-app-zapret";
execStart = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret start";
execStop = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
execStartPre = "${perAppZapretMarkUpScript}";
execStopPost = "${perAppZapretMarkDownScript}";
extraServiceConfig.Environment = perAppZapretEnv;
});
systemd.services.proxy-suite-zapret-vm-exempt =
services.proxy-suite.internal.services.proxy-suite-zapret-vm-exempt =
lib.mkIf (zapretCfg.enable && zapretCfg.cidrExemption.enable)
(
mkOneshotService {
+49 -43
View File
@@ -103,50 +103,56 @@ let
'';
in
{
environment.systemPackages = lib.mkBefore [ runtime.package ];
services.proxy-suite.internal.earlyPackages = [ runtime.package ];
systemd.services.proxy-suite-zapret2-cutoff = lib.mkIf cutoffCfg.enable cutoff.service;
systemd.timers.proxy-suite-zapret2-cutoff = lib.mkIf cutoffCfg.enable cutoff.timer;
services.proxy-suite.internal.services.proxy-suite-zapret2-cutoff =
lib.mkIf cutoffCfg.enable cutoff.service;
services.proxy-suite.internal.timers.proxy-suite-zapret2-cutoff =
lib.mkIf cutoffCfg.enable cutoff.timer;
systemd.services.proxy-suite-zapret = lib.mkIf zapretCfg.enable (mkOneshotService {
description = "zapret2 DPI bypass";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = awgServiceNames;
wantedBy = [ "multi-user.target" ];
preStart = mkPreStart;
runtimeDirectory = "proxy-suite-zapret";
stateDirectory = "proxy-suite";
execStart = "${runtime.initScript} start";
execStop = "${runtime.initScript} stop";
extraServiceConfig = {
ExecReload = "${runtime.initScript} restart";
Environment = runtime.mkEnv {
runtime = globalRuntime;
pidDir = "/run/proxy-suite-zapret";
};
};
});
services.proxy-suite.internal.services.proxy-suite-zapret =
lib.mkIf zapretCfg.enable
(mkOneshotService {
description = "zapret2 DPI bypass";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = awgServiceNames;
wantedBy = [ "multi-user.target" ];
preStart = mkPreStart;
runtimeDirectory = "proxy-suite-zapret";
stateDirectory = "proxy-suite";
execStart = "${runtime.initScript} start";
execStop = "${runtime.initScript} stop";
extraServiceConfig = {
ExecReload = "${runtime.initScript} restart";
Environment = runtime.mkEnv {
runtime = globalRuntime;
pidDir = "/run/proxy-suite-zapret";
};
};
});
systemd.services.proxy-suite-per-app-zapret = lib.mkIf perAppZapretCfg.enable (mkOneshotService {
description = "proxy-suite per-app-routing zapret2 backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
]
++ awgServiceNames;
preStart = mkPreStart;
runtimeDirectory = "proxy-suite-per-app-zapret";
stateDirectory = "proxy-suite";
execStart = "${runtime.initScript} start";
execStop = "${runtime.initScript} stop";
execStartPre = "${perAppZapretMarkUpScript}";
execStopPost = "${perAppZapretMarkDownScript}";
extraServiceConfig.Environment = runtime.mkEnv {
runtime = perAppRuntime;
pidDir = "/run/proxy-suite-per-app-zapret";
};
});
services.proxy-suite.internal.services.proxy-suite-per-app-zapret =
lib.mkIf perAppZapretCfg.enable
(mkOneshotService {
description = "proxy-suite per-app-routing zapret2 backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
]
++ awgServiceNames;
preStart = mkPreStart;
runtimeDirectory = "proxy-suite-per-app-zapret";
stateDirectory = "proxy-suite";
execStart = "${runtime.initScript} start";
execStop = "${runtime.initScript} stop";
execStartPre = "${perAppZapretMarkUpScript}";
execStopPost = "${perAppZapretMarkDownScript}";
extraServiceConfig.Environment = runtime.mkEnv {
runtime = perAppRuntime;
pidDir = "/run/proxy-suite-per-app-zapret";
};
});
}
+10
View File
@@ -2,6 +2,7 @@
system,
nixpkgs,
proxySuiteModule,
proxySuiteModules,
generatedOptionsDoc,
generatedReadmeDoc,
zapret,
@@ -44,11 +45,20 @@ let
amneziaWgRuntime = import ./checks/amnezia-wg-runtime.nix {
inherit pkgs nixpkgs proxySuiteModule;
};
hostChecks = import ./checks/hosts.nix {
inherit pkgs proxySuiteModules;
inherit (checkLib) mkTProxyConfig mkInboundsConfig;
};
proxyInboundsRuntime = import ./checks/proxy-inbounds-runtime.nix {
inherit pkgs proxySuiteModule;
};
in
moduleSuiteChecks
// {
proxy-suite-hosts = builtins.seq (builtins.deepSeq hostChecks.assertions true) (
pkgs.writeText "proxy-suite-hosts-check" "ok"
);
}
// pkgs.lib.optionalAttrs (system == "x86_64-linux") {
amneziawg-runtime = amneziaWgRuntime;
proxy-inbounds-runtime = proxyInboundsRuntime;
+224
View File
@@ -0,0 +1,224 @@
# The home-manager, system-manager and nix-on-droid adapters, evaluated against stubs of
# the options each host framework declares: the frameworks stay out of the flake lock,
# and the adapters only use option names they share with these stubs.
{
pkgs,
proxySuiteModules,
mkTProxyConfig,
mkInboundsConfig,
}:
let
lib = pkgs.lib;
inherit (lib) mkOption types;
stub = type: default: mkOption { inherit type default; };
anyAttrs = stub (types.attrsOf types.anything) { };
packages = stub (types.listOf types.package) [ ];
strings = stub (types.listOf types.str) [ ];
etc = stub (types.attrsOf (
types.submodule {
freeformType = types.attrsOf types.anything;
options.text = stub (types.nullOr types.lines) null;
}
)) { };
common = {
options = {
assertions = stub (types.listOf types.unspecified) [ ];
warnings = strings;
};
config._module.args.pkgs = pkgs;
};
hostStubs = {
homeManager.options = {
home.packages = packages;
xdg.stateHome = stub types.str "/home/u/.local/state";
xdg.cacheHome = stub types.str "/home/u/.cache";
systemd.user = {
services = anyAttrs;
timers = anyAttrs;
paths = anyAttrs;
tmpfiles.rules = strings;
};
};
systemManager.options = {
systemd =
let
units = stub (types.attrsOf (types.submodule { freeformType = types.attrsOf types.anything; })) { };
in
{
services = units;
timers = units;
paths = units;
tmpfiles.rules = strings;
};
environment.systemPackages = packages;
environment.etc = etc;
users.users = anyAttrs;
users.groups = anyAttrs;
networking.enableIPv6 = stub types.bool true;
networking.firewall.allowedTCPPorts = stub (types.listOf types.port) [ ];
networking.firewall.allowedUDPPorts = stub (types.listOf types.port) [ ];
};
nixOnDroid.options = {
user.home = stub types.str "/data/data/com.termux.nix/files/home";
environment.packages = packages;
environment.etc = etc;
build.activationAfter = stub (types.attrsOf types.str) { };
};
};
evalHost =
host: modules:
lib.evalModules {
modules = [
common
hostStubs.${host}
proxySuiteModules.${host}
]
++ modules;
};
failedAssertions =
fixture: map (a: a.message) (lib.filter (a: !a.assertion) fixture.config.assertions);
# Through JSON: derivations stop at their store paths, which is where the scripts get built.
forced = value: builtins.isString (builtins.toJSON value);
proxy = {
enable = true;
listener.port = 1080;
outbounds = [
{
tag = "primary";
url = "http://proxy.example.com:8080";
}
];
};
# What a rootless host can run.
rootlessSettings = {
services.proxy-suite = {
enable = true;
inherit proxy;
tgWsProxy = {
enable = true;
secretFile = "/run/secrets/tg";
};
warp = {
enable = true;
asOutbound = "singBox";
};
perAppRouting = {
enable = true;
proxychains.enable = true;
};
inbounds = {
enable = true;
listeners.vless = {
type = "vless";
port = 8443;
users = [ { uuidFile = "/run/secrets/uuid"; } ];
tls.certificateFile = "/c";
tls.keyFile = "/k";
};
};
};
};
homeManager = evalHost "homeManager" [ rootlessSettings ];
hmCfg = homeManager.config;
hmSocksConfig = mkTProxyConfig homeManager;
hmInboundsConfig = mkInboundsConfig homeManager;
systemManager = evalHost "systemManager" [
{
services.proxy-suite = {
enable = true;
proxy = proxy // {
tproxy.enable = true;
};
gui.enable = true;
userControl.enable = true;
};
}
];
smCfg = systemManager.config;
nixOnDroid = evalHost "nixOnDroid" [ rootlessSettings ];
nodCfg = nixOnDroid.config;
rejects =
host: settings: message:
lib.any (lib.hasInfix message) (
failedAssertions (
evalHost host [
rootlessSettings
{ services.proxy-suite = settings; }
]
)
);
in
{
assertions = [
(
assert failedAssertions homeManager == [ ];
assert hmCfg.services.proxy-suite.host.serviceManager == "systemd-user";
assert lib.hasPrefix "/home/u/.local/state/" hmCfg.services.proxy-suite.host.stateDir;
assert hmCfg.systemd.user.services ? proxy-suite-socks;
assert hmCfg.systemd.user.services ? proxy-suite-inbounds;
assert forced hmCfg.systemd.user.services;
# No setpriv on a user manager: nothing to drop to.
assert
!(lib.hasInfix "setpriv" (
toString hmCfg.systemd.user.services.proxy-suite-socks.Service.ExecStart
));
true
)
(
# Rootless, the socks unit only listens: no TProxy inbound, no SO_MARK.
assert lib.any (inbound: inbound.type == "mixed") hmSocksConfig.inbounds;
assert !(lib.any (inbound: inbound.type == "tproxy") hmSocksConfig.inbounds);
assert !(lib.any (outbound: outbound ? routing_mark) hmSocksConfig.outbounds);
assert !(lib.any (outbound: outbound ? routing_mark) (hmInboundsConfig.outbounds or [ ]));
true
)
(
assert failedAssertions systemManager == [ ];
assert smCfg.services.proxy-suite.host.privileged;
assert
smCfg.systemd.services.proxy-suite-socks.serviceConfig.SyslogIdentifier == "proxy-suite-socks";
assert smCfg.systemd.services ? proxy-suite-tproxy;
assert smCfg.environment.etc ? "polkit-1/rules.d/50-proxy-suite.rules";
assert smCfg.environment.etc ? "systemd/user/proxy-suite-gui.service";
assert forced smCfg.systemd.services;
true
)
(
assert failedAssertions nixOnDroid == [ ];
assert nodCfg.services.proxy-suite.host.serviceManager == "supervisor";
assert lib.hasSuffix "/bin/proxy-suitectl" nodCfg.services.proxy-suite.host.systemctl;
assert lib.any (p: lib.getName p == "proxy-suitectl") nodCfg.environment.packages;
assert lib.hasInfix "proxy-suitectl boot" nodCfg.build.activationAfter.proxySuite;
assert lib.hasInfix "proxy-suitectl ensure" nodCfg.environment.etc.profile.text;
assert forced nodCfg.build.activationAfter.proxySuite;
true
)
(
assert rejects "homeManager" { proxy.tproxy.enable = true; } "proxy.tproxy needs root";
assert rejects "homeManager" { proxy.tun.enable = true; } "proxy.tun needs root";
assert rejects "homeManager" { userControl.enable = true; } "userControl has nothing to grant";
assert rejects "nixOnDroid" { zapret.enable = true; } "zapret needs root";
assert rejects "nixOnDroid" {
perAppRouting.zapret.enable = true;
} "perAppRouting.zapret needs root";
assert rejects "nixOnDroid" { gui.enable = true; } "the GUI needs a desktop session";
assert rejects "nixOnDroid" {
inbounds.listeners.vless.port = lib.mkForce 443;
} "inbounds.listeners.vless.port = 443 is a privileged port";
true
)
];
}
+8
View File
@@ -444,6 +444,14 @@
touch "$out"
'';
# proxy-suitectl, nix-on-droid's service manager: real processes restarted, timed and stopped.
proxy-suite-supervisor-unit =
pkgs.runCommand "proxy-suite-supervisor-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; } ''
export PYTHONDONTWRITEBYTECODE=1 HOME="$TMPDIR"
python ${../../pkgs/proxy-ctl}/test_proxy_supervisor.py
touch "$out"
'';
# proxy_export: the running config made portable, and sing-box still accepts it.
proxy-export-unit =
pkgs.runCommand "proxy-suite-proxy-export-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; } ''
+1
View File
@@ -62,6 +62,7 @@ let
mkSubscriptionFetchBlock = _: "";
runtimeSubscriptionsFetchBlock = "";
jq = "${pkgs.jq}/bin/jq";
systemctl = "${pkgs.systemd}/bin/systemctl";
};
routeModeSetterScript = generated.readDerivation routeModeControlScripts.setRouteModeScript;
pinSetterScript = generated.readDerivation routeModeControlScripts.pinOutboundScript;
+1
View File
@@ -9,4 +9,5 @@
patches = (old.patches or [ ]) ++ [ ./patches/amneziawg-go-random-trailers-transport.patch ];
});
kernelModule = kernelPackages: kernelPackages.amneziawg;
wireproxy = import ./wireproxy-awg.nix { inherit pkgs; };
}
+6
View File
@@ -3,6 +3,10 @@ let
amneziaWg = import ./amneziawg.nix { inherit pkgs; };
mkTgWsProxy = _args: import ./tg-ws-proxy.nix { inherit pkgs; };
zapret2 = import ./zapret2.nix { inherit pkgs; };
mkProxySuiteSupervisor = import ./proxy-suite-supervisor.nix {
lib = pkgs.lib;
inherit pkgs;
};
mkProxyCtl = import ./proxy-ctl.nix {
lib = pkgs.lib;
inherit pkgs;
@@ -12,9 +16,11 @@ in
inherit amneziaWg;
amneziawg-tools = amneziaWg.tools;
amneziawg-go = amneziaWg.userspace;
wireproxy-awg = amneziaWg.wireproxy;
inherit
mkTgWsProxy
mkProxyCtl
mkProxySuiteSupervisor
zapret2
;
tg-ws-proxy = mkTgWsProxy { };
+40
View File
@@ -0,0 +1,40 @@
diff --git a/config.go b/config.go
--- a/config.go
+++ b/config.go
@@ -32,6 +32,7 @@
DNS []netip.Addr
MTU int
ListenPort *int
+ FwMark *int
CheckAlive []netip.Addr
CheckAliveInterval int
ASecConfig *ASecConfigType
@@ -296,6 +297,14 @@
device.ListenPort = &value
}
+ if sectionKey, err := section.GetKey("FwMark"); err == nil {
+ value, err := sectionKey.Int()
+ if err != nil {
+ return err
+ }
+ device.FwMark = &value
+ }
+
checkAlive, err := parseNetIP(section, "CheckAlive")
if err != nil {
return err
diff --git a/wireguard.go b/wireguard.go
--- a/wireguard.go
+++ b/wireguard.go
@@ -54,6 +54,10 @@
fmt.Fprintf(&request, "listen_port=%d\n", *conf.ListenPort)
}
+ if conf.FwMark != nil {
+ fmt.Fprintf(&request, "fwmark=%d\n", *conf.FwMark)
+ }
+
if conf.ASecConfig != nil {
aSecConfig := conf.ASecConfig
+13
View File
@@ -37,6 +37,12 @@
autoProxyEnabled,
autoProxyStateDir,
singBox,
stateDir ? "/var/lib/proxy-suite",
runtimeDir ? "/run",
serviceManager ? "systemd",
privileged ? "1",
# proxy-suitectl, when serviceManager is "supervisor".
supervisorCtl ? "",
guiRefreshInterval ? 3,
}:
@@ -79,6 +85,13 @@ let
AUTOPROXY_ENABLED = autoProxyEnabled;
AUTOPROXY_STATE_DIR = autoProxyStateDir;
SING_BOX = singBox;
STATE_DIR = stateDir;
RUNTIME_DIR = runtimeDir;
SERVICE_MANAGER = serviceManager;
PRIVILEGED = privileged;
}
// lib.optionalAttrs (supervisorCtl != "") {
SUPERVISOR_CTL = supervisorCtl;
};
envFlags = lib.concatStringsSep " " (
lib.mapAttrsToList (name: value: "--set ${name} ${lib.escapeShellArg value}") wrapperEnv
+60 -19
View File
@@ -165,8 +165,29 @@ def readable(path):
return bool(path) and os.access(path, os.R_OK)
def privileged():
"""Whether the services run as root: off on rootless hosts (home-manager, nix-on-droid)."""
return env("PRIVILEGED", "1") == "1"
def service_manager():
"""What runs the units: systemd, systemd-user (home-manager), or supervisor (nix-on-droid)."""
return env("SERVICE_MANAGER", "systemd")
def state_dir():
return env("STATE_DIR", "/var/lib/proxy-suite")
def runtime_dir():
"""The parent of the units' runtime directories (proxy-suite-socks, ...)."""
return env("RUNTIME_DIR", "/run")
def ask_group():
"""What lets a refused user in: root, or userControl's group with the scope for it."""
if not privileged():
return "check its owner and permissions"
return f"join the {env('USER_CONTROL_GROUP', 'proxy-suite')} group, or re-run with sudo"
@@ -212,8 +233,28 @@ def _exec(argv):
die(f"proxy-ctl: {argv[0]}: {e.strerror}", 126 if isinstance(e, PermissionError) else 127)
def _manager_argv(tool, args):
"""tool (systemctl, journalctl) with args, aimed at the manager that runs the units.
Under systemd-user every unit is a user unit, so a --user of the caller's is redundant.
Without systemd (nix-on-droid), proxy-suitectl answers both.
"""
if service_manager() == "systemd-user":
return [tool, "--user", *(a for a in args if a != "--user")]
if service_manager() == "supervisor":
ctl = env("SUPERVISOR_CTL", "proxy-suitectl")
rest = [a for a in args if a != "--user"]
return [ctl, "journal", *rest] if tool == "journalctl" else [ctl, *rest]
return [tool, *args]
def systemctl(*args, capture=False, quiet=False):
return _run(["systemctl", *args], capture=capture, quiet=quiet)
return _run(_manager_argv("systemctl", args), capture=capture, quiet=quiet)
def journal_hint(unit, count=None):
"""The command that shows unit's log, for messages."""
return " ".join(_manager_argv("journalctl", ["-u", unit, *(["-n", str(count)] if count else [])]))
def must(*args):
@@ -522,7 +563,7 @@ def _unit_states(units):
"""unit -> ActiveState for the units that exist, in one systemctl call."""
if not units:
return {}
_, out = _run(["systemctl", "show", "--property=Id,LoadState,ActiveState", "--", *units], capture=True, quiet=True)
_, out = systemctl("show", "--property=Id,LoadState,ActiveState", "--", *units, capture=True, quiet=True)
states = {}
for unit, block in zip(units, out.strip().split("\n\n")):
props = dict(line.split("=", 1) for line in block.splitlines() if "=" in line)
@@ -874,7 +915,7 @@ TEST_DOWNLOAD_SECONDS = 10
def _runtime_file(name):
return os.path.join(os.path.dirname(env("OUTBOUND_INVENTORY_FILE", "/run/proxy-suite-socks/outbounds.json")), name)
return os.path.join(os.path.dirname(env("OUTBOUND_INVENTORY_FILE", f"{runtime_dir()}/proxy-suite-socks/outbounds.json")), name)
def _test_ping(endpoint, timeout=3):
@@ -1156,8 +1197,8 @@ def cmd_unpin(*_):
def _runtime_dir(kind):
if kind == "outbound":
return env("RUNTIME_OUTBOUNDS_DIR", "/var/lib/proxy-suite/outbounds.d")
return env("RUNTIME_SUBS_DIR", "/var/lib/proxy-suite/subscriptions.d")
return env("RUNTIME_OUTBOUNDS_DIR", f"{state_dir()}/outbounds.d")
return env("RUNTIME_SUBS_DIR", f"{state_dir()}/subscriptions.d")
def _runtime_hidden(kind):
@@ -1275,7 +1316,7 @@ def _runtime_reload():
def _subscription_cache(tag):
return os.path.join(env("SUB_CACHE_DIR", "/var/lib/proxy-suite/subscriptions"), f"{tag}.json")
return os.path.join(env("SUB_CACHE_DIR", f"{state_dir()}/subscriptions"), f"{tag}.json")
def _runtime_entry_verify(kind, tag):
@@ -1413,7 +1454,7 @@ def _probe_paths():
def _probe_exits_file():
return env("PROBE_EXITS_FILE", "/run/proxy-suite-socks/probe-exits.json")
return env("PROBE_EXITS_FILE", f"{runtime_dir()}/proxy-suite-socks/probe-exits.json")
def _probe_site(url):
@@ -1756,7 +1797,7 @@ def _reputation_by_tag():
def _autoproxy_dir():
return env("AUTOPROXY_STATE_DIR", "/var/lib/proxy-suite/autoproxy")
return env("AUTOPROXY_STATE_DIR", f"{state_dir()}/autoproxy")
def _require_autoproxy():
@@ -1924,10 +1965,10 @@ def cmd_proxy_learn(host="", *_):
if systemctl("start", "proxy-suite-autoproxy-learn.service", quiet=True)[0]:
sys.stdout.flush()
print(f"The probe run failed. {host} is still queued and will be tried again at the next run.", file=sys.stderr)
die("Details: journalctl -u proxy-suite-autoproxy-learn -n 20")
die(f"Details: {journal_hint('proxy-suite-autoproxy-learn', 20)}")
h = (_autoproxy_state(path).get("hosts") or {}).get(host)
if h is None:
print("No verdict recorded; see: journalctl -u proxy-suite-autoproxy-learn")
print(f"No verdict recorded; see: {journal_hint('proxy-suite-autoproxy-learn')}")
elif h.get("exit"):
print(f"{_s(h.get('domain'))}: {_s(h.get('verdict'))} - routed via {_s(h['exit'])} from now on, no restart needed")
else:
@@ -1947,7 +1988,7 @@ def cmd_zapret(*args):
def _zapret_state_dir():
return env("ZAPRET_STATE_DIR", "/var/lib/proxy-suite/zapret2")
return env("ZAPRET_STATE_DIR", f"{state_dir()}/zapret2")
def _zapret_auto_file(name):
@@ -2074,7 +2115,7 @@ def cmd_zapret_cutoff(verb="status", *_):
denied(path, "write")
print("Probing this line; this takes a few minutes...")
if systemctl("start", "proxy-suite-zapret2-cutoff.service")[0]:
die("The probe failed. Details: journalctl -u proxy-suite-zapret2-cutoff -n 30")
die(f"The probe failed. Details: {journal_hint('proxy-suite-zapret2-cutoff', 30)}")
elif verb != "status":
usage("zapret cutoff [status|probe]")
@@ -2253,7 +2294,7 @@ def cmd_where(domain="", *_):
local = " and ".join(sorted(live))
if env("INBOUNDS_ENABLED") == "1":
inbounds_path = "/run/proxy-suite-inbounds/config.json"
inbounds_path = f"{runtime_dir()}/proxy-suite-inbounds/config.json"
if not readable(inbounds_path):
_where_row("inbounds", f"routing is not readable - {ask_group()}")
else:
@@ -2474,7 +2515,7 @@ def _inbound_links():
def _inbound_server_json(tag):
"""The XRay inbound as the server runs it, secrets and all."""
path = os.path.join(os.path.dirname(env("INBOUNDS_LINKS_FILE", "/run/proxy-suite-inbounds/links.json")), "config.json")
path = os.path.join(os.path.dirname(env("INBOUNDS_LINKS_FILE", f"{runtime_dir()}/proxy-suite-inbounds/links.json")), "config.json")
if not os.path.isfile(path):
die("No inbound config yet - is proxy-suite-inbounds running?")
if not readable(path):
@@ -2530,7 +2571,7 @@ def _inbound_stats(*args):
days = rest.pop(0)
if rest or kind not in STATS_KINDS or not re.fullmatch(r"[1-9][0-9]*", days):
usage("inbounds stats [days] [--by user|inbound|outbound]")
path = env("INBOUNDS_STATS_FILE", "/var/lib/proxy-suite/inbound-stats.json")
path = env("INBOUNDS_STATS_FILE", f"{state_dir()}/inbound-stats.json")
# Collect what XRay counted since the last run first; root and userControl
# members may, anyone else reads what the timer last wrote.
systemctl("--no-ask-password", "start", "proxy-suite-inbound-stats.service", quiet=True)
@@ -2581,7 +2622,7 @@ def _inbound_presence():
except (ValueError, AttributeError):
die("Unexpected answer from the inbounds' stats API.")
# As the timer last wrote it: the API already told who is online now.
path = env("INBOUNDS_STATS_FILE", "/var/lib/proxy-suite/inbound-stats.json")
path = env("INBOUNDS_STATS_FILE", f"{state_dir()}/inbound-stats.json")
seen = (read_json(path).get("seen") or {}) if readable(path) else {}
# Users nobody has seen yet, when the links say who exists.
path = env("INBOUNDS_LINKS_FILE")
@@ -2626,7 +2667,7 @@ def _inbound_subscriptions(*args):
qr = True
else:
user = arg
path = env("INBOUNDS_SUBS_FILE", "/run/proxy-suite-inbounds/subscriptions.json")
path = env("INBOUNDS_SUBS_FILE", f"{runtime_dir()}/proxy-suite-inbounds/subscriptions.json")
base = env("INBOUNDS_SUB_BASE_URL")
if not os.path.isfile(path):
die("No subscriptions available. Is proxy-suite-inbounds running, and is inbounds.subscriptions enabled?")
@@ -2699,9 +2740,9 @@ ALIASES = {
def cmd_logs(*units):
if units:
# One -u per unit: a bare second name would be taken as a journal match.
_exec(["journalctl", "-f", *(f"--unit={u}" for u in units)])
_exec(_manager_argv("journalctl", ["-f", *(f"--unit={u}" for u in units)]))
# journalctl takes unit globs, so the default needs no unit list of its own.
_exec(["journalctl", "-f", "-u", "proxy-suite-*"])
_exec(_manager_argv("journalctl", ["-f", "-u", "proxy-suite-*"]))
COMMANDS = {
+1
View File
@@ -1044,6 +1044,7 @@ class ProxySuiteGui(Adw.Application):
action.connect("activate", callback)
self.add_action(action)
elevated = Gio.SimpleAction.new_stateful("elevated", None, GLib.Variant.new_boolean(False))
elevated.set_enabled(ctl.privileged())
elevated.connect("change-state", self.on_elevated)
self.add_action(elevated)
retry = Gio.SimpleAction.new("retry-root", GLib.VariantType.new("as"))
+6 -1
View File
@@ -94,9 +94,14 @@ def is_root():
return os.geteuid() == 0
def can_elevate():
"""Whether running as root would get further: not on a rootless host, where the user owns everything."""
return ctl.privileged() and not is_root()
def needs_root(out, status):
"""A failed run that root could do: the front ends offer to retry it elevated."""
return bool(status) and status > 0 and not is_root() and any(ROOT_HINT.search(line) for line in out)
return bool(status) and status > 0 and can_elevate() and any(ROOT_HINT.search(line) for line in out)
STATE_ICONS = {"active": "●", "inactive": "○", "failed": "✗", "activating": "◐", "deactivating": "◐", "reloading": "◐"}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -558,7 +558,7 @@ class ProxyTui(App):
def check_action(self, action, parameters):
if action in ("retry_root", "switch_root"):
return not model.is_root()
return model.can_elevate()
# A row action that does not apply: its key does nothing.
if action != "act" or self.screen is not self.main:
return True
+46
View File
@@ -291,6 +291,52 @@ class ProbeWalkTest(EnvTest):
self.assertIn('pin: proxy.routing.rules = [ { outbound = "de"; domains = [ "sekai.test" ]; } ]', out)
class ServiceManagerTest(EnvTest):
def calls(self):
seen = []
self.patch("_run", lambda argv, **kw: seen.append(argv) or (0, ""))
return seen
def test_system_units(self):
seen = self.calls()
ctl.systemctl("--user", "start", "anchor.service")
ctl.systemctl("start", "proxy-suite-socks")
self.assertEqual(seen, [["systemctl", "--user", "start", "anchor.service"], ["systemctl", "start", "proxy-suite-socks"]])
self.assertEqual(ctl.journal_hint("proxy-suite-autoproxy-learn", 20), "journalctl -u proxy-suite-autoproxy-learn -n 20")
def test_user_units(self):
# home-manager: every unit is the user's, and a --user of the caller's is not doubled.
os.environ["SERVICE_MANAGER"] = "systemd-user"
seen = self.calls()
ctl.systemctl("--user", "stop", "anchor.service")
ctl._unit_states(["proxy-suite-socks"])
self.assertEqual(seen[0], ["systemctl", "--user", "stop", "anchor.service"])
self.assertEqual(seen[1][:3], ["systemctl", "--user", "show"])
self.assertEqual(ctl.journal_hint("proxy-suite-socks"), "journalctl --user -u proxy-suite-socks")
def test_supervisor_units(self):
# nix-on-droid: proxy-suitectl stands in for systemctl and journalctl.
os.environ.update(SERVICE_MANAGER="supervisor", SUPERVISOR_CTL="/bin/proxy-suitectl")
seen = self.calls()
ctl.systemctl("--user", "stop", "anchor.service")
ctl._unit_states(["proxy-suite-socks"])
self.assertEqual(seen[0], ["/bin/proxy-suitectl", "stop", "anchor.service"])
self.assertEqual(seen[1][:2], ["/bin/proxy-suitectl", "show"])
self.assertEqual(ctl.journal_hint("proxy-suite-socks", 5), "/bin/proxy-suitectl journal -u proxy-suite-socks -n 5")
def test_paths_follow_host_dirs(self):
for name in ("SUB_CACHE_DIR", "AUTOPROXY_STATE_DIR", "INBOUNDS_STATS_FILE", "OUTBOUND_INVENTORY_FILE"):
os.environ.pop(name, None)
os.environ.update(STATE_DIR="/home/u/.local/state/proxy-suite", RUNTIME_DIR="/tmp/ps")
self.assertEqual(ctl._autoproxy_dir(), "/home/u/.local/state/proxy-suite/autoproxy")
self.assertEqual(os.path.dirname(ctl._subscription_cache("x")), "/home/u/.local/state/proxy-suite/subscriptions")
def test_rootless_hosts_never_ask_for_root(self):
self.assertIn("sudo", ctl.ask_group())
os.environ["PRIVILEGED"] = "0"
self.assertNotIn("sudo", ctl.ask_group())
class AutoProxyTest(EnvTest):
def setUp(self):
super().setUp()
+172
View File
@@ -0,0 +1,172 @@
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
SUPERVISOR = os.path.join(HERE, "proxy_supervisor.py")
def wait_for(predicate, timeout=10):
deadline = time.time() + timeout
while time.time() < deadline:
value = predicate()
if value:
return value
time.sleep(0.05)
raise AssertionError("timed out")
class SupervisorTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="proxy-supervisor-")
self.run_dir = os.path.join(self.tmp, "run")
self.manifest = os.path.join(self.tmp, "manifest.json")
self.env = dict(
os.environ,
# Deeper than a socket address holds.
PROXY_SUITE_SUPERVISOR_DIR=os.path.join(self.tmp, "x" * 100, "supervisor"),
PROXY_SUITE_MANIFEST=self.manifest,
HOME=self.tmp,
)
self.write_manifest()
def tearDown(self):
subprocess.run([sys.executable, SUPERVISOR, "shutdown"], env=self.env, capture_output=True)
# The daemon removes its socket once every unit is down.
try:
wait_for(lambda: not self.daemon_running(), timeout=30)
finally:
shutil.rmtree(self.tmp, ignore_errors=True)
def daemon_running(self):
return os.path.exists(os.path.join(self.env["PROXY_SUITE_SUPERVISOR_DIR"], "control.sock"))
def write_manifest(self, crash_times=1, marker="one"):
out = os.path.join(self.tmp, "out")
sh = lambda text: ["/bin/sh -c " + json.dumps(text)]
manifest = {
"services": {
# Fails the first crash_times starts, then stays up.
"proxy-suite-counter": {
"Unit": {"Description": "counter"},
"Service": {
"Type": "simple",
"Restart": "on-failure",
"RestartSec": "100ms",
"Environment": [json.dumps(f"MARKER={marker}")],
"ExecStartPre": [f'/bin/sh -c "mkdir -p {out}"'],
"ExecStart": sh(
f'n=$(cat {out}/starts 2>/dev/null || echo 0); n=$((n+1)); echo $n > {out}/starts; '
f'echo "start $n $MARKER"; [ $n -gt {crash_times} ] || exit 3; exec sleep 1000'
),
"ExecStopPost": sh(f"echo stopped >> {out}/stops"),
},
"Install": {"WantedBy": ["default.target"]},
},
"proxy-suite-once": {
"Unit": {"Description": "oneshot", "After": ["proxy-suite-counter.service"]},
"Service": {
"Type": "oneshot",
"RemainAfterExit": True,
"ExecStart": sh(f"echo ran >> {out}/once"),
},
"Install": {"WantedBy": ["default.target"]},
},
"proxy-suite-tick": {
"Unit": {"Description": "timer job"},
"Service": {"Type": "oneshot", "ExecStart": sh(f"echo tick >> {out}/ticks")},
},
"proxy-suite-pin@": {
"Unit": {"Description": "template"},
"Service": {"Type": "oneshot", "ExecStart": sh(f"echo '%I' >> {out}/pins")},
},
},
"timers": {
"proxy-suite-tick": {
"Unit": {"Description": "tick"},
"Timer": {"OnActiveSec": "1s", "OnUnitActiveSec": "1s"},
"Install": {"WantedBy": ["timers.target"]},
},
},
"paths": {},
"tmpfiles": [f"d {self.run_dir} 0700 - - -"],
}
with open(self.manifest + ".tmp", "w") as f:
json.dump(manifest, f)
os.replace(self.manifest + ".tmp", self.manifest)
def ctl(self, *args):
p = subprocess.run([sys.executable, SUPERVISOR, *args], env=self.env, capture_output=True, text=True, timeout=60)
return p.returncode, p.stdout
def read(self, name):
try:
with open(os.path.join(self.tmp, "out", name)) as f:
return f.read().split()
except FileNotFoundError:
return []
def test_without_daemon(self):
self.assertEqual(self.ctl("is-active", "--quiet", "proxy-suite-counter"), (3, ""))
status, out = self.ctl("show", "--property=Id,LoadState,ActiveState", "--", "proxy-suite-counter", "nope")
self.assertEqual(status, 0)
self.assertEqual(
out.split("\n\n"),
["Id=proxy-suite-counter.service\nLoadState=loaded\nActiveState=inactive", "Id=nope.service\nLoadState=not-found\nActiveState=inactive\n"],
)
self.assertEqual(self.ctl("stop", "proxy-suite-counter")[0], 0)
self.assertFalse(self.daemon_running())
def test_boot_restart_timers_and_stop(self):
self.assertEqual(self.ctl("boot")[0], 0)
self.assertTrue(os.path.isdir(self.run_dir))
# Crashed once, restarted, then up.
wait_for(lambda: self.ctl("show", "-p", "SubState", "--value", "proxy-suite-counter")[1].strip() == "running")
self.assertEqual(self.read("starts"), ["2"])
self.assertEqual(self.read("stops"), ["stopped"])
self.assertEqual(self.read("once"), ["ran"])
self.assertEqual(self.ctl("is-active", "proxy-suite-once"), (0, "active\n"))
status, out = self.ctl("list-timers", "-o", "json", "proxy-suite-tick.timer")
timers = json.loads(out)
self.assertEqual([t["activates"] for t in timers], ["proxy-suite-tick.service"])
self.assertGreater(timers[0]["next"], (time.time() - 5) * 1e6)
wait_for(lambda: len(self.read("ticks")) >= 2)
# Template instances get %I unescaped.
self.assertEqual(self.ctl("start", "proxy-suite-pin@de\\x2dfra.service")[0], 0)
self.assertEqual(self.read("pins"), ["de-fra"])
status, out = self.ctl("journal", "-u", "proxy-suite-count*", "-o", "cat", "--since", "-1h", "--no-pager")
self.assertEqual([l for l in out.splitlines() if l.startswith("start")][:2], ["start 1 one", "start 2 one"])
self.assertIn("proxy-suitectl: exited with status 3; restarting", out)
self.assertEqual(self.ctl("journal", "-u", "proxy-suite-counter", "-n", "1", "-o", "cat")[1], "start 2 one\n")
self.assertEqual(self.ctl("stop", "proxy-suite-counter")[0], 0)
self.assertEqual(self.ctl("is-active", "proxy-suite-counter"), (3, "inactive\n"))
self.assertEqual(self.read("stops"), ["stopped", "stopped"])
# try-restart leaves a stopped unit stopped.
self.assertEqual(self.ctl("try-restart", "proxy-suite-counter")[0], 0)
self.assertEqual(self.ctl("is-active", "proxy-suite-counter")[0], 3)
def test_boot_again_restarts_changed_units(self):
self.write_manifest(crash_times=0)
self.ctl("boot")
wait_for(lambda: self.ctl("is-active", "proxy-suite-counter")[0] == 0)
pid = self.ctl("show", "-p", "MainPID", "--value", "proxy-suite-counter")[1].strip()
self.write_manifest(crash_times=0, marker="two")
self.assertEqual(self.ctl("boot")[0], 0)
wait_for(lambda: self.ctl("is-active", "proxy-suite-counter")[0] == 0)
self.assertNotEqual(self.ctl("show", "-p", "MainPID", "--value", "proxy-suite-counter")[1].strip(), pid)
self.assertIn("start 2 two", self.ctl("journal", "-u", "proxy-suite-counter", "-o", "cat")[1])
# The unchanged oneshot is not run again.
self.assertEqual(self.read("once"), ["ran"])
if __name__ == "__main__":
unittest.main()
+38
View File
@@ -0,0 +1,38 @@
# proxy-suitectl: the service manager of hosts without systemd (nix-on-droid). It reads
# the units from `manifest`, a path outside the store the host's activation points at the
# current generation's units, so the command itself does not change with the configuration.
{
lib,
pkgs,
}:
{
# Where the daemon keeps its socket, logs and credentials.
supervisorDir,
manifest,
# What %t and %S expand to.
runtimeDir,
stateDir,
}:
let
unwrapped = pkgs.writeScriptBin "proxy-suitectl" (
"#!${pkgs.python3}/bin/python3\n" + builtins.readFile ./proxy-ctl/proxy_supervisor.py
);
in
pkgs.symlinkJoin {
name = "proxy-suitectl";
paths = [ unwrapped ];
nativeBuildInputs = [ pkgs.makeWrapper ];
postBuild = ''
wrapProgram "$out/bin/proxy-suitectl" \
--set PROXY_SUITE_SUPERVISOR_DIR ${lib.escapeShellArg supervisorDir} \
--set PROXY_SUITE_MANIFEST ${lib.escapeShellArg manifest} \
--set PROXY_SUITE_RUNTIME_BASE ${lib.escapeShellArg runtimeDir} \
--set PROXY_SUITE_STATE_BASE ${lib.escapeShellArg stateDir}
'';
meta = {
description = "A systemctl-like supervisor for proxy-suite's units on hosts without systemd";
mainProgram = "proxy-suitectl";
};
}
+41
View File
@@ -0,0 +1,41 @@
# wireproxy with AmneziaWG 3.1: a profile as a SOCKS5 listener, with no interface or
# privileges, for asOutbound = "userspace". Its vendored amneziawg-go gets the suite's
# userspace patch, and wireproxy learns FwMark for hosts that capture traffic.
{ pkgs }:
pkgs.buildGo126Module (finalAttrs: {
pname = "wireproxy-awg";
version = "1.0.18";
src = pkgs.fetchFromGitHub {
owner = "artem-russkikh";
repo = "wireproxy-awg";
rev = "v${finalAttrs.version}";
hash = "sha256-aiDHUkAP9vuRVmdt/6be0ExaPheE7xWkI8twxVHTzYc=";
};
vendorHash = "sha256-jHi8bg8Y+L1Hio/UOrSGQNbF+tJg37tfYDjeqlVLmHM=";
patches = [ ./patches/wireproxy-awg-fwmark.patch ];
# The vendored copy, once it exists: the module fetch keeps upstream's.
overrideModAttrs = _: { preBuild = ""; };
preBuild = ''
chmod -R u+w vendor/github.com/amnezia-vpn/amneziawg-go/v3
patch -p1 -d vendor/github.com/amnezia-vpn/amneziawg-go/v3 \
< ${./patches/amneziawg-go-random-trailers-transport.patch}
'';
subPackages = [ "cmd/wireproxy" ];
ldflags = [
"-s"
"-w"
"-X main.version=${finalAttrs.version}"
];
meta = {
description = "WireGuard/AmneziaWG client as a userspace SOCKS5/HTTP proxy";
homepage = "https://github.com/artem-russkikh/wireproxy-awg";
license = pkgs.lib.licenses.isc;
mainProgram = "wireproxy";
};
})
+54 -5
View File
@@ -307,6 +307,42 @@ def as_outbound(config: str, fwmark: int) -> str:
return _set_interface_value(config, "FwMark", str(fwmark))
# Read once by wireproxy: repeated lines are joined into one list.
WIREPROXY_LIST_KEYS = {"address", "dns", "allowedips"}
# wg-quick's, which wireproxy has no use for.
WIREPROXY_DROPPED_KEYS = FORBIDDEN_WG_QUICK_KEYS | {"table", "fwmark"}
def as_wireproxy(config: str, socks_address: str, fwmark: int | None = None) -> str:
"""A wireproxy configuration: the profile, served as a SOCKS5 listener on socks_address.
With fwmark, the tunnel's own packets are marked, to get past TUN and TProxy capture.
"""
lines: list[str] = []
for name, pairs in conf_sections(config):
if name not in {"interface", "peer"}:
continue
if lines:
lines.append("")
lines.append(f"[{name.capitalize()}]")
lists: dict[str, list[str]] = {}
for key, value in pairs:
if key in WIREPROXY_DROPPED_KEYS:
continue
if key in WIREPROXY_LIST_KEYS:
if key not in lists:
lists[key] = []
lines.append(key)
lists[key].extend(item.strip() for item in value.split(",") if item.strip())
else:
lines.append(f"{key} = {value}")
lines = [f"{line} = {','.join(lists[line])}" if line in lists else line for line in lines]
if name == "interface" and fwmark is not None:
lines.append(f"fwmark = {fwmark}")
lines.extend(["", "[Socks5]", f"BindAddress = {socks_address}"])
return "\n".join(lines) + "\n"
def conf_sections(config: str) -> list[tuple[str, list[tuple[str, str]]]]:
"""Each [Section] of a WireGuard .conf, lowercased, with its key = value lines in order.
@@ -629,6 +665,7 @@ def write_private(path: str, content: str) -> None:
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--manifest")
parser.add_argument("--config", metavar="CONFIG", help="render a .conf file, as a configFile manifest")
parser.add_argument("--output")
parser.add_argument(
"--outbound-fwmark",
@@ -636,6 +673,11 @@ def main() -> int:
metavar="MARK",
help="render for an outbound-only interface: no routes or DNS, packets marked MARK",
)
parser.add_argument(
"--wireproxy",
metavar="ADDRESS",
help="render for wireproxy, as a SOCKS5 listener on ADDRESS (packets marked with --outbound-fwmark)",
)
parser.add_argument(
"--inspect",
metavar="CONFIG",
@@ -644,18 +686,25 @@ def main() -> int:
args = parser.parse_args()
try:
if args.inspect is not None:
if args.manifest is not None or args.output is not None:
if args.manifest is not None or args.config is not None or args.output is not None:
raise ConfigError("--inspect cannot be combined with rendering options")
config = _read_limited(args.inspect)
print(transport_implementation(config), probe_address(config), rekey_after_time(config))
return 0
if args.manifest is None or args.output is None:
raise ConfigError("--manifest and --output are required when rendering a configuration")
manifest = json.loads(_read_limited(args.manifest))
if (args.manifest is None) == (args.config is None) or args.output is None:
raise ConfigError(
"--output and one of --manifest or --config are required when rendering a configuration"
)
if args.config is not None:
manifest = {"kind": "configFile", "path": args.config}
else:
manifest = json.loads(_read_limited(args.manifest))
if not isinstance(manifest, dict):
raise ConfigError("manifest must be a JSON object")
config = prepare(manifest)
if args.outbound_fwmark is not None:
if args.wireproxy is not None:
config = as_wireproxy(config, args.wireproxy, args.outbound_fwmark)
elif args.outbound_fwmark is not None:
config = as_outbound(config, args.outbound_fwmark)
write_private(args.output, config)
except (ConfigError, KeyError, OSError, json.JSONDecodeError) as exc:
+22
View File
@@ -458,6 +458,28 @@ class AmneziaWgConfigTests(unittest.TestCase):
# The peer is untouched.
self.assertIn("Endpoint = vpn.example.com:51820", rendered)
def test_wireproxy_render_joins_lists_and_adds_socks_listener(self):
config = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1").replace(
"Address = 10.8.0.2/32",
"Address = 10.8.0.2/32\nAddress = fd00::2/128\nTable = off\nPostUp = true\nDNS = 9.9.9.9",
) + "AllowedIPs = ::/0\n\n[Peer]\nPublicKey = other\nAllowedIPs = 10.0.0.0/8\n"
rendered = amneziawg_config.as_wireproxy(config, "127.0.0.1:18700", 2)
sections = amneziawg_config.conf_sections(rendered)
self.assertEqual([name for name, _ in sections], ["interface", "peer", "peer", "socks5"])
interface = dict(sections[0][1])
self.assertEqual(interface["address"], "10.8.0.2/32,fd00::2/128")
self.assertEqual(interface["dns"], "9.9.9.9,1.1.1.1")
self.assertEqual(interface["fwmark"], "2")
self.assertEqual(interface["headerprotectionkey"], "header")
self.assertNotIn("table", interface)
self.assertNotIn("postup", interface)
self.assertEqual(dict(sections[1][1])["allowedips"], "0.0.0.0/0,::/0")
self.assertEqual(dict(sections[2][1])["publickey"], "other")
self.assertEqual(sections[3][1], [("bindaddress", "127.0.0.1:18700")])
# Rootless: no mark.
unmarked = amneziawg_config.as_wireproxy(config, "127.0.0.1:18700")
self.assertEqual(amneziawg_config.section_values(unmarked, "interface", "fwmark"), [])
if __name__ == "__main__":
unittest.main()