feat: awg runtime add
This commit is contained in:
39 files changed
+1581
-190
No files matched your search
@@ -146,6 +146,8 @@ Changes and secrets need root or the userControl group.
|
|||||||
proxy outbounds add [tag] <url|json|-> [--detour <tag>]
|
proxy outbounds add [tag] <url|json|-> [--detour <tag>]
|
||||||
add an outbound from a link or JSON (-: stdin);
|
add an outbound from a link or JSON (-: stdin);
|
||||||
--detour: connect through another outbound
|
--detour: connect through another outbound
|
||||||
|
proxy outbounds add [tag] <vpn://…|file.conf|-> [--container <name>]
|
||||||
|
add an AmneziaWG outbound (runs in wireproxy)
|
||||||
proxy outbounds chain <tag> <through-tag> [new tag]
|
proxy outbounds chain <tag> <through-tag> [new tag]
|
||||||
add a copy of an outbound that connects through another
|
add a copy of an outbound that connects through another
|
||||||
proxy outbounds rm <tag> remove a runtime outbound
|
proxy outbounds rm <tag> remove a runtime outbound
|
||||||
@@ -186,6 +188,9 @@ Changes and secrets need root or the userControl group.
|
|||||||
|
|
||||||
awg [list] AmneziaWG profiles
|
awg [list] AmneziaWG profiles
|
||||||
awg on <profile> | off [profile] | toggle [profile] | restart [profile]
|
awg on <profile> | off [profile] | toggle [profile] | restart [profile]
|
||||||
|
awg add [name] <vpn://…|file.conf|-> [--container <name>]
|
||||||
|
add a global profile (-: stdin)
|
||||||
|
awg rm <profile> remove a profile added with awg add
|
||||||
|
|
||||||
killswitch [status|on|off] block traffic outside the global tunnel;
|
killswitch [status|on|off] block traffic outside the global tunnel;
|
||||||
stays on until turned off here or with the tunnel
|
stays on until turned off here or with the tunnel
|
||||||
|
|||||||
@@ -66,6 +66,9 @@ Part of the [proxy-suite options reference](./index.md).
|
|||||||
- [vpn](#services-proxy-suite-amneziawg-profiles-name-vpn)
|
- [vpn](#services-proxy-suite-amneziawg-profiles-name-vpn)
|
||||||
- [vpnContainer](#services-proxy-suite-amneziawg-profiles-name-vpncontainer)
|
- [vpnContainer](#services-proxy-suite-amneziawg-profiles-name-vpncontainer)
|
||||||
- [vpnFile](#services-proxy-suite-amneziawg-profiles-name-vpnfile)
|
- [vpnFile](#services-proxy-suite-amneziawg-profiles-name-vpnfile)
|
||||||
|
- runtime
|
||||||
|
- [enable](#services-proxy-suite-amneziawg-runtime-enable)
|
||||||
|
- [interfaceName](#services-proxy-suite-amneziawg-runtime-interfacename)
|
||||||
- [serverUdpPorts](#services-proxy-suite-amneziawg-serverudpports)
|
- [serverUdpPorts](#services-proxy-suite-amneziawg-serverudpports)
|
||||||
- [toolsPackage](#services-proxy-suite-amneziawg-toolspackage)
|
- [toolsPackage](#services-proxy-suite-amneziawg-toolspackage)
|
||||||
- [userspacePackage](#services-proxy-suite-amneziawg-userspacepackage)
|
- [userspacePackage](#services-proxy-suite-amneziawg-userspacepackage)
|
||||||
@@ -548,6 +551,25 @@ File with a vpn:// export\.
|
|||||||
**Type:** null or string\
|
**Type:** null or string\
|
||||||
**Default:** `null`
|
**Default:** `null`
|
||||||
|
|
||||||
|
<a id="services-proxy-suite-amneziawg-runtime-enable"></a>
|
||||||
|
## services\.proxy-suite\.amneziaWg\.runtime\.enable
|
||||||
|
|
||||||
|
Let ` proxy-ctl ` add configs and ` vpn:// ` links without a rebuild: ` proxy-ctl awg add `
|
||||||
|
for a global profile (root hosts only), and ` proxy-ctl proxy outbounds add ` for an
|
||||||
|
outbound, which runs in wireproxy (needs ` proxy.enable `)\. wg-quick hooks such as
|
||||||
|
` PostUp ` are always refused in them\. With this on, ` profiles ` may be empty\.
|
||||||
|
|
||||||
|
**Type:** boolean\
|
||||||
|
**Default:** `true`
|
||||||
|
|
||||||
|
<a id="services-proxy-suite-amneziawg-runtime-interfacename"></a>
|
||||||
|
## services\.proxy-suite\.amneziaWg\.runtime\.interfaceName
|
||||||
|
|
||||||
|
Interface of the global profiles added at runtime\. Only one of them runs at a time, so they share it\.
|
||||||
|
|
||||||
|
**Type:** string matching the pattern ^\[A-Za-z0-9_\.-]{1,15}$\
|
||||||
|
**Default:** `"awg-rt"`
|
||||||
|
|
||||||
<a id="services-proxy-suite-amneziawg-serverudpports"></a>
|
<a id="services-proxy-suite-amneziawg-serverudpports"></a>
|
||||||
## services\.proxy-suite\.amneziaWg\.serverUdpPorts
|
## services\.proxy-suite\.amneziaWg\.serverUdpPorts
|
||||||
|
|
||||||
|
|||||||
@@ -122,6 +122,7 @@ Part of the [proxy-suite options reference](./index.md).
|
|||||||
- [via](#services-proxy-suite-inbounds-routing-via)
|
- [via](#services-proxy-suite-inbounds-routing-via)
|
||||||
- [zapretDirect](#services-proxy-suite-inbounds-routing-zapretdirect)
|
- [zapretDirect](#services-proxy-suite-inbounds-routing-zapretdirect)
|
||||||
- [serverAddress](#services-proxy-suite-inbounds-serveraddress)
|
- [serverAddress](#services-proxy-suite-inbounds-serveraddress)
|
||||||
|
- [serverAliases](#services-proxy-suite-inbounds-serveraliases)
|
||||||
- [shareLinks](#services-proxy-suite-inbounds-sharelinks)
|
- [shareLinks](#services-proxy-suite-inbounds-sharelinks)
|
||||||
- subscriptions
|
- subscriptions
|
||||||
- [enable](#services-proxy-suite-inbounds-subscriptions-enable)
|
- [enable](#services-proxy-suite-inbounds-subscriptions-enable)
|
||||||
@@ -1137,6 +1138,19 @@ Public address for share links\. ` null `: detect the uplink IPv4\.
|
|||||||
**Default:** `null`\
|
**Default:** `null`\
|
||||||
**Example:** `"vpn.example.com"`
|
**Example:** `"vpn.example.com"`
|
||||||
|
|
||||||
|
<a id="services-proxy-suite-inbounds-serveraliases"></a>
|
||||||
|
## services\.proxy-suite\.inbounds\.serverAliases
|
||||||
|
|
||||||
|
Other names and IPs of this host that clients reach through the tunnel, such as a
|
||||||
|
TURN relay’s name beside the site on ` serverAddress `\. Like ` serverAddress `, they go
|
||||||
|
direct on the listener ports instead of looping back through ` routing.via `, which
|
||||||
|
often cannot reach this host at all\. List the IPs too: a client that resolves a name
|
||||||
|
itself hands XRay the address, which no name rule matches\.
|
||||||
|
|
||||||
|
**Type:** list of string matching the pattern \[^\[:space:]]+\
|
||||||
|
**Default:** `[ ]`\
|
||||||
|
**Example:** `[ "turn.example.com" "203.0.113.10" "2001:db8::10" ]`
|
||||||
|
|
||||||
<a id="services-proxy-suite-inbounds-sharelinks"></a>
|
<a id="services-proxy-suite-inbounds-sharelinks"></a>
|
||||||
## services\.proxy-suite\.inbounds\.shareLinks
|
## services\.proxy-suite\.inbounds\.shareLinks
|
||||||
|
|
||||||
|
|||||||
@@ -43,6 +43,10 @@ services.proxy-suite = {
|
|||||||
enable = false;
|
enable = false;
|
||||||
kernelModulePackage = ‹amneziawg from boot.kernelPackages on NixOS, null elsewhere›;
|
kernelModulePackage = ‹amneziawg from boot.kernelPackages on NixOS, null elsewhere›;
|
||||||
profiles = { };
|
profiles = { };
|
||||||
|
runtime = {
|
||||||
|
enable = true;
|
||||||
|
interfaceName = "awg-rt";
|
||||||
|
};
|
||||||
serverUdpPorts = [ ];
|
serverUdpPorts = [ ];
|
||||||
toolsPackage = ‹proxy-suite's patched amneziawg-tools (pkgs/amneziawg.nix)›;
|
toolsPackage = ‹proxy-suite's patched amneziawg-tools (pkgs/amneziawg.nix)›;
|
||||||
userspacePackage = ‹proxy-suite's patched amneziawg-go (pkgs/amneziawg.nix)›;
|
userspacePackage = ‹proxy-suite's patched amneziawg-go (pkgs/amneziawg.nix)›;
|
||||||
@@ -81,6 +85,7 @@ services.proxy-suite = {
|
|||||||
zapretDirect = true;
|
zapretDirect = true;
|
||||||
};
|
};
|
||||||
serverAddress = null;
|
serverAddress = null;
|
||||||
|
serverAliases = [ ];
|
||||||
shareLinks = true;
|
shareLinks = true;
|
||||||
subscriptions = {
|
subscriptions = {
|
||||||
baseUrl = null;
|
baseUrl = null;
|
||||||
|
|||||||
@@ -41,7 +41,10 @@ What the group may do\. Empty allows everything\.
|
|||||||
- “zapret”: change zapret2’s learned sites, and ` zapret cutoff probe `\.
|
- “zapret”: change zapret2’s learned sites, and ` zapret cutoff probe `\.
|
||||||
- “stats”: ` inbounds stats `\.
|
- “stats”: ` inbounds stats `\.
|
||||||
- “whitelistBypass”: everything under ` proxy-ctl wl `\.
|
- “whitelistBypass”: everything under ` proxy-ctl wl `\.
|
||||||
|
- “amneziaWg”: add and remove global AmneziaWG profiles (` proxy-ctl awg add `, ` awg rm `)\.
|
||||||
|
A global profile takes over the host’s routes and DNS\. Starting and stopping one is
|
||||||
|
“services”; an AmneziaWG outbound is “outbounds”\.
|
||||||
|
|
||||||
**Type:** list of (one of “services”, “perApp”, “routing”, “outbounds”, “secrets”, “autoProxy”, “zapret”, “stats”, “whitelistBypass”)\
|
**Type:** list of (one of “services”, “perApp”, “routing”, “outbounds”, “secrets”, “autoProxy”, “zapret”, “stats”, “whitelistBypass”, “amneziaWg”)\
|
||||||
**Default:** `[ ]`\
|
**Default:** `[ ]`\
|
||||||
**Example:** `[ "services" "routing" ]`
|
**Example:** `[ "services" "routing" ]`
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{ config, lib, pkgs, ... }:
|
||||||
|
{
|
||||||
|
services.proxy-suite = {
|
||||||
|
enable = true;
|
||||||
|
amneziaWg.enable = true; # no profiles needed
|
||||||
|
userControl = {
|
||||||
|
enable = true;
|
||||||
|
scopes = [ "services" "amneziaWg" "outbounds" ]; # optional: no sudo for these
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -64,6 +64,43 @@ host's routes and DNS alone. Use it like any other outbound: for selection, in
|
|||||||
| `"userspace"` | yes | no | Runs in wireproxy. The only mode on home-manager and Nix-on-Droid. |
|
| `"userspace"` | yes | no | Runs in wireproxy. The only mode on home-manager and Nix-on-Droid. |
|
||||||
| `"singBox"` | no | no | Plain WireGuard inside sing-box. For servers without obfuscation, such as WARP. |
|
| `"singBox"` | no | no | Plain WireGuard inside sing-box. For servers without obfuscation, such as WARP. |
|
||||||
|
|
||||||
|
## Add one without rebuilding
|
||||||
|
|
||||||
|
`amneziaWg.enable` alone is enough: profiles and outbounds can come from `proxy-ctl` instead
|
||||||
|
of the config.
|
||||||
|
|
||||||
|
```nix
|
||||||
|
services.proxy-suite = {
|
||||||
|
enable = true;
|
||||||
|
amneziaWg.enable = true; # no profiles needed
|
||||||
|
userControl = {
|
||||||
|
enable = true;
|
||||||
|
scopes = [ "services" "amneziaWg" "outbounds" ]; # optional: no sudo for these
|
||||||
|
};
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
```sh
|
||||||
|
proxy-ctl awg add vpn://AAAA… # named after the export, or the server's host
|
||||||
|
proxy-ctl awg add home ~/home.conf # a name first; a link, a file, or - for stdin
|
||||||
|
proxy-ctl awg on home
|
||||||
|
proxy-ctl awg rm home
|
||||||
|
proxy-ctl proxy outbounds add de ~/de.conf # an outbound instead (needs proxy.enable)
|
||||||
|
```
|
||||||
|
|
||||||
|
- A global profile works like a declared one: `awg on`, the tray menu, the kill switch. The
|
||||||
|
ones added this way share one interface, `amneziaWg.runtime.interfaceName`.
|
||||||
|
- An outbound runs in wireproxy (like `asOutbound = "userspace"`), so the obfuscation stays.
|
||||||
|
It cannot chain through another outbound.
|
||||||
|
- In `proxy-tui` and the desktop app, paste a `vpn://` link or a whole `.conf` onto a tab: on
|
||||||
|
the Outbounds tab it becomes an outbound, anywhere else a global profile. The AmneziaWG tab
|
||||||
|
also adds one from a prompt, and removes what was added.
|
||||||
|
- Hooks (`PostUp` and the like) are always refused, whoever adds the config.
|
||||||
|
`--container <name>` picks one from a `vpn://` export that holds several.
|
||||||
|
- Adding and removing takes root, or a `userControl` scope: `amneziaWg` for global profiles,
|
||||||
|
`outbounds` for outbounds. Turning a profile on and off is `services`.
|
||||||
|
- They are kept across reboots. `amneziaWg.runtime.enable = false` turns all of this off.
|
||||||
|
|
||||||
## Good to know
|
## Good to know
|
||||||
|
|
||||||
- A profile that stops getting handshake replies moves to a new source port on its own.
|
- A profile that stops getting handshake replies moves to a new source port on its own.
|
||||||
@@ -77,5 +114,6 @@ host's routes and DNS alone. Use it like any other outbound: for selection, in
|
|||||||
## See also
|
## See also
|
||||||
|
|
||||||
- [`amneziaWg.profiles`](../options/amneziaWg.md#services-proxy-suite-amneziawg-profiles)
|
- [`amneziaWg.profiles`](../options/amneziaWg.md#services-proxy-suite-amneziawg-profiles)
|
||||||
|
- [`amneziaWg.runtime`](../options/amneziaWg.md#services-proxy-suite-amneziawg-runtime-enable)
|
||||||
- [`asOutbound`](../options/amneziaWg.md#services-proxy-suite-amneziawg-profiles-name-asoutbound)
|
- [`asOutbound`](../options/amneziaWg.md#services-proxy-suite-amneziawg-profiles-name-asoutbound)
|
||||||
- [`settings`](../options/amneziaWg.md#services-proxy-suite-amneziawg-profiles-name-settings)
|
- [`settings`](../options/amneziaWg.md#services-proxy-suite-amneziawg-profiles-name-settings)
|
||||||
+10
-3
@@ -37,7 +37,8 @@ Members of the group get the listed scopes. An empty `scopes` list grants all of
|
|||||||
|---|---|
|
|---|---|
|
||||||
| `services` | turning services on, off and restarting them |
|
| `services` | turning services on, off and restarting them |
|
||||||
| `routing` | `proxy pin`, `proxy unpin`, `proxy mode` |
|
| `routing` | `proxy pin`, `proxy unpin`, `proxy mode` |
|
||||||
| `outbounds` | adding, removing, enabling and disabling outbounds and subscriptions |
|
| `outbounds` | adding, removing, enabling and disabling outbounds and subscriptions, AmneziaWG outbounds included |
|
||||||
|
| `amneziaWg` | `awg add` and `awg rm`: global AmneziaWG profiles, which take over the host's routes and DNS |
|
||||||
| `perApp` | `apps run` with `tun`, `tproxy` and `zapret` profiles |
|
| `perApp` | `apps run` with `tun`, `tproxy` and `zapret` profiles |
|
||||||
| `secrets` | reading share links, subscription URLs and running configs |
|
| `secrets` | reading share links, subscription URLs and running configs |
|
||||||
| `autoProxy`, `zapret`, `stats`, `whitelistBypass` | the matching `proxy-ctl` groups |
|
| `autoProxy`, `zapret`, `stats`, `whitelistBypass` | the matching `proxy-ctl` groups |
|
||||||
@@ -49,13 +50,19 @@ admin password, or you run `proxy-ctl` with sudo.
|
|||||||
|
|
||||||
| Change | Lasts |
|
| Change | Lasts |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `proxy outbounds add`, `proxy subs add` | until removed with `rm`; kept across reboots |
|
| `proxy outbounds add`, `proxy subs add`, `awg add` | until removed with `rm`; kept across reboots |
|
||||||
| `proxy outbounds disable` | until `enable`; works on outbounds from Nix too |
|
| `proxy outbounds disable` | until `enable`; works on outbounds from Nix too |
|
||||||
| `proxy pin` | until `unpin`; kept across reboots |
|
| `proxy pin` | until `unpin`; kept across reboots |
|
||||||
| `proxy mode` | until the next reboot |
|
| `proxy mode` | until the next reboot |
|
||||||
| `… on` / `… off` | until the next reboot; boot state comes from the config |
|
| `… on` / `… off` | until the next reboot; boot state comes from the config |
|
||||||
|
|
||||||
Outbounds from the Nix config cannot be removed at runtime, only disabled.
|
Outbounds from the Nix config cannot be removed at runtime, only disabled. The same goes for
|
||||||
|
AmneziaWG profiles: `awg rm` only removes those added with `awg add`.
|
||||||
|
|
||||||
|
In the TUI and the app, pasting a link onto a tab adds it there: a share link becomes an
|
||||||
|
outbound, a subscription URL a subscription. An AmneziaWG `vpn://` link or a whole `.conf`
|
||||||
|
becomes a global profile, or an outbound when pasted onto the Outbounds tab. See
|
||||||
|
[Use an AmneziaWG config](./amneziawg.md).
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,11 @@ let
|
|||||||
awgGlobalGroup
|
awgGlobalGroup
|
||||||
awgOutboundRulePriority
|
awgOutboundRulePriority
|
||||||
awgServerUdpRulePriority
|
awgServerUdpRulePriority
|
||||||
|
runtimeAwgDir
|
||||||
|
runtimeOutboundsDir
|
||||||
|
awgRuntimeTunnelBasePort
|
||||||
|
awgRuntimeTunnelSlots
|
||||||
|
systemctl
|
||||||
;
|
;
|
||||||
killSwitchUnit = "proxy-suite-killswitch.service";
|
killSwitchUnit = "proxy-suite-killswitch.service";
|
||||||
# Profiles behind a loopback SOCKS hop, in a tunnel unit rather than awg-quick.
|
# Profiles behind a loopback SOCKS hop, in a tunnel unit rather than awg-quick.
|
||||||
@@ -91,8 +96,63 @@ let
|
|||||||
);
|
);
|
||||||
configTool = "${import ./lib/scripts-dir.nix { inherit lib; }}/amneziawg_config.py";
|
configTool = "${import ./lib/scripts-dir.nix { inherit lib; }}/amneziawg_config.py";
|
||||||
awgCommon = import ./awg-common.nix { inherit lib pkgs awgCfg; };
|
awgCommon = import ./awg-common.nix { inherit lib pkgs awgCfg; };
|
||||||
runtimeDir = name: "/run/${serviceName name}";
|
|
||||||
runtimeConfig = name: profile: "${runtimeDir name}/${profile.interfaceName}.conf";
|
# What a unit's scripts know of the profile they run. `init` is their first line and sets
|
||||||
|
# $profile_name; `runDir` is the runtime directory, as shell text; `source` the arguments
|
||||||
|
# amneziawg_config.py reads the profile with; `outbound` whether it is an "interface" one.
|
||||||
|
staticSpec = name: profile: {
|
||||||
|
inherit name profile;
|
||||||
|
template = false;
|
||||||
|
unit = serviceName name;
|
||||||
|
init = "profile_name=${lib.escapeShellArg name}";
|
||||||
|
runDir = "/run/${serviceName name}";
|
||||||
|
runtimeDirectory = serviceName name;
|
||||||
|
source = "--manifest ${lib.escapeShellArg (toString (manifestFor profile))}";
|
||||||
|
outbound = profile.asOutbound == "interface";
|
||||||
|
};
|
||||||
|
|
||||||
|
# Global profiles added with `proxy-ctl awg add`: instances of one template, the name
|
||||||
|
# passed in as $1 (%i), the .conf in runtimeAwgDir. They share an interface, and hooks are
|
||||||
|
# refused (--config), since whoever added one need not be root.
|
||||||
|
runtimeProfile = {
|
||||||
|
inherit (awgCfg.runtime) interfaceName;
|
||||||
|
asOutbound = null;
|
||||||
|
autostart = false;
|
||||||
|
settings = null;
|
||||||
|
};
|
||||||
|
runtimeSpec = {
|
||||||
|
name = "$profile_name";
|
||||||
|
profile = runtimeProfile;
|
||||||
|
template = true;
|
||||||
|
unit = "proxy-suite-awg@";
|
||||||
|
init = ''
|
||||||
|
profile_name=''${1:-}
|
||||||
|
if [[ ! $profile_name =~ ^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$ ]]; then
|
||||||
|
echo "proxy-suite: '$profile_name' is not an AmneziaWG profile name" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
'';
|
||||||
|
runDir = "/run/proxy-suite-awg-rt-$profile_name";
|
||||||
|
runtimeDirectory = "proxy-suite-awg-rt-%i";
|
||||||
|
source = ''--config "${runtimeAwgDir}/$profile_name.conf"'';
|
||||||
|
outbound = false;
|
||||||
|
};
|
||||||
|
specConfig = spec: "${spec.runDir}/${spec.profile.interfaceName}.conf";
|
||||||
|
|
||||||
|
# Runtime profiles cannot be named in Conflicts= at build time, and share one interface:
|
||||||
|
# starting any global profile stops the runtime ones still up. $1: its own instance, if one.
|
||||||
|
stopRuntimeProfiles = pkgs.writeShellScript "proxy-suite-awg" ''
|
||||||
|
set -uo pipefail
|
||||||
|
self="proxy-suite-awg@''${1:-}.service"
|
||||||
|
# A failed unit's line starts with a glyph: take the name wherever it is.
|
||||||
|
${systemctl} list-units --plain --no-legend --state=active,activating,reloading 'proxy-suite-awg@*.service' \
|
||||||
|
| ${pkgs.gnugrep}/bin/grep -o 'proxy-suite-awg@[^ ]*\.service' \
|
||||||
|
| while read -r unit; do
|
||||||
|
[[ $unit == "$self" ]] || ${systemctl} stop "$unit" || true
|
||||||
|
done
|
||||||
|
# grep finds nothing when none is up, which pipefail would make this script's failure.
|
||||||
|
exit 0
|
||||||
|
'';
|
||||||
# Keep proxy backend sockets (proxyMark) out of AWG's default-route table.
|
# Keep proxy backend sockets (proxyMark) out of AWG's default-route table.
|
||||||
proxyBypassRulePriority = 8998;
|
proxyBypassRulePriority = 8998;
|
||||||
bypassRule =
|
bypassRule =
|
||||||
@@ -211,14 +271,15 @@ let
|
|||||||
# awg-quick turns src_valid_mark on for a default route and never back off; left on, it
|
# awg-quick turns src_valid_mark on for a default route and never back off; left on, it
|
||||||
# changes how the kernel checks every marked packet's source. Put back as it was.
|
# changes how the kernel checks every marked packet's source. Put back as it was.
|
||||||
srcValidMark = "/proc/sys/net/ipv4/conf/all/src_valid_mark";
|
srcValidMark = "/proc/sys/net/ipv4/conf/all/src_valid_mark";
|
||||||
savedSrcValidMark = name: "${runtimeDir name}/src_valid_mark";
|
# Unquoted: a runtime profile's name is checked against [A-Za-z0-9_-] first (runtimeSpec).
|
||||||
saveSrcValidMark = name: ''
|
savedSrcValidMark = spec: "${spec.runDir}/src_valid_mark";
|
||||||
[[ -e ${savedSrcValidMark name} ]] || cat ${srcValidMark} > ${savedSrcValidMark name}
|
saveSrcValidMark = spec: ''
|
||||||
|
[[ -e ${savedSrcValidMark spec} ]] || cat ${srcValidMark} > ${savedSrcValidMark spec}
|
||||||
'';
|
'';
|
||||||
restoreSrcValidMark = name: ''
|
restoreSrcValidMark = spec: ''
|
||||||
if [[ -s ${savedSrcValidMark name} ]]; then
|
if [[ -s ${savedSrcValidMark spec} ]]; then
|
||||||
cat ${savedSrcValidMark name} > ${srcValidMark} || true
|
cat ${savedSrcValidMark spec} > ${srcValidMark} || true
|
||||||
rm -f ${savedSrcValidMark name}
|
rm -f ${savedSrcValidMark spec}
|
||||||
fi
|
fi
|
||||||
'';
|
'';
|
||||||
|
|
||||||
@@ -233,15 +294,15 @@ let
|
|||||||
|
|
||||||
# An outbound interface keeps the host's routes and resolver, and marks its packets so TUN and
|
# An outbound interface keeps the host's routes and resolver, and marks its packets so TUN and
|
||||||
# TProxy let them past. A global one under the kill switch marks them with a mark it knows.
|
# TProxy let them past. A global one under the kill switch marks them with a mark it knows.
|
||||||
prepareCommand = profile: output: ''
|
prepareCommand = spec: output: ''
|
||||||
${pkgs.python3}/bin/python3 ${configTool} \
|
${pkgs.python3}/bin/python3 ${configTool} \
|
||||||
--manifest ${lib.escapeShellArg (toString (manifestFor profile))} \
|
${spec.source} \
|
||||||
--output ${output}${
|
--output ${output}${
|
||||||
if profile.asOutbound == "interface" then
|
if spec.profile.asOutbound == "interface" then
|
||||||
" --outbound-fwmark ${toString cfg.proxy.tproxy.proxyMark}"
|
" --outbound-fwmark ${toString cfg.proxy.tproxy.proxyMark}"
|
||||||
else
|
else
|
||||||
lib.optionalString (
|
lib.optionalString (
|
||||||
derived.killSwitchEnabled && profile.asOutbound == null
|
derived.killSwitchEnabled && spec.profile.asOutbound == null
|
||||||
) " --fwmark ${toString awgGlobalFwmark} --resolve-endpoints"
|
) " --fwmark ${toString awgGlobalFwmark} --resolve-endpoints"
|
||||||
}
|
}
|
||||||
'';
|
'';
|
||||||
@@ -259,19 +320,27 @@ let
|
|||||||
exec "$@"
|
exec "$@"
|
||||||
'';
|
'';
|
||||||
|
|
||||||
|
# A global profile, or an "interface" outbound: a unit for a declared profile (staticSpec),
|
||||||
|
# or the template the runtime ones start from (runtimeSpec). `conflicts`: the global units
|
||||||
|
# it stops by starting.
|
||||||
mkService =
|
mkService =
|
||||||
name: profile:
|
spec: conflicts:
|
||||||
let
|
let
|
||||||
outbound = profile.asOutbound == "interface";
|
inherit (spec) name profile outbound;
|
||||||
configPath = runtimeConfig name profile;
|
configPath = specConfig spec;
|
||||||
prepare = pkgs.writeShellScript "proxy-suite-awg" ''
|
# Every script: a template's instance name comes in as $1.
|
||||||
|
withInit = body: ''
|
||||||
|
${spec.init}
|
||||||
|
${body}
|
||||||
|
'';
|
||||||
|
prepare = pkgs.writeShellScript "proxy-suite-awg" (withInit ''
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
${
|
${
|
||||||
lib.optionalString (
|
lib.optionalString (
|
||||||
derived.killSwitchEnabled && !outbound
|
derived.killSwitchEnabled && !outbound
|
||||||
) "${pkgs.util-linux}/bin/unshare --mount ${ownLookups} "
|
) "${pkgs.util-linux}/bin/unshare --mount ${ownLookups} "
|
||||||
}${prepareCommand profile (lib.escapeShellArg configPath)}
|
}${prepareCommand spec ''"${configPath}"''}
|
||||||
'';
|
'');
|
||||||
proxyBypassUp = pkgs.writeShellScript "proxy-suite-awg" ''
|
proxyBypassUp = pkgs.writeShellScript "proxy-suite-awg" ''
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
${clearBypassRules}
|
${clearBypassRules}
|
||||||
@@ -286,12 +355,12 @@ let
|
|||||||
set +e
|
set +e
|
||||||
${clearBypassRules}
|
${clearBypassRules}
|
||||||
'';
|
'';
|
||||||
start = pkgs.writeShellScript "proxy-suite-awg" ''
|
start = pkgs.writeShellScript "proxy-suite-awg" (withInit ''
|
||||||
set -Eeuo pipefail
|
set -Eeuo pipefail
|
||||||
|
|
||||||
cleanup() {
|
cleanup() {
|
||||||
set +e
|
set +e
|
||||||
${awgCfg.toolsPackage}/bin/awg-quick down ${lib.escapeShellArg configPath}
|
${awgCfg.toolsPackage}/bin/awg-quick down "${configPath}"
|
||||||
|
|
||||||
# Without the control socket awg-quick cannot find its fwmark; clean up this
|
# Without the control socket awg-quick cannot find its fwmark; clean up this
|
||||||
# interface only.
|
# interface only.
|
||||||
@@ -318,7 +387,7 @@ let
|
|||||||
if outbound then
|
if outbound then
|
||||||
outboundRuleCleanup name profile
|
outboundRuleCleanup name profile
|
||||||
else
|
else
|
||||||
repliesDown profile + restoreSrcValidMark name
|
repliesDown profile + restoreSrcValidMark spec
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
trap cleanup ERR
|
trap cleanup ERR
|
||||||
@@ -326,9 +395,9 @@ let
|
|||||||
${awgCommon.modprobe}
|
${awgCommon.modprobe}
|
||||||
|
|
||||||
read -r implementation probe _ < <(${pkgs.python3}/bin/python3 ${configTool} \
|
read -r implementation probe _ < <(${pkgs.python3}/bin/python3 ${configTool} \
|
||||||
--inspect ${lib.escapeShellArg configPath})
|
--inspect "${configPath}")
|
||||||
${lib.optionalString (!outbound) (saveSrcValidMark name)}
|
${lib.optionalString (!outbound) (saveSrcValidMark spec)}
|
||||||
${awgCommon.awgQuickUp "$implementation" (lib.escapeShellArg configPath)}
|
${awgCommon.awgQuickUp "$implementation" ''"${configPath}"''}
|
||||||
${if outbound then outboundRoutesUp name profile else repliesUp profile}
|
${if outbound then outboundRoutesUp name profile else repliesUp profile}
|
||||||
|
|
||||||
${mkHandshakeHelpers profile}
|
${mkHandshakeHelpers profile}
|
||||||
@@ -344,21 +413,23 @@ let
|
|||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
|
|
||||||
echo "proxy-suite: AmneziaWG profile '${name}' did not complete a handshake; rolling back routes" >&2
|
echo "proxy-suite: AmneziaWG profile '$profile_name' did not complete a handshake; rolling back routes" >&2
|
||||||
false
|
false
|
||||||
'';
|
'');
|
||||||
stop = pkgs.writeShellScript "proxy-suite-awg" ''
|
stop = pkgs.writeShellScript "proxy-suite-awg" (withInit ''
|
||||||
set -uo pipefail
|
set -uo pipefail
|
||||||
status=0
|
status=0
|
||||||
${awgCfg.toolsPackage}/bin/awg-quick down ${lib.escapeShellArg configPath} || status=$?
|
${awgCfg.toolsPackage}/bin/awg-quick down "${configPath}" || status=$?
|
||||||
${
|
${
|
||||||
if outbound then
|
if outbound then
|
||||||
outboundRuleCleanup name profile
|
outboundRuleCleanup name profile
|
||||||
else
|
else
|
||||||
repliesDown profile + restoreSrcValidMark name
|
repliesDown profile + restoreSrcValidMark spec
|
||||||
}
|
}
|
||||||
exit "$status"
|
exit "$status"
|
||||||
'';
|
'');
|
||||||
|
# A template's scripts get the instance name.
|
||||||
|
withArg = script: if spec.template then "${script} %i" else script;
|
||||||
in
|
in
|
||||||
(
|
(
|
||||||
if outbound then
|
if outbound then
|
||||||
@@ -372,7 +443,11 @@ let
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
description = "proxy-suite AmneziaWG client profile ${name}";
|
description =
|
||||||
|
if spec.template then
|
||||||
|
"proxy-suite AmneziaWG client profile %i (added at runtime)"
|
||||||
|
else
|
||||||
|
"proxy-suite AmneziaWG client profile ${name}";
|
||||||
# Start the local proxy before AWG takes the default route, so HTTP_PROXY clients
|
# Start the local proxy before AWG takes the default route, so HTTP_PROXY clients
|
||||||
# do not race it.
|
# do not race it.
|
||||||
after = [
|
after = [
|
||||||
@@ -386,7 +461,7 @@ let
|
|||||||
++ lib.optional cfg.proxy.enable "proxy-suite-socks.service"
|
++ lib.optional cfg.proxy.enable "proxy-suite-socks.service"
|
||||||
++ lib.optional derived.killSwitchEnabled killSwitchUnit;
|
++ lib.optional derived.killSwitchEnabled killSwitchUnit;
|
||||||
wantedBy = lib.optionals profile.autostart [ "multi-user.target" ];
|
wantedBy = lib.optionals profile.autostart [ "multi-user.target" ];
|
||||||
conflicts = allProfileConflicts name ++ [
|
conflicts = conflicts ++ [
|
||||||
"proxy-suite-tun.service"
|
"proxy-suite-tun.service"
|
||||||
"proxy-suite-tproxy.service"
|
"proxy-suite-tproxy.service"
|
||||||
"proxy-suite-zapret.service"
|
"proxy-suite-zapret.service"
|
||||||
@@ -410,7 +485,7 @@ let
|
|||||||
serviceConfig = {
|
serviceConfig = {
|
||||||
Type = "oneshot";
|
Type = "oneshot";
|
||||||
RemainAfterExit = true;
|
RemainAfterExit = true;
|
||||||
RuntimeDirectory = serviceName name;
|
RuntimeDirectory = spec.runtimeDirectory;
|
||||||
RuntimeDirectoryMode = "0700";
|
RuntimeDirectoryMode = "0700";
|
||||||
UMask = "0077";
|
UMask = "0077";
|
||||||
NoNewPrivileges = true;
|
NoNewPrivileges = true;
|
||||||
@@ -421,9 +496,14 @@ let
|
|||||||
ProtectKernelLogs = true;
|
ProtectKernelLogs = true;
|
||||||
RestrictRealtime = true;
|
RestrictRealtime = true;
|
||||||
RestrictSUIDSGID = true;
|
RestrictSUIDSGID = true;
|
||||||
ExecStartPre = [ prepare ] ++ lib.optionals (cfg.proxy.enable && !outbound) [ proxyBypassUp ];
|
# Another profile stopping clears the bypass rules on its way out: before they go in.
|
||||||
ExecStart = start;
|
ExecStartPre = [
|
||||||
ExecStop = stop;
|
(withArg prepare)
|
||||||
|
]
|
||||||
|
++ lib.optionals (!outbound && derived.awgRuntimeGlobal) [ (withArg stopRuntimeProfiles) ]
|
||||||
|
++ lib.optionals (cfg.proxy.enable && !outbound) [ proxyBypassUp ];
|
||||||
|
ExecStart = withArg start;
|
||||||
|
ExecStop = withArg stop;
|
||||||
}
|
}
|
||||||
// lib.optionalAttrs (cfg.proxy.enable && !outbound) {
|
// lib.optionalAttrs (cfg.proxy.enable && !outbound) {
|
||||||
ExecStopPost = proxyBypassDown;
|
ExecStopPost = proxyBypassDown;
|
||||||
@@ -464,10 +544,81 @@ let
|
|||||||
fi
|
fi
|
||||||
''}
|
''}
|
||||||
profile="$RUNTIME_DIRECTORY/profile.conf"
|
profile="$RUNTIME_DIRECTORY/profile.conf"
|
||||||
${prepareCommand profile ''"$profile"''}
|
${prepareCommand (staticSpec ob.name profile) ''"$profile"''}
|
||||||
'';
|
'';
|
||||||
};
|
};
|
||||||
|
|
||||||
|
# Outbounds added with `proxy-ctl proxy outbounds add`: <tag>.awg in the runtime outbound
|
||||||
|
# spool, and the loopback port proxy-ctl gave it in <tag>.port. They run in wireproxy,
|
||||||
|
# which keeps the obfuscation; --config refuses hooks, as the spool is group-writable.
|
||||||
|
runtimeTunnelLastPort = awgRuntimeTunnelBasePort + awgRuntimeTunnelSlots - 1;
|
||||||
|
runtimeTunnelService = mkTunnel {
|
||||||
|
description = "proxy-suite AmneziaWG tunnel behind the %i outbound (added at runtime)";
|
||||||
|
unit = "proxy-suite-awg-tunnel@";
|
||||||
|
runtimeDirectory = "proxy-suite-awg-tunnel-%i";
|
||||||
|
engine = "userspace";
|
||||||
|
tag = "$TUNNEL_TAG";
|
||||||
|
tunnelPort = "$TUNNEL_PORT";
|
||||||
|
execArgs = " %i";
|
||||||
|
# The sync unit starts one per entry.
|
||||||
|
wantedBy = [ ];
|
||||||
|
# A removed entry exits cleanly, and stays stopped.
|
||||||
|
restart = "on-failure";
|
||||||
|
profile = ''
|
||||||
|
TUNNEL_TAG=''${1:-}
|
||||||
|
if [[ ! $TUNNEL_TAG =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then
|
||||||
|
echo "proxy-suite: '$TUNNEL_TAG' is not an outbound tag" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
profile="${runtimeOutboundsDir}/$TUNNEL_TAG.awg"
|
||||||
|
if [[ ! -s $profile ]]; then
|
||||||
|
echo "proxy-suite: no AmneziaWG outbound '$TUNNEL_TAG' in ${runtimeOutboundsDir}" >&2
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
TUNNEL_PORT=$(${pkgs.coreutils}/bin/head -n 1 "${runtimeOutboundsDir}/$TUNNEL_TAG.port" 2>/dev/null || true)
|
||||||
|
if [[ ! $TUNNEL_PORT =~ ^[0-9]+$ ]] || (( TUNNEL_PORT < ${toString awgRuntimeTunnelBasePort} || TUNNEL_PORT > ${toString runtimeTunnelLastPort} )); then
|
||||||
|
echo "proxy-suite: AmneziaWG outbound '$TUNNEL_TAG' needs a port in ${toString awgRuntimeTunnelBasePort}-${toString runtimeTunnelLastPort} in $TUNNEL_TAG.port" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
export TUNNEL_TAG TUNNEL_PORT
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
|
||||||
|
# One tunnel per runtime AmneziaWG outbound, and none for an entry removed since: at boot,
|
||||||
|
# and with every proxy-suite-outbound-reload, which proxy-ctl starts after a change.
|
||||||
|
runtimeSyncService = {
|
||||||
|
description = "proxy-suite AmneziaWG outbounds added at runtime";
|
||||||
|
after = [ "network-online.target" ];
|
||||||
|
wants = [ "network-online.target" ];
|
||||||
|
wantedBy = [
|
||||||
|
"multi-user.target"
|
||||||
|
"proxy-suite-outbound-reload.service"
|
||||||
|
];
|
||||||
|
serviceConfig = {
|
||||||
|
Type = "oneshot";
|
||||||
|
ExecStart = pkgs.writeShellScript "proxy-suite-awg" ''
|
||||||
|
set -uo pipefail
|
||||||
|
declare -A keep=()
|
||||||
|
for entry in "${runtimeOutboundsDir}"/*.awg; do
|
||||||
|
[[ -e $entry ]] || continue
|
||||||
|
tag=''${entry##*/}
|
||||||
|
tag=''${tag%.awg}
|
||||||
|
keep[$tag]=1
|
||||||
|
${systemctl} start --no-block "proxy-suite-awg-tunnel@$tag.service" || true
|
||||||
|
done
|
||||||
|
${systemctl} list-units --all --plain --no-legend 'proxy-suite-awg-tunnel@*.service' \
|
||||||
|
| ${pkgs.gnugrep}/bin/grep -o 'proxy-suite-awg-tunnel@[^ ]*\.service' \
|
||||||
|
| while read -r unit; do
|
||||||
|
tag=''${unit#proxy-suite-awg-tunnel@}
|
||||||
|
tag=''${tag%.service}
|
||||||
|
[[ -n ''${keep[$tag]:-} ]] || ${systemctl} stop --no-block "$unit" || true
|
||||||
|
done
|
||||||
|
# grep finds nothing when no tunnel is loaded, which pipefail would make a failure.
|
||||||
|
exit 0
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
# Runs alongside a started profile. Its pings keep traffic flowing, and traffic makes
|
# Runs alongside a started profile. Its pings keep traffic flowing, and traffic makes
|
||||||
# WireGuard rekey every RekeyAfterTime (120 seconds by default); a handshake older than that
|
# WireGuard rekey every RekeyAfterTime (120 seconds by default); a handshake older than that
|
||||||
# on two checks in a row is a rekey that is not getting through, so the interface moves to
|
# on two checks in a row is a rekey that is not getting through, so the interface moves to
|
||||||
@@ -477,15 +628,18 @@ let
|
|||||||
# peer can keep rekeying while carrying no traffic. After three misses the peer is re-added
|
# peer can keep rekeying while carrying no traffic. After three misses the peer is re-added
|
||||||
# for a fresh session (a new port alone keeps the old one), at most once in five minutes.
|
# for a fresh session (a new port alone keeps the old one), at most once in five minutes.
|
||||||
mkWatchdog =
|
mkWatchdog =
|
||||||
name: profile:
|
spec:
|
||||||
let
|
let
|
||||||
|
inherit (spec) profile;
|
||||||
egressProbe = profile.asOutbound == "interface";
|
egressProbe = profile.asOutbound == "interface";
|
||||||
|
unit = if spec.template then "proxy-suite-awg@%i.service" else "${spec.unit}.service";
|
||||||
watchdog = pkgs.writeShellScript "proxy-suite-awg" ''
|
watchdog = pkgs.writeShellScript "proxy-suite-awg" ''
|
||||||
|
${spec.init}
|
||||||
set -uo pipefail
|
set -uo pipefail
|
||||||
read -r _ probe rekey < <(${pkgs.python3}/bin/python3 ${configTool} \
|
read -r _ probe rekey < <(${pkgs.python3}/bin/python3 ${configTool} \
|
||||||
--inspect ${lib.escapeShellArg (runtimeConfig name profile)}) || exit 1
|
--inspect "${specConfig spec}") || exit 1
|
||||||
if (( rekey == 0 )); then
|
if (( rekey == 0 )); then
|
||||||
echo "proxy-suite: AmneziaWG profile '${name}' never rekeys; nothing to watch" >&2
|
echo "proxy-suite: AmneziaWG profile '$profile_name' never rekeys; nothing to watch" >&2
|
||||||
exec ${pkgs.coreutils}/bin/sleep infinity
|
exec ${pkgs.coreutils}/bin/sleep infinity
|
||||||
fi
|
fi
|
||||||
${mkHandshakeHelpers profile}
|
${mkHandshakeHelpers profile}
|
||||||
@@ -512,7 +666,7 @@ let
|
|||||||
if (( $(handshake_age) <= rekey + 10 )); then
|
if (( $(handshake_age) <= rekey + 10 )); then
|
||||||
stale=0
|
stale=0
|
||||||
elif (( ++stale >= 2 )); then
|
elif (( ++stale >= 2 )); then
|
||||||
echo "proxy-suite: AmneziaWG profile '${name}' is not rekeying; moving to a new source port" >&2
|
echo "proxy-suite: AmneziaWG profile '$profile_name' is not rekeying; moving to a new source port" >&2
|
||||||
new_source_port
|
new_source_port
|
||||||
stale=0
|
stale=0
|
||||||
${lib.optionalString egressProbe "continue"}
|
${lib.optionalString egressProbe "continue"}
|
||||||
@@ -522,7 +676,7 @@ let
|
|||||||
${lib.escapeShellArg cfg.proxy.urlTest.url}; then
|
${lib.escapeShellArg cfg.proxy.urlTest.url}; then
|
||||||
misses=0
|
misses=0
|
||||||
elif (( ++misses >= 3 && SECONDS - last_session >= 300 )); then
|
elif (( ++misses >= 3 && SECONDS - last_session >= 300 )); then
|
||||||
echo "proxy-suite: AmneziaWG profile '${name}' carries no IPv4 past its peer; starting a new session" >&2
|
echo "proxy-suite: AmneziaWG profile '$profile_name' carries no IPv4 past its peer; starting a new session" >&2
|
||||||
new_session
|
new_session
|
||||||
misses=0
|
misses=0
|
||||||
last_session=$SECONDS
|
last_session=$SECONDS
|
||||||
@@ -532,12 +686,15 @@ let
|
|||||||
'';
|
'';
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
description = "proxy-suite AmneziaWG client profile ${name} watchdog";
|
description = "proxy-suite AmneziaWG client profile ${
|
||||||
bindsTo = [ "${serviceName name}.service" ];
|
if spec.template then "%i" else spec.name
|
||||||
after = [ "${serviceName name}.service" ];
|
} watchdog";
|
||||||
wantedBy = [ "${serviceName name}.service" ];
|
bindsTo = [ unit ];
|
||||||
|
after = [ unit ];
|
||||||
|
# A template's instances are pulled in by the profile's own Wants=.
|
||||||
|
wantedBy = lib.optional (!spec.template) unit;
|
||||||
serviceConfig = {
|
serviceConfig = {
|
||||||
ExecStart = watchdog;
|
ExecStart = if spec.template then "${watchdog} %i" else watchdog;
|
||||||
Restart = "on-failure";
|
Restart = "on-failure";
|
||||||
RestartSec = 5;
|
RestartSec = 5;
|
||||||
CapabilityBoundingSet = [
|
CapabilityBoundingSet = [
|
||||||
@@ -620,7 +777,9 @@ let
|
|||||||
)
|
)
|
||||||
) profileNames;
|
) profileNames;
|
||||||
|
|
||||||
interfaceNames = map (name: profiles.${name}.interfaceName) profileNames;
|
interfaceNames =
|
||||||
|
map (name: profiles.${name}.interfaceName) profileNames
|
||||||
|
++ lib.optional derived.awgRuntimeGlobal awgCfg.runtime.interfaceName;
|
||||||
autostartProfiles = builtins.filter (name: profiles.${name}.autostart) globalProfileNames;
|
autostartProfiles = builtins.filter (name: profiles.${name}.autostart) globalProfileNames;
|
||||||
globalAutostartCount =
|
globalAutostartCount =
|
||||||
builtins.length autostartProfiles + (if cfg.proxy.autostart != null then 1 else 0);
|
builtins.length autostartProfiles + (if cfg.proxy.autostart != null then 1 else 0);
|
||||||
@@ -630,10 +789,12 @@ in
|
|||||||
awgCfg.toolsPackage
|
awgCfg.toolsPackage
|
||||||
awgCfg.userspacePackage
|
awgCfg.userspacePackage
|
||||||
]
|
]
|
||||||
++ lib.optional (builtins.any (ob: ob.kind == "userspace") tunnelOutbounds) awgCfg.wireproxyPackage;
|
++ lib.optional (
|
||||||
|
derived.awgRuntimeOutbounds || builtins.any (ob: ob.kind == "userspace") tunnelOutbounds
|
||||||
|
) awgCfg.wireproxyPackage;
|
||||||
|
|
||||||
services.proxy-suite.internal.groups = lib.optional (
|
services.proxy-suite.internal.groups = lib.optional (
|
||||||
derived.killSwitchEnabled && globalProfileNames != [ ]
|
derived.killSwitchEnabled && derived.awgGlobalAvailable
|
||||||
) awgGlobalGroup;
|
) awgGlobalGroup;
|
||||||
|
|
||||||
services.proxy-suite.internal.kernelModulePackages =
|
services.proxy-suite.internal.kernelModulePackages =
|
||||||
@@ -649,11 +810,30 @@ in
|
|||||||
|
|
||||||
services.proxy-suite.internal.services = lib.mkMerge [
|
services.proxy-suite.internal.services = lib.mkMerge [
|
||||||
(lib.mapAttrs' (
|
(lib.mapAttrs' (
|
||||||
name: profile: lib.nameValuePair (serviceName name) (mkService name profile)
|
name: profile:
|
||||||
|
lib.nameValuePair (serviceName name) (
|
||||||
|
mkService (staticSpec name profile) (allProfileConflicts name)
|
||||||
|
)
|
||||||
) interfaceProfiles)
|
) interfaceProfiles)
|
||||||
(lib.mapAttrs' (
|
(lib.mapAttrs' (
|
||||||
name: profile: lib.nameValuePair "${serviceName name}-watchdog" (mkWatchdog name profile)
|
name: profile:
|
||||||
|
lib.nameValuePair "${serviceName name}-watchdog" (mkWatchdog (staticSpec name profile))
|
||||||
) interfaceProfiles)
|
) interfaceProfiles)
|
||||||
|
(lib.mkIf derived.awgRuntimeGlobal {
|
||||||
|
"proxy-suite-awg@" = lib.mkMerge [
|
||||||
|
(mkService runtimeSpec (map (other: "${serviceName other}.service") globalProfileNames))
|
||||||
|
{
|
||||||
|
wants = [ "proxy-suite-awg-watchdog@%i.service" ];
|
||||||
|
# The kill switch cannot order itself after instances it does not know.
|
||||||
|
before = [ killSwitchUnit ];
|
||||||
|
}
|
||||||
|
];
|
||||||
|
"proxy-suite-awg-watchdog@" = mkWatchdog runtimeSpec;
|
||||||
|
})
|
||||||
|
(lib.mkIf derived.awgRuntimeOutbounds {
|
||||||
|
"proxy-suite-awg-tunnel@" = runtimeTunnelService;
|
||||||
|
proxy-suite-awg-runtime-sync = runtimeSyncService;
|
||||||
|
})
|
||||||
(lib.listToAttrs (
|
(lib.listToAttrs (
|
||||||
map (ob: lib.nameValuePair (serviceName ob.name) (mkTunnelService ob)) tunnelOutbounds
|
map (ob: lib.nameValuePair (serviceName ob.name) (mkTunnelService ob)) tunnelOutbounds
|
||||||
))
|
))
|
||||||
@@ -667,8 +847,8 @@ in
|
|||||||
|
|
||||||
assertions = profileAssertions ++ [
|
assertions = profileAssertions ++ [
|
||||||
{
|
{
|
||||||
assertion = profiles != { };
|
assertion = profiles != { } || derived.awgRuntimeGlobal || derived.awgRuntimeOutbounds;
|
||||||
message = "proxy-suite: amneziaWg.enable requires at least one profile";
|
message = "proxy-suite: amneziaWg.enable needs a profile, or amneziaWg.runtime.enable for profiles added with proxy-ctl (global ones need a root host, outbounds proxy.enable)";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = builtins.length interfaceNames == builtins.length (lib.unique interfaceNames);
|
assertion = builtins.length interfaceNames == builtins.length (lib.unique interfaceNames);
|
||||||
|
|||||||
@@ -59,7 +59,7 @@ let
|
|||||||
# Some global tunnel for it to guard.
|
# Some global tunnel for it to guard.
|
||||||
killSwitchEnabled =
|
killSwitchEnabled =
|
||||||
cfg.killSwitch.enable
|
cfg.killSwitch.enable
|
||||||
&& (proxyEnabled && (globalTun.enable || globalTproxy.enable) || awgGlobalProfiles != { });
|
&& (proxyEnabled && (globalTun.enable || globalTproxy.enable) || awgGlobalAvailable);
|
||||||
perAppRoutingTun = cfg.perAppRouting.tun;
|
perAppRoutingTun = cfg.perAppRouting.tun;
|
||||||
perAppRoutingTproxy = cfg.perAppRouting.tproxy;
|
perAppRoutingTproxy = cfg.perAppRouting.tproxy;
|
||||||
zapretCfg = cfg.zapret;
|
zapretCfg = cfg.zapret;
|
||||||
@@ -158,6 +158,14 @@ let
|
|||||||
}
|
}
|
||||||
) (builtins.filter (name: awgProfiles.${name}.asOutbound != null) (builtins.attrNames awgProfiles));
|
) (builtins.filter (name: awgProfiles.${name}.asOutbound != null) (builtins.attrNames awgProfiles));
|
||||||
awgInterfaceOutbounds = builtins.filter (ob: ob.kind == "interface") awgOutbounds;
|
awgInterfaceOutbounds = builtins.filter (ob: ob.kind == "interface") awgOutbounds;
|
||||||
|
# Added with proxy-ctl at runtime: global profiles (`awg add`), as template instances
|
||||||
|
# sharing runtime.interfaceName, need root; outbounds (`proxy outbounds add`) run in
|
||||||
|
# wireproxy template instances, which the supervisor cannot template.
|
||||||
|
awgRuntimeEnabled = cfg.amneziaWg.enable && cfg.amneziaWg.runtime.enable;
|
||||||
|
awgRuntimeGlobal = awgRuntimeEnabled && cfg.host.privileged;
|
||||||
|
awgRuntimeOutbounds = awgRuntimeEnabled && proxyEnabled && cfg.host.serviceManager != "supervisor";
|
||||||
|
# Some global profile may run: declared, or added at runtime.
|
||||||
|
awgGlobalAvailable = awgGlobalProfiles != { } || awgRuntimeGlobal;
|
||||||
# Profiles run behind a loopback SOCKS hop rather than an interface.
|
# Profiles run behind a loopback SOCKS hop rather than an interface.
|
||||||
awgTunnelOutbounds = builtins.filter (ob: ob.kind != "interface") awgOutbounds;
|
awgTunnelOutbounds = builtins.filter (ob: ob.kind != "interface") awgOutbounds;
|
||||||
|
|
||||||
@@ -442,6 +450,12 @@ let
|
|||||||
awgOutboundRulePriority = 8991;
|
awgOutboundRulePriority = 8991;
|
||||||
# A global AmneziaWG profile's rules keeping the host's UDP services on the main table.
|
# A global AmneziaWG profile's rules keeping the host's UDP services on the main table.
|
||||||
awgServerUdpRulePriority = 8989;
|
awgServerUdpRulePriority = 8989;
|
||||||
|
# Global profiles and outbounds added with proxy-ctl: <name>.conf here, and
|
||||||
|
# <tag>.awg with <tag>.port in runtimeOutboundsDir.
|
||||||
|
runtimeAwgDir = "${stateDir}/amneziawg.d";
|
||||||
|
# Loopback SOCKS listeners of the runtime AmneziaWG outbounds, one per slot.
|
||||||
|
awgRuntimeTunnelBasePort = 18800;
|
||||||
|
awgRuntimeTunnelSlots = 32;
|
||||||
# sing-box's fake IP caches, one per TUN config; the start script hands it to the backend.
|
# sing-box's fake IP caches, one per TUN config; the start script hands it to the backend.
|
||||||
fakeIpCacheDir = "${stateDir}/fakeip";
|
fakeIpCacheDir = "${stateDir}/fakeip";
|
||||||
# Downloaded proxy.routing.ruleSets, one file each, written by the service user.
|
# Downloaded proxy.routing.ruleSets, one file each, written by the service user.
|
||||||
@@ -550,6 +564,9 @@ in
|
|||||||
torOnionInbounds
|
torOnionInbounds
|
||||||
proxyInboundOnionCapable
|
proxyInboundOnionCapable
|
||||||
awgGlobalProfiles
|
awgGlobalProfiles
|
||||||
|
awgGlobalAvailable
|
||||||
|
awgRuntimeGlobal
|
||||||
|
awgRuntimeOutbounds
|
||||||
awgOutbounds
|
awgOutbounds
|
||||||
awgInterfaceOutbounds
|
awgInterfaceOutbounds
|
||||||
awgTunnelOutbounds
|
awgTunnelOutbounds
|
||||||
|
|||||||
@@ -6,7 +6,12 @@
|
|||||||
}:
|
}:
|
||||||
|
|
||||||
let
|
let
|
||||||
inherit (import ./derived.nix { inherit lib cfg; }) constants awgGlobalProfiles;
|
inherit (import ./derived.nix { inherit lib cfg; })
|
||||||
|
constants
|
||||||
|
awgGlobalProfiles
|
||||||
|
awgGlobalAvailable
|
||||||
|
awgRuntimeGlobal
|
||||||
|
;
|
||||||
inherit (constants) serviceUser;
|
inherit (constants) serviceUser;
|
||||||
proxyCfg = cfg.proxy;
|
proxyCfg = cfg.proxy;
|
||||||
globalTproxy = proxyCfg.tproxy;
|
globalTproxy = proxyCfg.tproxy;
|
||||||
@@ -158,8 +163,10 @@ let
|
|||||||
++ lib.optional perAppTun.enable perAppTun.fwmark
|
++ lib.optional perAppTun.enable perAppTun.fwmark
|
||||||
++ lib.optional perAppTproxy.enable perAppTproxy.fwmark
|
++ lib.optional perAppTproxy.enable perAppTproxy.fwmark
|
||||||
++ lib.optional tgWsProxyBypassEnabled tgWsProxyCfg.fwmark
|
++ lib.optional tgWsProxyBypassEnabled tgWsProxyCfg.fwmark
|
||||||
++ lib.optional (awgGlobalProfiles != { }) constants.awgGlobalFwmark;
|
++ lib.optional awgGlobalAvailable constants.awgGlobalFwmark;
|
||||||
awgGlobalInterfaces = lib.mapAttrsToList (_: profile: profile.interfaceName) awgGlobalProfiles;
|
awgGlobalInterfaces =
|
||||||
|
lib.mapAttrsToList (_: profile: profile.interfaceName) awgGlobalProfiles
|
||||||
|
++ lib.optional awgRuntimeGlobal cfg.amneziaWg.runtime.interfaceName;
|
||||||
globalTunEnabled = proxyCfg.enable && proxyCfg.tun.enable;
|
globalTunEnabled = proxyCfg.enable && proxyCfg.tun.enable;
|
||||||
killSwitchAllowLines = ''
|
killSwitchAllowLines = ''
|
||||||
ip daddr $RESERVED_IP accept
|
ip daddr $RESERVED_IP accept
|
||||||
@@ -183,7 +190,7 @@ let
|
|||||||
ip daddr ${proxyCfg.tun.address} accept
|
ip daddr ${proxyCfg.tun.address} accept
|
||||||
${lib.optionalString proxyCfg.ipv6 "ip6 daddr ${constants.globalTunIPv6Address} accept"}
|
${lib.optionalString proxyCfg.ipv6 "ip6 daddr ${constants.globalTunIPv6Address} accept"}
|
||||||
''}
|
''}
|
||||||
${lib.optionalString (awgGlobalProfiles != { }) ''
|
${lib.optionalString awgGlobalAvailable ''
|
||||||
oifname { ${lib.concatMapStringsSep ", " (i: ''"${i}"'') awgGlobalInterfaces} } accept
|
oifname { ${lib.concatMapStringsSep ", " (i: ''"${i}"'') awgGlobalInterfaces} } accept
|
||||||
meta skgid "${constants.awgGlobalGroup}" accept
|
meta skgid "${constants.awgGlobalGroup}" accept
|
||||||
''}
|
''}
|
||||||
|
|||||||
@@ -66,6 +66,25 @@ in
|
|||||||
];
|
];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
runtime = {
|
||||||
|
enable = mkOption {
|
||||||
|
type = types.bool;
|
||||||
|
default = true;
|
||||||
|
description = ''
|
||||||
|
Let `proxy-ctl` add configs and `vpn://` links without a rebuild: `proxy-ctl awg add`
|
||||||
|
for a global profile (root hosts only), and `proxy-ctl proxy outbounds add` for an
|
||||||
|
outbound, which runs in wireproxy (needs `proxy.enable`). wg-quick hooks such as
|
||||||
|
`PostUp` are always refused in them. With this on, `profiles` may be empty.
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
|
||||||
|
interfaceName = mkOption {
|
||||||
|
type = types.strMatching "^[A-Za-z0-9_.-]{1,15}$";
|
||||||
|
default = "awg-rt";
|
||||||
|
description = "Interface of the global profiles added at runtime. Only one of them runs at a time, so they share it.";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
profiles = mkOption {
|
profiles = mkOption {
|
||||||
type = types.attrsOf t.profileType;
|
type = types.attrsOf t.profileType;
|
||||||
default = { };
|
default = { };
|
||||||
|
|||||||
@@ -30,6 +30,23 @@ in
|
|||||||
example = "vpn.example.com";
|
example = "vpn.example.com";
|
||||||
};
|
};
|
||||||
|
|
||||||
|
serverAliases = mkOption {
|
||||||
|
type = types.listOf (types.strMatching "[^[:space:]]+");
|
||||||
|
default = [ ];
|
||||||
|
description = ''
|
||||||
|
Other names and IPs of this host that clients reach through the tunnel, such as a
|
||||||
|
TURN relay's name beside the site on `serverAddress`. Like `serverAddress`, they go
|
||||||
|
direct on the listener ports instead of looping back through `routing.via`, which
|
||||||
|
often cannot reach this host at all. List the IPs too: a client that resolves a name
|
||||||
|
itself hands XRay the address, which no name rule matches.
|
||||||
|
'';
|
||||||
|
example = [
|
||||||
|
"turn.example.com"
|
||||||
|
"203.0.113.10"
|
||||||
|
"2001:db8::10"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
|
||||||
openFirewall = bool true "Open the firewall for every listener not on loopback.";
|
openFirewall = bool true "Open the firewall for every listener not on loopback.";
|
||||||
shareLinks = bool true "Generate client share links for `proxy-ctl inbounds link`. Readable by root, and by `userControl.group` with the secrets scope.";
|
shareLinks = bool true "Generate client share links for `proxy-ctl inbounds link`. Readable by root, and by `userControl.group` with the secrets scope.";
|
||||||
|
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ in
|
|||||||
"zapret"
|
"zapret"
|
||||||
"stats"
|
"stats"
|
||||||
"whitelistBypass"
|
"whitelistBypass"
|
||||||
|
"amneziaWg"
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
default = [ ];
|
default = [ ];
|
||||||
@@ -39,6 +40,9 @@ in
|
|||||||
- "zapret": change zapret2's learned sites, and `zapret cutoff probe`.
|
- "zapret": change zapret2's learned sites, and `zapret cutoff probe`.
|
||||||
- "stats": `inbounds stats`.
|
- "stats": `inbounds stats`.
|
||||||
- "whitelistBypass": everything under `proxy-ctl wl`.
|
- "whitelistBypass": everything under `proxy-ctl wl`.
|
||||||
|
- "amneziaWg": add and remove global AmneziaWG profiles (`proxy-ctl awg add`, `awg rm`).
|
||||||
|
A global profile takes over the host's routes and DNS. Starting and stopping one is
|
||||||
|
"services"; an AmneziaWG outbound is "outbounds".
|
||||||
'';
|
'';
|
||||||
example = [
|
example = [
|
||||||
"services"
|
"services"
|
||||||
|
|||||||
@@ -38,13 +38,15 @@ let
|
|||||||
};
|
};
|
||||||
|
|
||||||
# The address clients dial must stay reachable even when blockRu covers it
|
# The address clients dial must stay reachable even when blockRu covers it
|
||||||
# (a .ru domain or IP). After blockPrivate, so it cannot open the LAN.
|
# (a .ru domain or IP). After blockPrivate, so it cannot open the LAN. Its aliases
|
||||||
serverAddressIsIp =
|
# too: routing.via usually cannot loop back to this host, so they would fail there.
|
||||||
let
|
isIp =
|
||||||
addr = proxyInboundsCfg.serverAddress;
|
addr: lib.hasInfix ":" addr || builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+" addr != null;
|
||||||
in
|
serverAddresses =
|
||||||
addr != null
|
lib.optional (proxyInboundsCfg.serverAddress != null) proxyInboundsCfg.serverAddress
|
||||||
&& (lib.hasInfix ":" addr || builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+" addr != null);
|
++ proxyInboundsCfg.serverAliases;
|
||||||
|
serverIps = lib.unique (builtins.filter isIp serverAddresses);
|
||||||
|
serverNames = lib.unique (builtins.filter (addr: !isIp addr) serverAddresses);
|
||||||
|
|
||||||
# Only the ports clients dial there: the rest of this host (wildcard services the
|
# Only the ports clients dial there: the rest of this host (wildcard services the
|
||||||
# firewall keeps from the internet) must not be reachable through it.
|
# firewall keeps from the internet) must not be reachable through it.
|
||||||
@@ -59,23 +61,23 @@ let
|
|||||||
]
|
]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
# Names and IPs in rules of their own: XRay ANDs the fields of one rule.
|
||||||
|
mkServerAddressRule =
|
||||||
|
ruleTag: field: items:
|
||||||
|
lib.optional (items != [ ] && exceptionInboundTags != [ ]) {
|
||||||
|
type = "field";
|
||||||
|
inherit ruleTag;
|
||||||
|
${field} = items;
|
||||||
|
inboundTag = exceptionInboundTags;
|
||||||
|
port = lib.concatMapStringsSep "," toString serverAddressPorts;
|
||||||
|
outboundTag = "direct";
|
||||||
|
};
|
||||||
|
|
||||||
serverAddressRule =
|
serverAddressRule =
|
||||||
lib.optional (proxyInboundsCfg.serverAddress != null && exceptionInboundTags != [ ])
|
mkServerAddressRule "inbound-server-address-direct" "domain" (
|
||||||
(
|
map (name: "full:${name}") serverNames
|
||||||
{
|
)
|
||||||
type = "field";
|
++ mkServerAddressRule "inbound-server-address-direct-ip" "ip" serverIps;
|
||||||
ruleTag = "inbound-server-address-direct";
|
|
||||||
inboundTag = exceptionInboundTags;
|
|
||||||
port = lib.concatMapStringsSep "," toString serverAddressPorts;
|
|
||||||
outboundTag = "direct";
|
|
||||||
}
|
|
||||||
// (
|
|
||||||
if serverAddressIsIp then
|
|
||||||
{ ip = [ proxyInboundsCfg.serverAddress ]; }
|
|
||||||
else
|
|
||||||
{ domain = [ "full:${proxyInboundsCfg.serverAddress}" ]; }
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
blockRuRules = lib.optionals proxyInboundsCfg.routing.blockRu [
|
blockRuRules = lib.optionals proxyInboundsCfg.routing.blockRu [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -82,7 +82,12 @@ let
|
|||||||
++ map (j: j.port) derived.whitelistBypassJoiners
|
++ map (j: j.port) derived.whitelistBypassJoiners
|
||||||
++ lib.optionals derived.proxyInboundsEnabled (
|
++ lib.optionals derived.proxyInboundsEnabled (
|
||||||
map (listener: listener.internalPort) derived.proxyInboundsAwg
|
map (listener: listener.internalPort) derived.proxyInboundsAwg
|
||||||
);
|
)
|
||||||
|
++ awgRuntimeTunnelPorts;
|
||||||
|
# The loopback listeners of AmneziaWG outbounds added at runtime, one per slot.
|
||||||
|
awgRuntimeTunnelPorts = lib.optionals derived.awgRuntimeOutbounds (
|
||||||
|
lib.genList (i: constants.awgRuntimeTunnelBasePort + i) constants.awgRuntimeTunnelSlots
|
||||||
|
);
|
||||||
|
|
||||||
# A rootless host (home-manager, nix-on-droid) runs everything as the user: nothing
|
# A rootless host (home-manager, nix-on-droid) runs everything as the user: nothing
|
||||||
# that programs routing, firewalls or interfaces, and no privileged ports.
|
# that programs routing, firewalls or interfaces, and no privileged ports.
|
||||||
@@ -274,7 +279,7 @@ let
|
|||||||
(mkAssertion
|
(mkAssertion
|
||||||
(
|
(
|
||||||
!derived.killSwitchEnabled
|
!derived.killSwitchEnabled
|
||||||
|| derived.awgGlobalProfiles == { }
|
|| !derived.awgGlobalAvailable
|
||||||
|| !builtins.elem constants.awgGlobalFwmark (
|
|| !builtins.elem constants.awgGlobalFwmark (
|
||||||
[
|
[
|
||||||
globalTproxy.fwmark
|
globalTproxy.fwmark
|
||||||
@@ -461,11 +466,12 @@ let
|
|||||||
!proxyInboundsEnabled
|
!proxyInboundsEnabled
|
||||||
|| !lib.any (port: builtins.elem port derived.proxyInboundPorts) (
|
|| !lib.any (port: builtins.elem port derived.proxyInboundPorts) (
|
||||||
map (listener: listener.internalPort) derived.proxyInboundsAwg
|
map (listener: listener.internalPort) derived.proxyInboundsAwg
|
||||||
|
++ awgRuntimeTunnelPorts
|
||||||
++ builtins.attrValues derived.constants.xrayDnsBridgePorts
|
++ builtins.attrValues derived.constants.xrayDnsBridgePorts
|
||||||
++ lib.optionals hybridEnabled (builtins.attrValues derived.constants.xraySidecarPorts)
|
++ lib.optionals hybridEnabled (builtins.attrValues derived.constants.xraySidecarPorts)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
"proxy-suite: a proxyInbounds listener port collides with a port proxy-suite uses internally (the AmneziaWG listeners' loopback inbounds from 18700, 18533-18535, or the hybrid XRay sidecar's 33080, 33180 and 33280)"
|
"proxy-suite: a proxyInbounds listener port collides with a port proxy-suite uses internally (the AmneziaWG listeners' loopback inbounds from 18700, the runtime AmneziaWG outbounds' 18800-18831, 18533-18535, or the hybrid XRay sidecar's 33080, 33180 and 33280)"
|
||||||
)
|
)
|
||||||
# The prober opens one loopback listener per exit from probeBasePort; the WARP
|
# The prober opens one loopback listener per exit from probeBasePort; the WARP
|
||||||
# and AmneziaWG tunnels open two each from their own bases. They all bind
|
# and AmneziaWG tunnels open two each from their own bases. They all bind
|
||||||
@@ -764,7 +770,8 @@ let
|
|||||||
map (ib: ib.listener.amneziaWg.interfaceName) awgListeners
|
map (ib: ib.listener.amneziaWg.interfaceName) awgListeners
|
||||||
++ lib.optionals cfg.amneziaWg.enable (
|
++ lib.optionals cfg.amneziaWg.enable (
|
||||||
lib.mapAttrsToList (_: profile: profile.interfaceName) cfg.amneziaWg.profiles
|
lib.mapAttrsToList (_: profile: profile.interfaceName) cfg.amneziaWg.profiles
|
||||||
);
|
)
|
||||||
|
++ lib.optional derived.awgRuntimeGlobal cfg.amneziaWg.runtime.interfaceName;
|
||||||
otherInterfaces =
|
otherInterfaces =
|
||||||
lib.optional (proxyEnabled && globalTun.enable) globalTun.interface
|
lib.optional (proxyEnabled && globalTun.enable) globalTun.interface
|
||||||
++ lib.optional (perAppRoutingCfg.enable && perAppRoutingTun.enable) perAppRoutingTun.interface;
|
++ lib.optional (perAppRoutingCfg.enable && perAppRoutingTun.enable) perAppRoutingTun.interface;
|
||||||
|
|||||||
@@ -22,6 +22,9 @@ let
|
|||||||
proxyInboundsCfg
|
proxyInboundsCfg
|
||||||
proxyInboundsEnabled
|
proxyInboundsEnabled
|
||||||
amneziaWgProfileNamesFile
|
amneziaWgProfileNamesFile
|
||||||
|
awgRuntimeGlobal
|
||||||
|
awgRuntimeOutbounds
|
||||||
|
proxySuiteScriptsDir
|
||||||
ruleSets
|
ruleSets
|
||||||
pkgs
|
pkgs
|
||||||
;
|
;
|
||||||
@@ -73,6 +76,13 @@ in
|
|||||||
ROUTE_MODE_STATE_FILE = routeModeStateFile;
|
ROUTE_MODE_STATE_FILE = routeModeStateFile;
|
||||||
DEFAULT_ROUTE_MODE = if proxyCfg.routing.default == "proxy" then "blacklist" else "whitelist";
|
DEFAULT_ROUTE_MODE = if proxyCfg.routing.default == "proxy" then "blacklist" else "whitelist";
|
||||||
AWG_PROFILES_FILE = toString amneziaWgProfileNamesFile;
|
AWG_PROFILES_FILE = toString amneziaWgProfileNamesFile;
|
||||||
|
# Profiles and outbounds added with `awg add` and `proxy outbounds add`.
|
||||||
|
AWG_RUNTIME_GLOBAL = flag awgRuntimeGlobal;
|
||||||
|
AWG_RUNTIME_OUTBOUNDS = flag awgRuntimeOutbounds;
|
||||||
|
AWG_RUNTIME_DIR = constants.runtimeAwgDir;
|
||||||
|
AWG_CONFIG_TOOL = "${proxySuiteScriptsDir}/amneziawg_config.py";
|
||||||
|
AWG_TUNNEL_BASE_PORT = toString constants.awgRuntimeTunnelBasePort;
|
||||||
|
AWG_TUNNEL_SLOTS = toString constants.awgRuntimeTunnelSlots;
|
||||||
WL_FILE = toString (
|
WL_FILE = toString (
|
||||||
pkgs.writeText "proxy-suite-control" (
|
pkgs.writeText "proxy-suite-control" (
|
||||||
builtins.toJSON (
|
builtins.toJSON (
|
||||||
|
|||||||
@@ -175,24 +175,33 @@ lib.mkMerge [
|
|||||||
# files proxy-ctl drops here inherit the group; without the outbounds scope
|
# 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
|
# only root writes them. tmpfiles rather than the start scripts, so the group can add an
|
||||||
# outbound before the proxy has ever run.
|
# outbound before the proxy has ever run.
|
||||||
tmpfiles = lib.mkIf (cfg.enable && proxyEnabled) (
|
tmpfiles = lib.mkMerge [
|
||||||
map
|
(lib.mkIf (cfg.enable && proxyEnabled) (
|
||||||
(
|
map
|
||||||
dir:
|
(
|
||||||
"d ${dir} ${
|
dir:
|
||||||
if userControlAllows "outbounds" then
|
"d ${dir} ${
|
||||||
"2770 root ${userControlCfg.group}"
|
if userControlAllows "outbounds" then
|
||||||
else if constants.privileged then
|
"2770 root ${userControlCfg.group}"
|
||||||
"0700 root root"
|
else if constants.privileged then
|
||||||
else
|
"0700 root root"
|
||||||
"0700 - -"
|
else
|
||||||
} -"
|
"0700 - -"
|
||||||
)
|
} -"
|
||||||
[
|
)
|
||||||
constants.runtimeOutboundsDir
|
[
|
||||||
constants.runtimeSubscriptionsDir
|
constants.runtimeOutboundsDir
|
||||||
]
|
constants.runtimeSubscriptionsDir
|
||||||
);
|
]
|
||||||
|
))
|
||||||
|
# Global AmneziaWG profiles added at runtime. Listable, so the tray and TUI show
|
||||||
|
# their names to everyone; each file is 0600 (amneziawg_config.py writes it so).
|
||||||
|
(lib.mkIf (cfg.enable && derived.awgRuntimeGlobal) [
|
||||||
|
"d ${constants.runtimeAwgDir} ${
|
||||||
|
if userControlAllows "amneziaWg" then "2775 root ${userControlCfg.group}" else "0755 root root"
|
||||||
|
} -"
|
||||||
|
])
|
||||||
|
];
|
||||||
|
|
||||||
userServices = lib.mkMerge [
|
userServices = lib.mkMerge [
|
||||||
(mkNamedUnits userServiceEntries)
|
(mkNamedUnits userServiceEntries)
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ let
|
|||||||
"proxy-suite-route-mode@" = "routing";
|
"proxy-suite-route-mode@" = "routing";
|
||||||
"proxy-suite-outbound-reload." = "outbounds";
|
"proxy-suite-outbound-reload." = "outbounds";
|
||||||
"proxy-suite-subscription-update." = "outbounds";
|
"proxy-suite-subscription-update." = "outbounds";
|
||||||
|
# Tunnels of the AmneziaWG outbounds added at runtime; a global profile's own unit
|
||||||
|
# (proxy-suite-awg@) is "services", like the declared ones.
|
||||||
|
"proxy-suite-awg-tunnel@" = "outbounds";
|
||||||
|
"proxy-suite-awg-runtime-sync." = "outbounds";
|
||||||
"proxy-suite-autoproxy-learn." = "autoProxy";
|
"proxy-suite-autoproxy-learn." = "autoProxy";
|
||||||
"proxy-suite-zapret2-cutoff." = "zapret";
|
"proxy-suite-zapret2-cutoff." = "zapret";
|
||||||
"proxy-suite-inbound-stats." = "stats";
|
"proxy-suite-inbound-stats." = "stats";
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
torCfg,
|
torCfg,
|
||||||
whitelistBypassJoiners,
|
whitelistBypassJoiners,
|
||||||
awgOutbounds,
|
awgOutbounds,
|
||||||
|
awgRuntimeOutbounds ? false,
|
||||||
constants,
|
constants,
|
||||||
pureXrayEnabled,
|
pureXrayEnabled,
|
||||||
hybridEnabled,
|
hybridEnabled,
|
||||||
@@ -136,6 +137,27 @@ let
|
|||||||
OUTBOUND_SOURCES_JSON=$(${jq} --arg t "$1" --arg s "$2" '.[$t] = $s' <<< "$OUTBOUND_SOURCES_JSON")
|
OUTBOUND_SOURCES_JSON=$(${jq} --arg t "$1" --arg s "$2" '.[$t] = $s' <<< "$OUTBOUND_SOURCES_JSON")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# $1 tag, $2 loopback SOCKS port, $3 source label: mkTunnelOutboundBlock, for a port
|
||||||
|
# only known at runtime (an AmneziaWG outbound added with proxy-ctl).
|
||||||
|
_proxy_suite_add_socks_hop() {
|
||||||
|
local ob
|
||||||
|
ob=$(${jq} -nc --arg t "$1" --argjson p "$2" ${
|
||||||
|
lib.escapeShellArg (
|
||||||
|
if pureXrayEnabled then
|
||||||
|
''{protocol: "socks", tag: $t, settings: {address: "127.0.0.1", port: $p}}''
|
||||||
|
else
|
||||||
|
''{type: "socks", tag: $t, server: "127.0.0.1", server_port: $p}''
|
||||||
|
)
|
||||||
|
}) || return 1
|
||||||
|
${
|
||||||
|
if hybridEnabled then
|
||||||
|
''_proxy_suite_add_sing_box_ob "$ob"''
|
||||||
|
else
|
||||||
|
''OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")''
|
||||||
|
}
|
||||||
|
_proxy_suite_record_tag_source "$1" "$3"
|
||||||
|
}
|
||||||
|
|
||||||
# $1 sub tag, $2 file holding its URL, $3 its links file (absent for a cache
|
# $1 sub tag, $2 file holding its URL, $3 its links file (absent for a cache
|
||||||
# written before links existed: those entries share as JSON until the next update).
|
# written before links existed: those entries share as JSON until the next update).
|
||||||
_proxy_suite_record_subscription_share() {
|
_proxy_suite_record_subscription_share() {
|
||||||
@@ -196,13 +218,14 @@ let
|
|||||||
_proxy_suite_record_tag_source "$tag" "$source"
|
_proxy_suite_record_tag_source "$tag" "$source"
|
||||||
}
|
}
|
||||||
|
|
||||||
# Every runtime outbound, as "<tag>\t<file>" lines: <tag>.url or <tag>.json. proxy-ctl refuses
|
# Every runtime outbound, as "<tag>\t<file>" lines: <tag>.url, <tag>.json or <tag>.awg (an
|
||||||
|
# AmneziaWG config, behind a tunnel on the port in <tag>.port). proxy-ctl refuses
|
||||||
# the reserved names, but the spool is group-writable, so check again here:
|
# the reserved names, but the spool is group-writable, so check again here:
|
||||||
# a second outbound tagged "proxy" would quietly shadow the real one.
|
# a second outbound tagged "proxy" would quietly shadow the real one.
|
||||||
_proxy_suite_runtime_outbounds() {
|
_proxy_suite_runtime_outbounds() {
|
||||||
local f tag
|
local f tag
|
||||||
[ -d "${runtimeOutboundsDir}" ] || return 0
|
[ -d "${runtimeOutboundsDir}" ] || return 0
|
||||||
for f in "${runtimeOutboundsDir}"/*.url "${runtimeOutboundsDir}"/*.json; do
|
for f in "${runtimeOutboundsDir}"/*.url "${runtimeOutboundsDir}"/*.json${lib.optionalString awgRuntimeOutbounds ''"${runtimeOutboundsDir}"/*.awg''}; do
|
||||||
[ -e "$f" ] || continue
|
[ -e "$f" ] || continue
|
||||||
tag="''${f##*/}"
|
tag="''${f##*/}"
|
||||||
tag="''${tag%.*}"
|
tag="''${tag%.*}"
|
||||||
@@ -448,6 +471,8 @@ let
|
|||||||
[ -n "$RUNTIME_OB_TAG" ] || continue
|
[ -n "$RUNTIME_OB_TAG" ] || continue
|
||||||
case "$RUNTIME_OB_SRC" in
|
case "$RUNTIME_OB_SRC" in
|
||||||
*.json) _proxy_suite_add_json_outbound "$RUNTIME_OB_TAG" "$RUNTIME_OB_SRC" runtime ;;
|
*.json) _proxy_suite_add_json_outbound "$RUNTIME_OB_TAG" "$RUNTIME_OB_SRC" runtime ;;
|
||||||
|
# Its tunnel (proxy-suite-awg-tunnel@<tag>) checks the port again before listening.
|
||||||
|
*.awg) _proxy_suite_add_socks_hop "$RUNTIME_OB_TAG" "$(head -n 1 "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.port" 2>/dev/null)" runtime ;;
|
||||||
*) _proxy_suite_add_url_outbound "$RUNTIME_OB_TAG" "$(cat "$RUNTIME_OB_SRC")" runtime ;;
|
*) _proxy_suite_add_url_outbound "$RUNTIME_OB_TAG" "$(cat "$RUNTIME_OB_SRC")" runtime ;;
|
||||||
esac || { echo "proxy-suite: warning: ignoring runtime outbound '$RUNTIME_OB_TAG'" >&2; continue; }
|
esac || { echo "proxy-suite: warning: ignoring runtime outbound '$RUNTIME_OB_TAG'" >&2; continue; }
|
||||||
if [ -s "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.detour" ]; then
|
if [ -s "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.detour" ]; then
|
||||||
|
|||||||
@@ -128,6 +128,7 @@ let
|
|||||||
torCfg
|
torCfg
|
||||||
whitelistBypassJoiners
|
whitelistBypassJoiners
|
||||||
awgOutbounds
|
awgOutbounds
|
||||||
|
awgRuntimeOutbounds
|
||||||
constants
|
constants
|
||||||
pureXrayEnabled
|
pureXrayEnabled
|
||||||
hybridEnabled
|
hybridEnabled
|
||||||
|
|||||||
@@ -147,6 +147,9 @@ let
|
|||||||
# the WireGuard .conf. `engine` is "singBox" or "userspace"; only sing-box uses directPort,
|
# the WireGuard .conf. `engine` is "singBox" or "userspace"; only sing-box uses directPort,
|
||||||
# `endpoint`, a host:port in place of the profile's Endpoint, and `domainStrategy`, the
|
# `endpoint`, a host:port in place of the profile's Endpoint, and `domainStrategy`, the
|
||||||
# address family it dials destinations over first.
|
# address family it dials destinations over first.
|
||||||
|
#
|
||||||
|
# A template unit passes `tag` and `tunnelPort` as shell words ("$TUNNEL_TAG") that
|
||||||
|
# `profile` exports: the watchdog runs as a script of its own, after the exec.
|
||||||
mkTunnel =
|
mkTunnel =
|
||||||
{
|
{
|
||||||
description,
|
description,
|
||||||
@@ -158,6 +161,11 @@ let
|
|||||||
endpoint ? null,
|
endpoint ? null,
|
||||||
domainStrategy ? null,
|
domainStrategy ? null,
|
||||||
engine ? "singBox",
|
engine ? "singBox",
|
||||||
|
runtimeDirectory ? unit,
|
||||||
|
wantedBy ? [ "multi-user.target" ],
|
||||||
|
restart ? "always",
|
||||||
|
# " %i" for a template, whose `profile` reads the instance name from $1.
|
||||||
|
execArgs ? "",
|
||||||
}:
|
}:
|
||||||
let
|
let
|
||||||
chosen = (if engine == "userspace" then wireproxyEngine else singBoxEngine) {
|
chosen = (if engine == "userspace" then wireproxyEngine else singBoxEngine) {
|
||||||
@@ -188,18 +196,17 @@ let
|
|||||||
'';
|
'';
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
inherit description;
|
inherit description wantedBy;
|
||||||
after = [ "network-online.target" ];
|
after = [ "network-online.target" ];
|
||||||
wants = [ "network-online.target" ];
|
wants = [ "network-online.target" ];
|
||||||
wantedBy = [ "multi-user.target" ];
|
|
||||||
# Probe-triggered restarts must not trip the start limit.
|
# Probe-triggered restarts must not trip the start limit.
|
||||||
startLimitIntervalSec = 0;
|
startLimitIntervalSec = 0;
|
||||||
serviceConfig = {
|
serviceConfig = {
|
||||||
Type = "simple";
|
Type = "simple";
|
||||||
ExecStart = tunnelScript;
|
ExecStart = if execArgs == "" then tunnelScript else "${tunnelScript}${execArgs}";
|
||||||
Restart = "always";
|
Restart = restart;
|
||||||
RestartSec = 2;
|
RestartSec = 2;
|
||||||
RuntimeDirectory = unit;
|
RuntimeDirectory = runtimeDirectory;
|
||||||
RuntimeDirectoryMode = "0750";
|
RuntimeDirectoryMode = "0750";
|
||||||
UMask = "0077";
|
UMask = "0077";
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -134,6 +134,42 @@ pkgs.testers.runNixOSTest {
|
|||||||
userspace.succeed("systemctl stop proxy-suite-awg-test.service")
|
userspace.succeed("systemctl stop proxy-suite-awg-test.service")
|
||||||
userspace.fail("ip link show awg-test")
|
userspace.fail("ip link show awg-test")
|
||||||
|
|
||||||
|
with subtest("a profile added at runtime"):
|
||||||
|
# The same client as "test", as a .conf pasted in rather than declared.
|
||||||
|
userspace.succeed("""umask 077; cat > /root/rt.conf <<'EOF'
|
||||||
|
[Interface]
|
||||||
|
PrivateKey = ${keys.peer1.privateKey}
|
||||||
|
Address = 10.23.42.2/32
|
||||||
|
Jc = ${toString obfuscation.jc}
|
||||||
|
Jmin = ${toString obfuscation.jmin}
|
||||||
|
Jmax = ${toString obfuscation.jmax}
|
||||||
|
S1 = ${toString obfuscation.s1}
|
||||||
|
S2 = ${toString obfuscation.s2}
|
||||||
|
|
||||||
|
[Peer]
|
||||||
|
PublicKey = ${keys.peer0.publicKey}
|
||||||
|
Endpoint = 192.168.0.1:23542
|
||||||
|
AllowedIPs = 10.23.42.1/32
|
||||||
|
PersistentKeepalive = 5
|
||||||
|
EOF""")
|
||||||
|
userspace.succeed("proxy-ctl awg add rt /root/rt.conf")
|
||||||
|
userspace.succeed("test $(stat -c %a /var/lib/proxy-suite/amneziawg.d/rt.conf) = 600")
|
||||||
|
userspace.succeed("proxy-ctl awg list | grep -E 'rt +inactive +runtime'")
|
||||||
|
userspace.succeed("proxy-ctl awg on rt")
|
||||||
|
userspace.succeed("ip link show awg-rt")
|
||||||
|
userspace.succeed("ping -c 5 10.23.42.1")
|
||||||
|
userspace.succeed("systemctl is-active proxy-suite-awg-watchdog@rt.service")
|
||||||
|
# A declared profile takes over: they share the peer, and only one global tunnel runs.
|
||||||
|
userspace.succeed("systemctl start proxy-suite-awg-test.service")
|
||||||
|
userspace.fail("systemctl is-active proxy-suite-awg@rt.service")
|
||||||
|
userspace.fail("ip link show awg-rt")
|
||||||
|
userspace.succeed("systemctl stop proxy-suite-awg-test.service")
|
||||||
|
# Hooks are refused whoever adds the config, and nothing is written.
|
||||||
|
userspace.fail("sed 's/^Address/PostUp = touch \\/pwned\\nAddress/' /root/rt.conf | proxy-ctl awg add hooked -")
|
||||||
|
userspace.fail("test -e /var/lib/proxy-suite/amneziawg.d/hooked.conf")
|
||||||
|
userspace.succeed("proxy-ctl awg rm rt")
|
||||||
|
userspace.fail("test -e /var/lib/proxy-suite/amneziawg.d/rt.conf")
|
||||||
|
|
||||||
with subtest("failed handshake rolls back userspace routing"):
|
with subtest("failed handshake rolls back userspace routing"):
|
||||||
userspace.fail("systemctl start proxy-suite-awg-broken.service")
|
userspace.fail("systemctl start proxy-suite-awg-broken.service")
|
||||||
userspace.fail("ip link show awg-broken")
|
userspace.fail("ip link show awg-broken")
|
||||||
|
|||||||
+172
-4
@@ -67,6 +67,15 @@ let
|
|||||||
}
|
}
|
||||||
];
|
];
|
||||||
homeService = awgOnly.config.systemd.services.proxy-suite-awg-home;
|
homeService = awgOnly.config.systemd.services.proxy-suite-awg-home;
|
||||||
|
awgOnlyNoRuntime = mkProxySuite {
|
||||||
|
enable = true;
|
||||||
|
amneziaWg = {
|
||||||
|
enable = true;
|
||||||
|
kernelModulePackage = null;
|
||||||
|
runtime.enable = false;
|
||||||
|
profiles.home.configFile = "/run/secrets/awg.conf";
|
||||||
|
};
|
||||||
|
};
|
||||||
workService = awgOnly.config.systemd.services.proxy-suite-awg-work;
|
workService = awgOnly.config.systemd.services.proxy-suite-awg-work;
|
||||||
ctl = mkProxyCtlDerived awgOnly;
|
ctl = mkProxyCtlDerived awgOnly;
|
||||||
homeWatchdog = awgOnly.config.systemd.services.proxy-suite-awg-home-watchdog;
|
homeWatchdog = awgOnly.config.systemd.services.proxy-suite-awg-home-watchdog;
|
||||||
@@ -146,10 +155,105 @@ let
|
|||||||
];
|
];
|
||||||
withGlobalAwgService = withGlobalTun.config.systemd.services.proxy-suite-awg-home;
|
withGlobalAwgService = withGlobalTun.config.systemd.services.proxy-suite-awg-home;
|
||||||
withGlobalAwgStartPre = withGlobalAwgService.serviceConfig.ExecStartPre;
|
withGlobalAwgStartPre = withGlobalAwgService.serviceConfig.ExecStartPre;
|
||||||
withGlobalAwgBypassUp = generated.readDerivation (builtins.elemAt withGlobalAwgStartPre 1);
|
withGlobalAwgBypassUp = generated.readDerivation (builtins.elemAt withGlobalAwgStartPre 2);
|
||||||
|
|
||||||
|
# Nothing declared: every profile and AmneziaWG outbound comes from proxy-ctl.
|
||||||
|
runtimeOnly = evalProxySuite [
|
||||||
|
{
|
||||||
|
system.stateVersion = "26.05";
|
||||||
|
services.proxy-suite = {
|
||||||
|
enable = true;
|
||||||
|
killSwitch.enable = true;
|
||||||
|
userControl = {
|
||||||
|
enable = true;
|
||||||
|
scopes = [ "amneziaWg" ];
|
||||||
|
};
|
||||||
|
proxy = {
|
||||||
|
enable = true;
|
||||||
|
backend = "sing-box";
|
||||||
|
outbounds = [
|
||||||
|
{
|
||||||
|
tag = "primary";
|
||||||
|
url = "http://proxy.example.com:8080";
|
||||||
|
}
|
||||||
|
];
|
||||||
|
};
|
||||||
|
amneziaWg = {
|
||||||
|
enable = true;
|
||||||
|
kernelModulePackage = null;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
];
|
||||||
|
runtimeUnits = runtimeOnly.config.systemd.services;
|
||||||
|
|
||||||
|
# The scripts that list units, run against a systemctl that lists what the check says.
|
||||||
|
stubSystemctl = pkgs.writeShellScript "systemctl" ''
|
||||||
|
echo "$*" >> "$SYSTEMCTL_LOG"
|
||||||
|
if [ "$1" = list-units ]; then cat "$UNITS"; fi
|
||||||
|
'';
|
||||||
|
stubbed = evalProxySuite [
|
||||||
|
{
|
||||||
|
system.stateVersion = "26.05";
|
||||||
|
services.proxy-suite = {
|
||||||
|
enable = true;
|
||||||
|
host.systemctl = pkgs.lib.mkForce "${stubSystemctl}";
|
||||||
|
proxy = {
|
||||||
|
enable = true;
|
||||||
|
backend = "sing-box";
|
||||||
|
outbounds = [
|
||||||
|
{
|
||||||
|
tag = "primary";
|
||||||
|
url = "http://proxy.example.com:8080";
|
||||||
|
}
|
||||||
|
];
|
||||||
|
};
|
||||||
|
amneziaWg = {
|
||||||
|
enable = true;
|
||||||
|
kernelModulePackage = null;
|
||||||
|
profiles.home.configFile = "/run/secrets/awg.conf";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
];
|
||||||
|
stubbedUnits = stubbed.config.systemd.services;
|
||||||
|
runtimeTemplate = runtimeUnits."proxy-suite-awg@";
|
||||||
|
runtimeTunnel = runtimeUnits."proxy-suite-awg-tunnel@";
|
||||||
|
runtimeSync = generated.readDerivation runtimeUnits.proxy-suite-awg-runtime-sync.serviceConfig.ExecStart;
|
||||||
|
runtimeKillSwitchRules = checkLib.mkNftRules runtimeOnly "killSwitchRulesFile";
|
||||||
|
runtimeCtl = mkProxyCtlDerived runtimeOnly;
|
||||||
|
runtimeOutboundScript = generated.readDerivation runtimeUnits.proxy-suite-socks.serviceConfig.ExecStart;
|
||||||
withGlobalAwgBypassDown = generated.readDerivation withGlobalAwgService.serviceConfig.ExecStopPost;
|
withGlobalAwgBypassDown = generated.readDerivation withGlobalAwgService.serviceConfig.ExecStopPost;
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
|
# Nothing listed is no failure (grep finding nothing, under pipefail, once was); what is
|
||||||
|
# listed is stopped, a failed unit's glyph and all, but never the unit itself.
|
||||||
|
unitScripts = pkgs.runCommand "amneziawg-unit-scripts-check" { } ''
|
||||||
|
export SYSTEMCTL_LOG=$PWD/log UNITS=$PWD/units
|
||||||
|
stop=${builtins.elemAt stubbedUnits.proxy-suite-awg-home.serviceConfig.ExecStartPre 1}
|
||||||
|
sync=${stubbedUnits.proxy-suite-awg-runtime-sync.serviceConfig.ExecStart}
|
||||||
|
|
||||||
|
: > units
|
||||||
|
$stop
|
||||||
|
$stop self
|
||||||
|
$sync
|
||||||
|
! grep -q '^stop' log
|
||||||
|
|
||||||
|
printf '%s\n' \
|
||||||
|
'● proxy-suite-awg@gone.service loaded failed failed x' \
|
||||||
|
' proxy-suite-awg@self.service loaded active exited x' > units
|
||||||
|
: > log
|
||||||
|
$stop self
|
||||||
|
grep -qx 'stop proxy-suite-awg@gone.service' log
|
||||||
|
! grep -q 'stop proxy-suite-awg@self.service' log
|
||||||
|
|
||||||
|
printf '%s\n' '● proxy-suite-awg-tunnel@old.service loaded failed failed x' > units
|
||||||
|
: > log
|
||||||
|
$sync
|
||||||
|
grep -qx 'stop --no-block proxy-suite-awg-tunnel@old.service' log
|
||||||
|
touch "$out"
|
||||||
|
'';
|
||||||
|
|
||||||
manifest = pkgs.runCommand "amneziawg-secret-manifest-check" { } ''
|
manifest = pkgs.runCommand "amneziawg-secret-manifest-check" { } ''
|
||||||
${pkgs.python3}/bin/python3 - <<'PY'
|
${pkgs.python3}/bin/python3 - <<'PY'
|
||||||
import json
|
import json
|
||||||
@@ -185,7 +289,11 @@ in
|
|||||||
assert builtins.elem "proxy-suite-per-app-zapret.service" homeService.conflicts;
|
assert builtins.elem "proxy-suite-per-app-zapret.service" homeService.conflicts;
|
||||||
assert workService.wantedBy == [ ];
|
assert workService.wantedBy == [ ];
|
||||||
assert homeService.serviceConfig.NoNewPrivileges;
|
assert homeService.serviceConfig.NoNewPrivileges;
|
||||||
assert builtins.length homeService.serviceConfig.ExecStartPre == 1;
|
# Rendering, then stopping any profile added at runtime: they share an interface.
|
||||||
|
assert builtins.length homeService.serviceConfig.ExecStartPre == 2;
|
||||||
|
assert pkgs.lib.hasInfix "proxy-suite-awg@*.service" (
|
||||||
|
generated.readDerivation (builtins.elemAt homeService.serviceConfig.ExecStartPre 1)
|
||||||
|
);
|
||||||
assert !(homeService.serviceConfig ? ExecStopPost);
|
assert !(homeService.serviceConfig ? ExecStopPost);
|
||||||
# A silent handshake moves the interface to a new port: at start, and from the watchdog.
|
# A silent handshake moves the interface to a new port: at start, and from the watchdog.
|
||||||
assert pkgs.lib.hasInfix "set \"$interface\" listen-port 0" homeStart;
|
assert pkgs.lib.hasInfix "set \"$interface\" listen-port 0" homeStart;
|
||||||
@@ -255,7 +363,7 @@ in
|
|||||||
withGlobalTun.config.systemd.services.proxy-suite-per-app-zapret.conflicts;
|
withGlobalTun.config.systemd.services.proxy-suite-per-app-zapret.conflicts;
|
||||||
assert builtins.elem "proxy-suite-socks.service" withGlobalAwgService.after;
|
assert builtins.elem "proxy-suite-socks.service" withGlobalAwgService.after;
|
||||||
assert builtins.elem "proxy-suite-socks.service" withGlobalAwgService.wants;
|
assert builtins.elem "proxy-suite-socks.service" withGlobalAwgService.wants;
|
||||||
assert builtins.length withGlobalAwgStartPre == 2;
|
assert builtins.length withGlobalAwgStartPre == 3;
|
||||||
assert pkgs.lib.hasInfix "rule add" withGlobalAwgBypassUp;
|
assert pkgs.lib.hasInfix "rule add" withGlobalAwgBypassUp;
|
||||||
assert pkgs.lib.hasInfix "pref 8998" withGlobalAwgBypassUp;
|
assert pkgs.lib.hasInfix "pref 8998" withGlobalAwgBypassUp;
|
||||||
assert pkgs.lib.hasInfix "fwmark 2 lookup main" withGlobalAwgBypassUp;
|
assert pkgs.lib.hasInfix "fwmark 2 lookup main" withGlobalAwgBypassUp;
|
||||||
@@ -266,11 +374,71 @@ in
|
|||||||
assert pkgs.lib.hasInfix "fwmark 2 lookup main" withGlobalAwgBypassDown;
|
assert pkgs.lib.hasInfix "fwmark 2 lookup main" withGlobalAwgBypassDown;
|
||||||
true
|
true
|
||||||
)
|
)
|
||||||
|
# Profiles added with proxy-ctl: a template sharing one interface, which the kill switch
|
||||||
|
# knows; a tunnel template per outbound, started by a sync unit the reload pulls in.
|
||||||
|
(
|
||||||
|
assert runtimeTemplate.wantedBy == [ ];
|
||||||
|
assert builtins.elem "proxy-suite-awg-watchdog@%i.service" runtimeTemplate.wants;
|
||||||
|
assert builtins.elem "proxy-suite-killswitch.service" runtimeTemplate.before;
|
||||||
|
assert builtins.elem "proxy-suite-killswitch.service" runtimeTemplate.wants;
|
||||||
|
assert builtins.elem "proxy-suite-tun.service" runtimeTemplate.conflicts;
|
||||||
|
assert runtimeTemplate.serviceConfig.Group == "proxy-suite-awg";
|
||||||
|
assert runtimeTemplate.serviceConfig.RuntimeDirectory == "proxy-suite-awg-rt-%i";
|
||||||
|
assert pkgs.lib.hasSuffix " %i" runtimeTemplate.serviceConfig.ExecStart;
|
||||||
|
assert builtins.all (pkgs.lib.hasSuffix " %i") (
|
||||||
|
pkgs.lib.take 2 runtimeTemplate.serviceConfig.ExecStartPre
|
||||||
|
);
|
||||||
|
assert runtimeUnits."proxy-suite-awg-watchdog@".bindsTo == [ "proxy-suite-awg@%i.service" ];
|
||||||
|
assert runtimeUnits."proxy-suite-awg-watchdog@".wantedBy == [ ];
|
||||||
|
assert runtimeTunnel.wantedBy == [ ];
|
||||||
|
assert runtimeTunnel.serviceConfig.Restart == "on-failure";
|
||||||
|
assert runtimeTunnel.serviceConfig.RuntimeDirectory == "proxy-suite-awg-tunnel-%i";
|
||||||
|
assert builtins.elem "proxy-suite-outbound-reload.service"
|
||||||
|
runtimeUnits.proxy-suite-awg-runtime-sync.wantedBy;
|
||||||
|
assert pkgs.lib.hasInfix "proxy-suite-awg-tunnel@$tag.service" runtimeSync;
|
||||||
|
# The backend dials each one's tunnel on the port in <tag>.port.
|
||||||
|
assert pkgs.lib.hasInfix ''"/var/lib/proxy-suite/outbounds.d"/*.awg'' runtimeOutboundScript;
|
||||||
|
assert pkgs.lib.hasInfix "_proxy_suite_add_socks_hop" runtimeOutboundScript;
|
||||||
|
assert pkgs.lib.hasInfix ''oifname { "awg-rt" } accept'' runtimeKillSwitchRules;
|
||||||
|
assert pkgs.lib.hasInfix ''meta skgid "proxy-suite-awg" accept'' runtimeKillSwitchRules;
|
||||||
|
assert builtins.elem "d /var/lib/proxy-suite/amneziawg.d 2775 root proxy-suite -"
|
||||||
|
runtimeOnly.config.systemd.tmpfiles.rules;
|
||||||
|
assert builtins.elem "d /var/lib/proxy-suite/outbounds.d 0700 root root -"
|
||||||
|
runtimeOnly.config.systemd.tmpfiles.rules;
|
||||||
|
assert builtins.elem runtimeOnly.config.services.proxy-suite.amneziaWg.wireproxyPackage
|
||||||
|
runtimeOnly.config.environment.systemPackages;
|
||||||
|
assert pkgs.lib.hasInfix "proxy-suite-awg-tunnel@" runtimeOnly.config.security.polkit.extraConfig;
|
||||||
|
assert runtimeCtl.wrapperEnv.AWG_RUNTIME_GLOBAL == "1";
|
||||||
|
assert runtimeCtl.wrapperEnv.AWG_RUNTIME_OUTBOUNDS == "1";
|
||||||
|
assert runtimeCtl.wrapperEnv.AWG_RUNTIME_DIR == "/var/lib/proxy-suite/amneziawg.d";
|
||||||
|
assert pkgs.lib.hasSuffix "/amneziawg_config.py" runtimeCtl.wrapperEnv.AWG_CONFIG_TOOL;
|
||||||
|
assert runtimeCtl.awgProfiles == [ ];
|
||||||
|
# Declared profiles only in a configuration that turns the runtime ones off.
|
||||||
|
assert !(awgOnlyNoRuntime.config.systemd.services ? "proxy-suite-awg@");
|
||||||
|
assert
|
||||||
|
builtins.length awgOnlyNoRuntime.config.systemd.services.proxy-suite-awg-home.serviceConfig.ExecStartPre
|
||||||
|
== 1;
|
||||||
|
true
|
||||||
|
)
|
||||||
]
|
]
|
||||||
++ mkFailingAssertions mkBadProxySuiteFixture [
|
++ mkFailingAssertions mkBadProxySuiteFixture [
|
||||||
{
|
{
|
||||||
enable = true;
|
enable = true;
|
||||||
amneziaWg.enable = true;
|
amneziaWg = {
|
||||||
|
enable = true;
|
||||||
|
runtime.enable = false;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
{
|
||||||
|
enable = true;
|
||||||
|
amneziaWg = {
|
||||||
|
enable = true;
|
||||||
|
kernelModulePackage = null;
|
||||||
|
profiles.home = {
|
||||||
|
interfaceName = "awg-rt";
|
||||||
|
configFile = "/run/home.conf";
|
||||||
|
};
|
||||||
|
};
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
enable = true;
|
enable = true;
|
||||||
|
|||||||
@@ -151,8 +151,9 @@ in
|
|||||||
assert cfg.users.groups ? proxy-suite-awg;
|
assert cfg.users.groups ? proxy-suite-awg;
|
||||||
assert pkgs.lib.hasInfix "--fwmark 51820" awgKillSwitchPrepare;
|
assert pkgs.lib.hasInfix "--fwmark 51820" awgKillSwitchPrepare;
|
||||||
assert pkgs.lib.hasInfix ''meta skgid "proxy-suite-awg" accept'' rules;
|
assert pkgs.lib.hasInfix ''meta skgid "proxy-suite-awg" accept'' rules;
|
||||||
|
# And the one the profiles added at runtime share.
|
||||||
assert pkgs.lib.hasInfix
|
assert pkgs.lib.hasInfix
|
||||||
''oifname { "${cfg.services.proxy-suite.amneziaWg.profiles.home.interfaceName}" } accept''
|
''oifname { "${cfg.services.proxy-suite.amneziaWg.profiles.home.interfaceName}", "awg-rt" } accept''
|
||||||
rules;
|
rules;
|
||||||
assert pkgs.lib.hasInfix "meta mark { 1, 2, 51820 } accept" rules;
|
assert pkgs.lib.hasInfix "meta mark { 1, 2, 51820 } accept" rules;
|
||||||
assert !(pkgs.lib.hasInfix "skgid" killSwitchNftRules);
|
assert !(pkgs.lib.hasInfix "skgid" killSwitchNftRules);
|
||||||
|
|||||||
@@ -165,6 +165,18 @@ let
|
|||||||
];
|
];
|
||||||
smCfg = systemManager.config;
|
smCfg = systemManager.config;
|
||||||
|
|
||||||
|
# AmneziaWG with nothing declared: outbounds added with proxy-ctl run as user units.
|
||||||
|
hmRuntimeAwg = evalHost "homeManager" [
|
||||||
|
rootlessSettings
|
||||||
|
{
|
||||||
|
services.proxy-suite.amneziaWg = {
|
||||||
|
enable = true;
|
||||||
|
kernelModulePackage = null;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
];
|
||||||
|
hmRuntimeAwgUnits = hmRuntimeAwg.config.systemd.user.services;
|
||||||
|
|
||||||
nixOnDroid = evalHost "nixOnDroid" [ rootlessSettings ];
|
nixOnDroid = evalHost "nixOnDroid" [ rootlessSettings ];
|
||||||
nodCfg = nixOnDroid.config;
|
nodCfg = nixOnDroid.config;
|
||||||
|
|
||||||
@@ -200,6 +212,17 @@ in
|
|||||||
));
|
));
|
||||||
true
|
true
|
||||||
)
|
)
|
||||||
|
(
|
||||||
|
# Rootless: AmneziaWG outbounds added at runtime, never a global profile.
|
||||||
|
assert failedAssertions hmRuntimeAwg == [ ];
|
||||||
|
assert hmRuntimeAwgUnits ? "proxy-suite-awg-tunnel@";
|
||||||
|
assert hmRuntimeAwgUnits ? proxy-suite-awg-runtime-sync;
|
||||||
|
assert !(hmRuntimeAwgUnits ? "proxy-suite-awg@");
|
||||||
|
assert
|
||||||
|
!(lib.hasInfix "setpriv" (toString hmRuntimeAwgUnits."proxy-suite-awg-tunnel@".Service.ExecStart));
|
||||||
|
assert forced hmRuntimeAwgUnits;
|
||||||
|
true
|
||||||
|
)
|
||||||
(
|
(
|
||||||
# Rootless, the socks unit only listens: no TProxy inbound, no SO_MARK.
|
# 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 == "mixed") hmSocksConfig.inbounds;
|
||||||
@@ -244,6 +267,13 @@ in
|
|||||||
perAppRouting.zapret.enable = true;
|
perAppRouting.zapret.enable = true;
|
||||||
} "perAppRouting.zapret needs root";
|
} "perAppRouting.zapret needs root";
|
||||||
assert rejects "nixOnDroid" { gui.enable = true; } "the GUI needs a desktop session";
|
assert rejects "nixOnDroid" { gui.enable = true; } "the GUI needs a desktop session";
|
||||||
|
# No templates in proxy-suitectl, and no root for a global profile: nothing to add to.
|
||||||
|
assert rejects "nixOnDroid" {
|
||||||
|
amneziaWg = {
|
||||||
|
enable = true;
|
||||||
|
kernelModulePackage = null;
|
||||||
|
};
|
||||||
|
} "amneziaWg.enable needs a profile";
|
||||||
assert rejects "nixOnDroid" {
|
assert rejects "nixOnDroid" {
|
||||||
inbounds.listeners.vless.port = lib.mkForce 443;
|
inbounds.listeners.vless.port = lib.mkForce 443;
|
||||||
} "inbounds.listeners.vless.port = 443 is a privileged port";
|
} "inbounds.listeners.vless.port = 443 is a privileged port";
|
||||||
|
|||||||
@@ -332,6 +332,7 @@ in
|
|||||||
{
|
{
|
||||||
proxy-suite-module = builtins.seq validated (pkgs.writeText "proxy-suite-module-check" "ok");
|
proxy-suite-module = builtins.seq validated (pkgs.writeText "proxy-suite-module-check" "ok");
|
||||||
amneziawg-secret-manifest = amneziaWgChecks.manifest;
|
amneziawg-secret-manifest = amneziaWgChecks.manifest;
|
||||||
|
amneziawg-unit-scripts = amneziaWgChecks.unitScripts;
|
||||||
xray-jq-filter-runtime = xrayBackendChecks.runtime;
|
xray-jq-filter-runtime = xrayBackendChecks.runtime;
|
||||||
tor-guard-runtime = torChecks.runtime;
|
tor-guard-runtime = torChecks.runtime;
|
||||||
per-app-zapret-runtime = perAppRoutingChecks.runtime;
|
per-app-zapret-runtime = perAppRoutingChecks.runtime;
|
||||||
|
|||||||
@@ -122,6 +122,19 @@ let
|
|||||||
};
|
};
|
||||||
ipNamedConfig = mkInboundsConfig ipNamedFixture;
|
ipNamedConfig = mkInboundsConfig ipNamedFixture;
|
||||||
|
|
||||||
|
# Other names and IPs of this host, beside the one in share links.
|
||||||
|
aliasedFixture = mkInbounds {
|
||||||
|
serverAddress = "vpn.example.com";
|
||||||
|
serverAliases = [
|
||||||
|
"turn.example.com"
|
||||||
|
"203.0.113.10"
|
||||||
|
"2001:db8::10"
|
||||||
|
"vpn.example.com"
|
||||||
|
];
|
||||||
|
listeners.vless-in = realityListener;
|
||||||
|
};
|
||||||
|
aliasedConfig = mkInboundsConfig aliasedFixture;
|
||||||
|
|
||||||
unguardedFixture = mkInbounds {
|
unguardedFixture = mkInbounds {
|
||||||
routing = {
|
routing = {
|
||||||
blockRu = false;
|
blockRu = false;
|
||||||
@@ -812,7 +825,28 @@ let
|
|||||||
(ok ((ruleByTag blockedConfig "inbound-server-address-direct").inboundTag == [ "open" ]))
|
(ok ((ruleByTag blockedConfig "inbound-server-address-direct").inboundTag == [ "open" ]))
|
||||||
# No address to exempt when it is detected at runtime instead.
|
# No address to exempt when it is detected at runtime instead.
|
||||||
(ok (!builtins.elem "inbound-server-address-direct" (ruleTags relayConfig)))
|
(ok (!builtins.elem "inbound-server-address-direct" (ruleTags relayConfig)))
|
||||||
(ok ((ruleByTag ipNamedConfig "inbound-server-address-direct").ip == [ "82.146.44.102" ]))
|
(ok ((ruleByTag ipNamedConfig "inbound-server-address-direct-ip").ip == [ "82.146.44.102" ]))
|
||||||
|
(ok (!builtins.elem "inbound-server-address-direct" (ruleTags ipNamedConfig)))
|
||||||
|
(ok (!builtins.elem "inbound-server-address-direct-ip" (ruleTags namedConfig)))
|
||||||
|
# Aliases join serverAddress, names and IPs apart, as XRay ANDs one rule's fields.
|
||||||
|
(
|
||||||
|
assert
|
||||||
|
(ruleByTag aliasedConfig "inbound-server-address-direct").domain == [
|
||||||
|
"full:vpn.example.com"
|
||||||
|
"full:turn.example.com"
|
||||||
|
];
|
||||||
|
true
|
||||||
|
)
|
||||||
|
(
|
||||||
|
assert
|
||||||
|
(ruleByTag aliasedConfig "inbound-server-address-direct-ip").ip == [
|
||||||
|
"203.0.113.10"
|
||||||
|
"2001:db8::10"
|
||||||
|
];
|
||||||
|
true
|
||||||
|
)
|
||||||
|
(ok ((ruleByTag aliasedConfig "inbound-server-address-direct-ip").port == "443"))
|
||||||
|
(ok ((ruleByTag aliasedConfig "inbound-server-address-direct-ip").outboundTag == "direct"))
|
||||||
(ok (!builtins.elem "inbound-block-ru-domain" (ruleTags unguardedConfig)))
|
(ok (!builtins.elem "inbound-block-ru-domain" (ruleTags unguardedConfig)))
|
||||||
|
|
||||||
# A per-listener via becomes its own rule; listeners on the default do not.
|
# A per-listener via becomes its own rule; listeners on the default do not.
|
||||||
|
|||||||
@@ -73,7 +73,10 @@ pkgs.lib.mapAttrs mkPythonCheck {
|
|||||||
proxy-ctl-unit = {
|
proxy-ctl-unit = {
|
||||||
drv = "proxy-suite-proxy-ctl-unit";
|
drv = "proxy-suite-proxy-ctl-unit";
|
||||||
file = "${proxyCtl}/test_proxy_ctl.py";
|
file = "${proxyCtl}/test_proxy_ctl.py";
|
||||||
env = singBox;
|
# `awg add` and AmneziaWG outbounds hand their configs to it.
|
||||||
|
env = singBox // {
|
||||||
|
AWG_CONFIG_TOOL = "${scripts}/amneziawg_config.py";
|
||||||
|
};
|
||||||
};
|
};
|
||||||
# proxy-suitectl, nix-on-droid's service manager: real processes restarted, timed and stopped.
|
# proxy-suitectl, nix-on-droid's service manager: real processes restarted, timed and stopped.
|
||||||
proxy-suite-supervisor-unit = {
|
proxy-suite-supervisor-unit = {
|
||||||
|
|||||||
@@ -503,6 +503,8 @@ in
|
|||||||
has exclude zapret auto
|
has exclude zapret auto
|
||||||
has proxy-suite-awg-work logs
|
has proxy-suite-awg-work logs
|
||||||
has work awg on
|
has work awg on
|
||||||
|
has add awg
|
||||||
|
has rm awg
|
||||||
has torrent apps run
|
has torrent apps run
|
||||||
has unpin proxy
|
has unpin proxy
|
||||||
has newnym tor
|
has newnym tor
|
||||||
|
|||||||
+276
-10
@@ -65,6 +65,8 @@ Changes and secrets need root or the userControl group.
|
|||||||
proxy outbounds add [tag] <url|json|-> [--detour <tag>]
|
proxy outbounds add [tag] <url|json|-> [--detour <tag>]
|
||||||
add an outbound from a link or JSON (-: stdin);
|
add an outbound from a link or JSON (-: stdin);
|
||||||
--detour: connect through another outbound
|
--detour: connect through another outbound
|
||||||
|
proxy outbounds add [tag] <vpn://…|file.conf|-> [--container <name>]
|
||||||
|
add an AmneziaWG outbound (runs in wireproxy)
|
||||||
proxy outbounds chain <tag> <through-tag> [new tag]
|
proxy outbounds chain <tag> <through-tag> [new tag]
|
||||||
add a copy of an outbound that connects through another
|
add a copy of an outbound that connects through another
|
||||||
proxy outbounds rm <tag> remove a runtime outbound
|
proxy outbounds rm <tag> remove a runtime outbound
|
||||||
@@ -105,6 +107,9 @@ Changes and secrets need root or the userControl group.
|
|||||||
|
|
||||||
awg [list] AmneziaWG profiles
|
awg [list] AmneziaWG profiles
|
||||||
awg on <profile> | off [profile] | toggle [profile] | restart [profile]
|
awg on <profile> | off [profile] | toggle [profile] | restart [profile]
|
||||||
|
awg add [name] <vpn://…|file.conf|-> [--container <name>]
|
||||||
|
add a global profile (-: stdin)
|
||||||
|
awg rm <profile> remove a profile added with awg add
|
||||||
|
|
||||||
killswitch [status|on|off] block traffic outside the global tunnel;
|
killswitch [status|on|off] block traffic outside the global tunnel;
|
||||||
stays on until turned off here or with the tunnel
|
stays on until turned off here or with the tunnel
|
||||||
@@ -442,9 +447,35 @@ def _sub_tags():
|
|||||||
|
|
||||||
|
|
||||||
def _awg_profiles():
|
def _awg_profiles():
|
||||||
|
"""Global AmneziaWG profiles: the declared ones, then those added with `awg add`."""
|
||||||
|
declared = _awg_declared()
|
||||||
|
return declared + [p for p in _awg_runtime_profiles() if p not in declared]
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_declared():
|
||||||
return _json_list(env("AWG_PROFILES_FILE"))
|
return _json_list(env("AWG_PROFILES_FILE"))
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_added(profile):
|
||||||
|
"""Whether a profile was added with `awg add` (a declared one of that name wins)."""
|
||||||
|
return profile in _awg_runtime_profiles() and profile not in _awg_declared()
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_runtime_dir():
|
||||||
|
return env("AWG_RUNTIME_DIR", f"{state_dir()}/amneziawg.d")
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_runtime_profiles():
|
||||||
|
"""Profiles added with `awg add`: <name>.conf in a listable dir, each file root-only."""
|
||||||
|
if env("AWG_RUNTIME_GLOBAL") != "1":
|
||||||
|
return []
|
||||||
|
try:
|
||||||
|
names = os.listdir(_awg_runtime_dir())
|
||||||
|
except OSError:
|
||||||
|
return []
|
||||||
|
return sorted(n.removesuffix(".conf") for n in names if n.endswith(".conf") and AWG_NAME.fullmatch(n.removesuffix(".conf")))
|
||||||
|
|
||||||
|
|
||||||
# --- completion ---------------------------------------------------------------
|
# --- completion ---------------------------------------------------------------
|
||||||
#
|
#
|
||||||
# Candidates for the words already typed, one per line as word<TAB>description.
|
# Candidates for the words already typed, one per line as word<TAB>description.
|
||||||
@@ -612,8 +643,12 @@ COMPLETE = {
|
|||||||
"off": "stop a profile",
|
"off": "stop a profile",
|
||||||
"toggle": "start a profile if stopped, stop it if running",
|
"toggle": "start a profile if stopped, stop it if running",
|
||||||
"restart": "restart a profile",
|
"restart": "restart a profile",
|
||||||
|
"add": "add a profile from a .conf or vpn:// link",
|
||||||
|
"rm": "remove a profile added with awg add",
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"awg add": {"flags": {"--container": "which container of a vpn:// export"}},
|
||||||
|
"awg rm": {"args": lambda: _names(_awg_runtime_profiles())},
|
||||||
"awg on": {"args": lambda: _names(_awg_profiles())},
|
"awg on": {"args": lambda: _names(_awg_profiles())},
|
||||||
"awg off": {"args": lambda: _names(_awg_profiles())},
|
"awg off": {"args": lambda: _names(_awg_profiles())},
|
||||||
"awg toggle": {"args": lambda: _names(_awg_profiles())},
|
"awg toggle": {"args": lambda: _names(_awg_profiles())},
|
||||||
@@ -770,7 +805,8 @@ def _status_snapshot(states=None):
|
|||||||
name: {"available": unit in states, "active": states.get(unit) == "active"} for name, unit in SNAPSHOT_UNITS.items()
|
name: {"available": unit in states, "active": states.get(unit) == "active"} for name, unit in SNAPSHOT_UNITS.items()
|
||||||
}
|
}
|
||||||
snapshot["awg"] = {
|
snapshot["awg"] = {
|
||||||
"available": bool(profiles),
|
# With runtime profiles on, `awg add` can add the first one.
|
||||||
|
"available": bool(profiles) or env("AWG_RUNTIME_GLOBAL") == "1",
|
||||||
"profiles": profiles,
|
"profiles": profiles,
|
||||||
"active": next((p for p in profiles if states.get(_awg_service(p)) == "active"), ""),
|
"active": next((p for p in profiles if states.get(_awg_service(p)) == "active"), ""),
|
||||||
}
|
}
|
||||||
@@ -1006,7 +1042,14 @@ def cmd_outbounds(verb="list", *args):
|
|||||||
del args[i : i + 2]
|
del args[i : i + 2]
|
||||||
if not detour:
|
if not detour:
|
||||||
usage("proxy outbounds add [tag] <url|json|-> [--detour <tag>]")
|
usage("proxy outbounds add [tag] <url|json|-> [--detour <tag>]")
|
||||||
_runtime_entry_add("outbound", *args, detour=detour)
|
container = ""
|
||||||
|
if "--container" in args:
|
||||||
|
i = args.index("--container")
|
||||||
|
container = args[i + 1] if i + 1 < len(args) else ""
|
||||||
|
del args[i : i + 2]
|
||||||
|
if not container:
|
||||||
|
usage("proxy outbounds add [tag] <vpn://…|file.conf|-> [--container <name>]")
|
||||||
|
_runtime_entry_add("outbound", *args, detour=detour, container=container)
|
||||||
elif verb == "chain":
|
elif verb == "chain":
|
||||||
cmd_outbound_chain(*args)
|
cmd_outbound_chain(*args)
|
||||||
elif verb in ("rm", "remove", "del"):
|
elif verb in ("rm", "remove", "del"):
|
||||||
@@ -1409,13 +1452,13 @@ def _runtime_tags(kind):
|
|||||||
names = os.listdir(_runtime_dir(kind))
|
names = os.listdir(_runtime_dir(kind))
|
||||||
except OSError:
|
except OSError:
|
||||||
return []
|
return []
|
||||||
exts = (".url", ".json") if kind == "outbound" else (".url",)
|
exts = (".url", ".json", ".awg") if kind == "outbound" else (".url",)
|
||||||
return sorted(os.path.splitext(n)[0] for n in names if n.endswith(exts))
|
return sorted(os.path.splitext(n)[0] for n in names if n.endswith(exts))
|
||||||
|
|
||||||
|
|
||||||
def _runtime_path(kind, tag):
|
def _runtime_path(kind, tag):
|
||||||
"""The file behind a runtime entry, or its .url spelling when there is none."""
|
"""The file behind a runtime entry, or its .url spelling when there is none."""
|
||||||
for ext in (".url", ".json") if kind == "outbound" else (".url",):
|
for ext in (".url", ".json", ".awg") if kind == "outbound" else (".url",):
|
||||||
path = os.path.join(_runtime_dir(kind), tag + ext)
|
path = os.path.join(_runtime_dir(kind), tag + ext)
|
||||||
if os.path.exists(path):
|
if os.path.exists(path):
|
||||||
return path
|
return path
|
||||||
@@ -1453,6 +1496,8 @@ RUNTIME_TAG_MAX = 32
|
|||||||
|
|
||||||
def _runtime_source(kind, arg):
|
def _runtime_source(kind, arg):
|
||||||
"""Whether an add argument is the entry itself rather than its tag."""
|
"""Whether an add argument is the entry itself rather than its tag."""
|
||||||
|
if kind == "outbound" and (_awg_source(arg) or _awg_file(arg)):
|
||||||
|
return True
|
||||||
return "://" in arg or (kind == "outbound" and (arg == "-" or arg.lstrip().startswith("{")))
|
return "://" in arg or (kind == "outbound" and (arg == "-" or arg.lstrip().startswith("{")))
|
||||||
|
|
||||||
|
|
||||||
@@ -1516,7 +1561,7 @@ def _unique_runtime_tag(kind, name, fallback):
|
|||||||
return tag
|
return tag
|
||||||
|
|
||||||
|
|
||||||
def _runtime_entry_add(kind, *args, detour=""):
|
def _runtime_entry_add(kind, *args, detour="", container=""):
|
||||||
what = "<url|json|-> [--detour <tag>]" if kind == "outbound" else "<url>"
|
what = "<url|json|-> [--detour <tag>]" if kind == "outbound" else "<url>"
|
||||||
shape = f"proxy {_runtime_noun(kind)} add [tag] {what}"
|
shape = f"proxy {_runtime_noun(kind)} add [tag] {what}"
|
||||||
if len(args) == 1 and _runtime_source(kind, args[0]):
|
if len(args) == 1 and _runtime_source(kind, args[0]):
|
||||||
@@ -1534,6 +1579,13 @@ def _runtime_entry_add(kind, *args, detour=""):
|
|||||||
die(f"Cannot chain through '{detour}': not an outbound. See: proxy-ctl proxy outbounds")
|
die(f"Cannot chain through '{detour}': not an outbound. See: proxy-ctl proxy outbounds")
|
||||||
if kind == "outbound" and url == "-":
|
if kind == "outbound" and url == "-":
|
||||||
url = sys.stdin.read()
|
url = sys.stdin.read()
|
||||||
|
if kind == "outbound" and _awg_file(url):
|
||||||
|
url = _awg_input(url)
|
||||||
|
if kind == "outbound" and _awg_source(url):
|
||||||
|
_awg_outbound_add(tag, url, detour, container)
|
||||||
|
return
|
||||||
|
if container:
|
||||||
|
die("--container only applies to an AmneziaWG vpn:// link.")
|
||||||
if not tag:
|
if not tag:
|
||||||
tag = _runtime_tag_for(kind, url)
|
tag = _runtime_tag_for(kind, url)
|
||||||
_check_runtime_tag(kind, tag)
|
_check_runtime_tag(kind, tag)
|
||||||
@@ -1583,6 +1635,8 @@ def cmd_outbound_chain(tag="", hop="", new_tag="", *_):
|
|||||||
die(f"'{tag}' cannot chain through itself; name another outbound as the hop.")
|
die(f"'{tag}' cannot chain through itself; name another outbound as the hop.")
|
||||||
entry = _outbound_share_entry(tag)
|
entry = _outbound_share_entry(tag)
|
||||||
source = _s(entry.get("url") or "")
|
source = _s(entry.get("url") or "")
|
||||||
|
if not source and _awg_tunnel_hop(entry.get("outbound") or {}):
|
||||||
|
die(f"'{tag}' is an AmneziaWG outbound: its tunnel dials the peer itself and cannot go through another outbound.")
|
||||||
if not source:
|
if not source:
|
||||||
ob = entry.get("outbound") or {}
|
ob = entry.get("outbound") or {}
|
||||||
if not ob:
|
if not ob:
|
||||||
@@ -1610,7 +1664,7 @@ def _runtime_entry_rm(kind, tag="", *_):
|
|||||||
try:
|
try:
|
||||||
os.unlink(path)
|
os.unlink(path)
|
||||||
# Its hop, and a disable left from it: a new entry of this name would inherit them.
|
# Its hop, and a disable left from it: a new entry of this name would inherit them.
|
||||||
for extra in (".detour", ".disabled") if kind == "outbound" else ():
|
for extra in (".detour", ".disabled", ".port") if kind == "outbound" else ():
|
||||||
if os.path.exists(os.path.join(_runtime_dir(kind), tag + extra)):
|
if os.path.exists(os.path.join(_runtime_dir(kind), tag + extra)):
|
||||||
os.unlink(os.path.join(_runtime_dir(kind), tag + extra))
|
os.unlink(os.path.join(_runtime_dir(kind), tag + extra))
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
@@ -2832,15 +2886,227 @@ def cmd_where(domain="", *_):
|
|||||||
# --- awg ----------------------------------------------------------------------
|
# --- awg ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
AWG_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_-]{0,31}")
|
||||||
|
|
||||||
|
|
||||||
def _awg_service(profile):
|
def _awg_service(profile):
|
||||||
|
# Added with `awg add`: an instance of the template, which reads amneziawg.d/<name>.conf.
|
||||||
|
if profile and _awg_added(profile):
|
||||||
|
return f"proxy-suite-awg@{profile}"
|
||||||
return f"proxy-suite-awg-{profile}"
|
return f"proxy-suite-awg-{profile}"
|
||||||
|
|
||||||
|
|
||||||
|
# --- AmneziaWG configs added at runtime -----------------------------------------
|
||||||
|
#
|
||||||
|
# A .conf or vpn:// link becomes a global profile (`awg add`, amneziawg.d/<name>.conf) or an
|
||||||
|
# outbound (`proxy outbounds add`, outbounds.d/<tag>.awg with its tunnel's port in <tag>.port).
|
||||||
|
# amneziawg_config.py --import checks and normalizes it, hooks refused. The config always
|
||||||
|
# reaches it on stdin: keys in argv would show in ps.
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_source(text):
|
||||||
|
"""Whether text is an AmneziaWG config itself: a vpn:// link, or .conf text."""
|
||||||
|
t = (text or "").strip()
|
||||||
|
return t.startswith("vpn://") or ("[interface]" in t.lower() and "[peer]" in t.lower())
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_file(arg):
|
||||||
|
"""Whether an add argument names a .conf or vpn:// export on disk."""
|
||||||
|
return bool(arg) and arg.endswith((".conf", ".vpn")) and os.path.isfile(os.path.expanduser(arg))
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_input(arg):
|
||||||
|
"""The config an add argument stands for: stdin (-), the text itself, or a file's."""
|
||||||
|
if arg == "-":
|
||||||
|
return sys.stdin.read()
|
||||||
|
if _awg_source(arg):
|
||||||
|
return arg
|
||||||
|
path = os.path.expanduser(arg)
|
||||||
|
try:
|
||||||
|
return read_text(path)
|
||||||
|
except OSError as e:
|
||||||
|
die(f"Cannot read {path}: {e.strerror or e}")
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_import(text, *args):
|
||||||
|
"""amneziawg_config.py --import on text: its output, or its complaint as ours."""
|
||||||
|
tool = env("AWG_CONFIG_TOOL")
|
||||||
|
if not tool:
|
||||||
|
die("AmneziaWG is not enabled in this configuration.")
|
||||||
|
try:
|
||||||
|
p = subprocess.run([sys.executable, tool, "--import", "-", *args], input=text, capture_output=True, text=True)
|
||||||
|
except OSError as e:
|
||||||
|
die(f"Cannot run {tool}: {e}")
|
||||||
|
if p.returncode:
|
||||||
|
message = p.stderr.strip().removeprefix("amneziawg-config: ") or f"{tool} exited with {p.returncode}"
|
||||||
|
die(message.replace("set vpnContainer", "pick one with --container <name>"))
|
||||||
|
return p.stdout
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_describe(text, container=""):
|
||||||
|
"""What the config says of itself: {"name", "endpoint"}. Dies when it is not one."""
|
||||||
|
out = _awg_import(text, "--describe", *(["--container", container] if container else []))
|
||||||
|
try:
|
||||||
|
described = json.loads(out)
|
||||||
|
except ValueError:
|
||||||
|
described = {}
|
||||||
|
return described if isinstance(described, dict) else {}
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_label(described, fallback):
|
||||||
|
"""A name for an entry added without one: the export's description, else awg-<its host>."""
|
||||||
|
name = _s(described.get("name") or "")
|
||||||
|
host = _s(described.get("endpoint") or "").rsplit(":", 1)[0].strip("[]")
|
||||||
|
if name and name == host:
|
||||||
|
return f"awg-{_host_label(host)}"
|
||||||
|
return name or fallback
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_write(text, path, container=""):
|
||||||
|
"""The normalized config at path, 0600; the directory must let us in."""
|
||||||
|
directory = os.path.dirname(path)
|
||||||
|
if not os.access(directory, os.W_OK | os.X_OK):
|
||||||
|
denied(directory, "write to")
|
||||||
|
_awg_import(text, "--output", path, *(["--container", container] if container else []))
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_tunnel_ports():
|
||||||
|
return range(int(env("AWG_TUNNEL_BASE_PORT", "18800")), int(env("AWG_TUNNEL_BASE_PORT", "18800")) + int(env("AWG_TUNNEL_SLOTS", "32")))
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_tunnel_hop(ob):
|
||||||
|
"""Whether a backend outbound is the SOCKS hop to a runtime AmneziaWG tunnel."""
|
||||||
|
port = ob.get("server_port") or (ob.get("settings") or {}).get("port")
|
||||||
|
server = ob.get("server") or (ob.get("settings") or {}).get("address")
|
||||||
|
return server == "127.0.0.1" and isinstance(port, int) and port in _awg_tunnel_ports()
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_free_port():
|
||||||
|
taken = set()
|
||||||
|
directory = _runtime_dir("outbound")
|
||||||
|
try:
|
||||||
|
names = os.listdir(directory)
|
||||||
|
except OSError:
|
||||||
|
names = []
|
||||||
|
for name in names:
|
||||||
|
if name.endswith(".port"):
|
||||||
|
try:
|
||||||
|
taken.add(int(read_text(os.path.join(directory, name)).split()[0]))
|
||||||
|
except (OSError, ValueError, IndexError):
|
||||||
|
pass
|
||||||
|
port = next((p for p in _awg_tunnel_ports() if p not in taken), None)
|
||||||
|
if port is None:
|
||||||
|
die(f"No free port for another AmneziaWG outbound: all {len(_awg_tunnel_ports())} are taken. Remove one first.")
|
||||||
|
return port
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_outbound_add(tag, text, detour, container):
|
||||||
|
require_enabled("AWG_RUNTIME_OUTBOUNDS", "Adding AmneziaWG outbounds at runtime")
|
||||||
|
if detour:
|
||||||
|
die("An AmneziaWG outbound cannot chain through another: its tunnel dials the peer itself.")
|
||||||
|
described = _awg_describe(text, container)
|
||||||
|
if not tag:
|
||||||
|
tag = _unique_runtime_tag("outbound", _awg_label(described, "awg"), "awg")
|
||||||
|
_check_runtime_tag("outbound", tag)
|
||||||
|
print(f"Tag: {tag} (none given; pass one first to choose it)")
|
||||||
|
directory = _runtime_dir("outbound")
|
||||||
|
if not os.access(directory, os.W_OK | os.X_OK):
|
||||||
|
denied(directory, "write to")
|
||||||
|
port = _awg_free_port()
|
||||||
|
old = os.umask(0o027)
|
||||||
|
try:
|
||||||
|
# The port first: the config is what the start script and the sync unit look for.
|
||||||
|
for extra in (".detour", ".disabled"):
|
||||||
|
if os.path.exists(os.path.join(directory, tag + extra)):
|
||||||
|
os.unlink(os.path.join(directory, tag + extra)) # left from an earlier entry of this name
|
||||||
|
with open(os.path.join(directory, f"{tag}.port"), "w", encoding="utf-8") as f:
|
||||||
|
f.write(f"{port}\n")
|
||||||
|
except OSError:
|
||||||
|
denied(directory, "write to")
|
||||||
|
finally:
|
||||||
|
os.umask(old)
|
||||||
|
_awg_write(text, os.path.join(directory, f"{tag}.awg"), container)
|
||||||
|
_runtime_reload()
|
||||||
|
_runtime_entry_verify("outbound", tag)
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_add(*args):
|
||||||
|
shape = "awg add [name] <vpn://…|file.conf|-> [--container <name>]"
|
||||||
|
args = list(args)
|
||||||
|
container = ""
|
||||||
|
if "--container" in args:
|
||||||
|
i = args.index("--container")
|
||||||
|
container = args[i + 1] if i + 1 < len(args) else ""
|
||||||
|
del args[i : i + 2]
|
||||||
|
if not container:
|
||||||
|
usage(shape)
|
||||||
|
require_enabled("AWG_RUNTIME_GLOBAL", "Adding AmneziaWG profiles at runtime")
|
||||||
|
if len(args) == 1:
|
||||||
|
name, source = "", args[0]
|
||||||
|
elif len(args) == 2 and (_awg_source(args[0]) or args[0] == "-"):
|
||||||
|
die(f"The name goes first, the config after it: proxy-ctl {shape}")
|
||||||
|
elif len(args) == 2:
|
||||||
|
name, source = args
|
||||||
|
else:
|
||||||
|
usage(shape)
|
||||||
|
# "warp" names WARP's own AmneziaWG unit (_warp_unit).
|
||||||
|
taken = {*_awg_profiles(), "warp"}
|
||||||
|
if name == "warp":
|
||||||
|
die("'warp' is reserved for WARP; pick another name.")
|
||||||
|
if name:
|
||||||
|
if not AWG_NAME.fullmatch(name):
|
||||||
|
die(f"Invalid profile name '{name}': up to 32 letters, digits, dashes and underscores, starting with a letter or digit.")
|
||||||
|
if name in taken:
|
||||||
|
die(f"An AmneziaWG profile named '{name}' already exists." + ("" if name in _awg_runtime_profiles() else " It is declared in the NixOS configuration."))
|
||||||
|
text = _awg_input(source)
|
||||||
|
described = _awg_describe(text, container)
|
||||||
|
if not name:
|
||||||
|
base = re.sub(r"[^A-Za-z0-9_-]+", "-", _awg_label(described, "awg")).strip("-_")[:32].strip("-_") or "awg"
|
||||||
|
name, n = base, 1
|
||||||
|
while name in taken:
|
||||||
|
n += 1
|
||||||
|
name = f"{base[: 32 - len(str(n)) - 1]}-{n}"
|
||||||
|
print(f"Name: {name} (none given; pass one first to choose it)")
|
||||||
|
_awg_write(text, os.path.join(_awg_runtime_dir(), f"{name}.conf"), container)
|
||||||
|
print(f"Added AmneziaWG profile: {name} - start it with: proxy-ctl awg on {name}")
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_rm(name="", *_):
|
||||||
|
if not name:
|
||||||
|
usage("awg rm <profile>")
|
||||||
|
if name not in _awg_runtime_profiles():
|
||||||
|
if name in _awg_profiles():
|
||||||
|
die(f"'{name}' is declared in the NixOS configuration; remove it there.")
|
||||||
|
die(f"No AmneziaWG profile named '{name}' was added with awg add.")
|
||||||
|
directory = _awg_runtime_dir()
|
||||||
|
if not os.access(directory, os.W_OK | os.X_OK):
|
||||||
|
denied(directory, "write to")
|
||||||
|
unit = _awg_service(name)
|
||||||
|
if svc_active(unit) or svc_state(unit) == "failed":
|
||||||
|
must("stop", unit)
|
||||||
|
# As `awg off`: the kill switch would otherwise hold with no tunnel to guard.
|
||||||
|
if svc_exists(KILL_SWITCH):
|
||||||
|
systemctl("stop", KILL_SWITCH)
|
||||||
|
try:
|
||||||
|
os.unlink(os.path.join(directory, f"{name}.conf"))
|
||||||
|
except FileNotFoundError:
|
||||||
|
pass
|
||||||
|
except OSError:
|
||||||
|
denied(os.path.join(directory, f"{name}.conf"), "remove")
|
||||||
|
print(f"Removed AmneziaWG profile: {name}")
|
||||||
|
|
||||||
|
|
||||||
def _active_awg_profiles():
|
def _active_awg_profiles():
|
||||||
return [p for p in _awg_profiles() if svc_active(_awg_service(p))]
|
return [p for p in _awg_profiles() if svc_active(_awg_service(p))]
|
||||||
|
|
||||||
|
|
||||||
def cmd_awg(verb="list", *args):
|
def cmd_awg(verb="list", *args):
|
||||||
|
if verb == "add":
|
||||||
|
_awg_add(*args)
|
||||||
|
return
|
||||||
|
if verb in ("rm", "remove", "del"):
|
||||||
|
_awg_rm(*args)
|
||||||
|
return
|
||||||
profiles = _awg_profiles()
|
profiles = _awg_profiles()
|
||||||
if args and args[0] not in profiles:
|
if args and args[0] not in profiles:
|
||||||
die(f"Unknown AmneziaWG profile: {args[0]}")
|
die(f"Unknown AmneziaWG profile: {args[0]}")
|
||||||
@@ -2854,11 +3120,11 @@ def cmd_awg(verb="list", *args):
|
|||||||
usage("awg toggle <profile>")
|
usage("awg toggle <profile>")
|
||||||
if verb in ("list", "status"):
|
if verb in ("list", "status"):
|
||||||
if not profiles:
|
if not profiles:
|
||||||
print("No AmneziaWG profiles configured.")
|
print("No AmneziaWG profiles configured." + (" Add one with: proxy-ctl awg add <vpn://…|file.conf>" if env("AWG_RUNTIME_GLOBAL") == "1" else ""))
|
||||||
return
|
return
|
||||||
print(f" {'PROFILE':<24} STATUS")
|
print(f" {'PROFILE':<24} {'STATUS':<12} SOURCE")
|
||||||
for profile in profiles:
|
for profile in profiles:
|
||||||
print(f" {profile:<24} {svc_state(_awg_service(profile)) or 'unknown'}")
|
print(f" {profile:<24} {svc_state(_awg_service(profile)) or 'unknown':<12} {'runtime' if _awg_added(profile) else 'declared'}")
|
||||||
elif verb == "on":
|
elif verb == "on":
|
||||||
if not args:
|
if not args:
|
||||||
usage("awg on <profile>")
|
usage("awg on <profile>")
|
||||||
@@ -2873,7 +3139,7 @@ def cmd_awg(verb="list", *args):
|
|||||||
if verb == "off" and svc_exists(KILL_SWITCH):
|
if verb == "off" and svc_exists(KILL_SWITCH):
|
||||||
systemctl("stop", KILL_SWITCH)
|
systemctl("stop", KILL_SWITCH)
|
||||||
else:
|
else:
|
||||||
usage("awg [list] | on <profile> | off [profile] | toggle [profile] | restart [profile]")
|
usage("awg [list] | on <profile> | off [profile] | toggle [profile] | restart [profile] | add [name] <config> | rm <profile>")
|
||||||
|
|
||||||
|
|
||||||
# --- wl -----------------------------------------------------------------------
|
# --- wl -----------------------------------------------------------------------
|
||||||
|
|||||||
+14
-12
@@ -953,11 +953,11 @@ class Window(Adw.ApplicationWindow):
|
|||||||
except GLib.Error as e:
|
except GLib.Error as e:
|
||||||
self.toast(f"Cannot read the clipboard: {e.message}")
|
self.toast(f"Cannot read the clipboard: {e.message}")
|
||||||
return
|
return
|
||||||
argv, what = model.paste_argv(page.tab.id, text)
|
argv, what, stdin = model.paste_argv(page.tab.id, text)
|
||||||
if argv is None:
|
if argv is None:
|
||||||
self.toast(what)
|
self.toast(what)
|
||||||
else:
|
else:
|
||||||
self.app.run_argv("run", argv, self)
|
self.app.run_argv("run", argv, self, stdin=stdin)
|
||||||
|
|
||||||
def follow_logs(self):
|
def follow_logs(self):
|
||||||
self.app.run_argv("suspend", ["logs"], self)
|
self.app.run_argv("suspend", ["logs"], self)
|
||||||
@@ -977,13 +977,14 @@ class Window(Adw.ApplicationWindow):
|
|||||||
def with_text(text=""):
|
def with_text(text=""):
|
||||||
try:
|
try:
|
||||||
argv = action.argv(row, text, self.app.states)
|
argv = action.argv(row, text, self.app.states)
|
||||||
|
stdin = action.stdin(row, text) if action.stdin else None
|
||||||
except (ValueError, IndexError) as e:
|
except (ValueError, IndexError) as e:
|
||||||
self.toast(f"Cannot run that: {e}")
|
self.toast(f"Cannot run that: {e}")
|
||||||
return
|
return
|
||||||
if model.needs_confirm(action, row):
|
if model.needs_confirm(action, row):
|
||||||
self.app.confirm(argv, lambda: self.app.run_argv(action.mode, argv, self), self)
|
self.app.confirm(argv, lambda: self.app.run_argv(action.mode, argv, self, stdin=stdin), self)
|
||||||
else:
|
else:
|
||||||
self.app.run_argv(action.mode, argv, self)
|
self.app.run_argv(action.mode, argv, self, stdin=stdin)
|
||||||
|
|
||||||
if not action.prompt:
|
if not action.prompt:
|
||||||
with_text()
|
with_text()
|
||||||
@@ -1280,9 +1281,10 @@ class ProxySuiteGui(Adw.Application):
|
|||||||
dialog.connect("response", lambda _, r: r == "run" and then())
|
dialog.connect("response", lambda _, r: r == "run" and then())
|
||||||
dialog.present(parent)
|
dialog.present(parent)
|
||||||
|
|
||||||
def run_argv(self, mode, argv, win, root=False):
|
def run_argv(self, mode, argv, win, root=False, stdin=None):
|
||||||
"""run: a toast; dialog, suspend, pause: output streamed into a dialog; copy: the last line to the clipboard.
|
"""run: a toast; dialog, suspend, pause: output streamed into a dialog; copy: the last line to the clipboard.
|
||||||
root, or the elevated toggle: through pkexec. Never `apps run`, which is per user."""
|
root, or the elevated toggle: through pkexec. Never `apps run`, which is per user.
|
||||||
|
stdin: text proxy-ctl reads (argv says "-"), kept out of argv and pkexec's log."""
|
||||||
root = (root or self.elevated()) and argv[:1] != ["apps"]
|
root = (root or self.elevated()) and argv[:1] != ["apps"]
|
||||||
command = f"{'pkexec ' if root else ''}proxy-ctl {shlex.join(argv)}"
|
command = f"{'pkexec ' if root else ''}proxy-ctl {shlex.join(argv)}"
|
||||||
retry_argv = argv
|
retry_argv = argv
|
||||||
@@ -1295,12 +1297,12 @@ class ProxySuiteGui(Adw.Application):
|
|||||||
dialog.present(win)
|
dialog.present(win)
|
||||||
elif win is not None:
|
elif win is not None:
|
||||||
win.toast(f"… {command}")
|
win.toast(f"… {command}")
|
||||||
threading.Thread(target=self.stream, args=(command, argv, mode, win, dialog, qr, root, retry_argv), daemon=True).start()
|
threading.Thread(target=self.stream, args=(command, argv, mode, win, dialog, qr, root, retry_argv, stdin), daemon=True).start()
|
||||||
|
|
||||||
def stream(self, command, argv, mode, win, dialog, qr, root, retry_argv):
|
def stream(self, command, argv, mode, win, dialog, qr, root, retry_argv, stdin=None):
|
||||||
out = []
|
out = []
|
||||||
try:
|
try:
|
||||||
p = model.popen(argv, "pkexec" if root else None)
|
p = model.popen(argv, "pkexec" if root else None, stdin=stdin)
|
||||||
if dialog:
|
if dialog:
|
||||||
GLib.idle_add(lambda: dialog.running(p, stoppable=not root) and False)
|
GLib.idle_add(lambda: dialog.running(p, stoppable=not root) and False)
|
||||||
for line in p.stdout:
|
for line in p.stdout:
|
||||||
@@ -1313,13 +1315,13 @@ class ProxySuiteGui(Adw.Application):
|
|||||||
status = 127
|
status = 127
|
||||||
if root and status == 126 and not out:
|
if root and status == 126 and not out:
|
||||||
out.append("authentication cancelled") # pkexec: the password dialog was dismissed
|
out.append("authentication cancelled") # pkexec: the password dialog was dismissed
|
||||||
GLib.idle_add(lambda: self.ran(command, mode, win, dialog, qr, out, status, retry_argv) and False)
|
GLib.idle_add(lambda: self.ran(command, mode, win, dialog, qr, out, status, retry_argv, stdin) and False)
|
||||||
|
|
||||||
def ran(self, command, mode, win, dialog, qr, out, status, retry_argv):
|
def ran(self, command, mode, win, dialog, qr, out, status, retry_argv, stdin=None):
|
||||||
last = last_line(out)
|
last = last_line(out)
|
||||||
text = "\n".join(out)
|
text = "\n".join(out)
|
||||||
output = (command, text)
|
output = (command, text)
|
||||||
retry = (lambda: self.run_argv(mode, retry_argv, win, root=True)) if model.needs_root(out, status) else None
|
retry = (lambda: self.run_argv(mode, retry_argv, win, root=True, stdin=stdin)) if model.needs_root(out, status) else None
|
||||||
if win is not None:
|
if win is not None:
|
||||||
win.last_output = output
|
win.last_output = output
|
||||||
win.last_retry = retry
|
win.last_retry = retry
|
||||||
|
|||||||
+126
-20
@@ -66,6 +66,7 @@ class Action:
|
|||||||
mode: str = "run" # run: result in the feedback line; dialog: output streamed into a dialog; suspend: hand over the terminal; pause: suspend, then wait for enter; copy: last line to the clipboard
|
mode: str = "run" # run: result in the feedback line; dialog: output streamed into a dialog; suspend: hand over the terminal; pause: suspend, then wait for enter; copy: last line to the clipboard
|
||||||
offered: Callable = None # () -> this configuration has it; None: every one does
|
offered: Callable = None # () -> this configuration has it; None: every one does
|
||||||
tty: bool = False # it asks on the terminal: only a front end that hands the terminal over offers it
|
tty: bool = False # it asks on the terminal: only a front end that hands the terminal over offers it
|
||||||
|
stdin: Callable = None # (selected row or None, prompt text) -> text proxy-ctl reads on stdin, or None
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -150,6 +151,7 @@ TOGGLES = {
|
|||||||
"proxy-suite-zapret": ["zapret"],
|
"proxy-suite-zapret": ["zapret"],
|
||||||
}
|
}
|
||||||
AWG_PREFIX = ctl._awg_service("")
|
AWG_PREFIX = ctl._awg_service("")
|
||||||
|
AWG_RUNTIME_PREFIX = "proxy-suite-awg@"
|
||||||
ZAPRET_LISTS = (
|
ZAPRET_LISTS = (
|
||||||
("learned", "zapret-hosts-auto.txt"),
|
("learned", "zapret-hosts-auto.txt"),
|
||||||
("pinned", "zapret-hosts-user.txt"),
|
("pinned", "zapret-hosts-user.txt"),
|
||||||
@@ -183,8 +185,11 @@ def _wl_argv(verb, *extra):
|
|||||||
|
|
||||||
def _awg_profile(row):
|
def _awg_profile(row):
|
||||||
"""The global AmneziaWG profile behind a row, or empty."""
|
"""The global AmneziaWG profile behind a row, or empty."""
|
||||||
name = row["unit"].removeprefix(AWG_PREFIX)
|
unit = row["unit"]
|
||||||
return name if row["unit"].startswith(AWG_PREFIX) and name in ctl._awg_profiles() else ""
|
for prefix in (AWG_RUNTIME_PREFIX, AWG_PREFIX):
|
||||||
|
if unit.startswith(prefix) and (name := unit.removeprefix(prefix)) in ctl._awg_profiles():
|
||||||
|
return name
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
def _unit_argv(row, verb):
|
def _unit_argv(row, verb):
|
||||||
@@ -264,6 +269,44 @@ def outbound_summary():
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def awg_rows(states):
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"key": p,
|
||||||
|
"profile": p,
|
||||||
|
"unit": ctl._awg_service(p),
|
||||||
|
"state": states.get(ctl._awg_service(p)) or "inactive",
|
||||||
|
"source": "runtime" if ctl._awg_added(p) else "declared",
|
||||||
|
}
|
||||||
|
for p in ctl._awg_profiles()
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_available(_):
|
||||||
|
return bool(ctl._awg_profiles()) or ctl.env("AWG_RUNTIME_GLOBAL") == "1"
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_add(text):
|
||||||
|
"""[name] <config> as typed: (name or None, the config or a path to it)."""
|
||||||
|
text = text.strip()
|
||||||
|
if ctl._awg_source(text):
|
||||||
|
return None, text
|
||||||
|
parts = text.split(None, 1)
|
||||||
|
return (parts[0], parts[1].strip()) if len(parts) == 2 else (None, text)
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_add_argv(text):
|
||||||
|
name, source = _awg_add(text)
|
||||||
|
# The config itself goes on stdin: in argv its keys would show in ps, sudo's log and here.
|
||||||
|
what = "-" if ctl._awg_source(source) else _path(source)
|
||||||
|
return ["awg", "add", *([name] if name else []), what]
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_add_stdin(text):
|
||||||
|
_, source = _awg_add(text)
|
||||||
|
return source if ctl._awg_source(source) else None
|
||||||
|
|
||||||
|
|
||||||
def subscription_rows(_):
|
def subscription_rows(_):
|
||||||
rows = []
|
rows = []
|
||||||
for source, tags in (("static", ctl._sub_tags()), ("runtime", ctl._runtime_tags("subscription"))):
|
for source, tags in (("static", ctl._sub_tags()), ("runtime", ctl._runtime_tags("subscription"))):
|
||||||
@@ -441,9 +484,19 @@ def _sub_url(row):
|
|||||||
|
|
||||||
|
|
||||||
def _add_args(text):
|
def _add_args(text):
|
||||||
"""[tag] <url>, or JSON with spaces in it, as `proxy-ctl ... add` takes them."""
|
"""[tag] <url>, or JSON with spaces in it, as `proxy-ctl ... add` takes them.
|
||||||
|
An AmneziaWG config becomes "-": _add_stdin hands it over on stdin."""
|
||||||
text = text.strip()
|
text = text.strip()
|
||||||
return [text] if text.startswith("{") else text.split(None, 1)
|
if text.startswith("{"):
|
||||||
|
return [text]
|
||||||
|
name, source = _awg_add(text)
|
||||||
|
if ctl._awg_source(source):
|
||||||
|
return [*([name] if name else []), "-"]
|
||||||
|
return text.split(None, 1)
|
||||||
|
|
||||||
|
|
||||||
|
def _add_stdin(text):
|
||||||
|
return _awg_add_stdin(text)
|
||||||
|
|
||||||
|
|
||||||
def _zapret_auto():
|
def _zapret_auto():
|
||||||
@@ -519,6 +572,28 @@ TABS = [
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
Tab(
|
||||||
|
"awg",
|
||||||
|
"AmneziaWG",
|
||||||
|
_awg_available,
|
||||||
|
[("profile", "Profile"), ("state", "State"), ("source", "Source")],
|
||||||
|
awg_rows,
|
||||||
|
summary=lambda: "Only one global tunnel runs at a time: starting a profile stops TUN, TProxy and any other profile.",
|
||||||
|
actions=[
|
||||||
|
Action("space", "start / stop", lambda r, *_: ["awg", "off" if r["state"] == "active" else "on", r["profile"]], when=ROW),
|
||||||
|
Action("ctrl+r", "restart it", lambda r, *_: ["awg", "restart", r["profile"]], when=lambda r: r["state"] in ("active", "failed")),
|
||||||
|
Action("l", "follow its logs", lambda r, *_: ["logs", r["unit"]], when=ROW, mode="suspend"),
|
||||||
|
Action(
|
||||||
|
"n",
|
||||||
|
"add a profile (name optional)…",
|
||||||
|
lambda r, t, _: _awg_add_argv(t),
|
||||||
|
prompt="[name] <vpn://… or a .conf path> - e.g. home vpn://… (or paste a whole .conf onto the table)",
|
||||||
|
stdin=lambda r, t: _awg_add_stdin(t),
|
||||||
|
offered=lambda: ctl.env("AWG_RUNTIME_GLOBAL") == "1",
|
||||||
|
),
|
||||||
|
Action("d", "remove it", lambda r, *_: ["awg", "rm", r["profile"]], when=lambda r: r["source"] == "runtime", confirm=True),
|
||||||
|
],
|
||||||
|
),
|
||||||
Tab(
|
Tab(
|
||||||
"routing",
|
"routing",
|
||||||
"Routing",
|
"Routing",
|
||||||
@@ -557,7 +632,8 @@ TABS = [
|
|||||||
"n",
|
"n",
|
||||||
"add a runtime outbound (tag optional)…",
|
"add a runtime outbound (tag optional)…",
|
||||||
lambda r, t, _: ["proxy", "outbounds", "add", *_add_args(t)],
|
lambda r, t, _: ["proxy", "outbounds", "add", *_add_args(t)],
|
||||||
prompt="[tag] <url or JSON> - e.g. de-1 vless://… or just vless://…",
|
prompt="[tag] <url, JSON or vpn://> - e.g. de-1 vless://… or just vless://…",
|
||||||
|
stdin=lambda r, t: _add_stdin(t),
|
||||||
),
|
),
|
||||||
Action(
|
Action(
|
||||||
"h",
|
"h",
|
||||||
@@ -704,28 +780,42 @@ OUTBOUND_ADD = ["proxy", "outbounds", "add"]
|
|||||||
|
|
||||||
|
|
||||||
def paste_argv(tab_id, text):
|
def paste_argv(tab_id, text):
|
||||||
"""What pasting the clipboard onto a tab runs: (argv, ""), or (None, why it runs nothing).
|
"""What pasting the clipboard onto a tab runs: (argv, "", stdin), or (None, why it runs nothing, None).
|
||||||
|
|
||||||
Dumb on purpose: a share link becomes an outbound, a subscription URL a subscription,
|
Dumb on purpose: a share link becomes an outbound, a subscription URL a subscription,
|
||||||
a bare host a pinned or learned one. The tag comes from the link, as `add` derives it.
|
a bare host a pinned or learned one, an AmneziaWG vpn:// link or .conf a global profile
|
||||||
|
(an outbound on the outbounds tab). The tag comes from the link, as `add` derives it.
|
||||||
"""
|
"""
|
||||||
text = (text or "").strip()
|
text = (text or "").strip()
|
||||||
if not text:
|
if not text:
|
||||||
return None, "Nothing to paste."
|
return None, "Nothing to paste.", None
|
||||||
|
if ctl._awg_source(text):
|
||||||
|
return _awg_paste(tab_id, text)
|
||||||
if text.startswith("{"):
|
if text.startswith("{"):
|
||||||
return [*OUTBOUND_ADD, text], "" # only outbounds take JSON
|
return [*OUTBOUND_ADD, text], "", None # only outbounds take JSON
|
||||||
if len(text.splitlines()) > 1:
|
if len(text.splitlines()) > 1:
|
||||||
return None, "Paste one link at a time."
|
return None, "Paste one link at a time.", None
|
||||||
scheme = text.split("://", 1)[0].lower() if "://" in text else ""
|
scheme = text.split("://", 1)[0].lower() if "://" in text else ""
|
||||||
if scheme in PROXY_SCHEMES:
|
if scheme in PROXY_SCHEMES:
|
||||||
return [*OUTBOUND_ADD, text], ""
|
return [*OUTBOUND_ADD, text], "", None
|
||||||
if scheme in ("http", "https"):
|
if scheme in ("http", "https"):
|
||||||
return ([*OUTBOUND_ADD, text] if tab_id == "outbounds" else ["proxy", "subs", "add", text]), ""
|
return ([*OUTBOUND_ADD, text] if tab_id == "outbounds" else ["proxy", "subs", "add", text]), "", None
|
||||||
if scheme:
|
if scheme:
|
||||||
return None, f"Nothing takes a {scheme}:// link."
|
return None, f"Nothing takes a {scheme}:// link.", None
|
||||||
if HOST.fullmatch(text) and tab_id in HOST_ARGV:
|
if HOST.fullmatch(text) and tab_id in HOST_ARGV:
|
||||||
return [*HOST_ARGV[tab_id], text], ""
|
return [*HOST_ARGV[tab_id], text], "", None
|
||||||
return None, "Not a share link, a subscription URL or a host."
|
return None, "Not a share link, a subscription URL or a host.", None
|
||||||
|
|
||||||
|
|
||||||
|
def _awg_paste(tab_id, text):
|
||||||
|
"""An AmneziaWG config, on stdin: an outbound where outbounds are, else a global profile."""
|
||||||
|
outbound = ctl.env("AWG_RUNTIME_OUTBOUNDS") == "1"
|
||||||
|
global_ = ctl.env("AWG_RUNTIME_GLOBAL") == "1"
|
||||||
|
if outbound and (tab_id == "outbounds" or not global_):
|
||||||
|
return [*OUTBOUND_ADD, "-"], "", text
|
||||||
|
if global_:
|
||||||
|
return ["awg", "add", "-"], "", text
|
||||||
|
return None, "AmneziaWG configs cannot be added here: amneziaWg.runtime is off in this configuration.", None
|
||||||
|
|
||||||
|
|
||||||
def available_tabs(states):
|
def available_tabs(states):
|
||||||
@@ -795,13 +885,28 @@ def load_tab_as_root(tab, via):
|
|||||||
return None, (p.stderr.strip().splitlines() or [f"exit status {p.returncode}"])[-1]
|
return None, (p.stderr.strip().splitlines() or [f"exit status {p.returncode}"])[-1]
|
||||||
|
|
||||||
|
|
||||||
def popen(argv, root=None):
|
def popen(argv, root=None, stdin=None):
|
||||||
"""proxy-ctl with its output streamed: its own process group, so stop() takes down what it spawned too.
|
"""proxy-ctl with its output streamed: its own process group, so stop() takes down what it spawned too.
|
||||||
root: "pkexec" to run it as root, asking through the desktop's polkit agent."""
|
root: "pkexec" to run it as root, asking through the desktop's polkit agent.
|
||||||
return subprocess.Popen(
|
stdin: text for it to read (argv then says "-"), kept out of argv, ps and sudo's log."""
|
||||||
elevated(argv, root) if root else [CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
|
p = subprocess.Popen(
|
||||||
|
elevated(argv, root) if root else [CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||||
|
stdin=subprocess.DEVNULL if stdin is None else subprocess.PIPE,
|
||||||
text=True, errors="replace", start_new_session=True,
|
text=True, errors="replace", start_new_session=True,
|
||||||
)
|
)
|
||||||
|
feed(p, stdin)
|
||||||
|
return p
|
||||||
|
|
||||||
|
|
||||||
|
def feed(p, stdin):
|
||||||
|
"""Hands a started process its stdin text, and closes it."""
|
||||||
|
if stdin is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
p.stdin.write(stdin)
|
||||||
|
p.stdin.close()
|
||||||
|
except (BrokenPipeError, OSError):
|
||||||
|
pass # it exited first: its output says why
|
||||||
|
|
||||||
|
|
||||||
def stop(proc):
|
def stop(proc):
|
||||||
@@ -889,7 +994,8 @@ def tray_menu(snap, outbounds=None):
|
|||||||
if snap[name]["available"]:
|
if snap[name]["available"]:
|
||||||
active = snap[name]["active"]
|
active = snap[name]["active"]
|
||||||
traffic.append(MenuItem(name, label, kind="check", checked=active, argv=["proxy", name, "off" if active else "on"]))
|
traffic.append(MenuItem(name, label, kind="check", checked=active, argv=["proxy", name, "off" if active else "on"]))
|
||||||
if snap["awg"]["available"]:
|
# Available with none added yet: nothing to pick until `awg add`.
|
||||||
|
if snap["awg"]["available"] and snap["awg"]["profiles"]:
|
||||||
current = snap["awg"]["active"]
|
current = snap["awg"]["active"]
|
||||||
traffic.append(
|
traffic.append(
|
||||||
MenuItem(
|
MenuItem(
|
||||||
|
|||||||
+23
-15
@@ -433,7 +433,7 @@ class ProxyTui(App):
|
|||||||
self.typed = {} # prompt title -> what was last typed there
|
self.typed = {} # prompt title -> what was last typed there
|
||||||
self.feedback_timer = None
|
self.feedback_timer = None
|
||||||
self.last_output = None # (title, text)
|
self.last_output = None # (title, text)
|
||||||
self.retry = None # (mode, argv) of the last run that only root could do
|
self.retry = None # (mode, argv, stdin) of the last run that only root could do
|
||||||
self.animation_level = "none" # tab switches land at once
|
self.animation_level = "none" # tab switches land at once
|
||||||
self.register_theme(THEME)
|
self.register_theme(THEME)
|
||||||
self.theme = THEME.name
|
self.theme = THEME.name
|
||||||
@@ -641,11 +641,11 @@ class ProxyTui(App):
|
|||||||
if self.screen is not self.main:
|
if self.screen is not self.main:
|
||||||
return
|
return
|
||||||
event.stop()
|
event.stop()
|
||||||
argv, what = model.paste_argv(self.active_tab(), event.text)
|
argv, what, stdin = model.paste_argv(self.active_tab(), event.text)
|
||||||
if argv is None:
|
if argv is None:
|
||||||
self.feedback(what, False)
|
self.feedback(what, False)
|
||||||
else:
|
else:
|
||||||
self.run_argv("run", argv)
|
self.run_argv("run", argv, stdin)
|
||||||
|
|
||||||
def action_where(self):
|
def action_where(self):
|
||||||
self.perform(model.WHERE, None)
|
self.perform(model.WHERE, None)
|
||||||
@@ -705,13 +705,14 @@ class ProxyTui(App):
|
|||||||
def with_text(text=""):
|
def with_text(text=""):
|
||||||
try:
|
try:
|
||||||
argv = action.argv(row, text, self.states)
|
argv = action.argv(row, text, self.states)
|
||||||
|
stdin = action.stdin(row, text) if action.stdin else None
|
||||||
except (ValueError, IndexError) as e: # an unbalanced quote in a typed command
|
except (ValueError, IndexError) as e: # an unbalanced quote in a typed command
|
||||||
self.feedback(f"Cannot run that: {e}", False)
|
self.feedback(f"Cannot run that: {e}", False)
|
||||||
return
|
return
|
||||||
if model.needs_confirm(action, row):
|
if model.needs_confirm(action, row):
|
||||||
self.push_screen(Confirm(f"proxy-ctl {shlex.join(argv)}"), lambda ok: ok and self.run_argv(action.mode, argv))
|
self.push_screen(Confirm(f"proxy-ctl {shlex.join(argv)}"), lambda ok: ok and self.run_argv(action.mode, argv, stdin))
|
||||||
else:
|
else:
|
||||||
self.run_argv(action.mode, argv)
|
self.run_argv(action.mode, argv, stdin)
|
||||||
|
|
||||||
def typed(text):
|
def typed(text):
|
||||||
if text:
|
if text:
|
||||||
@@ -724,7 +725,8 @@ class ProxyTui(App):
|
|||||||
else:
|
else:
|
||||||
with_text()
|
with_text()
|
||||||
|
|
||||||
def run_argv(self, mode, argv):
|
def run_argv(self, mode, argv, stdin=None):
|
||||||
|
"""stdin: text proxy-ctl reads (argv says "-"); only for runs that stay in the TUI."""
|
||||||
command = f"proxy-ctl {shlex.join(argv)}"
|
command = f"proxy-ctl {shlex.join(argv)}"
|
||||||
if mode in ("suspend", "pause"):
|
if mode in ("suspend", "pause"):
|
||||||
self.foreground(mode, [CTL, *argv])
|
self.foreground(mode, [CTL, *argv])
|
||||||
@@ -734,7 +736,7 @@ class ProxyTui(App):
|
|||||||
if dialog:
|
if dialog:
|
||||||
self.push_screen(dialog)
|
self.push_screen(dialog)
|
||||||
self.feedback(f"… {command}")
|
self.feedback(f"… {command}")
|
||||||
self.stream(command, argv, dialog, mode == "copy")
|
self.stream(command, argv, dialog, mode == "copy", stdin)
|
||||||
|
|
||||||
def foreground(self, mode, argv):
|
def foreground(self, mode, argv):
|
||||||
with self.suspend():
|
with self.suspend():
|
||||||
@@ -747,10 +749,10 @@ class ProxyTui(App):
|
|||||||
self.action_reload()
|
self.action_reload()
|
||||||
|
|
||||||
@work(thread=True)
|
@work(thread=True)
|
||||||
def stream(self, command, argv, dialog, copy=False):
|
def stream(self, command, argv, dialog, copy=False, stdin=None):
|
||||||
out = []
|
out = []
|
||||||
try:
|
try:
|
||||||
p = model.popen(argv)
|
p = model.popen(argv, stdin=stdin)
|
||||||
if dialog:
|
if dialog:
|
||||||
dialog.proc = p
|
dialog.proc = p
|
||||||
for line in p.stdout:
|
for line in p.stdout:
|
||||||
@@ -761,9 +763,9 @@ class ProxyTui(App):
|
|||||||
except OSError as e:
|
except OSError as e:
|
||||||
out.append(f"cannot run proxy-ctl: {e}")
|
out.append(f"cannot run proxy-ctl: {e}")
|
||||||
status = 127
|
status = 127
|
||||||
self.call_from_thread(self.finish, command, argv, dialog, copy, out, status, stream_shown=True)
|
self.call_from_thread(self.finish, command, argv, dialog, copy, out, status, stream_shown=True, stdin=stdin)
|
||||||
|
|
||||||
def finish(self, command, argv, dialog, copy, out, status, stream_shown=False):
|
def finish(self, command, argv, dialog, copy, out, status, stream_shown=False, stdin=None):
|
||||||
"""A run's end: the feedback line, the clipboard, and the dialog's tail."""
|
"""A run's end: the feedback line, the clipboard, and the dialog's tail."""
|
||||||
if dialog and not stream_shown:
|
if dialog and not stream_shown:
|
||||||
for line in out:
|
for line in out:
|
||||||
@@ -784,7 +786,7 @@ class ProxyTui(App):
|
|||||||
hints = ["o: full output"] if len(out) > 1 and not dialog else []
|
hints = ["o: full output"] if len(out) > 1 and not dialog else []
|
||||||
self.retry = None
|
self.retry = None
|
||||||
if model.needs_root(out, status):
|
if model.needs_root(out, status):
|
||||||
self.retry = ("dialog" if dialog else "copy" if copy else "run", argv)
|
self.retry = ("dialog" if dialog else "copy" if copy else "run", argv, stdin)
|
||||||
hints.append("!: retry as root")
|
hints.append("!: retry as root")
|
||||||
if dialog:
|
if dialog:
|
||||||
dialog.offer_retry()
|
dialog.offer_retry()
|
||||||
@@ -795,7 +797,8 @@ class ProxyTui(App):
|
|||||||
if not self.retry:
|
if not self.retry:
|
||||||
self.feedback("Nothing to retry as root.")
|
self.feedback("Nothing to retry as root.")
|
||||||
return
|
return
|
||||||
(mode, argv), self.retry = self.retry, None
|
(mode, argv, *rest), self.retry = self.retry, None
|
||||||
|
stdin = rest[0] if rest else None
|
||||||
command = f"sudo proxy-ctl {shlex.join(argv)}"
|
command = f"sudo proxy-ctl {shlex.join(argv)}"
|
||||||
root_argv = model.elevated(argv, "sudo")
|
root_argv = model.elevated(argv, "sudo")
|
||||||
# sudo asks on the terminal, so the run happens there; the output comes back as usual.
|
# sudo asks on the terminal, so the run happens there; the output comes back as usual.
|
||||||
@@ -803,7 +806,12 @@ class ProxyTui(App):
|
|||||||
with self.suspend():
|
with self.suspend():
|
||||||
print(f"$ {command}", flush=True)
|
print(f"$ {command}", flush=True)
|
||||||
try:
|
try:
|
||||||
p = subprocess.Popen(root_argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace")
|
# sudo asks for the password on the terminal itself, so stdin can carry the text.
|
||||||
|
p = subprocess.Popen(
|
||||||
|
root_argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors="replace",
|
||||||
|
**({"stdin": subprocess.PIPE} if stdin is not None else {}),
|
||||||
|
)
|
||||||
|
model.feed(p, stdin)
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
p, status, out = None, 127, [f"cannot run sudo: {e}"]
|
p, status, out = None, 127, [f"cannot run sudo: {e}"]
|
||||||
if p:
|
if p:
|
||||||
@@ -821,7 +829,7 @@ class ProxyTui(App):
|
|||||||
dialog = Output(command, wrap="--qr" not in argv) if mode == "dialog" else None
|
dialog = Output(command, wrap="--qr" not in argv) if mode == "dialog" else None
|
||||||
if dialog:
|
if dialog:
|
||||||
self.push_screen(dialog)
|
self.push_screen(dialog)
|
||||||
self.finish(command, argv, dialog, mode == "copy", out, status)
|
self.finish(command, argv, dialog, mode == "copy", out, status, stdin=stdin)
|
||||||
|
|
||||||
def action_switch_root(self):
|
def action_switch_root(self):
|
||||||
def switch(ok):
|
def switch(ok):
|
||||||
|
|||||||
@@ -602,7 +602,9 @@ class AutoProxyTest(EnvTest):
|
|||||||
self.assertIn("proxy-suite group, or re-run with sudo", err)
|
self.assertIn("proxy-suite group, or re-run with sudo", err)
|
||||||
|
|
||||||
|
|
||||||
class RuntimeEntryTest(EnvTest):
|
class RuntimeSpoolTest(EnvTest):
|
||||||
|
"""The runtime spools, and a backend that reads them back on every reload."""
|
||||||
|
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
super().setUp()
|
super().setUp()
|
||||||
os.environ.update(
|
os.environ.update(
|
||||||
@@ -636,6 +638,8 @@ class RuntimeEntryTest(EnvTest):
|
|||||||
self.backend_start()
|
self.backend_start()
|
||||||
return 0, ""
|
return 0, ""
|
||||||
|
|
||||||
|
|
||||||
|
class RuntimeEntryTest(RuntimeSpoolTest):
|
||||||
def test_tag_for(self):
|
def test_tag_for(self):
|
||||||
tag = ctl._runtime_tag_for
|
tag = ctl._runtime_tag_for
|
||||||
self.assertEqual(tag("outbound", "vless://u@de1.example.net:443?security=reality#%F0%9F%87%A9%F0%9F%87%AA%20DE-1"), "DE-1")
|
self.assertEqual(tag("outbound", "vless://u@de1.example.net:443?security=reality#%F0%9F%87%A9%F0%9F%87%AA%20DE-1"), "DE-1")
|
||||||
@@ -754,6 +758,115 @@ class RuntimeEntryTest(EnvTest):
|
|||||||
self.assertEqual(os.listdir(self.path("outbounds.d")), [])
|
self.assertEqual(os.listdir(self.path("outbounds.d")), [])
|
||||||
|
|
||||||
|
|
||||||
|
AWG_CONF = """[Interface]
|
||||||
|
PrivateKey = private
|
||||||
|
Address = 10.8.0.2/32
|
||||||
|
|
||||||
|
[Peer]
|
||||||
|
PublicKey = public
|
||||||
|
AllowedIPs = 0.0.0.0/0
|
||||||
|
Endpoint = vpn.example.com:51820
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def awg_vpn_link(description):
|
||||||
|
"""A vpn:// export carrying AWG_CONF, as the Amnezia app writes one."""
|
||||||
|
import base64
|
||||||
|
import zlib
|
||||||
|
|
||||||
|
data = json.dumps({"description": description, "containers": [{"container": "amnezia-awg", "awg": {"last_config": json.dumps({"config": AWG_CONF})}}]}).encode()
|
||||||
|
return "vpn://" + base64.urlsafe_b64encode(len(data).to_bytes(4, "big") + zlib.compress(data)).decode().rstrip("=")
|
||||||
|
|
||||||
|
|
||||||
|
class AmneziaWgRuntimeTest(RuntimeSpoolTest):
|
||||||
|
"""`awg add`/`rm` and AmneziaWG outbounds: amneziawg_config.py itself checks and writes them."""
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
tool = os.environ.get("AWG_CONFIG_TOOL") or os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../scripts/amneziawg_config.py")
|
||||||
|
os.makedirs(self.path("amneziawg.d"))
|
||||||
|
os.environ.update(
|
||||||
|
AWG_CONFIG_TOOL=tool,
|
||||||
|
AWG_RUNTIME_GLOBAL="1",
|
||||||
|
AWG_RUNTIME_OUTBOUNDS="1",
|
||||||
|
AWG_RUNTIME_DIR=self.path("amneziawg.d"),
|
||||||
|
AWG_PROFILES_FILE=self.write("awg-profiles.json", ["home"]),
|
||||||
|
AWG_TUNNEL_BASE_PORT="18800",
|
||||||
|
AWG_TUNNEL_SLOTS="2",
|
||||||
|
)
|
||||||
|
self.active = set()
|
||||||
|
self.patch("svc_active", lambda unit: unit in self.active)
|
||||||
|
self.patch("svc_state", lambda unit: "active" if unit in self.active else "inactive")
|
||||||
|
self.patch("svc_exists", lambda unit: True)
|
||||||
|
|
||||||
|
def test_add_and_rm_global_profiles(self):
|
||||||
|
# Named after the server's host, then after the export's description; the config on stdin.
|
||||||
|
self.assertIn("Name: awg-example (none given", ok(ctl.cmd_awg, "add", AWG_CONF))
|
||||||
|
self.assertIn("Name: awg-example-2", ok(ctl.cmd_awg, "add", AWG_CONF))
|
||||||
|
with mock.patch.object(sys, "stdin", io.StringIO(awg_vpn_link("Work VPN"))):
|
||||||
|
self.assertIn("Name: Work-VPN", ok(ctl.cmd_awg, "add", "-"))
|
||||||
|
conf = self.write("office.conf", AWG_CONF)
|
||||||
|
ok(ctl.cmd_awg, "add", "office", conf)
|
||||||
|
path = self.path("amneziawg.d/office.conf")
|
||||||
|
self.assertEqual(os.stat(path).st_mode & 0o777, 0o600)
|
||||||
|
self.assertIn("Endpoint = vpn.example.com:51820", ctl.read_text(path))
|
||||||
|
self.assertEqual(ctl._awg_profiles(), ["home", "Work-VPN", "awg-example", "awg-example-2", "office"])
|
||||||
|
self.assertEqual(ctl._awg_service("office"), "proxy-suite-awg@office")
|
||||||
|
self.assertEqual(ctl._awg_service("home"), "proxy-suite-awg-home")
|
||||||
|
listing = ok(ctl.cmd_awg, "list")
|
||||||
|
self.assertRegex(listing, r"home\s+inactive\s+declared")
|
||||||
|
self.assertRegex(listing, r"office\s+inactive\s+runtime")
|
||||||
|
self.assertIn("office", ctl._complete_tree("awg", "rm"))
|
||||||
|
# Refused: a taken or reserved name, the wrong order, hooks, and anything but a config.
|
||||||
|
for args, why in [
|
||||||
|
(("home", AWG_CONF), "declared in the NixOS configuration"),
|
||||||
|
(("office", AWG_CONF), "already exists"),
|
||||||
|
(("warp", AWG_CONF), "reserved"),
|
||||||
|
(("bad name", AWG_CONF), "Invalid profile name"),
|
||||||
|
((AWG_CONF, "later"), "The name goes first"),
|
||||||
|
(("hooked", AWG_CONF.replace("Address", "PostUp = id\nAddress")), "privileged"),
|
||||||
|
(("nothing", "vless://u@x.test:443"), "Cannot read"),
|
||||||
|
]:
|
||||||
|
with self.subTest(args=args[0][:10]):
|
||||||
|
status, _, err = run(ctl.cmd_awg, "add", *args)
|
||||||
|
self.assertNotEqual(status, 0)
|
||||||
|
self.assertIn(why, err)
|
||||||
|
self.assertFalse(os.path.exists(self.path("amneziawg.d/hooked.conf")))
|
||||||
|
# rm: only what awg add added; a running one stops first, and its kill switch with it.
|
||||||
|
self.assertIn("remove it there", run(ctl.cmd_awg, "rm", "home")[2])
|
||||||
|
self.active.add("proxy-suite-awg@office")
|
||||||
|
self.assertIn("Removed AmneziaWG profile: office", ok(ctl.cmd_awg, "rm", "office"))
|
||||||
|
self.assertIn(("stop", "proxy-suite-awg@office"), self.started)
|
||||||
|
self.assertIn(("stop", ctl.KILL_SWITCH), self.started)
|
||||||
|
self.assertFalse(os.path.exists(path))
|
||||||
|
self.assertNotIn("office", ctl._awg_profiles())
|
||||||
|
# Off in the configuration: nothing to add to, and nothing listed.
|
||||||
|
os.environ["AWG_RUNTIME_GLOBAL"] = "0"
|
||||||
|
self.assertIn("not enabled", run(ctl.cmd_awg, "add", AWG_CONF)[2])
|
||||||
|
self.assertEqual(ctl._awg_profiles(), ["home"])
|
||||||
|
|
||||||
|
def test_outbounds(self):
|
||||||
|
self.assertIn("Tag: awg-example", ok(ctl.cmd_outbounds, "add", AWG_CONF))
|
||||||
|
self.assertEqual(ctl.read_text(self.path("outbounds.d/awg-example.port")), "18800\n")
|
||||||
|
self.assertEqual(os.stat(self.path("outbounds.d/awg-example.awg")).st_mode & 0o777, 0o600)
|
||||||
|
self.assertIn("proxy-suite-outbound-reload.service", self.started)
|
||||||
|
# A file, with a tag: the next port.
|
||||||
|
self.assertIn("Added outbound: de", ok(ctl.cmd_outbounds, "add", "de", self.write("de.conf", AWG_CONF)))
|
||||||
|
self.assertEqual(ctl.read_text(self.path("outbounds.d/de.port")), "18801\n")
|
||||||
|
self.assertIn("No free port", run(ctl.cmd_outbounds, "add", "fr", AWG_CONF)[2])
|
||||||
|
self.assertIn("cannot chain", run(ctl.cmd_outbounds, "add", "fr", AWG_CONF, "--detour", "primary")[2])
|
||||||
|
self.assertIn("--container only applies", run(ctl.cmd_outbounds, "add", "x", "vless://u@x.test:443", "--container", "c")[2])
|
||||||
|
# A copy through a hop makes no sense for a tunnel that dials its peer itself.
|
||||||
|
self.write("outbound-share.json", {"outbounds": {"de": {"outbound": {"type": "socks", "server": "127.0.0.1", "server_port": 18801}}}})
|
||||||
|
self.assertIn("AmneziaWG outbound", run(ctl.cmd_outbound_chain, "de", "primary")[2])
|
||||||
|
# rm takes the port along, which frees it.
|
||||||
|
ok(ctl.cmd_outbounds, "rm", "de")
|
||||||
|
self.assertFalse(os.path.exists(self.path("outbounds.d/de.port")))
|
||||||
|
self.assertEqual(ctl._awg_free_port(), 18801)
|
||||||
|
os.environ["AWG_RUNTIME_OUTBOUNDS"] = "0"
|
||||||
|
self.assertIn("not enabled", run(ctl.cmd_outbounds, "add", "fr", AWG_CONF)[2])
|
||||||
|
|
||||||
|
|
||||||
class ZapretAutoTest(EnvTest):
|
class ZapretAutoTest(EnvTest):
|
||||||
@unittest.skipIf(os.geteuid() == 0, "root writes anything")
|
@unittest.skipIf(os.geteuid() == 0, "root writes anything")
|
||||||
def test_clear_replaces_what_it_cannot_write(self):
|
def test_clear_replaces_what_it_cannot_write(self):
|
||||||
|
|||||||
@@ -11,7 +11,10 @@ import unittest
|
|||||||
from unittest import mock
|
from unittest import mock
|
||||||
|
|
||||||
import proxy_ctl as ctl
|
import proxy_ctl as ctl
|
||||||
import proxy_model as model
|
|
||||||
|
CLI_AWG_PROFILES = ctl._awg_profiles # before setUp patches it
|
||||||
|
|
||||||
|
import proxy_model as model # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
def walk(items):
|
def walk(items):
|
||||||
@@ -244,10 +247,67 @@ class ModelTest(unittest.TestCase):
|
|||||||
("zapret", "not a host", "Not a share link"),
|
("zapret", "not a host", "Not a share link"),
|
||||||
]:
|
]:
|
||||||
with self.subTest(text=text):
|
with self.subTest(text=text):
|
||||||
argv, message = paste(tab, text)
|
argv, message, stdin = paste(tab, text)
|
||||||
self.assertIsNone(argv)
|
self.assertIsNone(argv)
|
||||||
|
self.assertIsNone(stdin)
|
||||||
self.assertIn(why, message)
|
self.assertIn(why, message)
|
||||||
|
|
||||||
|
def test_paste_amneziawg(self):
|
||||||
|
conf = "[Interface]\nPrivateKey = secret\nAddress = 10.8.0.2/32\n\n[Peer]\nPublicKey = p\nAllowedIPs = 0.0.0.0/0\n"
|
||||||
|
runtime = {"AWG_RUNTIME_GLOBAL": "1", "AWG_RUNTIME_OUTBOUNDS": "1"}
|
||||||
|
with mock.patch.dict(os.environ, runtime):
|
||||||
|
# A global profile, but an outbound on the outbounds tab. The config itself only on stdin.
|
||||||
|
self.assertEqual(model.paste_argv("services", conf), (["awg", "add", "-"], "", conf.strip()))
|
||||||
|
self.assertEqual(model.paste_argv("awg", "vpn://AAAA"), (["awg", "add", "-"], "", "vpn://AAAA"))
|
||||||
|
self.assertEqual(model.paste_argv("outbounds", "vpn://AAAA"), (["proxy", "outbounds", "add", "-"], "", "vpn://AAAA"))
|
||||||
|
with mock.patch.dict(os.environ, {"AWG_RUNTIME_GLOBAL": "0", "AWG_RUNTIME_OUTBOUNDS": "1"}):
|
||||||
|
self.assertEqual(model.paste_argv("services", "vpn://AAAA")[0], ["proxy", "outbounds", "add", "-"])
|
||||||
|
with mock.patch.dict(os.environ, {"AWG_RUNTIME_GLOBAL": "0", "AWG_RUNTIME_OUTBOUNDS": "0"}):
|
||||||
|
argv, why, stdin = model.paste_argv("services", conf)
|
||||||
|
self.assertIsNone(argv)
|
||||||
|
self.assertIn("amneziaWg.runtime", why)
|
||||||
|
|
||||||
|
def test_awg_tab(self):
|
||||||
|
tab = next(t for t in model.TABS if t.id == "awg")
|
||||||
|
with tempfile.TemporaryDirectory() as d:
|
||||||
|
open(os.path.join(d, "added.conf"), "w").close()
|
||||||
|
profiles = os.path.join(d, "profiles.json")
|
||||||
|
with open(profiles, "w") as f:
|
||||||
|
json.dump(["home"], f)
|
||||||
|
env = {"AWG_RUNTIME_GLOBAL": "1", "AWG_RUNTIME_DIR": d, "AWG_PROFILES_FILE": profiles}
|
||||||
|
with mock.patch.dict(os.environ, env), mock.patch.object(ctl, "_awg_profiles", CLI_AWG_PROFILES):
|
||||||
|
self.assertTrue(tab.available({}))
|
||||||
|
rows, _ = model.load_tab(tab, {"proxy-suite-awg@added": "active"})
|
||||||
|
self.assertEqual(
|
||||||
|
[(r["profile"], r["unit"], r["state"], r["source"]) for r in rows],
|
||||||
|
[("home", "proxy-suite-awg-home", "inactive", "declared"), ("added", "proxy-suite-awg@added", "active", "runtime")],
|
||||||
|
)
|
||||||
|
self.assertEqual([a.key for a in model.applicable(tab, rows[0])], ["space", "l", "n"])
|
||||||
|
self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["space", "ctrl+r", "l", "n", "d"])
|
||||||
|
act = {a.key: a for a in tab.actions}
|
||||||
|
self.assertEqual(act["space"].argv(rows[1], "", {}), ["awg", "off", "added"])
|
||||||
|
self.assertEqual(act["d"].argv(rows[1], "", {}), ["awg", "rm", "added"])
|
||||||
|
# The Services tab's row for the instance toggles it through `awg` too.
|
||||||
|
self.assertEqual(model.toggle_argv({"unit": "proxy-suite-awg@added", "state": "active"}), ["awg", "off", "added"])
|
||||||
|
add = next(a for a in tab.actions if a.key == "n")
|
||||||
|
self.assertEqual((add.argv(None, "work vpn://AAAA", {}), add.stdin(None, "work vpn://AAAA")), (["awg", "add", "work", "-"], "vpn://AAAA"))
|
||||||
|
self.assertEqual((add.argv(None, "vpn://AAAA", {}), add.stdin(None, "vpn://AAAA")), (["awg", "add", "-"], "vpn://AAAA"))
|
||||||
|
# A path goes as one: proxy-ctl reads it, and it may run as root elsewhere.
|
||||||
|
self.assertEqual((add.argv(None, "work /tmp/w.conf", {}), add.stdin(None, "work /tmp/w.conf")), (["awg", "add", "work", "/tmp/w.conf"], None))
|
||||||
|
outbound_add = next(a for a in next(t for t in model.TABS if t.id == "outbounds").actions if a.key == "n")
|
||||||
|
self.assertEqual(outbound_add.argv(None, "de vpn://AAAA", {}), ["proxy", "outbounds", "add", "de", "-"])
|
||||||
|
self.assertEqual(outbound_add.stdin(None, "de vpn://AAAA"), "vpn://AAAA")
|
||||||
|
self.assertEqual(outbound_add.argv(None, "de vless://x", {}), ["proxy", "outbounds", "add", "de", "vless://x"])
|
||||||
|
self.assertIsNone(outbound_add.stdin(None, "de vless://x"))
|
||||||
|
|
||||||
|
def test_popen_feeds_stdin(self):
|
||||||
|
with mock.patch.object(model, "CTL", "cat"):
|
||||||
|
for stdin, out in (("secret\n", "secret\n"), (None, "")):
|
||||||
|
p = model.popen([], stdin=stdin)
|
||||||
|
with p.stdout:
|
||||||
|
self.assertEqual(p.stdout.read(), out)
|
||||||
|
p.wait()
|
||||||
|
|
||||||
def test_load_tab(self):
|
def test_load_tab(self):
|
||||||
tab = next(t for t in model.TABS if t.id == "outbounds")
|
tab = next(t for t in model.TABS if t.id == "outbounds")
|
||||||
inventory = {"tags": ["a", "b"], "pinned": "b", "detours": {"a": "b"}, "excluded": ["b"]}
|
inventory = {"tags": ["a", "b"], "pinned": "b", "detours": {"a": "b"}, "excluded": ["b"]}
|
||||||
|
|||||||
@@ -54,7 +54,8 @@ class TuiTest(unittest.TestCase):
|
|||||||
patcher.start()
|
patcher.start()
|
||||||
self.addCleanup(patcher.stop)
|
self.addCleanup(patcher.stop)
|
||||||
self.ran = []
|
self.ran = []
|
||||||
patcher = mock.patch.object(tui.ProxyTui, "run_argv", lambda app, mode, argv: self.ran.append(argv))
|
# A run with stdin is recorded with it: (argv, stdin).
|
||||||
|
patcher = mock.patch.object(tui.ProxyTui, "run_argv", lambda app, mode, argv, stdin=None: self.ran.append(argv if stdin is None else (argv, stdin)))
|
||||||
patcher.start()
|
patcher.start()
|
||||||
self.addCleanup(patcher.stop)
|
self.addCleanup(patcher.stop)
|
||||||
|
|
||||||
@@ -69,7 +70,7 @@ class TuiTest(unittest.TestCase):
|
|||||||
|
|
||||||
def test_retry_root_leaves_sigint_to_sudo(self):
|
def test_retry_root_leaves_sigint_to_sudo(self):
|
||||||
"""Ctrl-C at sudo's password prompt is sudo's: raised here it would take the TUI down with it."""
|
"""Ctrl-C at sudo's password prompt is sudo's: raised here it would take the TUI down with it."""
|
||||||
app = mock.MagicMock(retry=("run", ["proxy", "on"]))
|
app = mock.MagicMock(retry=("run", ["proxy", "on"], None))
|
||||||
app.suspend.return_value = contextlib.nullcontext()
|
app.suspend.return_value = contextlib.nullcontext()
|
||||||
before, during = signal.getsignal(signal.SIGINT), []
|
before, during = signal.getsignal(signal.SIGINT), []
|
||||||
with mock.patch.object(tui.subprocess, "Popen") as popen, contextlib.redirect_stdout(io.StringIO()):
|
with mock.patch.object(tui.subprocess, "Popen") as popen, contextlib.redirect_stdout(io.StringIO()):
|
||||||
@@ -79,6 +80,20 @@ class TuiTest(unittest.TestCase):
|
|||||||
self.assertEqual(during, [signal.SIG_IGN])
|
self.assertEqual(during, [signal.SIG_IGN])
|
||||||
self.assertEqual(signal.getsignal(signal.SIGINT), before)
|
self.assertEqual(signal.getsignal(signal.SIGINT), before)
|
||||||
self.assertEqual(app.finish.call_args.args[-2:], (["done"], 0))
|
self.assertEqual(app.finish.call_args.args[-2:], (["done"], 0))
|
||||||
|
self.assertNotIn("stdin", popen.call_args.kwargs)
|
||||||
|
|
||||||
|
def test_retry_root_carries_stdin(self):
|
||||||
|
"""A config pasted on stdin reaches sudo's proxy-ctl the same way."""
|
||||||
|
app = mock.MagicMock(retry=("run", ["awg", "add", "-"], "vpn://AAAA"))
|
||||||
|
app.suspend.return_value = contextlib.nullcontext()
|
||||||
|
with mock.patch.object(tui.subprocess, "Popen") as popen, contextlib.redirect_stdout(io.StringIO()):
|
||||||
|
popen.return_value.stdout = iter(["Added\n"])
|
||||||
|
popen.return_value.wait.return_value = 0
|
||||||
|
tui.ProxyTui.action_retry_root(app)
|
||||||
|
self.assertEqual(popen.call_args.args[0][-3:], ["awg", "add", "-"])
|
||||||
|
self.assertEqual(popen.call_args.kwargs["stdin"], tui.subprocess.PIPE)
|
||||||
|
popen.return_value.stdin.write.assert_called_once_with("vpn://AAAA")
|
||||||
|
self.assertEqual(app.finish.call_args.kwargs["stdin"], "vpn://AAAA")
|
||||||
|
|
||||||
def test_filter_sort_pack(self):
|
def test_filter_sort_pack(self):
|
||||||
rows = [{"key": "a", "host": "a.example", "kind": "learned"}, {"key": "b", "host": "learned.org", "kind": "pinned"}]
|
rows = [{"key": "a", "host": "a.example", "kind": "learned"}, {"key": "b", "host": "learned.org", "kind": "pinned"}]
|
||||||
@@ -139,6 +154,12 @@ class TuiTest(unittest.TestCase):
|
|||||||
await pilot.pause()
|
await pilot.pause()
|
||||||
self.assertEqual(self.ran, [])
|
self.assertEqual(self.ran, [])
|
||||||
self.assertIn("ftp:// link", str(app.main.query_one("#feedback").content))
|
self.assertIn("ftp:// link", str(app.main.query_one("#feedback").content))
|
||||||
|
# An AmneziaWG config: its keys go on stdin, never into argv.
|
||||||
|
self.env["AWG_RUNTIME_OUTBOUNDS"] = "1"
|
||||||
|
conf = "[Interface]\nPrivateKey = k\n[Peer]\nPublicKey = p"
|
||||||
|
app.post_message(events.Paste(conf))
|
||||||
|
await pilot.pause()
|
||||||
|
self.assertEqual(self.ran.pop(), (["proxy", "outbounds", "add", "-"], conf))
|
||||||
|
|
||||||
asyncio.run(run())
|
asyncio.run(run())
|
||||||
|
|
||||||
@@ -211,7 +232,16 @@ class TuiTest(unittest.TestCase):
|
|||||||
self.assertEqual(self.ran.pop(), ["awg", "restart", "p"])
|
self.assertEqual(self.ran.pop(), ["awg", "restart", "p"])
|
||||||
app.table().move_cursor(row=list(app.rows["services"]).index("proxy-suite-tun"))
|
app.table().move_cursor(row=list(app.rows["services"]).index("proxy-suite-tun"))
|
||||||
|
|
||||||
# Right arrow moves to Routing and its table has focus.
|
# Right arrow moves to AmneziaWG, there with a profile, and its table has focus.
|
||||||
|
await pilot.press("right")
|
||||||
|
await self.settle(app, pilot)
|
||||||
|
self.assertEqual((app.active_tab(), app.focused.id), ("awg", "awg-table"))
|
||||||
|
await pilot.press("space")
|
||||||
|
self.assertEqual(self.ran.pop(), ["awg", "off", "p"])
|
||||||
|
# Declared: nothing removes it here.
|
||||||
|
self.assertNotIn("d", app.screen.active_bindings)
|
||||||
|
|
||||||
|
# On to Routing.
|
||||||
await pilot.press("right")
|
await pilot.press("right")
|
||||||
await self.settle(app, pilot)
|
await self.settle(app, pilot)
|
||||||
self.assertEqual((app.active_tab(), app.focused.id), ("routing", "routing-table"))
|
self.assertEqual((app.active_tab(), app.focused.id), ("routing", "routing-table"))
|
||||||
@@ -263,7 +293,7 @@ class TuiTest(unittest.TestCase):
|
|||||||
await pilot.press("escape")
|
await pilot.press("escape")
|
||||||
|
|
||||||
# An empty tab says how to fill it.
|
# An empty tab says how to fill it.
|
||||||
await pilot.press("4")
|
await pilot.press("5")
|
||||||
await self.settle(app, pilot)
|
await self.settle(app, pilot)
|
||||||
self.assertIn("Nothing here yet. n: add a runtime subscription", str(app.main.query_one("#subs-summary").content))
|
self.assertIn("Nothing here yet. n: add a runtime subscription", str(app.main.query_one("#subs-summary").content))
|
||||||
|
|
||||||
@@ -280,7 +310,7 @@ class TuiTest(unittest.TestCase):
|
|||||||
# Brackets in a summary are text, not markup.
|
# Brackets in a summary are text, not markup.
|
||||||
self.env["ZAPRET_CUTOFF_ENABLED"] = "1"
|
self.env["ZAPRET_CUTOFF_ENABLED"] = "1"
|
||||||
self.capture = "Probed: [b] from [/x]\nCutoff: none on this line\n"
|
self.capture = "Probed: [b] from [/x]\nCutoff: none on this line\n"
|
||||||
await pilot.press("5")
|
await pilot.press("6")
|
||||||
await self.settle(app, pilot)
|
await self.settle(app, pilot)
|
||||||
self.assertIn("[/x]", str(app.main.query_one("#zapret-summary").content))
|
self.assertIn("[/x]", str(app.main.query_one("#zapret-summary").content))
|
||||||
await self.settle(app, pilot)
|
await self.settle(app, pilot)
|
||||||
@@ -333,7 +363,7 @@ class TuiTest(unittest.TestCase):
|
|||||||
self.env["INBOUNDS_ENABLED"] = "1"
|
self.env["INBOUNDS_ENABLED"] = "1"
|
||||||
app.action_reload()
|
app.action_reload()
|
||||||
await self.settle(app, pilot)
|
await self.settle(app, pilot)
|
||||||
await pilot.press("6")
|
await pilot.press("7")
|
||||||
await self.settle(app, pilot)
|
await self.settle(app, pilot)
|
||||||
await pilot.press("c")
|
await pilot.press("c")
|
||||||
self.assertEqual(self.ran.pop(), ["inbounds", "link", "vless", "alice"])
|
self.assertEqual(self.ran.pop(), ["inbounds", "link", "vless", "alice"])
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import json
|
|||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import socket
|
import socket
|
||||||
|
import sys
|
||||||
import tempfile
|
import tempfile
|
||||||
import zlib
|
import zlib
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -736,6 +737,35 @@ def prepare(manifest: dict[str, Any]) -> str:
|
|||||||
return config
|
return config
|
||||||
|
|
||||||
|
|
||||||
|
def import_source(text: str, container: str | None = None) -> tuple[str, dict[str, str]]:
|
||||||
|
"""A pasted .conf or vpn:// link as a normalized .conf, and what it says about itself.
|
||||||
|
|
||||||
|
For profiles added at runtime: hooks are refused whatever the source, since whoever may
|
||||||
|
add one need not be root. The name is the export's description, else its server's host.
|
||||||
|
"""
|
||||||
|
text = text.strip()
|
||||||
|
name = ""
|
||||||
|
if text.startswith("vpn://"):
|
||||||
|
data = decode_vpn_link(text)
|
||||||
|
config = extract_vpn_config(data, container)
|
||||||
|
for key in ("description", "name", "hostName"):
|
||||||
|
if isinstance(data.get(key), str) and data[key].strip():
|
||||||
|
name = data[key].strip()
|
||||||
|
break
|
||||||
|
elif "[interface]" in text.lower():
|
||||||
|
if container:
|
||||||
|
raise ConfigError("--container only applies to a vpn:// link")
|
||||||
|
config = _apply_awg3_mtu_default(text + "\n")
|
||||||
|
else:
|
||||||
|
raise ConfigError("expected an AmneziaWG .conf or a vpn:// link")
|
||||||
|
validate_config(config)
|
||||||
|
endpoints = section_values(config, "peer", "endpoint")
|
||||||
|
endpoint = endpoints[0] if endpoints else ""
|
||||||
|
if not name and endpoint:
|
||||||
|
name = endpoint.rsplit(":", 1)[0].strip("[]")
|
||||||
|
return config, {"name": name, "endpoint": endpoint}
|
||||||
|
|
||||||
|
|
||||||
def write_private(path: str, content: str) -> None:
|
def write_private(path: str, content: str) -> None:
|
||||||
destination = Path(path)
|
destination = Path(path)
|
||||||
destination.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
destination.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||||
@@ -782,6 +812,18 @@ def main() -> int:
|
|||||||
action="store_true",
|
action="store_true",
|
||||||
help="write Endpoint names as the addresses they resolve to here",
|
help="write Endpoint names as the addresses they resolve to here",
|
||||||
)
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--import",
|
||||||
|
dest="import_",
|
||||||
|
metavar="SOURCE",
|
||||||
|
help="normalize a .conf or vpn:// link (a path, or - for stdin), hooks refused",
|
||||||
|
)
|
||||||
|
parser.add_argument("--container", help="with --import: which container of a vpn:// export")
|
||||||
|
parser.add_argument(
|
||||||
|
"--describe",
|
||||||
|
action="store_true",
|
||||||
|
help="with --import: print the name and endpoint it carries as JSON",
|
||||||
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--inspect",
|
"--inspect",
|
||||||
metavar="CONFIG",
|
metavar="CONFIG",
|
||||||
@@ -795,6 +837,25 @@ def main() -> int:
|
|||||||
config = _read_limited(args.inspect)
|
config = _read_limited(args.inspect)
|
||||||
print(transport_implementation(config), probe_address(config), rekey_after_time(config))
|
print(transport_implementation(config), probe_address(config), rekey_after_time(config))
|
||||||
return 0
|
return 0
|
||||||
|
if args.import_ is not None:
|
||||||
|
if args.manifest is not None or args.config is not None:
|
||||||
|
raise ConfigError("--import cannot be combined with --manifest or --config")
|
||||||
|
if args.output is None and not args.describe:
|
||||||
|
raise ConfigError("--import needs --output, --describe or both")
|
||||||
|
if args.import_ == "-":
|
||||||
|
text = sys.stdin.read(MAX_INPUT_BYTES + 1)
|
||||||
|
if len(text) > MAX_INPUT_BYTES:
|
||||||
|
raise ConfigError(f"input exceeds {MAX_INPUT_BYTES} bytes")
|
||||||
|
else:
|
||||||
|
text = _read_limited(args.import_)
|
||||||
|
config, described = import_source(text, args.container)
|
||||||
|
if args.output is not None:
|
||||||
|
write_private(args.output, config)
|
||||||
|
if args.describe:
|
||||||
|
print(json.dumps(described))
|
||||||
|
return 0
|
||||||
|
if args.container is not None or args.describe:
|
||||||
|
raise ConfigError("--container and --describe only apply to --import")
|
||||||
if (args.manifest is None) == (args.config is None) or args.output is None:
|
if (args.manifest is None) == (args.config is None) or args.output is None:
|
||||||
raise ConfigError(
|
raise ConfigError(
|
||||||
"--output and one of --manifest or --config are required when rendering a configuration"
|
"--output and one of --manifest or --config are required when rendering a configuration"
|
||||||
@@ -815,7 +876,7 @@ def main() -> int:
|
|||||||
if args.resolve_endpoints:
|
if args.resolve_endpoints:
|
||||||
config = resolve_endpoints(config)
|
config = resolve_endpoints(config)
|
||||||
write_private(args.output, config)
|
write_private(args.output, config)
|
||||||
except (ConfigError, KeyError, OSError, json.JSONDecodeError) as exc:
|
except (ConfigError, KeyError, OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||||
parser.exit(1, f"amneziawg-config: {exc}\n")
|
parser.exit(1, f"amneziawg-config: {exc}\n")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|||||||
@@ -536,6 +536,62 @@ class AmneziaWgConfigTests(unittest.TestCase):
|
|||||||
unmarked = amneziawg_config.as_wireproxy(config, "127.0.0.1:18700")
|
unmarked = amneziawg_config.as_wireproxy(config, "127.0.0.1:18700")
|
||||||
self.assertEqual(amneziawg_config.section_values(unmarked, "interface", "fwmark"), [])
|
self.assertEqual(amneziawg_config.section_values(unmarked, "interface", "fwmark"), [])
|
||||||
|
|
||||||
|
def import_cli(self, text, *args):
|
||||||
|
return subprocess.run(
|
||||||
|
[sys.executable, amneziawg_config.__file__, "--import", "-", *args],
|
||||||
|
input=text,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_import_conf_and_vpn_links(self):
|
||||||
|
conf = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1")
|
||||||
|
config, described = amneziawg_config.import_source(conf)
|
||||||
|
self.assertIn("MTU = 1280", config)
|
||||||
|
self.assertEqual(described, {"name": "vpn.example.com", "endpoint": "vpn.example.com:51820"})
|
||||||
|
|
||||||
|
data = vpn_data(("amnezia-awg", "awg", BASE_CONFIG))
|
||||||
|
data["description"] = "Home server"
|
||||||
|
config, described = amneziawg_config.import_source(encode_vpn(data))
|
||||||
|
self.assertIn("DNS = 1.1.1.1,8.8.8.8", config)
|
||||||
|
self.assertEqual(described["name"], "Home server")
|
||||||
|
|
||||||
|
direct = "vpn://" + base64.urlsafe_b64encode(conf.encode()).decode()
|
||||||
|
self.assertIn("[Peer]", amneziawg_config.import_source(direct)[0])
|
||||||
|
|
||||||
|
def test_import_picks_a_container_and_refuses_hooks(self):
|
||||||
|
data = vpn_data(
|
||||||
|
("amnezia-awg", "awg", BASE_CONFIG),
|
||||||
|
("amnezia-awg2", "awg", BASE_CONFIG.replace("10.8.0.2", "10.9.0.2")),
|
||||||
|
)
|
||||||
|
data["defaultContainer"] = "not-awg"
|
||||||
|
with self.assertRaisesRegex(ConfigError, "multiple AmneziaWG"):
|
||||||
|
amneziawg_config.import_source(encode_vpn(data))
|
||||||
|
self.assertIn("10.9.0.2", amneziawg_config.import_source(encode_vpn(data), "amnezia-awg2")[0])
|
||||||
|
conf = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1")
|
||||||
|
with self.assertRaisesRegex(ConfigError, "only applies"):
|
||||||
|
amneziawg_config.import_source(conf, "amnezia-awg")
|
||||||
|
with self.assertRaisesRegex(ConfigError, "privileged"):
|
||||||
|
amneziawg_config.import_source(conf.replace("Address =", "PostUp = id\nAddress ="))
|
||||||
|
with self.assertRaisesRegex(ConfigError, "expected"):
|
||||||
|
amneziawg_config.import_source("vless://nope")
|
||||||
|
|
||||||
|
def test_import_cli_writes_a_private_conf_and_describes_it(self):
|
||||||
|
conf = BASE_CONFIG.replace("$PRIMARY_DNS,$SECONDARY_DNS", "1.1.1.1")
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
output = Path(directory) / "home.conf"
|
||||||
|
result = self.import_cli(conf, "--describe", "--output", str(output))
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
self.assertEqual(json.loads(result.stdout)["name"], "vpn.example.com")
|
||||||
|
self.assertEqual(output.stat().st_mode & 0o777, 0o600)
|
||||||
|
self.assertIn("[Interface]", output.read_text())
|
||||||
|
hooked = self.import_cli(conf.replace("Address =", "PreUp = id\nAddress ="), "--output", str(output))
|
||||||
|
self.assertEqual(hooked.returncode, 1)
|
||||||
|
self.assertIn("privileged", hooked.stderr)
|
||||||
|
# A refused import leaves what was there.
|
||||||
|
self.assertIn("[Interface]", output.read_text())
|
||||||
|
self.assertEqual(self.import_cli(conf).returncode, 1)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
Reference in new issue
Block a user