20 Commits
Author SHA1 Message Date
FUFSoB fdb2b08790 refactor: overhaul of options and features
Includes, but not limited to:
- zapret2 support
- declarative inbounds
- proxy-ctl revamp
- automatic proxy learning
2026-09-13 22:37:45 +05:00
fufsob b892384527 fix: subs fixes 2026-09-10 09:42:25 +00:00
fufsob 2a319d1f88 feat/wip/fix: add inbounds support, fix ssh-proxy 2026-09-09 16:38:52 +00:00
fufsob ea7916dffb fix: small ssh-proxy fixes 2026-09-08 19:41:58 +00:00
FUFSoB 7a106326ea feat/wip: ssh-proxy 2026-09-08 23:36:47 +05:00
github-actions[bot]andFUFSoB 9a1604554d chore(deps): refresh flakes and external pins (#12)
Co-authored-by: FUFSoB <32937947+FUFSoB@users.noreply.github.com>
2026-09-08 14:30:15 +05:00
FUFSoB 8cdef28f21 feat(awg): obfuscation file 2026-09-06 09:57:16 +05:00
FUFSoB 1ac17f281d fix; xray tun 2026-09-05 18:04:42 +05:00
FUFSoB a456534801 feat(wip): amnezia-wg 3.1 support 2026-08-30 18:07:43 +05:00
github-actions[bot]andFUFSoB 539f6a13ee chore(deps): refresh flakes and external pins (#11)
Co-authored-by: FUFSoB <32937947+FUFSoB@users.noreply.github.com>
2026-08-17 11:59:43 +05:00
github-actions[bot]andFUFSoB 47a07d971c chore(deps): refresh flakes and external pins (#9)
Co-authored-by: FUFSoB <32937947+FUFSoB@users.noreply.github.com>
2026-08-03 15:23:32 +05:00
fufsob 9f4e45b58a Revert "fix: temp migration of zapret and tg-ws-proxy to archive.org"
This reverts commit 835651c460.
2026-08-03 06:45:43 +00:00
FUFSoB e54c9463dd chore: refactoring (split) 2026-07-11 10:54:37 +05:00
FUFSoB 835651c460 fix: temp migration of zapret and tg-ws-proxy to archive.org 2026-07-10 18:48:06 +05:00
FUFSoB 57a3426c85 fix: per-site config was not working properly 2026-07-02 19:18:55 +05:00
FUFSoB 459a864478 feat: allow setting zapret configs per default domains and default configs 2026-06-29 23:17:00 +05:00
FUFSoB 5b185114b6 fix: remove tgwsproxy keepalive option - removed from upstream 2026-06-29 22:29:28 +05:00
github-actions[bot]andFUFSoB 89fbff9eb1 chore(deps): refresh flakes and external pins (#5)
Co-authored-by: FUFSoB <32937947+FUFSoB@users.noreply.github.com>
2026-06-29 22:09:56 +05:00
FUFSoB b493a11e5a fix: accept zapret config names with any amount of spaces, fixes #6 2026-06-27 10:34:51 +05:00
FUFSoB 7ca7f4000b fix: various fixes 2026-06-24 23:08:16 +05:00
179 changed files with 27663 additions and 14978 deletions

No files matched your search

+55 -23
View File
@@ -4,6 +4,11 @@ on:
schedule:
- cron: "0 6 * * 1"
workflow_dispatch:
inputs:
force_nixpkgs:
description: "Update nixpkgs even when no watched package version changed"
type: boolean
default: false
permissions:
contents: write
@@ -27,38 +32,73 @@ jobs:
id: nixpkgs_gate
run: |
set -euo pipefail
chmod +x scripts/check-nixpkgs-relevance.sh
scripts/check-nixpkgs-relevance.sh >> "$GITHUB_OUTPUT"
- name: Update flake inputs
run: |
set -euo pipefail
if [[ "${{ steps.nixpkgs_gate.outputs.should_update_nixpkgs }}" == "true" ]]; then
nix flake lock --update-input nixpkgs
if [[ "${{ steps.nixpkgs_gate.outputs.should_update_nixpkgs }}" == "true" || "${{ inputs.force_nixpkgs }}" == "true" ]]; then
nix flake update nixpkgs
else
echo "Skipping nixpkgs update: watched package versions on nixos-unstable are unchanged."
fi
nix flake lock --update-input zapret
nix flake update zapret
- name: Update tg-ws-proxy pin
- name: Update pinned sources
env:
GITHUB_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
chmod +x scripts/update-tg-ws-proxy.sh
scripts/update-tg-ws-proxy.sh
scripts/update-pins.sh --self-test
scripts/update-pins.sh | tee "$RUNNER_TEMP/pin-updates.txt"
- name: Detect dependency file changes
id: changes
run: |
set -euo pipefail
if git diff --quiet -- flake.lock pkgs/tg-ws-proxy.nix; then
if git diff --quiet -- flake.lock pkgs; then
echo "has_changes=false" >> "$GITHUB_OUTPUT"
else
echo "has_changes=true" >> "$GITHUB_OUTPUT"
fi
- name: Build updated packages
if: steps.changes.outputs.has_changes == 'true'
run: |
set -euo pipefail
mapfile -t attrs < <(scripts/update-pins.sh --attrs)
nix build --no-link "${attrs[@]}"
- name: Run flake checks
if: steps.changes.outputs.has_changes == 'true'
run: nix flake check
run: nix flake check --print-build-logs
- name: Compose pull request body
if: steps.changes.outputs.has_changes == 'true'
run: |
set -euo pipefail
{
echo "## Automated dependency update"
echo
echo "Managed by CI; the \`ci/update-dependencies\` branch is reused across runs."
echo
echo "### Pinned sources"
if [[ -s "$RUNNER_TEMP/pin-updates.txt" ]]; then
sed 's/^/- /' "$RUNNER_TEMP/pin-updates.txt"
else
echo "- no pin changes"
fi
echo
echo "### Flake inputs"
echo "- nixpkgs updated: \`${{ steps.nixpkgs_gate.outputs.should_update_nixpkgs }}\`"
echo "- changed watched attrs: \`${{ steps.nixpkgs_gate.outputs.nixpkgs_changed_watch_attrs }}\`"
echo "- zapret: refreshed every run"
echo
echo '```'
git diff --stat -- flake.lock pkgs
echo '```'
} > "$RUNNER_TEMP/pr-body.md"
cat "$RUNNER_TEMP/pr-body.md" >> "$GITHUB_STEP_SUMMARY"
- name: Create or update pull request
if: steps.changes.outputs.has_changes == 'true'
@@ -66,23 +106,15 @@ jobs:
with:
branch: ci/update-dependencies
delete-branch: false
commit-message: "chore(deps): refresh flakes and external pins"
title: "chore(deps): refresh flakes and external pins"
add-paths: |
flake.lock
pkgs
commit-message: "chore(deps): refresh flake inputs and pinned sources"
title: "chore(deps): refresh flake inputs and pinned sources"
body-path: ${{ runner.temp }}/pr-body.md
labels: |
dependencies
nix
body: |
## Automated dependency update
This PR is managed by CI and the same branch is reused across runs.
### Included updates
- `flake.lock` updates (`zapret` always, `nixpkgs` only when watched package versions change on `nixos-unstable`)
- `pkgs/tg-ws-proxy.nix` pin refresh (`rev` + `hash`)
### Nixpkgs gate result
- should update nixpkgs: `${{ steps.nixpkgs_gate.outputs.should_update_nixpkgs }}`
- changed watched attrs: `${{ steps.nixpkgs_gate.outputs.nixpkgs_changed_watch_attrs }}`
- name: No dependency changes
if: steps.changes.outputs.has_changes != 'true'
+88 -101
View File
@@ -1,47 +1,34 @@
# proxy-suite-flake
Declarative proxy stack for NixOS.
Declarative proxy stack for NixOS, built for dealing with Roskomnadzor and the usual Russian ISP nonsense. Configure it in Nix, rebuild, and it runs as systemd services.
Bundles [sing-box](https://github.com/SagerNet/sing-box), [XRay](https://github.com/XTLS/Xray-core), [zapret-discord-youtube](https://github.com/kartavkun/zapret-discord-youtube), and [tg-ws-proxy](https://github.com/Flowseal/tg-ws-proxy). Built specifically for dealing with Roskomnadzor (RKN) and the usual Russian ISP nonsense.
Bundles [sing-box](https://github.com/SagerNet/sing-box), [XRay](https://github.com/XTLS/Xray-core), [AmneziaWG](https://github.com/amnezia-vpn/amneziawg-go), [zapret-discord-youtube](https://github.com/kartavkun/zapret-discord-youtube), [zapret2](https://github.com/bol-van/zapret2) and [tg-ws-proxy](https://github.com/Flowseal/tg-ws-proxy).
The goal is to replace GUI clients like v2rayN and throne – you configure your proxies in Nix, rebuild, and they just work as systemd services.
## Features
---
## What it gives you
- **SOCKS5/HTTP proxy** on `127.0.0.1:1080` when `proxy.enable = true`
- **Backend choice** – use SingBox or XRay through the same `services.proxy-suite.proxy` option tree
- **Transparent proxy (TProxy)** – redirect all system traffic through the active backend without configuring each app; start/stop on demand or autostart at boot
- **TUN mode** – full tunnel via a virtual network interface; useful when TProxy doesn't cover something, with optional boot-time autostart
- **Per-app wrapping** – run selected apps through the local proxy with `proxy-ctl wrap <profile> -- <command>`, without enabling global TProxy or TUN
- **Subscription URLs** – point at a v2rayN/Clash-format subscription endpoint; the module fetches, decodes, and imports all proxies automatically, with a periodic refresh timer
- **Multiple outbounds** with automatic latency-based switching or manual selection
- **Per-outbound routing** – route specific domains, IPs, or geo sets to specific servers
- **Protocol support**: vless (Reality, TLS), vmess, trojan, shadowsocks, hysteria2, socks5, socks4, http/https proxy; SingBox also supports TUIC v5, while XRay supports XHTTP/ECH share links
- **`proxy-ctl`** – control script for managing services, switching outbounds, and following logs
- **DPI bypass** via zapret – handles YouTube, Discord, and other sites defined by the project
- **Telegram proxy** – running local MTProto WebSocket proxy using tg-ws-proxy
---
- Local SOCKS5/HTTP proxy on `127.0.0.1:1080`, backed by sing-box, XRay, or both
- Global TProxy or TUN mode, on demand or at boot
- Per-app routing: `proxy-ctl apps run <profile> -- <cmd>` through proxychains, a per-app TUN/TProxy, or zapret
- Outbounds from URLs, raw JSON or subscriptions; manual or latency-based selection; per-outbound routing
- vless (REALITY, TLS), vmess, trojan, shadowsocks, hysteria2, socks, http; TUIC on sing-box, XHTTP/ECH on XRay
- autoProxy: finds which exit reaches a blocked site and routes it there
- zapret DPI bypass, including zapret2, which learns blocked sites at runtime
- AmneziaWG 1.x–3.x tunnels from `.conf`, `vpn://`, or Nix
- Telegram MTProto WebSocket proxy and SSH SOCKS5 tunnel
- Server inbounds with share links, QR codes, per-user subscriptions and traffic stats
- A tray indicator and the `proxy-ctl` CLI
## Setup
Add to your flake inputs:
```nix
inputs.proxy-suite.url = "github:FUFSoB/proxy-suite-flake";
```
No need to add zapret separately – it comes along as a transitive input.
Add the module to your NixOS configuration:
```nix
modules = [ inputs.proxy-suite.nixosModules.default ];
```
Feature-complete starter config:
Starter config:
```nix
services.proxy-suite = {
@@ -49,70 +36,51 @@ services.proxy-suite = {
proxy = {
enable = true;
singBox.enable = true;
# Or use XRay instead:
# xray.enable = true;
backend = "sing-box"; # or "xray", or "hybrid"
port = 1080;
# url ends up in the Nix store; use urlFile for real secrets.
outbounds = [ { tag = "nl-vps"; url = "hy2://password@example.com:443?sni=example.com"; } ];
subscriptions = [ { tag = "main-sub"; urlFile = "/run/secrets/sub-url"; } ];
selection = "urltest"; # Default is "first", without any complex selector
# Individual proxy example
outbounds = [
{
tag = "nl-vps";
# Inline url is convenient for testing, but ends up in the Nix store.
# For real use, prefer urlFile with a url file.
url = "hy2://password@example.com:443?sni=example.com";
}
];
# Subscription example
subscriptions = [
{
tag = "main-sub";
# urlFile is also available to keep the URL out of the Nix store.
url = "https://example.com/subscription-list.txt";
}
];
# Automatic switching of outbound based on latency.
# Default is "first", which just uses the first one in the list.
selection = "urltest";
# Keep both available; autostart only one global tunnel.
tproxy = {
enable = true;
autostart = false;
perApp.enable = true;
};
tun = {
enable = true;
autostart = false;
perApp.enable = true;
};
};
zapret = {
enable = true;
perApp.enable = true;
tproxy.enable = true;
tun.enable = true;
};
perAppRouting = {
enable = true;
createDefaultProfiles = true;
proxychains.enable = true;
tun.enable = true;
tproxy.enable = true;
zapret.enable = true;
};
tray = {
zapret.enable = true;
sshProxy = {
enable = true;
autostart = true;
server = {
user = "root";
host = "ssh.example.com";
};
identityFile = "/run/secrets/proxy-suite-ssh-key";
hostKeyFile = "/run/secrets/proxy-suite-ssh-known-hosts";
};
# Only one AWG, TUN or TProxy global tunnel runs at a time.
amneziaWg = {
enable = true;
profiles.home.configFile = "/run/secrets/home-amneziawg.conf";
profiles.work.vpnFile = "/run/secrets/work-amnezia.vpn";
};
tgWsProxy = {
enable = true;
port = 1443;
# Inline secret is convenient for testing, but ends up in the Nix store.
# For real use, prefer secretFile with a secret file.
secret = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
secretFile = "/run/secrets/tg-ws-proxy-secret";
};
tray.enable = true;
};
```
@@ -120,36 +88,55 @@ services.proxy-suite = {
## Options
To see options and documentation, check out the [options reference](./docs/options.md).
Options and generated README help are refreshed with `nix run .#update-docs`.
---
See the [options reference](./docs/options/index.md), one page per option group. Regenerate it and the help below with `nix run .#update-docs`.
## `proxy-ctl help`
Generated from current `proxy-ctl help` output.
<!-- proxy-ctl-help:start -->
```text
Usage: proxy-ctl <command> [args]
Usage: proxy-ctl <group> [verb] [args]
A group without a verb shows its status or list.
Commands:
help show this help message
status [--tray] show status of all proxy-suite services
proxy on|off enable/disable the proxy backend stack
tproxy on|off enable/disable TProxy transparent mode
tun on|off enable/disable TUN mode
route-mode default|whitelist|blacklist|all-proxy|all-bypass|status
set temporary routing override
zapret on|off enable/disable zapret-discord-youtube
restart restart active global proxy-suite services
logs [service] follow service logs (default: proxy-suite-socks)
outbounds list outbounds and current selection
select <tag> switch to a specific outbound (selector mode)
apps list configured per-app routing profiles
wrap <profile> -- <cmd> run a command via a perAppRouting profile
subscription list show subscriptions, cache age, and proxy count
subscription update force-refresh all subscription caches and restart active proxy services
status [--tray] services and routing mode
restart restart active services
logs [unit] follow logs (default: every proxy-suite unit)
where <domain> how this host is routed right now
proxy [status|on|off] local proxy backend
proxy outbounds [list] outbounds, where each came from, and the pick
proxy outbounds add <tag> <url> add an outbound at runtime
proxy outbounds rm <tag> remove a runtime outbound
proxy select [<tag>|auto] pin the priority outbound (no tag: pick from a menu)
proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]
show or override the routing mode
proxy subs [list|update] subscription caches; update refetches them
proxy subs add <tag> <url> add a subscription at runtime
proxy subs rm <tag> remove a runtime subscription
proxy tun [status|on|off] global TUN mode
proxy tproxy [status|on|off] global TProxy mode
proxy auto [list] what autoProxy routed, and via which exit (sudo, or userControl)
proxy auto probe <domain>[/path] [--json] [--exits a,b | --via tag]
find an exit that reaches a domain
proxy auto learn <domain> probe now and route it if an exit works (sudo)
proxy auto queue [count] destinations waiting to be probed (sudo, or userControl)
zapret [status|on|off] DPI bypass
zapret auto [list] hosts zapret2 learned as blocked
zapret auto add|forget|exclude <domain>
pin, forget, or never learn a host (sudo)
zapret auto clear forget every learned host (sudo)
awg [list] AmneziaWG profiles and their state
awg on <profile> | off [profile] | restart [profile]
ssh [status|on|off] SSH SOCKS5 tunnel
apps [list] per-app routing profiles
apps run <profile> -- <cmd> [args] run a command through a profile
inbounds [list] server inbounds
inbounds link <tag> [user] [--qr] client share link
inbounds sub [user] [--qr] subscription users, or one user's URL
inbounds stats [days] traffic per user (sudo, or userControl)
```
<!-- proxy-ctl-help:end -->
-5694
View File
File diff suppressed because it is too large. Load diff
+885
View File
@@ -0,0 +1,885 @@
# services.proxy-suite.amneziaWg
Part of the [proxy-suite options reference](./index.md).
## Options
- amneziaWg
- [enable](#services-proxy-suite-amneziawg-enable)
- [kernelModulePackage](#services-proxy-suite-amneziawg-kernelmodulepackage)
- [profiles](#services-proxy-suite-amneziawg-profiles)
- `<name>`
- [allowConfigHooks](#services-proxy-suite-amneziawg-profiles-name-allowconfighooks)
- [autostart](#services-proxy-suite-amneziawg-profiles-name-autostart)
- [configFile](#services-proxy-suite-amneziawg-profiles-name-configfile)
- [interfaceName](#services-proxy-suite-amneziawg-profiles-name-interfacename)
- [settings](#services-proxy-suite-amneziawg-profiles-name-settings)
- [addresses](#services-proxy-suite-amneziawg-profiles-name-settings-addresses)
- [dns](#services-proxy-suite-amneziawg-profiles-name-settings-dns)
- [listenPort](#services-proxy-suite-amneziawg-profiles-name-settings-listenport)
- [mtu](#services-proxy-suite-amneziawg-profiles-name-settings-mtu)
- [obfuscation](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation)
- [contentPaddingAddition](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-contentpaddingaddition)
- [disableCookies](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-disablecookies)
- [h1](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h1)
- [h2](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h2)
- [h3](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h3)
- [h4](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h4)
- [headerProtectionKey](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-headerprotectionkey)
- [headerProtectionKeyFile](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-headerprotectionkeyfile)
- [i1](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i1)
- [i2](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i2)
- [i3](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i3)
- [i4](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i4)
- [i5](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i5)
- [jc](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-jc)
- [jmax](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-jmax)
- [jmin](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-jmin)
- [keepaliveTimeout](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-keepalivetimeout)
- [maxHandshakeAttempts](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-maxhandshakeattempts)
- [randomTrailers](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-randomtrailers)
- [rejectAfterTime](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-rejectaftertime)
- [rekeyAfterTime](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-rekeyaftertime)
- [rekeyTimeout](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-rekeytimeout)
- [s1](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s1)
- [s2](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s2)
- [s3](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s3)
- [s4](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s4)
- [obfuscationFile](#services-proxy-suite-amneziawg-profiles-name-settings-obfuscationfile)
- [peers](#services-proxy-suite-amneziawg-profiles-name-settings-peers)
- item
- [advancedSecurity](#services-proxy-suite-amneziawg-profiles-name-settings-peers-advancedsecurity)
- [allowedIPs](#services-proxy-suite-amneziawg-profiles-name-settings-peers-allowedips)
- [endpoint](#services-proxy-suite-amneziawg-profiles-name-settings-peers-endpoint)
- [persistentKeepalive](#services-proxy-suite-amneziawg-profiles-name-settings-peers-persistentkeepalive)
- [presharedKey](#services-proxy-suite-amneziawg-profiles-name-settings-peers-presharedkey)
- [presharedKeyFile](#services-proxy-suite-amneziawg-profiles-name-settings-peers-presharedkeyfile)
- [publicKey](#services-proxy-suite-amneziawg-profiles-name-settings-peers-publickey)
- [privateKey](#services-proxy-suite-amneziawg-profiles-name-settings-privatekey)
- [privateKeyFile](#services-proxy-suite-amneziawg-profiles-name-settings-privatekeyfile)
- [table](#services-proxy-suite-amneziawg-profiles-name-settings-table)
- [vpn](#services-proxy-suite-amneziawg-profiles-name-vpn)
- [vpnContainer](#services-proxy-suite-amneziawg-profiles-name-vpncontainer)
- [vpnFile](#services-proxy-suite-amneziawg-profiles-name-vpnfile)
- [toolsPackage](#services-proxy-suite-amneziawg-toolspackage)
- [userspacePackage](#services-proxy-suite-amneziawg-userspacepackage)
<a id="services-proxy-suite-amneziawg-enable"></a>
## services\.proxy-suite\.amneziaWg\.enable
Whether to enable native AmneziaWG client profiles\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-amneziawg-kernelmodulepackage"></a>
## services\.proxy-suite\.amneziaWg\.kernelModulePackage
AWG 3\.1 kernel module package\. Set null to use userspace-only fallback\.
*Type:*
null or package
*Default:*
```nix
<derivation amneziawg-3.1.20260812>
```
<a id="services-proxy-suite-amneziawg-profiles"></a>
## services\.proxy-suite\.amneziaWg\.profiles
Named AmneziaWG client profiles\. Only one global profile can be active\.
*Type:*
attribute set of (submodule)
*Default:*
```nix
{ }
```
<a id="services-proxy-suite-amneziawg-profiles-name-allowconfighooks"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.allowConfigHooks
Allow trusted imported configs to execute wg-quick hooks or use SaveConfig\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-amneziawg-profiles-name-autostart"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.autostart
Whether to start this profile at boot\. At most one profile may autostart\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-amneziawg-profiles-name-configfile"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.configFile
Runtime path to an AmneziaWG \.conf file\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-interfacename"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.interfaceName
Linux interface name\. It must fit Linux’s 15-character limit\.
*Type:*
string matching the pattern ^\[A-Za-z0-9_\.-]{1,15}$
*Default:*
```nix
"awg-‹name›"
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings
Typed declarative AmneziaWG client configuration\.
*Type:*
null or (submodule)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-addresses"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.addresses
IP prefixes assigned to the AWG interface\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"10.8.0.2/32"
]
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-dns"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.dns
DNS servers installed while this profile is active\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-listenport"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.listenPort
Optional local UDP listen port\.
*Type:*
null or 16 bit unsigned integer; between 0 and 65535 (both inclusive)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-mtu"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.mtu
Optional interface MTU\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation
AmneziaWG 1\.x through 3\.x obfuscation parameters\.
*Type:*
submodule
*Default:*
```nix
{ }
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-contentpaddingaddition"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.contentPaddingAddition
AWG 3 content-padding addition or range\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-disablecookies"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.disableCookies
AWG 3 cookie suppression (DisableCookies)\.
*Type:*
null or boolean
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h1"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.h1
Handshake-init header or range (H1)\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h2"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.h2
Handshake-response header or range (H2)\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h3"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.h3
Cookie-reply header or range (H3)\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-h4"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.h4
Transport-message header or range (H4)\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-headerprotectionkey"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.headerProtectionKey
Inline AWG 3 header-protection key\. Prefer headerProtectionKeyFile\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-headerprotectionkeyfile"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.headerProtectionKeyFile
Runtime path containing the AWG 3 header-protection key\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i1"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.i1
First custom signature packet (I1)\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i2"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.i2
Second custom signature packet (I2)\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i3"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.i3
Third custom signature packet (I3)\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i4"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.i4
Fourth custom signature packet (I4)\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-i5"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.i5
Fifth custom signature packet (I5)\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-jc"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.jc
Junk packet count (Jc)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-jmax"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.jmax
Maximum junk packet size (Jmax)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-jmin"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.jmin
Minimum junk packet size (Jmin)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-keepalivetimeout"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.keepaliveTimeout
AWG 3 keepalive timeout or range\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-maxhandshakeattempts"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.maxHandshakeAttempts
AWG 3 maximum handshake attempts or range\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-randomtrailers"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.randomTrailers
AWG 3 random transport trailers (RandomTrailers)\.
*Type:*
null or boolean
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-rejectaftertime"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.rejectAfterTime
AWG 3 reject-after interval or range\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-rekeyaftertime"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.rekeyAfterTime
AWG 3 rekey interval or range\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-rekeytimeout"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.rekeyTimeout
AWG 3 rekey timeout or range\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s1"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.s1
Handshake-init padding (S1)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s2"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.s2
Handshake-response padding (S2)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s3"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.s3
Cookie-reply padding (S3)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscation-s4"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscation\.s4
Transport-message padding (S4)\.
*Type:*
null or (unsigned integer, meaning >=0)
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-obfuscationfile"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.obfuscationFile
Runtime path to a partial JSON object using the same field names and
value types as obfuscation, excluding headerProtectionKeyFile\.
Values are combined with public obfuscation settings at service startup
without putting the file contents in the Nix store\. Omitted or null
fields are unset; duplicate JSON keys and fields set in both sources
are rejected\. A file-provided headerProtectionKey also conflicts with
obfuscation\.headerProtectionKeyFile\. Private and preshared keys use
their existing file options\. Restart the profile after secret rotation\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"/run/secrets/awg-obfuscation.json"
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-peers"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.peers
AmneziaWG peers\.
*Type:*
list of (submodule)
*Default:*
```nix
[ ]
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-peers-advancedsecurity"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.peers\.\*\.advancedSecurity
Optional AWG peer AdvancedSecurity setting\.
*Type:*
null or boolean
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-peers-allowedips"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.peers\.\*\.allowedIPs
IP prefixes routed to and accepted from this peer\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"0.0.0.0/0"
"::/0"
]
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-peers-endpoint"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.peers\.\*\.endpoint
Optional peer endpoint in host:port form\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"vpn.example.com:51820"
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-peers-persistentkeepalive"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.peers\.\*\.persistentKeepalive
Persistent keepalive seconds, optionally expressed as an AWG 3 range\.
*Type:*
null or unsigned integer, meaning >=0, or string matching the pattern ^(\[0-9]+|\[0-9]±\[0-9]+|\\(off\\))$
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-peers-presharedkey"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.peers\.\*\.presharedKey
Inline peer preshared key\. Prefer presharedKeyFile for secrets\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-peers-presharedkeyfile"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.peers\.\*\.presharedKeyFile
Runtime path containing the peer preshared key\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-peers-publickey"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.peers\.\*\.publicKey
AmneziaWG peer public key\.
*Type:*
string matching the pattern \[^\[:space:]]+
<a id="services-proxy-suite-amneziawg-profiles-name-settings-privatekey"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.privateKey
Inline client private key\. Prefer privateKeyFile\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-privatekeyfile"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.privateKeyFile
Runtime path containing the client private key\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-settings-table"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.settings\.table
wg-quick routing table name/number, auto, or off\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-vpn"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.vpn
Inline self-contained vpn:// export\. This value is stored in the Nix store\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-vpncontainer"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.vpnContainer
AWG container/protocol identifier to select when a vpn:// bundle is ambiguous\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-profiles-name-vpnfile"></a>
## services\.proxy-suite\.amneziaWg\.profiles\.\<name>\.vpnFile
Runtime path containing a self-contained vpn:// export\.
*Type:*
null or string
*Default:*
```nix
null
```
<a id="services-proxy-suite-amneziawg-toolspackage"></a>
## services\.proxy-suite\.amneziaWg\.toolsPackage
AWG 3\.1 package providing awg and awg-quick\.
*Type:*
package
*Default:*
```nix
<derivation amneziawg-tools-3.1.20260812>
```
<a id="services-proxy-suite-amneziawg-userspacepackage"></a>
## services\.proxy-suite\.amneziaWg\.userspacePackage
AWG 3\.1 userspace implementation used when the kernel interface is unavailable\.
*Type:*
package
*Default:*
```nix
<derivation amneziawg-go-3.1.20260828>
```
+55
View File
@@ -0,0 +1,55 @@
# services.proxy-suite.geodata
Part of the [proxy-suite options reference](./index.md).
## Options
- geodata
- singBox
- [geoip](#services-proxy-suite-geodata-singbox-geoip)
- [geosite](#services-proxy-suite-geodata-singbox-geosite)
- xray
- [assets](#services-proxy-suite-geodata-xray-assets)
<a id="services-proxy-suite-geodata-singbox-geoip"></a>
## services\.proxy-suite\.geodata\.singBox\.geoip
Package with share/sing-box/rule-set/geoip-NAME\.srs (country codes by default)\.
*Type:*
package
*Default:*
```nix
pkgs.sing-geoip
```
<a id="services-proxy-suite-geodata-singbox-geosite"></a>
## services\.proxy-suite\.geodata\.singBox\.geosite
Package with share/sing-box/rule-set/geosite-NAME\.srs\.
*Type:*
package
*Default:*
```nix
pkgs.sing-geosite
```
<a id="services-proxy-suite-geodata-xray-assets"></a>
## services\.proxy-suite\.geodata\.xray\.assets
Package with share/v2ray/{geoip,geosite}\.dat for every XRay process\. Null uses XRay’s own
country-only data, where a tag like “geoip:telegram” stops XRay from starting\.
*Type:*
null or package
*Default:*
```nix
pkgs.v2ray-rules-dat
```
File diff suppressed because it is too large. Load diff
+353
View File
@@ -0,0 +1,353 @@
# proxy-suite options
Generated from the `services.proxy-suite` option descriptions under
[`modules/proxy-suite/options/`](/modules/proxy-suite/options/).
Update the module option docs there instead of editing these files by hand.
## Option groups
- [amneziaWg](./amneziaWg.md)
- [geodata](./geodata.md)
- [inbounds](./inbounds.md)
- [perAppRouting](./perAppRouting.md)
- [proxy](./proxy.md)
- [sshProxy](./sshProxy.md)
- [tgWsProxy](./tgWsProxy.md)
- [tray](./tray.md)
- [userControl](./userControl.md)
- [zapret](./zapret.md)
## Complete default config
```nix
services.proxy-suite = {
amneziaWg = {
enable = false;
kernelModulePackage = pkgs.amneziawg;
profiles = { };
toolsPackage = pkgs.amneziawg-tools;
userspacePackage = pkgs.amneziawg-go;
};
enable = false;
geodata = {
singBox = {
geoip = pkgs.sing-geoip;
geosite = pkgs.sing-geosite;
};
xray = {
assets = pkgs.v2ray-rules-dat;
};
};
inbounds = {
enable = false;
listeners = { };
openFirewall = true;
package = pkgs.xray;
routing = {
blockPrivate = true;
blockRu = true;
proxy = {
domains = [ ];
geoips = [ ];
geosites = [ ];
ips = [ ];
};
via = "proxy";
zapretDirect = true;
};
serverAddress = null;
shareLinks = true;
subscriptions = {
baseUrl = null;
enable = false;
group = "nginx";
};
};
perAppRouting = {
createDefaultProfiles = false;
enable = false;
profiles = [ ];
proxychains = {
enable = false;
proxyDns = true;
quiet = true;
};
tproxy = {
enable = false;
fwmark = 17;
localSubnets = [
"192.168.0.0/16"
];
routeTable = 102;
};
tun = {
address = "172.20.0.1/30";
enable = false;
fwmark = 16;
interface = "psperapptun0";
localSubnets = [
"192.168.0.0/16"
];
mtu = 1400;
routeTable = 101;
};
zapret = {
enable = false;
filterMark = 268435456;
qnum = 201;
};
};
proxy = {
auth = { };
autoProxy = {
enable = false;
exclude = [ ];
interval = "10m";
maxExits = 12;
probeBasePort = 18540;
probesPerRun = 200;
slowBelowKiBps = 150;
ttlDays = 30;
};
autostart = null;
backend = "sing-box";
dns = {
local = {
address = "1.1.1.1";
port = 53;
type = "udp";
};
remote = {
address = "1.1.1.1";
port = 53;
type = "udp";
};
};
enable = false;
listener = {
address = "127.0.0.1";
auth = {
password = null;
passwordFile = null;
username = null;
};
port = 1080;
};
outbounds = [ ];
routing = {
block = {
domains = [ ];
geoips = [ ];
geosites = [ ];
ips = [ ];
};
default = "proxy";
direct = {
domains = [ ];
geoips = [ ];
geosites = [ ];
ips = [ ];
};
directRu = true;
proxy = {
domains = [ ];
geoips = [ ];
geosites = [ ];
ips = [ ];
};
rules = [ ];
};
selection = "first";
singBox = {
clashApiPort = 9090;
package = pkgs.sing-box;
urlTest = { };
};
subscriptionUpdateInterval = "1d";
subscriptions = [ ];
tproxy = {
enable = false;
fwmark = 1;
localSubnets = [
"192.168.0.0/16"
];
port = 1085;
proxyMark = 2;
routeTable = 100;
};
tun = {
address = "172.19.0.1/30";
enable = false;
interface = "singtun0";
mtu = 1400;
};
urlTest = {
interval = "3m";
tolerance = 50;
url = "https://www.gstatic.com/generate_204";
};
xray = {
package = pkgs.xray;
};
};
sshProxy = {
asOutbound = false;
domainStrategy = null;
enable = false;
extraArgs = [ ];
hostKey = [ ];
hostKeyFile = null;
identityFile = null;
knownHostsFile = null;
listener = {
address = "127.0.0.1";
port = 1091;
};
server = {
host = null;
port = 22;
user = null;
};
serviceUser = null;
strictHostKeyChecking = "accept-new";
};
tgWsProxy = {
bufferKiB = 256;
bypassTransparentProxy = true;
cloudflare = {
domains = [ ];
fallback = true;
workerDomains = [ ];
};
dcIps = { };
enable = false;
fakeTlsDomain = null;
fwmark = 4;
listener = {
address = "127.0.0.1";
port = 1443;
};
log = {
file = null;
keep = 1;
maxSizeMiB = 5.0;
verbose = false;
};
poolSize = 4;
proxyProtocol = false;
secret = null;
secretFile = null;
};
tray = {
autostart = true;
enable = false;
pollInterval = 5;
};
userControl = {
allow = [
"global"
"perApp"
];
global = { };
group = "proxy-suite";
perApp = { };
};
zapret = {
cidrExemption = {
cidrs = [ ];
enable = false;
};
directSync = {
enable = true;
upstreamIps = false;
userIps = true;
};
enable = false;
engine = "zapret-discord-youtube";
zapret-discord-youtube = {
configName = "general(ALT)";
domains = [ ];
excludeDomains = [ ];
excludeIps = [ ];
gameFilter = "null";
hostlistRules = [ ];
includeExtraUpstreamLists = false;
ips = [ ];
};
zapret2 = {
autoHostlist = {
debugLog = false;
enable = true;
failThreshold = 3;
failTime = 300;
incomingMaxseq = 4096;
retransMaxseq = 32768;
retransReset = true;
retransThreshold = 3;
udpIn = 1;
udpOut = 4;
};
blobs = {
quic_initial = "quic_initial_www_google_com.bin";
tls_clienthello = "tls_clienthello_www_google_com.bin";
};
domains = [ ];
excludeDomains = [ ];
ipv6 = false;
ports = {
tcp = "80,443,1984,2053,2083,2087,2096,5222,8443";
udp = "443,590-600,1400,3478-3481,5349,19294-19344,49152-65535";
};
profiles = [
''
--filter-tcp=443,80,1984,5222 --filter-l7=http,tls,mtproto <HOSTLIST>
--payload=tls_client_hello,mtproto_initial
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
--lua-desync=fake:blob=tls_clienthello:tls_mod=rnd,dupsid,sni=fonts.google.com:tcp_seq=10000:strategy=1
--lua-desync=multisplit:pos=1,midsld:seqovl=1:seqovl_pattern=tls_clienthello:tcp_ts_up:strategy=1
--lua-desync=fake:blob=0x00000000:tcp_ack=-66000:tls_mod=rnd,dupsid,sni=www.google.com:repeats=2:strategy=2
--lua-desync=multisplit:pos=1,midsld:strategy=2
--lua-desync=hostfakesplit:host=ozon.ru:midhost=host-2:seqovl=sniext+3:seqovl_pattern=tls_clienthello:badsum:tcp_md5:tcp_ts_up:strategy=3
--lua-desync=hostfakesplit:tcp_md5:tcp_ts_up:strategy=3
--payload=http_req
--lua-desync=http_methodeol:badsum
''
''
--filter-udp=443 --filter-l7=quic <HOSTLIST_NOAUTO>
--payload=quic_initial
--lua-desync=fake:blob=quic_initial:repeats=11
''
''
--filter-udp=590-600,1400,3478-3481,5349,19294-19344,49152-65535
--filter-l7=wireguard,stun,discord,mtproto,unknown
--out-range=<n2
--payload=wireguard_initiation,wireguard_response,wireguard_cookie,stun,discord_ip_discovery,mtproto_initial,unknown
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
--lua-desync=fake:repeats=6:strategy=1
--lua-desync=fake:blob=quic_initial:repeats=6:strategy=2
''
];
};
};
};
```
<a id="services-proxy-suite-enable"></a>
## services\.proxy-suite\.enable
Whether to enable proxy-suite\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
+407
View File
@@ -0,0 +1,407 @@
# services.proxy-suite.perAppRouting
Part of the [proxy-suite options reference](./index.md).
## Options
- perAppRouting
- [enable](#services-proxy-suite-perapprouting-enable)
- [createDefaultProfiles](#services-proxy-suite-perapprouting-createdefaultprofiles)
- [profiles](#services-proxy-suite-perapprouting-profiles)
- item
- [name](#services-proxy-suite-perapprouting-profiles-name)
- [route](#services-proxy-suite-perapprouting-profiles-route)
- proxychains
- [enable](#services-proxy-suite-perapprouting-proxychains-enable)
- [proxyDns](#services-proxy-suite-perapprouting-proxychains-proxydns)
- [quiet](#services-proxy-suite-perapprouting-proxychains-quiet)
- tproxy
- [enable](#services-proxy-suite-perapprouting-tproxy-enable)
- [fwmark](#services-proxy-suite-perapprouting-tproxy-fwmark)
- [localSubnets](#services-proxy-suite-perapprouting-tproxy-localsubnets)
- [routeTable](#services-proxy-suite-perapprouting-tproxy-routetable)
- tun
- [enable](#services-proxy-suite-perapprouting-tun-enable)
- [address](#services-proxy-suite-perapprouting-tun-address)
- [fwmark](#services-proxy-suite-perapprouting-tun-fwmark)
- [interface](#services-proxy-suite-perapprouting-tun-interface)
- [localSubnets](#services-proxy-suite-perapprouting-tun-localsubnets)
- [mtu](#services-proxy-suite-perapprouting-tun-mtu)
- [routeTable](#services-proxy-suite-perapprouting-tun-routetable)
- zapret
- [enable](#services-proxy-suite-perapprouting-zapret-enable)
- [filterMark](#services-proxy-suite-perapprouting-zapret-filtermark)
- [qnum](#services-proxy-suite-perapprouting-zapret-qnum)
<a id="services-proxy-suite-perapprouting-enable"></a>
## services\.proxy-suite\.perAppRouting\.enable
Whether to enable per-app routing (` proxy-ctl apps run `)\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-perapprouting-createdefaultprofiles"></a>
## services\.proxy-suite\.perAppRouting\.createDefaultProfiles
Add a profile named after each enabled backend (proxychains, tun, tproxy, zapret) unless
one with that name already exists\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-perapprouting-profiles"></a>
## services\.proxy-suite\.perAppRouting\.profiles
Profiles for ` proxy-ctl apps run <name> -- <command> `\.
*Type:*
list of (submodule)
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
{
name = "steam-browser";
route = "proxychains";
}
]
```
<a id="services-proxy-suite-perapprouting-profiles-name"></a>
## services\.proxy-suite\.perAppRouting\.profiles\.\*\.name
Profile name, unique\.
*Type:*
string matching the pattern ^\[a-z0-9]\[a-z0-9-]\*$
*Example:*
```nix
"steam-browser"
```
<a id="services-proxy-suite-perapprouting-profiles-route"></a>
## services\.proxy-suite\.perAppRouting\.profiles\.\*\.route
Backend: “direct” (unchanged), “proxychains”, or the per-app “tun”, “tproxy” or “zapret”
backend of perAppRouting\.
*Type:*
one of “direct”, “proxychains”, “tun”, “tproxy”, “zapret”
*Default:*
```nix
"proxychains"
```
<a id="services-proxy-suite-perapprouting-proxychains-enable"></a>
## services\.proxy-suite\.perAppRouting\.proxychains\.enable
Whether to enable the proxychains backend (TCP apps, through LD_PRELOAD)\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-perapprouting-proxychains-proxydns"></a>
## services\.proxy-suite\.perAppRouting\.proxychains\.proxyDns
Resolve DNS through the proxy (proxy_dns)\.
*Type:*
boolean
*Default:*
```nix
true
```
<a id="services-proxy-suite-perapprouting-proxychains-quiet"></a>
## services\.proxy-suite\.perAppRouting\.proxychains\.quiet
Silence proxychains (quiet_mode)\.
*Type:*
boolean
*Default:*
```nix
true
```
<a id="services-proxy-suite-perapprouting-tproxy-enable"></a>
## services\.proxy-suite\.perAppRouting\.tproxy\.enable
Whether to enable the per-app TProxy backend\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-perapprouting-tproxy-fwmark"></a>
## services\.proxy-suite\.perAppRouting\.tproxy\.fwmark
Mark that steers wrapped apps into routeTable\.
*Type:*
signed integer
*Default:*
```nix
17
```
<a id="services-proxy-suite-perapprouting-tproxy-localsubnets"></a>
## services\.proxy-suite\.perAppRouting\.tproxy\.localSubnets
Subnets that bypass interception (DNS excepted)\.
*Type:*
list of string
*Default:*
```nix
[
"192.168.0.0/16"
]
```
*Example:*
```nix
[
"192.168.0.0/16"
"10.0.0.0/8"
]
```
<a id="services-proxy-suite-perapprouting-tproxy-routetable"></a>
## services\.proxy-suite\.perAppRouting\.tproxy\.routeTable
Policy-routing table of the per-app TProxy\.
*Type:*
signed integer
*Default:*
```nix
102
```
<a id="services-proxy-suite-perapprouting-tun-enable"></a>
## services\.proxy-suite\.perAppRouting\.tun\.enable
Whether to enable the per-app TUN backend\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-perapprouting-tun-address"></a>
## services\.proxy-suite\.perAppRouting\.tun\.address
Per-app TUN interface address (CIDR)\.
*Type:*
string
*Default:*
```nix
"172.20.0.1/30"
```
<a id="services-proxy-suite-perapprouting-tun-fwmark"></a>
## services\.proxy-suite\.perAppRouting\.tun\.fwmark
Mark that steers wrapped apps into routeTable\.
*Type:*
signed integer
*Default:*
```nix
16
```
<a id="services-proxy-suite-perapprouting-tun-interface"></a>
## services\.proxy-suite\.perAppRouting\.tun\.interface
Per-app TUN interface name\.
*Type:*
string
*Default:*
```nix
"psperapptun0"
```
<a id="services-proxy-suite-perapprouting-tun-localsubnets"></a>
## services\.proxy-suite\.perAppRouting\.tun\.localSubnets
Subnets wrapped apps reach directly\.
*Type:*
list of string
*Default:*
```nix
[
"192.168.0.0/16"
]
```
*Example:*
```nix
[
"192.168.0.0/16"
"10.0.0.0/8"
]
```
<a id="services-proxy-suite-perapprouting-tun-mtu"></a>
## services\.proxy-suite\.perAppRouting\.tun\.mtu
Per-app TUN interface MTU\.
*Type:*
signed integer
*Default:*
```nix
1400
```
<a id="services-proxy-suite-perapprouting-tun-routetable"></a>
## services\.proxy-suite\.perAppRouting\.tun\.routeTable
Policy-routing table of the per-app TUN\.
*Type:*
signed integer
*Default:*
```nix
101
```
<a id="services-proxy-suite-perapprouting-zapret-enable"></a>
## services\.proxy-suite\.perAppRouting\.zapret\.enable
Whether to enable the per-app zapret backend: a second zapret instance for wrapped apps only\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-perapprouting-zapret-filtermark"></a>
## services\.proxy-suite\.perAppRouting\.zapret\.filterMark
Mark bit that selects wrapped app traffic\.
*Type:*
signed integer
*Default:*
```nix
268435456
```
<a id="services-proxy-suite-perapprouting-zapret-qnum"></a>
## services\.proxy-suite\.perAppRouting\.zapret\.qnum
NFQUEUE number\. Must differ from the global instance’s\.
*Type:*
signed integer
*Default:*
```nix
201
```
File diff suppressed because it is too large. Load diff
+307
View File
@@ -0,0 +1,307 @@
# services.proxy-suite.sshProxy
Part of the [proxy-suite options reference](./index.md).
## Options
- sshProxy
- [enable](#services-proxy-suite-sshproxy-enable)
- [asOutbound](#services-proxy-suite-sshproxy-asoutbound)
- [domainStrategy](#services-proxy-suite-sshproxy-domainstrategy)
- [extraArgs](#services-proxy-suite-sshproxy-extraargs)
- [hostKey](#services-proxy-suite-sshproxy-hostkey)
- [hostKeyFile](#services-proxy-suite-sshproxy-hostkeyfile)
- [identityFile](#services-proxy-suite-sshproxy-identityfile)
- [knownHostsFile](#services-proxy-suite-sshproxy-knownhostsfile)
- listener
- [address](#services-proxy-suite-sshproxy-listener-address)
- [port](#services-proxy-suite-sshproxy-listener-port)
- server
- [host](#services-proxy-suite-sshproxy-server-host)
- [port](#services-proxy-suite-sshproxy-server-port)
- [user](#services-proxy-suite-sshproxy-server-user)
- [serviceUser](#services-proxy-suite-sshproxy-serviceuser)
- [strictHostKeyChecking](#services-proxy-suite-sshproxy-stricthostkeychecking)
<a id="services-proxy-suite-sshproxy-enable"></a>
## services\.proxy-suite\.sshProxy\.enable
Whether to enable an SSH dynamic SOCKS5 tunnel\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-sshproxy-asoutbound"></a>
## services\.proxy-suite\.sshProxy\.asOutbound
Add the tunnel as an outbound tagged “ssh-proxy”\. sing-box dials SSH itself; XRay goes
through the OpenSSH unit’s SOCKS listener\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-sshproxy-domainstrategy"></a>
## services\.proxy-suite\.sshProxy\.domainStrategy
Resolve destinations locally before the tunnel (XRay only)\. Can break geo-steered CDNs\.
*Type:*
null or one of “prefer_ipv4”, “prefer_ipv6”, “ipv4_only”, “ipv6_only”
*Default:*
```nix
null
```
*Example:*
```nix
"prefer_ipv4"
```
<a id="services-proxy-suite-sshproxy-extraargs"></a>
## services\.proxy-suite\.sshProxy\.extraArgs
Extra OpenSSH arguments\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"-J"
"jump.example.com"
]
```
<a id="services-proxy-suite-sshproxy-hostkey"></a>
## services\.proxy-suite\.sshProxy\.hostKey
Accepted host keys (sing-box)\. List every key ` ssh-keyscan ` prints: the algorithm is
negotiated\. Empty accepts any key\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI..."
]
```
<a id="services-proxy-suite-sshproxy-hostkeyfile"></a>
## services\.proxy-suite\.sshProxy\.hostKeyFile
Known-hosts file to read hostKey from at runtime (sing-box)\. Wins over hostKey\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"/root/.ssh/known_hosts"
```
<a id="services-proxy-suite-sshproxy-identityfile"></a>
## services\.proxy-suite\.sshProxy\.identityFile
Runtime path to the private key\. Null uses the agent or OpenSSH defaults\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"/run/secrets/proxy-suite-ssh-key"
```
<a id="services-proxy-suite-sshproxy-knownhostsfile"></a>
## services\.proxy-suite\.sshProxy\.knownHostsFile
Known-hosts file for OpenSSH\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"/run/secrets/proxy-suite-ssh-known-hosts"
```
<a id="services-proxy-suite-sshproxy-listener-address"></a>
## services\.proxy-suite\.sshProxy\.listener\.address
Address of the OpenSSH SOCKS5 listener\.
*Type:*
string matching the pattern \[^\[:space:]]+
*Default:*
```nix
"127.0.0.1"
```
<a id="services-proxy-suite-sshproxy-listener-port"></a>
## services\.proxy-suite\.sshProxy\.listener\.port
Port of the OpenSSH SOCKS5 listener\.
*Type:*
16 bit unsigned integer; between 0 and 65535 (both inclusive)
*Default:*
```nix
1091
```
<a id="services-proxy-suite-sshproxy-server-host"></a>
## services\.proxy-suite\.sshProxy\.server\.host
SSH server\.
*Type:*
null or string matching the pattern \[^\[:space:]]+
*Default:*
```nix
null
```
*Example:*
```nix
"ssh.example.com"
```
<a id="services-proxy-suite-sshproxy-server-port"></a>
## services\.proxy-suite\.sshProxy\.server\.port
SSH server port\.
*Type:*
16 bit unsigned integer; between 0 and 65535 (both inclusive)
*Default:*
```nix
22
```
<a id="services-proxy-suite-sshproxy-server-user"></a>
## services\.proxy-suite\.sshProxy\.server\.user
SSH login user\.
*Type:*
null or string matching the pattern \[^\[:space:]]+
*Default:*
```nix
null
```
*Example:*
```nix
"root"
```
<a id="services-proxy-suite-sshproxy-serviceuser"></a>
## services\.proxy-suite\.sshProxy\.serviceUser
Unix user running the OpenSSH unit\.
*Type:*
null or string matching the pattern \[^\[:space:]]+
*Default:*
```nix
null
```
*Example:*
```nix
"proxy"
```
<a id="services-proxy-suite-sshproxy-stricthostkeychecking"></a>
## services\.proxy-suite\.sshProxy\.strictHostKeyChecking
OpenSSH host key policy\.
*Type:*
one of “yes”, “accept-new”, “no”
*Default:*
```nix
"accept-new"
```
*Example:*
```nix
"yes"
```
+349
View File
@@ -0,0 +1,349 @@
# services.proxy-suite.tgWsProxy
Part of the [proxy-suite options reference](./index.md).
## Options
- tgWsProxy
- [enable](#services-proxy-suite-tgwsproxy-enable)
- [bufferKiB](#services-proxy-suite-tgwsproxy-bufferkib)
- [bypassTransparentProxy](#services-proxy-suite-tgwsproxy-bypasstransparentproxy)
- cloudflare
- [domains](#services-proxy-suite-tgwsproxy-cloudflare-domains)
- [fallback](#services-proxy-suite-tgwsproxy-cloudflare-fallback)
- [workerDomains](#services-proxy-suite-tgwsproxy-cloudflare-workerdomains)
- [dcIps](#services-proxy-suite-tgwsproxy-dcips)
- [fakeTlsDomain](#services-proxy-suite-tgwsproxy-faketlsdomain)
- [fwmark](#services-proxy-suite-tgwsproxy-fwmark)
- listener
- [address](#services-proxy-suite-tgwsproxy-listener-address)
- [port](#services-proxy-suite-tgwsproxy-listener-port)
- log
- [file](#services-proxy-suite-tgwsproxy-log-file)
- [keep](#services-proxy-suite-tgwsproxy-log-keep)
- [maxSizeMiB](#services-proxy-suite-tgwsproxy-log-maxsizemib)
- [verbose](#services-proxy-suite-tgwsproxy-log-verbose)
- [poolSize](#services-proxy-suite-tgwsproxy-poolsize)
- [proxyProtocol](#services-proxy-suite-tgwsproxy-proxyprotocol)
- [secret](#services-proxy-suite-tgwsproxy-secret)
- [secretFile](#services-proxy-suite-tgwsproxy-secretfile)
<a id="services-proxy-suite-tgwsproxy-enable"></a>
## services\.proxy-suite\.tgWsProxy\.enable
Whether to enable the Telegram MTProto WebSocket proxy\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-tgwsproxy-bufferkib"></a>
## services\.proxy-suite\.tgWsProxy\.bufferKiB
Socket buffer size, in KiB\.
*Type:*
integer between 4 and 2147483647 (both inclusive)
*Default:*
```nix
256
```
<a id="services-proxy-suite-tgwsproxy-bypasstransparentproxy"></a>
## services\.proxy-suite\.tgWsProxy\.bypassTransparentProxy
Keep the relay’s own connections out of TUN/TProxy, which would otherwise loop them\.
*Type:*
boolean
*Default:*
```nix
true
```
<a id="services-proxy-suite-tgwsproxy-cloudflare-domains"></a>
## services\.proxy-suite\.tgWsProxy\.cloudflare\.domains
Cloudflare-proxied domains for WebSocket fallback\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"cdn.example.com"
]
```
<a id="services-proxy-suite-tgwsproxy-cloudflare-fallback"></a>
## services\.proxy-suite\.tgWsProxy\.cloudflare\.fallback
Fall back to Cloudflare when direct WebSocket fails\.
*Type:*
boolean
*Default:*
```nix
true
```
<a id="services-proxy-suite-tgwsproxy-cloudflare-workerdomains"></a>
## services\.proxy-suite\.tgWsProxy\.cloudflare\.workerDomains
Cloudflare Worker domains, tried first\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"worker.example.com"
]
```
<a id="services-proxy-suite-tgwsproxy-dcips"></a>
## services\.proxy-suite\.tgWsProxy\.dcIps
Relay IP per Telegram DC ID\.
*Type:*
attribute set of string
*Default:*
```nix
{ }
```
*Example:*
```nix
{
"2" = "149.154.167.220";
}
```
<a id="services-proxy-suite-tgwsproxy-faketlsdomain"></a>
## services\.proxy-suite\.tgWsProxy\.fakeTlsDomain
SNI for Fake TLS masking (ee-secret links)\.
*Type:*
null or string matching the pattern \.+
*Default:*
```nix
null
```
*Example:*
```nix
"www.example.com"
```
<a id="services-proxy-suite-tgwsproxy-fwmark"></a>
## services\.proxy-suite\.tgWsProxy\.fwmark
Packet mark bypassTransparentProxy uses\.
*Type:*
signed integer
*Default:*
```nix
4
```
<a id="services-proxy-suite-tgwsproxy-listener-address"></a>
## services\.proxy-suite\.tgWsProxy\.listener\.address
Bind address\.
*Type:*
string
*Default:*
```nix
"127.0.0.1"
```
<a id="services-proxy-suite-tgwsproxy-listener-port"></a>
## services\.proxy-suite\.tgWsProxy\.listener\.port
Listen port\.
*Type:*
16 bit unsigned integer; between 0 and 65535 (both inclusive)
*Default:*
```nix
1443
```
<a id="services-proxy-suite-tgwsproxy-log-file"></a>
## services\.proxy-suite\.tgWsProxy\.log\.file
Rotating log file\. Null logs to stderr\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"/var/log/tg-ws-proxy.log"
```
<a id="services-proxy-suite-tgwsproxy-log-keep"></a>
## services\.proxy-suite\.tgWsProxy\.log\.keep
Rotated logs kept\.
*Type:*
positive integer, meaning >0
*Default:*
```nix
1
```
<a id="services-proxy-suite-tgwsproxy-log-maxsizemib"></a>
## services\.proxy-suite\.tgWsProxy\.log\.maxSizeMiB
Log size before rotation, in MiB\.
*Type:*
positive integer or floating point number, meaning >0
*Default:*
```nix
5.0
```
<a id="services-proxy-suite-tgwsproxy-log-verbose"></a>
## services\.proxy-suite\.tgWsProxy\.log\.verbose
Debug logging\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-tgwsproxy-poolsize"></a>
## services\.proxy-suite\.tgWsProxy\.poolSize
WebSocket pool size per DC; 0 disables pooling\.
*Type:*
unsigned integer, meaning >=0
*Default:*
```nix
4
```
<a id="services-proxy-suite-tgwsproxy-proxyprotocol"></a>
## services\.proxy-suite\.tgWsProxy\.proxyProtocol
Accept a PROXY protocol v1 header from a fronting reverse proxy\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-tgwsproxy-secret"></a>
## services\.proxy-suite\.tgWsProxy\.secret
Inline MTProto secret (` openssl rand -hex 16 `)\. Ends up in the Nix store; prefer secretFile\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
```
<a id="services-proxy-suite-tgwsproxy-secretfile"></a>
## services\.proxy-suite\.tgWsProxy\.secretFile
Runtime path to the MTProto secret\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"/run/secrets/tg-ws-proxy-secret"
```
+58
View File
@@ -0,0 +1,58 @@
# services.proxy-suite.tray
Part of the [proxy-suite options reference](./index.md).
## Options
- tray
- [enable](#services-proxy-suite-tray-enable)
- [autostart](#services-proxy-suite-tray-autostart)
- [pollInterval](#services-proxy-suite-tray-pollinterval)
<a id="services-proxy-suite-tray-enable"></a>
## services\.proxy-suite\.tray\.enable
Whether to enable the system tray indicator\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-tray-autostart"></a>
## services\.proxy-suite\.tray\.autostart
Start the tray in graphical sessions (XDG autostart)\.
*Type:*
boolean
*Default:*
```nix
true
```
<a id="services-proxy-suite-tray-pollinterval"></a>
## services\.proxy-suite\.tray\.pollInterval
Status refresh interval, in seconds\.
*Type:*
positive integer, meaning >0
*Default:*
```nix
5
```
+52
View File
@@ -0,0 +1,52 @@
# services.proxy-suite.userControl
Part of the [proxy-suite options reference](./index.md).
## Options
- userControl
- [allow](#services-proxy-suite-usercontrol-allow)
- [group](#services-proxy-suite-usercontrol-group)
<a id="services-proxy-suite-usercontrol-allow"></a>
## services\.proxy-suite\.userControl\.allow
What userControl\.group may control without a password:
- “global”: the global units (proxy, tun, tproxy, zapret, restart, subs update)\.
- “perApp”: the per-app backend units used by ` proxy-ctl apps run `\.
Empty grants no passwordless control\.
*Type:*
list of (one of “global”, “perApp”)
*Default:*
```nix
[
"global"
"perApp"
]
```
*Example:*
```nix
[
"global"
]
```
<a id="services-proxy-suite-usercontrol-group"></a>
## services\.proxy-suite\.userControl\.group
Group whose members may run privileged ` proxy-ctl ` commands without a password\.
*Type:*
string matching the pattern ^\[a-z_]\[a-z0-9_-]\*$
*Default:*
```nix
"proxy-suite"
```
+848
View File
@@ -0,0 +1,848 @@
# services.proxy-suite.zapret
Part of the [proxy-suite options reference](./index.md).
## Options
- zapret
- [enable](#services-proxy-suite-zapret-enable)
- cidrExemption
- [enable](#services-proxy-suite-zapret-cidrexemption-enable)
- [cidrs](#services-proxy-suite-zapret-cidrexemption-cidrs)
- directSync
- [enable](#services-proxy-suite-zapret-directsync-enable)
- [upstreamIps](#services-proxy-suite-zapret-directsync-upstreamips)
- [userIps](#services-proxy-suite-zapret-directsync-userips)
- [engine](#services-proxy-suite-zapret-engine)
- zapret-discord-youtube
- [configName](#services-proxy-suite-zapret-zapret-discord-youtube-configname)
- [domains](#services-proxy-suite-zapret-zapret-discord-youtube-domains)
- [excludeDomains](#services-proxy-suite-zapret-zapret-discord-youtube-excludedomains)
- [excludeIps](#services-proxy-suite-zapret-zapret-discord-youtube-excludeips)
- [gameFilter](#services-proxy-suite-zapret-zapret-discord-youtube-gamefilter)
- [hostlistRules](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules)
- item
- [enableDirectSync](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-enabledirectsync)
- [configName](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-configname)
- [defaultDomains](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-defaultdomains)
- [defaultIps](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-defaultips)
- [domains](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-domains)
- [ips](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-ips)
- [name](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-name)
- [nfqwsArgs](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-nfqwsargs)
- [preset](#services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-preset)
- [includeExtraUpstreamLists](#services-proxy-suite-zapret-zapret-discord-youtube-includeextraupstreamlists)
- [ips](#services-proxy-suite-zapret-zapret-discord-youtube-ips)
- zapret2
- autoHostlist
- [enable](#services-proxy-suite-zapret-zapret2-autohostlist-enable)
- [debugLog](#services-proxy-suite-zapret-zapret2-autohostlist-debuglog)
- [failThreshold](#services-proxy-suite-zapret-zapret2-autohostlist-failthreshold)
- [failTime](#services-proxy-suite-zapret-zapret2-autohostlist-failtime)
- [incomingMaxseq](#services-proxy-suite-zapret-zapret2-autohostlist-incomingmaxseq)
- [retransMaxseq](#services-proxy-suite-zapret-zapret2-autohostlist-retransmaxseq)
- [retransReset](#services-proxy-suite-zapret-zapret2-autohostlist-retransreset)
- [retransThreshold](#services-proxy-suite-zapret-zapret2-autohostlist-retransthreshold)
- [udpIn](#services-proxy-suite-zapret-zapret2-autohostlist-udpin)
- [udpOut](#services-proxy-suite-zapret-zapret2-autohostlist-udpout)
- [blobs](#services-proxy-suite-zapret-zapret2-blobs)
- [domains](#services-proxy-suite-zapret-zapret2-domains)
- [excludeDomains](#services-proxy-suite-zapret-zapret2-excludedomains)
- [ipv6](#services-proxy-suite-zapret-zapret2-ipv6)
- ports
- [tcp](#services-proxy-suite-zapret-zapret2-ports-tcp)
- [udp](#services-proxy-suite-zapret-zapret2-ports-udp)
- [profiles](#services-proxy-suite-zapret-zapret2-profiles)
<a id="services-proxy-suite-zapret-enable"></a>
## services\.proxy-suite\.zapret\.enable
Whether to enable zapret DPI bypass\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-zapret-cidrexemption-enable"></a>
## services\.proxy-suite\.zapret\.cidrExemption\.enable
Whether to enable exempting subnets from zapret, e\.g\. NATed VMs whose traffic it would break\.
*Type:*
boolean
*Default:*
```nix
false
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-zapret-cidrexemption-cidrs"></a>
## services\.proxy-suite\.zapret\.cidrExemption\.cidrs
Exempted subnets\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"192.168.123.0/24"
]
```
<a id="services-proxy-suite-zapret-directsync-enable"></a>
## services\.proxy-suite\.zapret\.directSync\.enable
Add zapret’s domain hostlists to proxy\.routing\.direct\.
*Type:*
boolean
*Default:*
```nix
true
```
<a id="services-proxy-suite-zapret-directsync-upstreamips"></a>
## services\.proxy-suite\.zapret\.directSync\.upstreamIps
Add zapret’s upstream ipsets to proxy\.routing\.direct\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-zapret-directsync-userips"></a>
## services\.proxy-suite\.zapret\.directSync\.userIps
Add zapret-discord-youtube\.ips, minus zapret-discord-youtube\.excludeIps, to proxy\.routing\.direct\.
*Type:*
boolean
*Default:*
```nix
true
```
<a id="services-proxy-suite-zapret-engine"></a>
## services\.proxy-suite\.zapret\.engine
“zapret-discord-youtube”: nfqws with curated presets and static hostlists (zapret\.zapret-discord-youtube)\.
“zapret2”: nfqws2, which learns blocked hosts at runtime (zapret\.zapret2)\.
*Type:*
one of “zapret-discord-youtube”, “zapret2”
*Default:*
```nix
"zapret-discord-youtube"
```
*Example:*
```nix
"zapret2"
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-configname"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.configName
Upstream strategy preset\. Names that differ only in whitespace match\.
*Type:*
string
*Default:*
```nix
"general(ALT)"
```
*Example:*
```nix
"general (ALT9)"
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-domains"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.domains
Extra domains to bypass\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"youtube.com"
]
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-excludedomains"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.excludeDomains
Domains never bypassed\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"music.youtube.com"
]
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-excludeips"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.excludeIps
IPs/CIDRs never bypassed\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"203.0.113.10/32"
]
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-gamefilter"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.gameFilter
Game traffic filter, or “null” for off\.
*Type:*
one of “all”, “tcp”, “udp”, “null”
*Default:*
```nix
"null"
```
*Example:*
```nix
"all"
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules
Extra named hostlists, each with its own strategy: cloned from a preset or configName,
or given as nfqwsArgs\.
*Type:*
list of (submodule)
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
{
configName = "general(ALT9)";
defaultDomains = [
"youtube"
];
name = "youtube-alt9";
}
{
domains = [
"example.com"
];
name = "custom-sites";
preset = "general";
}
]
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-enabledirectsync"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.enableDirectSync
Include these domains in zapret\.directSync\.
*Type:*
boolean
*Default:*
```nix
true
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-configname"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.configName
Config to clone strategies from\. Exclusive with nfqwsArgs\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"general(ALT9)"
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-defaultdomains"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.defaultDomains
Upstream lists to include (“discord” = “general”, “youtube” = “google”)\. Without preset,
use one per rule so the strategy family can be inferred\.
*Type:*
list of (one of “general”, “google”, “discord”, “youtube”, “instagram”, “soundcloud”, “twitter”)
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"google"
]
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-defaultips"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.defaultIps
Upstream ipsets to include (“all” is ipset-all\.txt)\.
*Type:*
list of value “all” (singular enum)
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"all"
]
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-domains"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.domains
Domains in this hostlist\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"example.com"
]
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-ips"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.ips
IPs/CIDRs in this rule’s ipset\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"203.0.113.0/24"
]
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-name"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.name
Hostlist name (hostlists/list-\<name>\.txt)\.
*Type:*
string matching the pattern ^\[a-z0-9]\[a-z0-9-]\*$
*Example:*
```nix
"cloudflare"
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-nfqwsargs"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.nfqwsArgs
Raw NFQWS arguments; --hostlist and --new are added\. Exclusive with configName\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"--filter-tcp=443 --dpi-desync=fake,multisplit"
]
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-hostlistrules-preset"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.hostlistRules\.\*\.preset
Strategy family to clone, from configName or the active config\.
*Type:*
null or one of “general”, “google”, “instagram”, “soundcloud”, “twitter”
*Default:*
```nix
null
```
*Example:*
```nix
"google"
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-includeextraupstreamlists"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.includeExtraUpstreamLists
Also use the upstream instagram, soundcloud and twitter lists\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-zapret-zapret-discord-youtube-ips"></a>
## services\.proxy-suite\.zapret\.zapret-discord-youtube\.ips
Extra IPs/CIDRs to bypass\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"203.0.113.0/24"
]
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-enable"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.enable
Learn blocked hosts: after failThreshold failures (retransmissions, early RST, DPI
redirect, one-sided UDP) a host joins /var/lib/proxy-suite/zapret2/zapret-hosts-auto\.txt\.
Off, only zapret2\.domains and ` proxy-ctl zapret auto add ` are acted on\.
*Type:*
boolean
*Default:*
```nix
true
```
*Example:*
```nix
true
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-debuglog"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.debugLog
Log why hosts are or are not learned to zapret-hosts-auto-debug\.log\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-failthreshold"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.failThreshold
Failures before a host is learned\.
*Type:*
positive integer, meaning >0
*Default:*
```nix
3
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-failtime"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.failTime
Seconds allowed between two failures before the count resets\.
*Type:*
positive integer, meaning >0
*Default:*
```nix
300
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-incomingmaxseq"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.incomingMaxseq
Incoming sequence number past which an RST or redirect is not a failure\.
*Type:*
positive integer, meaning >0
*Default:*
```nix
4096
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-retransmaxseq"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.retransMaxseq
Outgoing sequence number past which failure detection stops\.
*Type:*
positive integer, meaning >0
*Default:*
```nix
32768
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-retransreset"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.retransReset
RST a stalled client once retransThreshold is hit, so failures are counted fast\.
*Type:*
boolean
*Default:*
```nix
true
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-retransthreshold"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.retransThreshold
Retransmissions of the first request that count as one failure\.
*Type:*
positive integer, meaning >0
*Default:*
```nix
3
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-udpin"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.udpIn
Incoming UDP packets at or below which an exchange is one-sided\.
*Type:*
positive integer, meaning >0
*Default:*
```nix
1
```
<a id="services-proxy-suite-zapret-zapret2-autohostlist-udpout"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.udpOut
Outgoing UDP packets before a one-sided exchange counts as a failure\.
*Type:*
positive integer, meaning >0
*Default:*
```nix
4
```
<a id="services-proxy-suite-zapret-zapret2-blobs"></a>
## services\.proxy-suite\.zapret\.zapret2\.blobs
Fake payloads by name (blob=\<name>): a file in zapret2’s files/fake, or an absolute path\.
*Type:*
attribute set of string
*Default:*
```nix
{
quic_initial = "quic_initial_www_google_com.bin";
tls_clienthello = "tls_clienthello_www_google_com.bin";
}
```
*Example:*
```nix
{
tls_clienthello = "/etc/proxy-suite/my_clienthello.bin";
}
```
<a id="services-proxy-suite-zapret-zapret2-domains"></a>
## services\.proxy-suite\.zapret\.zapret2\.domains
Domains always treated as blocked\. At runtime: ` proxy-ctl zapret auto add `\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"rutracker.org"
]
```
<a id="services-proxy-suite-zapret-zapret2-excludedomains"></a>
## services\.proxy-suite\.zapret\.zapret2\.excludeDomains
Domains never touched or learned\. At runtime: ` proxy-ctl zapret auto exclude `\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"bank.example.com"
]
```
<a id="services-proxy-suite-zapret-zapret2-ipv6"></a>
## services\.proxy-suite\.zapret\.zapret2\.ipv6
Intercept IPv6 as well as IPv4\.
*Type:*
boolean
*Default:*
```nix
false
```
<a id="services-proxy-suite-zapret-zapret2-ports-tcp"></a>
## services\.proxy-suite\.zapret\.zapret2\.ports\.tcp
TCP ports sent to NFQUEUE\. Must cover every port a profile filters on\.
*Type:*
string
*Default:*
```nix
"80,443,1984,2053,2083,2087,2096,5222,8443"
```
<a id="services-proxy-suite-zapret-zapret2-ports-udp"></a>
## services\.proxy-suite\.zapret\.zapret2\.ports\.udp
UDP ports sent to NFQUEUE\. Must cover every port a profile filters on\.
*Type:*
string
*Default:*
```nix
"443,590-600,1400,3478-3481,5349,19294-19344,49152-65535"
```
<a id="services-proxy-suite-zapret-zapret2-profiles"></a>
## services\.proxy-suite\.zapret\.zapret2\.profiles
nfqws2 profiles, joined with --new; first match wins\. \<HOSTLIST> expands to the hostlist
arguments, \<HOSTLIST_NOAUTO> to the same without learning\. --qnum, --fwmark and --lua-init
are added automatically\.
*Type:*
list of string
*Default:*
```nix
[
''
--filter-tcp=443,80,1984,5222 --filter-l7=http,tls,mtproto <HOSTLIST>
--payload=tls_client_hello,mtproto_initial
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
--lua-desync=fake:blob=tls_clienthello:tls_mod=rnd,dupsid,sni=fonts.google.com:tcp_seq=10000:strategy=1
--lua-desync=multisplit:pos=1,midsld:seqovl=1:seqovl_pattern=tls_clienthello:tcp_ts_up:strategy=1
--lua-desync=fake:blob=0x00000000:tcp_ack=-66000:tls_mod=rnd,dupsid,sni=www.google.com:repeats=2:strategy=2
--lua-desync=multisplit:pos=1,midsld:strategy=2
--lua-desync=hostfakesplit:host=ozon.ru:midhost=host-2:seqovl=sniext+3:seqovl_pattern=tls_clienthello:badsum:tcp_md5:tcp_ts_up:strategy=3
--lua-desync=hostfakesplit:tcp_md5:tcp_ts_up:strategy=3
--payload=http_req
--lua-desync=http_methodeol:badsum
''
''
--filter-udp=443 --filter-l7=quic <HOSTLIST_NOAUTO>
--payload=quic_initial
--lua-desync=fake:blob=quic_initial:repeats=11
''
''
--filter-udp=590-600,1400,3478-3481,5349,19294-19344,49152-65535
--filter-l7=wireguard,stun,discord,mtproto,unknown
--out-range=<n2
--payload=wireguard_initiation,wireguard_response,wireguard_cookie,stun,discord_ip_discovery,mtproto_initial,unknown
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
--lua-desync=fake:repeats=6:strategy=1
--lua-desync=fake:blob=quic_initial:repeats=6:strategy=2
''
]
```
*Example:*
```nix
[
"--filter-tcp=443 --filter-l7=tls <HOSTLIST> --payload=tls_client_hello --lua-desync=multisplit:pos=1,midsld"
]
```
Generated
+9 -43
View File
@@ -1,30 +1,12 @@
{
"nodes": {
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1731533236,
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1779560665,
"narHash": "sha256-tpyBcxPpcQb8ukyNF7DoCwfSY3VPsxHoYwj00Cayv5o=",
"lastModified": 1788614874,
"narHash": "sha256-7QYjT2vHLuX9Z1pdxHXDKCbh1CR3D/2rywB9Tx0MPRg=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "64c08a7ca051951c8eae34e3e3cb1e202fe36786",
"rev": "c043004d1c6985732bcc1cbc5a9c9aecbbb4e0f0",
"type": "github"
},
"original": {
@@ -40,35 +22,19 @@
"zapret": "zapret"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
},
"zapret": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": [
"nixpkgs"
],
"zapret-flowseal": "zapret-flowseal"
},
"locked": {
"lastModified": 1780265315,
"narHash": "sha256-akozC33JwGQM1S5R5dS2sG/Wsh9k0AVfHgszBySiY/o=",
"lastModified": 1788726932,
"narHash": "sha256-MehJgJpN7BGMaDES9I0aj/YG6JkRlSj5RiZDZfclNpc=",
"owner": "kartavkun",
"repo": "zapret-discord-youtube",
"rev": "9d8c3110075117a7d9c0f73395fc3eafa6b76222",
"rev": "64a8ee76f4f2e4a8d2751cb732f13448ee1e4fcf",
"type": "github"
},
"original": {
@@ -80,11 +46,11 @@
"zapret-flowseal": {
"flake": false,
"locked": {
"lastModified": 1780149029,
"narHash": "sha256-mXBl6jYku2zXaiSlzzmf1WhhsDYKEvqltLlebxU6kgA=",
"lastModified": 1788121958,
"narHash": "sha256-WMpxbtA2OH340e4uuXR0tcUW0D6V9Kzs0KI1iKqkXBM=",
"owner": "Flowseal",
"repo": "zapret-discord-youtube",
"rev": "7e9b42a00b4c1c3bb5370401b9befcb8565b3ac6",
"rev": "6cec828910d0809863205702182a3557d9d0e8c3",
"type": "github"
},
"original": {
+13 -4
View File
@@ -1,5 +1,5 @@
{
description = "NixOS proxy suite - SingBox, XRay, zapret, tg-ws-proxy";
description = "NixOS proxy suite - SingBox, XRay, AmneziaWG 3.1, zapret, tg-ws-proxy";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
@@ -22,7 +22,7 @@
];
forAll = nixpkgs.lib.genAttrs systems;
pkgsFor = system: import nixpkgs { inherit system; };
proxySuiteModule = import ./modules/proxy-suite { inherit zapret; };
proxySuiteModule = import ./modules/proxy-suite { inherit zapret nixpkgs; };
mkOptionsDoc = import ./nix/options-doc.nix {
inherit nixpkgs pkgsFor proxySuiteModule;
};
@@ -44,11 +44,14 @@
overlays.default = final: prev: {
inherit (import ./pkgs/default.nix { pkgs = final; })
amneziawg-tools
amneziawg-go
mkProxyCtl
mkProxySuiteTray
mkTgWsProxy
tg-ws-proxy
proxy-suite-tray
zapret2
;
};
@@ -77,19 +80,25 @@
options_output_path="$(nix build --no-link --print-out-paths "''${repo_root}#optionsDoc")"
readme_output_path="$(nix build --no-link --print-out-paths "''${repo_root}#readmeDoc")"
install -Dm644 "''${options_output_path}" "''${repo_root}/docs/options.md"
mkdir -p "''${repo_root}/docs"
rm -rf "''${repo_root}/docs/options"
cp -r --no-preserve=mode,ownership "''${options_output_path}" "''${repo_root}/docs/options"
install -Dm644 "''${readme_output_path}" "''${repo_root}/README.md"
echo "updated ''${repo_root}/docs/options.md"
echo "updated ''${repo_root}/docs/options/"
echo "updated ''${repo_root}/README.md"
'';
};
in
{
inherit (suitePkgs)
amneziawg-tools
amneziawg-go
tg-ws-proxy
proxy-suite-tray
zapret2
;
xray = import ./pkgs/xray.nix { inherit pkgs; };
optionsDoc = mkOptionsDoc system;
readmeDoc = mkReadmeDoc system;
update-docs = updateDocs;
+335
View File
@@ -0,0 +1,335 @@
# Native AmneziaWG client profile services.
{
config,
lib,
pkgs,
cfg,
}:
let
awgCfg = cfg.amneziaWg;
profiles = awgCfg.profiles;
profileNames = builtins.attrNames profiles;
serviceName = name: "proxy-suite-awg-${name}";
serviceNames = map serviceName profileNames;
allProfileConflicts =
name:
map (other: "${serviceName other}.service") (builtins.filter (other: other != name) profileNames);
sourceCount =
profile:
builtins.length (
builtins.filter (value: value != null) [
profile.configFile
profile.vpnFile
profile.vpn
profile.settings
]
);
inlineVpnFile = name: profile: pkgs.writeText "proxy-suite-awg-${name}.vpn" profile.vpn;
sourceKind =
profile:
if profile.configFile != null then
"configFile"
else if profile.vpnFile != null then
"vpnFile"
else if profile.vpn != null then
"vpn"
else
"settings";
sourcePath =
name: profile:
if profile.configFile != null then
profile.configFile
else if profile.vpnFile != null then
profile.vpnFile
else if profile.vpn != null then
inlineVpnFile name profile
else
null;
manifestFor =
name: profile:
pkgs.writeText "proxy-suite-awg-${name}-manifest.json" (
builtins.toJSON (
{
kind = sourceKind profile;
allowConfigHooks = profile.allowConfigHooks;
vpnContainer = profile.vpnContainer;
}
// lib.optionalAttrs (sourcePath name profile != null) { path = sourcePath name profile; }
// lib.optionalAttrs (profile.settings != null) { settings = profile.settings; }
)
);
configTool = ../../scripts/amneziawg_config.py;
runtimeDir = name: "/run/${serviceName name}";
runtimeConfig = name: profile: "${runtimeDir name}/${profile.interfaceName}.conf";
# Keep proxy backend sockets (proxyMark) out of AWG's default-route table.
proxyBypassRulePriority = 8998;
mkService =
name: profile:
let
manifest = manifestFor name profile;
configPath = runtimeConfig name profile;
prepare = pkgs.writeShellScript "proxy-suite-awg-${name}-prepare" ''
set -euo pipefail
${pkgs.python3}/bin/python3 ${configTool} \
--manifest ${lib.escapeShellArg (toString manifest)} \
--output ${lib.escapeShellArg configPath}
'';
proxyBypassUp = pkgs.writeShellScript "proxy-suite-awg-${name}-proxy-bypass-up" ''
set -euo pipefail
add_bypass_rule() {
local family="$1"
while ${pkgs.iproute2}/bin/ip "$family" rule del \
pref ${toString proxyBypassRulePriority} \
fwmark ${toString cfg.proxy.tproxy.proxyMark} lookup main 2>/dev/null; do :; done
if ! ${pkgs.iproute2}/bin/ip "$family" rule add \
pref ${toString proxyBypassRulePriority} \
fwmark ${toString cfg.proxy.tproxy.proxyMark} lookup main 2>/dev/null; then
# IPv4 is required, or the proxy backend is captured by AWG; IPv6 is best-
# effort.
if [ "$family" = "-4" ]; then
echo "proxy-suite: unable to install the AWG proxy-backend bypass rule" >&2
return 1
fi
fi
}
add_bypass_rule -4
add_bypass_rule -6
'';
proxyBypassDown = pkgs.writeShellScript "proxy-suite-awg-${name}-proxy-bypass-down" ''
set +e
while ${pkgs.iproute2}/bin/ip -4 rule del \
pref ${toString proxyBypassRulePriority} \
fwmark ${toString cfg.proxy.tproxy.proxyMark} lookup main 2>/dev/null; do :; done
while ${pkgs.iproute2}/bin/ip -6 rule del \
pref ${toString proxyBypassRulePriority} \
fwmark ${toString cfg.proxy.tproxy.proxyMark} lookup main 2>/dev/null; do :; done
'';
start = pkgs.writeShellScript "proxy-suite-awg-${name}-start" ''
set -Eeuo pipefail
cleanup() {
set +e
${awgCfg.toolsPackage}/bin/awg-quick down ${lib.escapeShellArg configPath}
# Without the control socket awg-quick cannot find its fwmark; clean up this
# interface only.
for family in -4 -6; do
had_table=0
for table in $(${pkgs.iproute2}/bin/ip "$family" route show table all 2>/dev/null \
| ${pkgs.gawk}/bin/awk '$1 == "default" && $2 == "dev" && $3 == "${profile.interfaceName}" { for (i = 1; i <= NF; i++) if ($i == "table") print $(i + 1) }'); do
had_table=1
while ${pkgs.iproute2}/bin/ip "$family" rule delete table "$table" 2>/dev/null; do :; done
${pkgs.iproute2}/bin/ip "$family" route flush table "$table" 2>/dev/null || true
done
if (( had_table )); then
${pkgs.iproute2}/bin/ip "$family" rule delete table main suppress_prefixlength 0 2>/dev/null || true
fi
done
if command -v nft >/dev/null; then
nft list tables 2>/dev/null \
| ${pkgs.gnugrep}/bin/grep -F " wg-quick-${profile.interfaceName}" \
| while read -r _ family table; do nft delete table "$family" "$table" 2>/dev/null || true; done
fi
${config.networking.resolvconf.package}/bin/resolvconf -d "${profile.interfaceName}" -f 2>/dev/null || true
${pkgs.iproute2}/bin/ip link delete dev ${lib.escapeShellArg profile.interfaceName} 2>/dev/null || true
}
trap cleanup ERR
${lib.optionalString (awgCfg.kernelModulePackage != null) ''
${pkgs.kmod}/bin/modprobe amneziawg 2>/dev/null || true
''}
implementation="$(${pkgs.python3}/bin/python3 ${configTool} \
--transport-implementation ${lib.escapeShellArg configPath})"
# The 3.1.20260812 kernel module drops RandomTrailers packets with ranged H1-H3;
# userspace carries the fix.
if [[ "$implementation" == userspace ]]; then
WG_QUICK_FORCE_USERSPACE_IMPLEMENTATION=1 \
WG_QUICK_USERSPACE_IMPLEMENTATION=${awgCfg.userspacePackage}/bin/amneziawg-go \
${awgCfg.toolsPackage}/bin/awg-quick up ${lib.escapeShellArg configPath}
else
WG_QUICK_USERSPACE_IMPLEMENTATION=${awgCfg.userspacePackage}/bin/amneziawg-go \
${awgCfg.toolsPackage}/bin/awg-quick up ${lib.escapeShellArg configPath}
fi
probe="$(${pkgs.python3}/bin/python3 ${configTool} --probe-address ${lib.escapeShellArg configPath})"
for _ in $(${pkgs.coreutils}/bin/seq 1 15); do
${pkgs.iputils}/bin/ping -n -c 1 -W 1 "$probe" >/dev/null 2>&1 || true
if ${awgCfg.toolsPackage}/bin/awg show ${lib.escapeShellArg profile.interfaceName} latest-handshakes 2>/dev/null \
| ${pkgs.gawk}/bin/awk '$2 + 0 > 0 { found = 1 } END { exit !found }'; then
trap - ERR
exit 0
fi
done
echo "proxy-suite: AmneziaWG profile '${name}' did not complete a handshake; rolling back routes" >&2
false
'';
stop = pkgs.writeShellScript "proxy-suite-awg-${name}-stop" ''
set -euo pipefail
exec ${awgCfg.toolsPackage}/bin/awg-quick down ${lib.escapeShellArg configPath}
'';
in
{
description = "proxy-suite AmneziaWG client profile ${name}";
# Start the local proxy before AWG takes the default route, so HTTP_PROXY clients
# do not race it.
after = [
"network-online.target"
"zapret-discord-youtube.service"
]
++ lib.optional cfg.proxy.enable "proxy-suite-socks.service";
wants = [ "network-online.target" ] ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service";
wantedBy = lib.optionals profile.autostart [ "multi-user.target" ];
conflicts = allProfileConflicts name ++ [
"proxy-suite-tun.service"
"proxy-suite-tproxy.service"
"zapret-discord-youtube.service"
"proxy-suite-per-app-zapret.service"
"proxy-suite-zapret-vm-exempt.service"
];
path = [
awgCfg.toolsPackage
awgCfg.userspacePackage
pkgs.coreutils
pkgs.gnugrep
pkgs.iproute2
pkgs.iputils
pkgs.kmod
config.networking.firewall.package
config.networking.resolvconf.package
];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
RuntimeDirectory = serviceName name;
RuntimeDirectoryMode = "0700";
UMask = "0077";
NoNewPrivileges = true;
LockPersonality = true;
ProtectClock = true;
ProtectControlGroups = true;
ProtectHostname = true;
ProtectKernelLogs = true;
RestrictRealtime = true;
RestrictSUIDSGID = true;
ExecStartPre = [ prepare ] ++ lib.optionals cfg.proxy.enable [ proxyBypassUp ];
ExecStart = start;
ExecStop = stop;
}
// lib.optionalAttrs cfg.proxy.enable {
ExecStopPost = proxyBypassDown;
};
};
profileAssertions = lib.concatMap (
name:
let
profile = profiles.${name};
settings = profile.settings;
obfuscation = if settings == null then null else settings.obfuscation;
in
[
{
assertion = builtins.match "^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$" name != null;
message = "proxy-suite: AmneziaWG profile '${name}' must be a safe 1-32 character identifier";
}
{
assertion = sourceCount profile == 1;
message = "proxy-suite: AmneziaWG profile '${name}' must set exactly one of configFile, vpnFile, vpn, or settings";
}
{
assertion = profile.vpnContainer == null || profile.vpn != null || profile.vpnFile != null;
message = "proxy-suite: AmneziaWG profile '${name}': vpnContainer requires vpn or vpnFile";
}
{
assertion = settings == null || settings.addresses != [ ];
message = "proxy-suite: AmneziaWG profile '${name}': declarative settings require at least one address";
}
{
assertion = settings == null || settings.peers != [ ];
message = "proxy-suite: AmneziaWG profile '${name}': declarative settings require at least one peer";
}
{
assertion =
settings == null || ((settings.privateKey != null) != (settings.privateKeyFile != null));
message = "proxy-suite: AmneziaWG profile '${name}': set exactly one of settings.privateKey or settings.privateKeyFile";
}
{
assertion =
obfuscation == null
|| ((obfuscation.headerProtectionKey != null) != (obfuscation.headerProtectionKeyFile != null))
|| (obfuscation.headerProtectionKey == null && obfuscation.headerProtectionKeyFile == null);
message = "proxy-suite: AmneziaWG profile '${name}': set at most one header-protection key source";
}
]
++ lib.optionals (settings != null) (
lib.imap0 (index: peer: {
assertion = peer.presharedKey == null || peer.presharedKeyFile == null;
message = "proxy-suite: AmneziaWG profile '${name}' peer ${toString index}: set at most one preshared key source";
}) settings.peers
)
) profileNames;
interfaceNames = map (name: profiles.${name}.interfaceName) profileNames;
autostartProfiles = builtins.filter (name: profiles.${name}.autostart) profileNames;
globalAutostartCount = builtins.length autostartProfiles + (if cfg.proxy.autostart != null then 1 else 0);
in
{
environment.systemPackages = [
awgCfg.toolsPackage
awgCfg.userspacePackage
];
boot.extraModulePackages = lib.optionals (awgCfg.kernelModulePackage != null) [
awgCfg.kernelModulePackage
];
systemd.services = lib.mkMerge [
(lib.mapAttrs' (
name: profile: lib.nameValuePair (serviceName name) (mkService name profile)
) profiles)
(lib.mkIf cfg.proxy.tun.enable {
proxy-suite-tun.conflicts = map (name: "${name}.service") serviceNames;
})
(lib.mkIf cfg.proxy.tproxy.enable {
proxy-suite-tproxy.conflicts = map (name: "${name}.service") serviceNames;
})
];
assertions = profileAssertions ++ [
{
assertion = profiles != { };
message = "proxy-suite: amneziaWg.enable requires at least one profile";
}
{
assertion = builtins.length interfaceNames == builtins.length (lib.unique interfaceNames);
message = "proxy-suite: AmneziaWG profile interface names must be unique";
}
{
assertion = builtins.length autostartProfiles <= 1;
message = "proxy-suite: at most one AmneziaWG profile may autostart";
}
{
assertion = globalAutostartCount <= 1;
message = "proxy-suite: at most one AmneziaWG, TUN, or TProxy global mode may autostart";
}
{
assertion =
!cfg.proxy.tun.enable
|| builtins.all (interface: interface != cfg.proxy.tun.interface) interfaceNames;
message = "proxy-suite: AmneziaWG interfaces must differ from proxy.tun.interface";
}
{
assertion =
!cfg.perAppRouting.tun.enable
|| builtins.all (interface: interface != cfg.perAppRouting.tun.interface) interfaceNames;
message = "proxy-suite: AmneziaWG interfaces must differ from perAppRouting.tun.interface";
}
];
}
+28
View File
@@ -0,0 +1,28 @@
# Renders every per-exit autoProxy rule-set file from the learned state.
#
# Shared by the socks start script and the prober. The start script needs it
# because sing-box refuses to start when a local rule-set path is missing, so
# every file it will be told about must exist first; the prober needs it to
# publish what it learns, which sing-box then picks up without a restart.
{ pkgs }:
pkgs.writeShellScript "proxy-suite-autoproxy-render" ''
set -euo pipefail
# $1 - probe-exits.json (index -> tag -> path), $2 - state.json
export PATH=${pkgs.lib.makeBinPath [
pkgs.coreutils
pkgs.jq
]}
jq -c '.[]' "$1" | while IFS= read -r exit; do
tag=$(jq -r '.tag' <<<"$exit")
path=$(jq -r '.path' <<<"$exit")
# Written aside and renamed into place: sing-box reloads on rename (as well
# as on in-place writes), and it never reads a half-written file.
jq -c --arg t "$tag" '
[(.domains // {}) | to_entries[] | select(.value.exit == $t) | .key] as $d
| {version: 1, rules: (if ($d | length) > 0 then [{domain_suffix: $d}] else [] end)}
' "$2" > "$path.tmp"
mv -f "$path.tmp" "$path"
done
''
@@ -0,0 +1,27 @@
# Folds sampler observations ($o: [{d, h, exit, slow, peak}]) into the state. $hits
# crawls on direct within a day make a domain owed an exit (.slowWant); once routed it
# is judged on that exit only: a fast transfer keeps it, two slow ones move it to the
# next. Never moved: censor verdicts (zapret's) and .slowSkip domains.
.slowHits = ((.slowHits // {}) | with_entries(select(.value.first + 86400 > $now)))
| .slowWant = (.slowWant // {})
| reduce $o[] as $x (.;
.domains[$x.d] as $r
| if $r.verdict == "slow" then
if $x.exit != $r.exit then .
elif $x.slow then .domains[$x.d].bad = (($r.bad // 0) + 1)
else .domains[$x.d] += {bad: 0, at: $now} end
elif $r.exit != null or $x.exit != "direct" or ($x.slow | not)
or .slowWant[$x.d] != null
or ((.slowSkip[$x.d] // 0) > $now)
or (.hosts[$x.h].verdict == "censor") then .
else
.slowHits[$x.h] = {n: ((.slowHits[$x.h].n // 0) + 1), first: (.slowHits[$x.h].first // $now)}
| if .slowHits[$x.h].n >= $hits then
.slowWant[$x.d] = {host: $x.h, tried: []} | del(.slowHits[$x.h])
else . end
end)
| ([.domains | to_entries[] | select(.value.verdict == "slow" and (.value.bad // 0) >= 2)]) as $moved
| reduce $moved[] as $e (.;
del(.domains[$e.key])
| .slowWant[$e.key] = {host: $e.value.host, tried: ($e.value.tried // [$e.value.exit])})
| .slowSkip = ((.slowSkip // {}) | with_entries(select(.value > $now)))
@@ -0,0 +1,19 @@
# Slurped Clash API /connections snapshots, a second apart, in; per host and exit that
# moved at least $min bytes: host<TAB>exit<TAB>slow|fast<TAB>peak. Slow never beat
# $below in any second (paced streams burst, so they read fast). Probe listeners are
# skipped; chains[0] is the carrying exit.
[.[] | [(.connections // [])[]
| select((.metadata.type // "") | test("/probe-in-") | not)
| {id, host: (.metadata.host // ""), exit: (.chains[0] // ""), d: .download}]]
| . as $s
| [range(1; length) as $i
| ($s[$i - 1] | map({key: .id, value: .d}) | from_entries) as $p
| $s[$i][] | select($p[.id] != null)
| {id, host, exit, delta: (.d - $p[.id])}]
| group_by(.id)
| map({host: .[0].host, exit: .[0].exit, total: (map(.delta) | add), peak: (map(.delta) | max)})
| map(select(.host != "" and .exit != "" and .total >= $min))
# One line per host and exit; its best connection decides.
| group_by(.host + "\t" + .exit)
| map(max_by(.peak))[]
| "\(.host)\t\(.exit)\t\(if .peak < $below then "slow" else "fast" end)\t\(.peak)"
+418
View File
@@ -0,0 +1,418 @@
# autoProxy: probes the destinations the inbound listener dials through each
# exit in turn and remembers the first exit that gets content. The probe itself
# is `proxy-ctl proxy auto probe --json`, so every verdict is reproducible by hand.
{
lib,
pkgs,
cfg,
proxyCtl,
autoProxyStateDir,
}:
let
apCfg = cfg.proxy.autoProxy;
render = import ./autoproxy-render.nix { inherit pkgs; };
bin = lib.makeBinPath [
pkgs.coreutils
pkgs.curl
pkgs.gawk
pkgs.gnugrep
pkgs.gnused
pkgs.jq
pkgs.systemd
pkgs.util-linux
proxyCtl
];
excludePattern = lib.concatStringsSep "|" (map lib.escapeRegex apCfg.exclude);
# Sets $clash_api (empty when the API is off) and $clash_auth (curl args).
clashApiBlock = ''
socks_config="$(dirname "$index")/config.json"
clash_api=$(jq -r '.experimental.clash_api.external_controller // empty' "$socks_config" 2>/dev/null || true)
clash_secret=$(jq -r '.experimental.clash_api.secret // empty' "$socks_config" 2>/dev/null || true)
clash_auth=()
[ -z "$clash_secret" ] || clash_auth=(-H "Authorization: Bearer $clash_secret")
'';
sampler = pkgs.writeShellScript "proxy-suite-autoproxy-sample" ''
set -euo pipefail
export PATH=${bin}
state_dir=''${AUTOPROXY_STATE_DIR:-${lib.escapeShellArg autoProxyStateDir}}
index=''${PROBE_EXITS_FILE:-/run/proxy-suite-socks/probe-exits.json}
${clashApiBlock}
if [ -z "$clash_api" ]; then
echo "sing-box has no Clash API (selection = \"first\"?); nothing to sample"
exit 0
fi
install -d -m 0750 "$state_dir"
# Eleven snapshots a second apart: ten one-second deltas per connection.
lines=$(
for i in $(seq 0 10); do
[ "$i" -eq 0 ] || sleep 1
curl -sS --noproxy '*' --max-time 1 "''${clash_auth[@]}" "http://$clash_api/connections" 2>/dev/null ||
echo '{}'
done | jq -s -r --argjson min ${toString (300 * 1024)} \
--argjson below ${toString (apCfg.slowBelowKiBps * 1024)} -f ${./autoproxy-slow-sample.jq} || true
)
[ -z "$lines" ] || printf '%s\n' "$lines" >> "$state_dir/samples"
'';
runner = pkgs.writeShellScript "proxy-suite-autoproxy-run" ''
set -euo pipefail
export PATH=${bin}
# --requests-only: just the `proxy-ctl proxy auto learn` requests.
mode=''${1:-full}
# Overridable to rehearse a run against a scratch copy; the units never set them.
state_dir=''${AUTOPROXY_STATE_DIR:-${lib.escapeShellArg autoProxyStateDir}}
export PROBE_EXITS_FILE=''${PROBE_EXITS_FILE:-/run/proxy-suite-socks/probe-exits.json}
index=$PROBE_EXITS_FILE
state="$state_dir/state.json"
requests="$state_dir/requests"
now=$(date +%s)
ttl=$(( ${toString apCfg.ttlDays} * 86400 ))
if [ ! -r "$index" ]; then
echo "no probe listeners - is proxy-suite-socks running with autoProxy on?"
exit 0
fi
install -d -m 0750 "$state_dir"
# Timer runs and learn requests take turns on the state.
exec 9> "$state_dir/lock"
flock 9
# Leftovers of a run that died partway; taken requests go back in line.
rm -f "$state_dir/verdicts.json" "$state_dir/proxied-domains.txt" "$state".?????? "$state_dir/samples.taking"
if [ -e "$requests.taking" ]; then
cat "$requests.taking" >> "$requests"
rm -f "$requests.taking"
fi
if [ -e "$state" ] && ! jq -e 'type == "object"' "$state" > /dev/null 2>&1; then
echo "$state is unreadable; set aside as $state.broken, starting fresh" >&2
mv -f "$state" "$state.broken"
fi
[ -s "$state" ] || echo '{"domains":{},"hosts":{},"exits":{},"backlog":{}}' > "$state"
# Written aside and renamed, so a killed run never truncates the state.
update() {
local tmp
tmp=$(mktemp "$state.XXXXXX")
if ! jq "$@" "$state" > "$tmp"; then
rm -f "$tmp"
echo "could not update $state; it is left as it was" >&2
return 1
fi
# mktemp makes it 0600; the state dir is 0750, so group-readable is enough.
chmod 0640 "$tmp"
mv -f "$tmp" "$state"
}
# $1 registrable domain, $2 host probed, $3 probe JSON. Routes apply to the
# whole domain (geo-blocks are drawn around sites); other verdicts only to
# the host probed.
record() {
update --arg d "$1" --arg h "$2" --argjson r "$3" --argjson now "$now" '
(if $r.verdict == "destination" then
.domains[$d] = {verdict: "destination", exit: $r.exit, host: $h,
path: ($r.path // "/"), at: $now}
else . end)
| .hosts[$h] = {
domain: $d,
verdict: ($r.verdict // "error"),
exit: (if $r.verdict == "destination" then $r.exit else null end),
at: $now
}
| del(.backlog[$h])'
}
# Prefixes each host line with "registrable-domain<TAB>".
# ponytail: last two labels, or three under a short list of two-label
# suffixes. Switch to the Public Suffix List if a domain gets merged wrongly.
to_reg() {
awk -F'\t' '
BEGIN {
n = split("co.uk org.uk ac.uk gov.uk com.au net.au org.au co.jp ne.jp or.jp com.br com.tr co.kr com.cn com.hk co.in co.za com.ua com.mx co.nz", s, " ")
for (i = 1; i <= n; i++) two[s[i]] = 1
}
{
n = split($1, l, ".")
if (n < 2) next
k = (n >= 3 && (l[n - 1] "." l[n]) in two) ? l[n - 2] "." l[n - 1] "." l[n] : l[n - 1] "." l[n]
print k "\t" $0
}'
}
# The pinned direct listener, since TUN/TProxy capture --noproxy too.
direct_url=$(jq -r '.[0] | "http://127.0.0.1:\(.port)"' "$index")
# --- 1. verdicts are about this host's address; drop them if it changed ---
egress=$(curl -sS -f --proxy "$direct_url" --max-time 10 https://api.ipify.org 2>/dev/null || true)
# An error page or a captive portal must not pass for a new address: anything
# that is not one discards every verdict this host learned.
[[ "$egress" =~ ^[0-9a-fA-F.:]+$ ]] || egress=""
if [ -n "$egress" ] && [ "$(jq -r '.egress // ""' "$state")" != "$egress" ]; then
echo "egress is now $egress; discarding everything learned for the old address"
update --arg e "$egress" \
'{egress: $e, domains: {}, hosts: {}, exits: {}, backlog: (.backlog // {}), lastRun: (.lastRun // 0)}'
fi
# --- 2. which network (AS) each exit leaves from, once per TTL ---
while IFS=$'\t' read -r tag port; do
at=$(jq -r --arg t "$tag" '.exits[$t].at // 0' "$state")
[ $(( now - at )) -ge "$ttl" ] || continue
info=$(curl -sS --proxy "http://127.0.0.1:$port" --max-time 10 https://ipinfo.io/json 2>/dev/null || true)
ip=$(jq -r '.ip // empty' <<<"$info" 2>/dev/null || true)
asn=$(jq -r '(.org // "") | split(" ")[0]' <<<"$info" 2>/dev/null || true)
[ -n "$ip" ] || continue
update --arg t "$tag" --arg ip "$ip" --arg asn "$asn" --argjson now "$now" \
'.exits[$t] = {ip: $ip, asn: $asn, at: $now}'
done < <(jq -r '.[] | "\(.tag)\t\(.port)"' "$index")
# Round 1: one exit per AS. Round 2, only if all refused: the rest.
rounds=$(jq -c --slurpfile s "$state" '
[.[1:][] | {tag, asn: ($s[0].exits[.tag].asn // "")}]
| reduce .[] as $e ({seen: {}, r1: [], r2: []};
if $e.asn == "" or (.seen[$e.asn] | not)
then .r1 += [$e.tag] | .seen[$e.asn] = true
else .r2 += [$e.tag] end)
| {r1: (.r1 | join(",")), r2: (.r2 | join(","))}' "$index")
round1=$(jq -r .r1 <<<"$rounds")
round2=$(jq -r .r2 <<<"$rounds")
walk() {
local out verdict
out=$(proxy-ctl proxy auto probe --json --exits "$round1" "$1" 2>/dev/null || echo '{}')
verdict=$(jq -r '.verdict // "error"' <<<"$out")
if { [ "$verdict" = both-fail ] || [ "$verdict" = unreachable ]; } && [ -n "$round2" ]; then
out=$(proxy-ctl proxy auto probe --json --exits "$round2" "$1" 2>/dev/null || echo '{}')
fi
printf '%s' "$out"
}
# Route changes take effect immediately, not at the end of the run.
publish() { ${render} "$index" "$state"; }
requeue=()
if [ "$mode" = full ]; then
# --- 3. re-check remembered exits, once per TTL ---
# Probed routes only; slowness routes are judged by the sampler (4b).
while IFS=$'\t' read -r dom host exit; do
out=$(proxy-ctl proxy auto probe --json --exits "$exit" "$host" 2>/dev/null || echo '{}')
verdict=$(jq -r '.verdict // "error"' <<<"$out")
if [ "$verdict" = destination ] && [ "$(jq -r '.exit // ""' <<<"$out")" = "$exit" ]; then
update --arg d "$dom" --argjson now "$now" '.domains[$d].at = $now'
elif [ "$verdict" = ok ]; then
echo "recheck $dom: reachable directly now, dropping $exit"
update --arg d "$dom" 'del(.domains[$d])'
record "$dom" "$host" "$out"
publish
else
echo "recheck $dom: $exit no longer works ($verdict), walking again"
update --arg d "$dom" 'del(.domains[$d])'
publish
requeue+=("$dom"$'\t'"$host")
fi
done < <(jq -r --argjson now "$now" --argjson every "$ttl" '
.domains | to_entries[]
| select(.value.verdict == "destination" and ($now - .value.at) >= $every)
| "\(.key)\t\(.value.host)\t\(.value.exit)"' "$state")
# --- 4. what clients dialled since the last run, counted per host ---
# Hit counts accumulate in a backlog that survives between runs.
last=$(jq -r '.lastRun // 0' "$state")
if [ "$last" -gt 0 ]; then since="@$last"; else since="-${apCfg.interval}"; fi
dialled=$(
journalctl -u proxy-suite-inbounds --since "$since" --no-pager -o cat 2>/dev/null |
sed -n 's/.* accepted tcp:\([a-zA-Z0-9._-]*\):[0-9]*.*/\1/p' |
grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' |
${lib.optionalString (excludePattern != "") "grep -vE '(^|\\.)(${excludePattern})$' |"}
to_reg || true
)
counts=$(
printf '%s\n' "$dialled" |
awk -F'\t' 'NF == 2 { n[$2]++; d[$2] = $1 } END { for (h in n) print h "\t" d[h] "\t" n[h] }' |
jq -R -s -c 'split("\n") | map(select(length > 0) | split("\t")
| {key: .[0], value: {domain: .[1], hits: (.[2] | tonumber)}}) | from_entries'
)
# Skipped: hosts of an already routed domain, hosts judged within the TTL.
# Dropped: entries older than the TTL, and those a route now covers.
update --argjson c "$counts" --argjson now "$now" --argjson ttl "$ttl" '
. as $s
| .lastRun = $now
| .backlog = (reduce ($c | to_entries[]) as $e (($s.backlog // {});
if ($s.domains[$e.value.domain].exit != null)
or ((($s.hosts[$e.key].at // 0) + $ttl) > $now)
then .
else .[$e.key] = {
domain: $e.value.domain,
hits: ((.[$e.key].hits // 0) + $e.value.hits),
first: (.[$e.key].first // $now)
} end))
| .backlog |= with_entries(select(.value.first + $ttl > $now
and $s.domains[.value.domain].exit == null))'
# --- 4b. what the sampler saw crawl (see autoproxy-slow-judge.jq) ---
if [ -s "$state_dir/samples" ]; then
mv -f "$state_dir/samples" "$state_dir/samples.taking"
obs=$(
grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}'$'\t' "$state_dir/samples.taking" |
${lib.optionalString (excludePattern != "") "grep -vE '(^|\\.)(${excludePattern})'$'\\t' |"}
to_reg |
jq -R -s -c 'split("\n") | map(select(length > 0) | split("\t")
| {d: .[0], h: .[1], exit: .[2], slow: (.[3] == "slow"), peak: (.[4] | tonumber)})' ||
echo '[]'
)
rm -f "$state_dir/samples.taking"
before=$(jq -c '.domains' "$state")
update --argjson o "$obs" --argjson now "$now" --argjson ttl "$ttl" --argjson hits 3 \
-f ${./autoproxy-slow-judge.jq}
# Each crawling destination gets the next exit, in probe order, that
# answers it as well as direct does (`probe --via`). None left: it
# stays direct for a TTL.
while IFS=$'\t' read -r dom host tried; do
was=''${tried##*,}
via=""
while IFS= read -r tag; do
[[ ",$tried," != *",$tag,"* ]] || continue
tried="''${tried:+$tried,}$tag"
if [ "$(proxy-ctl proxy auto probe --json --via "$tag" "$host" < /dev/null 2>/dev/null |
jq -r '.verdict // ""' 2>/dev/null)" = ok ]; then
via=$tag
break
fi
done < <(jq -r '.[1:][] | .tag' "$index")
if [ -n "$via" ]; then
echo "slow $dom: crawls ''${was:+via $was}''${was:-directly}, routed via $via"
update --arg d "$dom" --arg h "$host" --arg e "$via" --arg tried "$tried" --argjson now "$now" '
.domains[$d] = {verdict: "slow", exit: $e, host: $h, at: $now, tried: ($tried | split(","))}
| del(.slowWant[$d])'
else
echo "slow $dom: crawls ''${was:+via $was}''${was:-directly}, and no other exit reaches it; left direct"
update --arg d "$dom" --argjson until $(( now + ttl )) '.slowSkip[$d] = $until | del(.slowWant[$d])'
fi
done < <(jq -r '(.slowWant // {}) | to_entries[]
| "\(.key)\t\(.value.host)\t\(.value.tried | join(","))"' "$state")
[ "$(jq -c '.domains' "$state")" = "$before" ] || publish
fi
fi
# --- 5. probe: requests (uncapped), then broken routes, then the backlog ---
asked=()
if [ -s "$requests" ]; then
mv -f "$requests" "$requests.taking"
mapfile -t asked < <(grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' "$requests.taking" | to_reg || true)
rm -f "$requests.taking"
fi
backlog=()
if [ "$mode" = full ]; then
mapfile -t backlog < <(jq -r --argjson now "$now" --argjson ttl "$ttl" '
. as $s | (.backlog // {}) | to_entries
| map(select(($s.domains[.value.domain].exit == null)
and ((($s.hosts[.key].at // 0) + $ttl) <= $now)))
| sort_by(-.value.hits) | .[] | "\(.value.domain)\t\(.key)"' "$state")
fi
declare -A seen routed
probe_row() {
local dom=''${1%%$'\t'*} host=''${1#*$'\t'} out
{ [ -z "''${seen[$host]:-}" ] && [ -z "''${routed[$dom]:-}" ]; } || return 1
seen[$host]=1
out=$(walk "$host")
# A probe that failed to run is no verdict; the host is probed again.
if [ "$(jq -r '.verdict // "error"' <<<"$out")" = error ]; then
echo "probe $host -> error, not recorded"
return 0
fi
record "$dom" "$host" "$out"
if [ "$(jq -r '.verdict // ""' <<<"$out")" = destination ]; then
routed[$dom]=1
publish
fi
# A censor verdict names an exit that got through, but zapret owns it.
echo "probe $host -> $(jq -r '(.verdict // "error") + (if .verdict == "destination" then " via " + .exit
elif .exit then " (" + .exit + " reaches it; left to zapret)" else "" end)' <<<"$out")"
}
for row in "''${asked[@]}"; do probe_row "$row" || true; done
probed=0
for row in "''${requeue[@]}" "''${backlog[@]}"; do
[ "$probed" -lt ${toString apCfg.probesPerRun} ] || break
if probe_row "$row"; then probed=$(( probed + 1 )); fi
done
echo "probed ''${#asked[@]} requested and $probed queued host(s); $(jq '(.backlog // {}) | length' "$state") still waiting"
# sing-box reloads the rewritten rule-sets itself.
${render} "$index" "$state"
'';
# Group: `proxy-ctl proxy auto list|queue` reads state.json. Set on every unit that
# declares the directory - systemd re-applies the ownership on each start.
stateDirConfig = {
StateDirectory = "proxy-suite/autoproxy";
StateDirectoryMode = "0750";
}
// lib.optionalAttrs (cfg.userControl.allow != [ ]) { Group = cfg.userControl.group; };
mkUnit = description: args: {
inherit description;
after = [
"proxy-suite-socks.service"
"proxy-suite-inbounds.service"
];
wants = [ "proxy-suite-socks.service" ];
serviceConfig = {
Type = "oneshot";
ExecStart = "${runner}${args}";
}
// stateDirConfig;
};
in
{
systemd.services.proxy-suite-autoproxy =
mkUnit "proxy-suite - find the exit that reaches each destination, and remember it" "";
systemd.services.proxy-suite-autoproxy-learn =
mkUnit "proxy-suite - probe the destinations asked for with proxy-ctl proxy auto learn" " --requests-only";
systemd.services.proxy-suite-autoproxy-sample = lib.mkIf (apCfg.slowBelowKiBps > 0) {
description = "proxy-suite - watch live transfers for destinations that crawl directly";
after = [ "proxy-suite-socks.service" ];
serviceConfig = {
Type = "oneshot";
ExecStart = "${sampler}";
}
// stateDirConfig;
};
systemd.timers.proxy-suite-autoproxy-sample = lib.mkIf (apCfg.slowBelowKiBps > 0) {
description = "proxy-suite autoProxy transfer sampling";
wantedBy = [ "timers.target" ];
timerConfig = {
OnActiveSec = "1m";
OnUnitActiveSec = "1m";
AccuracySec = "5s";
};
};
systemd.timers.proxy-suite-autoproxy = {
description = "proxy-suite autoProxy probe schedule";
wantedBy = [ "timers.target" ];
timerConfig = {
# Not OnBootSec: after a rebuild restarts the timer, OnUnitActiveSec had
# nothing to count from and the prober never ran again.
OnActiveSec = "10m";
OnUnitActiveSec = apCfg.interval;
RandomizedDelaySec = "2m";
Persistent = true;
};
};
}
@@ -0,0 +1,87 @@
# XRay config template for the inbound service. Inbounds and pinned outbounds
# are injected at start, so no credential reaches the Nix store.
{
lib,
derived,
inboundRules,
mkDnsServer,
}:
let
inherit (derived)
proxyCfg
proxyInboundsNeedLocalProxy
proxyInboundsResolveInSingBox
;
localProxyAddress =
if
builtins.elem proxyCfg.listener.address [
"0.0.0.0"
"::"
""
]
then
"127.0.0.1"
else
proxyCfg.listener.address;
# The client stack's SOCKS listener; credentials are injected at start.
localProxyOutbound = lib.optional proxyInboundsNeedLocalProxy {
protocol = "socks";
tag = "proxy";
settings = {
servers = [
{
address = localProxyAddress;
port = proxyCfg.listener.port;
}
];
};
};
in
{
log.loglevel = "warning";
dns.servers = [
(mkDnsServer "remote" proxyCfg.dns.remote)
(mkDnsServer "local" proxyCfg.dns.local)
];
inbounds = [ ];
# Per-user counters for proxy-suite-inbound-stats, on loopback only.
stats = { };
api = {
tag = "api";
listen = "127.0.0.1:${toString derived.constants.inboundStatsApiPort}";
services = [ "StatsService" ];
};
policy.levels."0" = {
statsUserUplink = true;
statsUserDownlink = true;
};
outbounds = localProxyOutbound ++ [
{
protocol = "freedom";
tag = "direct";
settings = { };
}
{
protocol = "blackhole";
tag = "block";
settings = { };
}
];
routing = {
# AsIs where sing-box dials: resolving here made every new site wait on a
# lookup through the proxy, and sing-box enforces blockPrivate after its
# own. Where XRay dials itself it must resolve, and IPOnDemand: under
# IPIfNonMatch the network-only final rule matches names unresolved.
domainStrategy = if proxyInboundsResolveInSingBox then "AsIs" else "IPOnDemand";
domainMatcher = "hybrid";
rules = inboundRules.xrayInboundRules;
};
}
@@ -0,0 +1,195 @@
# Build-time sing-box backend configuration templates.
# Proxy outbounds are injected at service start time, not here.
{
lib,
derived,
rules,
}:
let
constants = derived.constants;
inherit (derived)
proxyCfg
singBoxCfg
hybridEnabled
globalTun
globalTproxy
clashApiEnabled
perAppRoutingTun
;
inherit (constants)
xrayDnsBridgePorts
;
direct = rules.direct;
defaultTunAutoRouteTableIndex = constants.tunAutoRouteTableIndex;
defaultTunAutoRouteRulePriority = constants.tunAutoRouteRulePriority;
mkDnsServer =
tag: upstream: detour:
{
inherit tag;
type = upstream.type;
server = upstream.address;
server_port = upstream.port;
}
// lib.optionalAttrs (detour != null) { inherit detour; };
mkDnsConfig =
{
localDetour ? null,
}:
{
servers = [
(mkDnsServer "remote" proxyCfg.dns.remote "proxy")
(mkDnsServer "local" proxyCfg.dns.local localDetour)
];
rules =
lib.optional (builtins.elem "google" proxyCfg.routing.proxy.geosites) {
rule_set = [ "geosite-google" ];
server = "remote";
}
++ lib.optional (direct.geosites != [ ]) {
rule_set = map (s: "geosite-${s}") direct.geosites;
server = "local";
};
final = if (proxyCfg.routing.default == "proxy") then "remote" else "local";
};
xrayDnsBridgeHijackRule = {
inbound = [ "xray-dns-in" ];
network = [
"tcp"
"udp"
];
action = "hijack-dns";
};
clashApiBlock = lib.optionalAttrs clashApiEnabled {
experimental.clash_api.external_controller =
"127.0.0.1:${toString singBoxCfg.clashApiPort}";
};
mkConfig =
{
enableMixed ? false,
enableTProxy ? false,
enableTun ? false,
tunInterface ? globalTun.interface,
tunAddress ? globalTun.address,
tunMtu ? globalTun.mtu,
tunAutoRoute ? true,
tunAutoRouteTableIndex ? defaultTunAutoRouteTableIndex,
tunAutoRouteRuleIndex ? defaultTunAutoRouteRulePriority,
tunAutoRedirect ? true,
tunStrictRoute ? true,
forceLocalDnsViaProxy ? false,
useOutboundRoutingMark ? false,
enableClashApi ? clashApiEnabled,
enableXrayDnsBridge ? hybridEnabled,
xrayDnsBridgePort ? xrayDnsBridgePorts.socks,
}:
{
log.level = "warn";
dns = mkDnsConfig {
localDetour = if forceLocalDnsViaProxy then "proxy" else null;
};
inbounds =
lib.optional enableXrayDnsBridge {
type = "direct";
tag = "xray-dns-in";
listen = "127.0.0.1";
listen_port = xrayDnsBridgePort;
}
++ lib.optional enableMixed {
type = "mixed";
tag = "mixed-in";
listen = proxyCfg.listener.address;
listen_port = proxyCfg.listener.port;
}
++ lib.optional enableTProxy {
type = "tproxy";
tag = "tproxy-in";
listen = "127.0.0.1";
listen_port = globalTproxy.port;
}
++ lib.optional enableTun (
{
type = "tun";
tag = "tun-in";
interface_name = tunInterface;
address = [ tunAddress ];
mtu = tunMtu;
auto_route = tunAutoRoute;
auto_redirect = tunAutoRedirect;
strict_route = tunStrictRoute;
stack = "mixed";
}
// lib.optionalAttrs tunAutoRoute {
iproute2_table_index = tunAutoRouteTableIndex;
iproute2_rule_index = tunAutoRouteRuleIndex;
}
);
outbounds = [
(
{
type = "direct";
tag = "direct";
}
// lib.optionalAttrs useOutboundRoutingMark { routing_mark = globalTproxy.proxyMark; }
)
{
type = "block";
tag = "block";
}
];
route = {
default_domain_resolver = "local";
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets;
rules = lib.optionals enableXrayDnsBridge [ xrayDnsBridgeHijackRule ] ++ rules.singBoxRoutingRules;
final = if (proxyCfg.routing.default == "proxy") then "proxy" else "direct";
}
// lib.optionalAttrs (enableTun && tunAutoRoute) {
auto_detect_interface = true;
};
}
// lib.optionalAttrs enableClashApi clashApiBlock;
in
{
tproxy = mkConfig {
enableMixed = true;
enableTProxy = true;
useOutboundRoutingMark = true;
xrayDnsBridgePort = xrayDnsBridgePorts.socks;
};
tun = mkConfig {
enableTun = true;
tunInterface = globalTun.interface;
tunAddress = globalTun.address;
tunMtu = globalTun.mtu;
tunAutoRoute = true;
tunAutoRedirect = true;
tunStrictRoute = true;
forceLocalDnsViaProxy = false;
enableClashApi = false;
xrayDnsBridgePort = xrayDnsBridgePorts.tun;
};
perAppTun = mkConfig {
enableTun = true;
tunInterface = perAppRoutingTun.interface;
tunAddress = perAppRoutingTun.address;
tunMtu = perAppRoutingTun.mtu;
tunAutoRoute = false;
tunAutoRedirect = false;
tunStrictRoute = false;
forceLocalDnsViaProxy = false;
useOutboundRoutingMark = globalTproxy.enable;
enableClashApi = false;
xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun;
};
}
@@ -0,0 +1,288 @@
# Build-time XRay backend configuration templates.
# Proxy outbounds are injected at service start time, not here.
{
lib,
derived,
rules,
}:
let
constants = derived.constants;
inherit (derived)
proxyCfg
globalTun
globalTproxy
perAppRoutingTun
;
inherit (constants)
xrayGlobalTunIPv6Address
xrayPerAppTunIPv6Address
;
fakeDnsPools = [
{
ipPool = "198.18.0.0/15";
poolSize = 32768;
}
{
ipPool = "fc00::/18";
poolSize = 32768;
}
];
dnsAddress =
upstream: if upstream.type == "tcp" then "tcp://${upstream.address}" else upstream.address;
mkDnsServer = tag: upstream: {
address = dnsAddress upstream;
inherit tag;
port = upstream.port;
queryStrategy = "UseIP";
};
mkTunDnsConfig =
{
preferRemote ? (proxyCfg.routing.default == "proxy"),
}:
let
primaryTag = if preferRemote then "remote" else "local";
secondaryTag = if preferRemote then "local" else "remote";
primaryUpstream = if preferRemote then proxyCfg.dns.remote else proxyCfg.dns.local;
secondaryUpstream = if preferRemote then proxyCfg.dns.local else proxyCfg.dns.remote;
in
{
queryStrategy = "UseIP";
tag = "dns-in";
servers = [
{
address = "fakedns";
tag = "fakedns";
}
(mkDnsServer primaryTag primaryUpstream)
(mkDnsServer secondaryTag secondaryUpstream)
];
};
mkSniffing =
{
fakeDnsOnly ? false,
}:
if fakeDnsOnly then
{
enabled = true;
destOverride = [ "fakedns" ];
metadataOnly = true;
}
else
{
enabled = true;
destOverride = [
"http"
"tls"
"quic"
];
};
standardSniffing = mkSniffing { };
tunDnsHijackRule = {
type = "field";
inboundTag = [ "tun-in" ];
network = "tcp,udp";
port = 53;
outboundTag = "dns-out";
ruleTag = "dns-hijack";
};
tunDnsUpstreamRule = {
type = "field";
inboundTag = [ "dns-in" ];
network = "tcp,udp";
outboundTag = "direct";
ruleTag = "dns-upstream-direct";
};
finalRule =
tag:
{
type = "field";
network = "tcp,udp";
ruleTag = "final-default";
}
// (
if tag == "proxy" && proxyCfg.selection == "urltest" then
{ balancerTag = "proxy"; }
else
{ outboundTag = tag; }
);
directOutbound =
useOutboundRoutingMark:
{
protocol = "freedom";
tag = "direct";
settings = { };
}
// lib.optionalAttrs useOutboundRoutingMark {
streamSettings.sockopt.mark = globalTproxy.proxyMark;
};
mkConfig =
{
enableMixed ? false,
enableTProxy ? false,
enableTun ? false,
tunInterface ? globalTun.interface,
tunAddress ? globalTun.address,
tunIPv6Address ? null,
tunMtu ? globalTun.mtu,
useOutboundRoutingMark ? false,
enableUrlTest ? proxyCfg.selection == "urltest",
domainStrategy ? "IPIfNonMatch",
enableTunFakeDns ? false,
}:
let
tunDnsServers = [
(if (proxyCfg.routing.default == "proxy") then proxyCfg.dns.remote.address else proxyCfg.dns.local.address)
(if (proxyCfg.routing.default == "proxy") then proxyCfg.dns.local.address else proxyCfg.dns.remote.address)
];
tunSniffing = mkSniffing { fakeDnsOnly = enableTunFakeDns; };
dnsConfig =
if enableTunFakeDns then
mkTunDnsConfig { }
else
{
servers = [
(mkDnsServer "remote" proxyCfg.dns.remote)
(mkDnsServer "local" proxyCfg.dns.local)
];
};
tunOutbounds = lib.optionals enableTunFakeDns [
{
protocol = "dns";
tag = "dns-out";
settings = {
userLevel = 0;
rules = [
{
action = "direct";
qType = "2-27,29-65535";
}
];
};
}
];
routingRules =
lib.optionals enableTunFakeDns [
tunDnsUpstreamRule
tunDnsHijackRule
]
++ rules.xrayRoutingRules
++ [ (finalRule (if (proxyCfg.routing.default == "proxy") then "proxy" else "direct")) ];
in
{
log.loglevel = "warning";
dns = dnsConfig;
inbounds =
lib.optional enableMixed {
tag = "mixed-in";
protocol = "socks";
listen = proxyCfg.listener.address;
port = proxyCfg.listener.port;
settings = {
auth = "noauth";
udp = true;
ip = proxyCfg.listener.address;
};
sniffing = standardSniffing;
}
++ lib.optional enableTProxy {
tag = "tproxy-in";
protocol = "tunnel";
listen = "127.0.0.1";
port = globalTproxy.port;
settings = {
allowedNetwork = "tcp,udp";
followRedirect = true;
};
streamSettings.sockopt.tproxy = "tproxy";
sniffing = standardSniffing;
}
++ lib.optional enableTun {
tag = "tun-in";
protocol = "tun";
settings = {
name = tunInterface;
mtu = tunMtu;
gateway = [ tunAddress ] ++ lib.optionals (tunIPv6Address != null) [ tunIPv6Address ];
dns = tunDnsServers;
userLevel = 0;
autoOutboundsInterface = "auto";
};
sniffing = tunSniffing;
};
outbounds = tunOutbounds ++ [
(directOutbound useOutboundRoutingMark)
{
protocol = "blackhole";
tag = "block";
settings = { };
}
];
routing = {
domainStrategy = domainStrategy;
domainMatcher = "hybrid";
rules = routingRules;
}
// lib.optionalAttrs enableUrlTest {
balancers = [
{
tag = "proxy";
selector = [ "proxy-suite-ob-" ];
strategy = {
type = "leastPing";
};
}
];
};
}
// lib.optionalAttrs enableUrlTest {
observatory = {
subjectSelector = [ "proxy-suite-ob-" ];
probeUrl = proxyCfg.urlTest.url;
probeInterval = proxyCfg.urlTest.interval;
};
}
// lib.optionalAttrs enableTunFakeDns { fakedns = fakeDnsPools; };
in
{
# Reused by the server-side inbound template, which builds a different config
# shape out of the same backend primitives.
inherit mkDnsServer;
tproxy = mkConfig {
enableMixed = true;
enableTProxy = true;
useOutboundRoutingMark = true;
};
tun = mkConfig {
enableTun = true;
tunInterface = globalTun.interface;
tunAddress = globalTun.address;
tunIPv6Address = xrayGlobalTunIPv6Address;
tunMtu = globalTun.mtu;
useOutboundRoutingMark = true;
enableTunFakeDns = true;
};
perAppTun = mkConfig {
enableTun = true;
tunInterface = perAppRoutingTun.interface;
tunAddress = perAppRoutingTun.address;
tunIPv6Address = xrayPerAppTunIPv6Address;
tunMtu = perAppRoutingTun.mtu;
useOutboundRoutingMark = true;
enableTunFakeDns = true;
};
}
+60 -452
View File
@@ -9,472 +9,78 @@
let
derived = import ./derived.nix { inherit lib cfg; };
inherit (derived)
proxyCfg
singBoxCfg
xrayEnabled
hybridEnabled
pureXrayEnabled
globalTun
globalTproxy
clashApiEnabled
;
perAppTun = derived.perAppRoutingTun;
direct = rules.direct;
xrayGlobalTunIPv6Address = "fd66:19::1/64";
xrayPerAppTunIPv6Address = "fd66:20::1/64";
xrayFakeDnsPools = [
{
ipPool = "198.18.0.0/15";
poolSize = 32768;
}
{
ipPool = "fc00::/18";
poolSize = 32768;
}
];
stripCidr = cidr: builtins.head (lib.splitString "/" cidr);
mkSingBoxDnsServer =
tag: upstream: detour:
{
inherit tag;
type = upstream.type;
server = upstream.address;
server_port = upstream.port;
}
// lib.optionalAttrs (detour != null) { inherit detour; };
mkSingBoxDnsConfig =
{
localDetour ? null,
}:
{
servers = [
(mkSingBoxDnsServer "remote" proxyCfg.dns.remote "proxy")
(mkSingBoxDnsServer "local" proxyCfg.dns.local localDetour)
];
rules =
lib.optional (builtins.elem "google" proxyCfg.routing.proxy.geosites) {
rule_set = [ "geosite-google" ];
server = "remote";
}
++ lib.optional (direct.geosites != [ ]) {
rule_set = map (s: "geosite-${s}") direct.geosites;
server = "local";
};
final = if proxyCfg.proxyByDefault then "remote" else "local";
};
xrayDnsBridgeHijackRule = {
inbound = [ "xray-dns-in" ];
network = [
"tcp"
"udp"
];
action = "hijack-dns";
singBoxTemplates = import ./config-templates/sing-box.nix {
inherit
lib
derived
rules
;
};
xrayTemplates = import ./config-templates/xray.nix {
inherit
lib
derived
rules
;
};
clashApiBlock = lib.optionalAttrs clashApiEnabled {
experimental = {
clash_api = {
external_controller = "127.0.0.1:${toString singBoxCfg.clashApiPort}";
};
};
inboundRules = import ./rules/proxy-inbounds.nix {
inherit lib;
inherit (derived) proxyInboundsCfg proxyInbounds;
inherit (rules) zapretDirectRules;
};
mkSingBoxConfig =
{
enableMixed ? false,
enableTProxy ? false,
enableTun ? false,
tunInterface ? globalTun.interface,
tunAddress ? globalTun.address,
tunMtu ? globalTun.mtu,
tunAutoRoute ? true,
tunAutoRouteTableIndex ? 2022,
tunAutoRouteRuleIndex ? 9000,
tunAutoRedirect ? true,
tunStrictRoute ? true,
forceLocalDnsViaProxy ? false,
useOutboundRoutingMark ? false,
enableClashApi ? clashApiEnabled,
enableXrayDnsBridge ? hybridEnabled,
xrayDnsBridgePort ? 18533,
}:
{
log.level = "warn";
dns = mkSingBoxDnsConfig {
localDetour = if forceLocalDnsViaProxy then "proxy" else null;
};
inbounds =
lib.optional enableXrayDnsBridge {
type = "direct";
tag = "xray-dns-in";
listen = "127.0.0.1";
listen_port = xrayDnsBridgePort;
}
++ lib.optional enableMixed {
type = "mixed";
tag = "mixed-in";
listen = proxyCfg.listenAddress;
listen_port = proxyCfg.port;
}
++ lib.optional enableTProxy {
type = "tproxy";
tag = "tproxy-in";
listen = "127.0.0.1";
listen_port = globalTproxy.port;
}
++ lib.optional enableTun (
{
type = "tun";
tag = "tun-in";
interface_name = tunInterface;
address = [ tunAddress ];
mtu = tunMtu;
auto_route = tunAutoRoute;
auto_redirect = tunAutoRedirect;
strict_route = tunStrictRoute;
stack = "mixed";
}
// lib.optionalAttrs tunAutoRoute {
iproute2_table_index = tunAutoRouteTableIndex;
iproute2_rule_index = tunAutoRouteRuleIndex;
}
);
outbounds = [
(
{
type = "direct";
tag = "direct";
}
// lib.optionalAttrs useOutboundRoutingMark { routing_mark = globalTproxy.proxyMark; }
)
{
type = "block";
tag = "block";
}
];
route = {
default_domain_resolver = "local";
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets;
rules = lib.optionals enableXrayDnsBridge [ xrayDnsBridgeHijackRule ] ++ rules.singBoxRoutingRules;
final = if proxyCfg.proxyByDefault then "proxy" else "direct";
}
// lib.optionalAttrs (enableTun && tunAutoRoute) {
auto_detect_interface = true;
};
}
// lib.optionalAttrs enableClashApi clashApiBlock;
xrayDnsAddress =
upstream: if upstream.type == "tcp" then "tcp://${upstream.address}" else upstream.address;
mkXrayDnsServer = tag: upstream: {
address = xrayDnsAddress upstream;
inherit tag;
port = upstream.port;
queryStrategy = "UseIP";
proxyInboundsTemplate = import ./config-templates/proxy-inbounds.nix {
inherit lib derived inboundRules;
inherit (xrayTemplates) mkDnsServer;
};
mkXraySniffing =
{
fakeDnsOnly ? false,
}:
if fakeDnsOnly then
{
enabled = true;
destOverride = [ "fakedns" ];
metadataOnly = true;
}
else
{
enabled = true;
destOverride = [
"http"
"tls"
"quic"
];
};
xraySniffing = mkXraySniffing { };
mkXrayTunDnsConfig =
{
preferRemote ? proxyCfg.proxyByDefault,
}:
let
primaryTag = if preferRemote then "remote" else "local";
secondaryTag = if preferRemote then "local" else "remote";
primaryUpstream = if preferRemote then proxyCfg.dns.remote else proxyCfg.dns.local;
secondaryUpstream = if preferRemote then proxyCfg.dns.local else proxyCfg.dns.remote;
in
{
queryStrategy = "UseIP";
tag = "dns-in";
servers = [
{
address = "fakedns";
tag = "fakedns";
}
(mkXrayDnsServer primaryTag primaryUpstream)
(mkXrayDnsServer secondaryTag secondaryUpstream)
];
};
xrayTunDnsHijackRule = {
type = "field";
inboundTag = [ "tun-in" ];
network = "tcp,udp";
port = 53;
outboundTag = "dns-out";
ruleTag = "dns-hijack";
# Listener specification handed to build-inbound.py at service start. Secrets
# appear here only as paths; the script reads them at runtime.
proxyInboundsSpec = {
serverAddress = derived.proxyInboundsCfg.serverAddress;
shareLinks = derived.proxyInboundsCfg.shareLinks;
listeners = map (ib: {
inherit (ib) tag;
inherit (ib.listener)
type
port
sharePort
users
flow
method
transport
tls
reality
xrayJson
jsonFile
;
listen = ib.listener.address;
}) derived.proxyInbounds;
};
xrayTunDnsUpstreamRule = {
type = "field";
inboundTag = [ "dns-in" ];
network = "tcp,udp";
outboundTag = "direct";
ruleTag = "dns-upstream-direct";
};
selectedTemplates = if derived.pureXrayEnabled then xrayTemplates else singBoxTemplates;
routeModeRules =
if derived.pureXrayEnabled then rules.xrayRouteModeRules else rules.singBoxRouteModeRules;
xrayFinalRule =
tag:
{
type = "field";
network = "tcp,udp";
ruleTag = "final-default";
}
// (
if tag == "proxy" && proxyCfg.selection == "urltest" then
{ balancerTag = "proxy"; }
else
{ outboundTag = tag; }
);
xrayRouteRules = rules.xrayRoutingRules ++ [
(xrayFinalRule (if proxyCfg.proxyByDefault then "proxy" else "direct"))
];
xrayDirectOutbound =
useOutboundRoutingMark:
{
protocol = "freedom";
tag = "direct";
settings = { };
}
// lib.optionalAttrs useOutboundRoutingMark {
streamSettings.sockopt.mark = globalTproxy.proxyMark;
};
mkXrayConfig =
{
enableMixed ? false,
enableTProxy ? false,
enableTun ? false,
tunInterface ? globalTun.interface,
tunAddress ? globalTun.address,
tunIPv6Address ? null,
tunMtu ? globalTun.mtu,
useOutboundRoutingMark ? false,
enableUrlTest ? proxyCfg.selection == "urltest",
domainStrategy ? "IPIfNonMatch",
enableTunFakeDns ? false,
}:
let
tunDnsServers = [
(if proxyCfg.proxyByDefault then proxyCfg.dns.remote.address else proxyCfg.dns.local.address)
(if proxyCfg.proxyByDefault then proxyCfg.dns.local.address else proxyCfg.dns.remote.address)
];
xrayTunSniffing = mkXraySniffing { fakeDnsOnly = enableTunFakeDns; };
xrayDnsConfig =
if enableTunFakeDns then
mkXrayTunDnsConfig { }
else
{
servers = [
(mkXrayDnsServer "remote" proxyCfg.dns.remote)
(mkXrayDnsServer "local" proxyCfg.dns.local)
];
};
xrayTunOutbounds = lib.optionals enableTunFakeDns [
{
protocol = "dns";
tag = "dns-out";
settings = {
userLevel = 0;
rules = [
{
action = "direct";
qType = "2-27,29-65535";
}
];
};
}
];
xrayRoutingRules =
lib.optionals enableTunFakeDns [
xrayTunDnsUpstreamRule
xrayTunDnsHijackRule
]
++ rules.xrayRoutingRules
++ [ (xrayFinalRule (if proxyCfg.proxyByDefault then "proxy" else "direct")) ];
in
{
log.loglevel = "warning";
dns = xrayDnsConfig;
inbounds =
lib.optional enableMixed {
tag = "mixed-in";
protocol = "socks";
listen = proxyCfg.listenAddress;
port = proxyCfg.port;
settings = {
auth = "noauth";
udp = true;
ip = proxyCfg.listenAddress;
};
sniffing = xraySniffing;
}
++ lib.optional enableTProxy {
tag = "tproxy-in";
protocol = "tunnel";
listen = "127.0.0.1";
port = globalTproxy.port;
settings = {
allowedNetwork = "tcp,udp";
followRedirect = true;
};
streamSettings.sockopt.tproxy = "tproxy";
sniffing = xraySniffing;
}
++ lib.optional enableTun {
tag = "tun-in";
protocol = "tun";
settings = {
name = tunInterface;
mtu = tunMtu;
gateway = [ tunAddress ] ++ lib.optionals (tunIPv6Address != null) [ tunIPv6Address ];
dns = tunDnsServers;
userLevel = 0;
autoOutboundsInterface = "auto";
};
sniffing = xrayTunSniffing;
};
outbounds = xrayTunOutbounds ++ [
(xrayDirectOutbound useOutboundRoutingMark)
{
protocol = "blackhole";
tag = "block";
settings = { };
}
];
routing = {
domainStrategy = domainStrategy;
domainMatcher = "hybrid";
rules = xrayRoutingRules;
}
// lib.optionalAttrs enableUrlTest {
balancers = [
{
tag = "proxy";
selector = [ "proxy-suite-ob-" ];
strategy = {
type = "leastPing";
};
}
];
};
}
// lib.optionalAttrs enableUrlTest {
observatory = {
subjectSelector = [ "proxy-suite-ob-" ];
probeUrl = proxyCfg.urlTest.url;
probeInterval = proxyCfg.urlTest.interval;
};
}
// lib.optionalAttrs enableTunFakeDns { fakedns = xrayFakeDnsPools; };
singBoxTproxyTemplate = mkSingBoxConfig {
enableMixed = true;
enableTProxy = true;
useOutboundRoutingMark = true;
xrayDnsBridgePort = 18533;
};
singBoxTunTemplate = mkSingBoxConfig {
enableTun = true;
tunInterface = globalTun.interface;
tunAddress = globalTun.address;
tunMtu = globalTun.mtu;
tunAutoRoute = true;
tunAutoRedirect = true;
tunStrictRoute = true;
forceLocalDnsViaProxy = false;
enableClashApi = false;
xrayDnsBridgePort = 18534;
};
singBoxPerAppTunTemplate = mkSingBoxConfig {
enableTun = true;
tunInterface = perAppTun.interface;
tunAddress = perAppTun.address;
tunMtu = perAppTun.mtu;
tunAutoRoute = false;
tunAutoRedirect = false;
tunStrictRoute = false;
forceLocalDnsViaProxy = false;
useOutboundRoutingMark = globalTproxy.enable;
enableClashApi = false;
xrayDnsBridgePort = 18535;
};
xrayTproxyTemplate = mkXrayConfig {
enableMixed = true;
enableTProxy = true;
useOutboundRoutingMark = true;
};
xrayTunTemplate = mkXrayConfig {
enableTun = true;
tunInterface = globalTun.interface;
tunAddress = globalTun.address;
tunIPv6Address = xrayGlobalTunIPv6Address;
tunMtu = globalTun.mtu;
useOutboundRoutingMark = true;
enableTunFakeDns = true;
};
xrayPerAppTunTemplate = mkXrayConfig {
enableTun = true;
tunInterface = perAppTun.interface;
tunAddress = perAppTun.address;
tunIPv6Address = xrayPerAppTunIPv6Address;
tunMtu = perAppTun.mtu;
useOutboundRoutingMark = true;
enableTunFakeDns = true;
};
tproxyTemplate = if pureXrayEnabled then xrayTproxyTemplate else singBoxTproxyTemplate;
tunTemplate = if pureXrayEnabled then xrayTunTemplate else singBoxTunTemplate;
perAppTunTemplate = if pureXrayEnabled then xrayPerAppTunTemplate else singBoxPerAppTunTemplate;
routeModeRules = if pureXrayEnabled then rules.xrayRouteModeRules else rules.singBoxRouteModeRules;
tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (builtins.toJSON tproxyTemplate);
tunFile = pkgs.writeText "proxy-suite-tun-template.json" (builtins.toJSON tunTemplate);
tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (
builtins.toJSON selectedTemplates.tproxy
);
tunFile = pkgs.writeText "proxy-suite-tun-template.json" (
builtins.toJSON selectedTemplates.tun
);
perAppTunFile = pkgs.writeText "proxy-suite-per-app-tun-template.json" (
builtins.toJSON perAppTunTemplate
builtins.toJSON selectedTemplates.perAppTun
);
routeModeRulesFile = pkgs.writeText "proxy-suite-route-mode-rules.json" (
builtins.toJSON routeModeRules
);
proxyInboundsFile = pkgs.writeText "proxy-suite-inbounds-template.json" (
builtins.toJSON proxyInboundsTemplate
);
proxyInboundsSpecFile = pkgs.writeText "proxy-suite-inbounds-spec.json" (
builtins.toJSON proxyInboundsSpec
);
in
{
inherit
@@ -482,5 +88,7 @@ in
tunFile
perAppTunFile
routeModeRulesFile
proxyInboundsFile
proxyInboundsSpecFile
;
}
+119 -59
View File
@@ -1,6 +1,7 @@
# Factory function – receives the zapret flake, returns a NixOS module.
# This lets consumers add a single flake input and get everything transitively.
{ zapret }:
# Factory function – receives the zapret flake and this flake's own nixpkgs,
# returns a NixOS module. This lets consumers add a single flake input and get
# everything transitively.
{ zapret, nixpkgs }:
{
config,
@@ -13,76 +14,49 @@ let
cfg = config.services.proxy-suite;
packages = import ../../pkgs/default.nix { inherit pkgs; };
nftr = import ./nftables.nix { inherit lib pkgs cfg; };
derived = import ./derived.nix { inherit lib cfg; };
in
{
imports = [
./options
];
config = lib.mkIf cfg.enable (
let
rules = import ./rules.nix {
inherit
lib
pkgs
cfg
zapret
;
};
configs = import ./config.nix {
inherit
lib
pkgs
cfg
rules
;
};
in
lib.mkMerge [
(import ./service {
inherit
config
lib
pkgs
packages
cfg
;
inherit (configs) tproxyFile tunFile perAppTunFile routeModeRulesFile;
inherit (nftr)
nftablesRulesFile
perAppTproxyRulesFile
perAppZapretRulesFile
perAppTunChainFile
ip
nft
;
})
config = lib.mkMerge [
{
# xray and sing-box default to this flake's own nixpkgs (redirect it
# with inputs.nixpkgs.follows), not the system's: a stable release lags
# both by months, and current xray needs a newer Go than stable ships.
_module.args.proxySuiteUpstream =
let
upstream = nixpkgs.legacyPackages.${pkgs.stdenv.hostPlatform.system};
in
{
xray = import ../../pkgs/xray.nix { pkgs = upstream; };
inherit (upstream) sing-box;
};
}
(lib.mkIf (cfg.zapret.enable || cfg.zapret.perApp.enable) (
import ./zapret.nix {
(lib.mkIf cfg.enable (
let
rules = import ./rules.nix {
inherit
lib
pkgs
cfg
zapret
;
inherit (nftr) perAppZapretRulesFile nft;
}
))
(lib.mkIf cfg.tgWsProxy.enable (
import ./tg-ws-proxy.nix {
};
configs = import ./config.nix {
inherit
lib
pkgs
packages
cfg
rules
;
}
))
(lib.mkIf cfg.tray.enable (
import ./tray.nix {
};
in
lib.mkMerge [
(import ./service {
inherit
config
lib
@@ -90,8 +64,94 @@ in
packages
cfg
;
}
))
]
);
inherit (configs)
tproxyFile
tunFile
perAppTunFile
routeModeRulesFile
proxyInboundsFile
proxyInboundsSpecFile
;
inherit (nftr)
nftablesRulesFile
perAppTproxyRulesFile
perAppZapretRulesFile
perAppTunChainFile
ip
nft
;
})
(lib.mkIf (cfg.zapret.engine == "zapret-discord-youtube" && (cfg.zapret.enable || cfg.perAppRouting.zapret.enable)) (
import ./zapret.nix {
inherit
lib
pkgs
cfg
zapret
;
inherit (nftr) perAppZapretRulesFile nft;
}
))
(lib.mkIf (cfg.zapret.engine == "zapret2" && (cfg.zapret.enable || cfg.perAppRouting.zapret.enable)) (
import ./zapret2.nix {
inherit
lib
pkgs
cfg
packages
;
inherit (nftr) perAppZapretRulesFile nft;
}
))
(lib.mkIf cfg.tgWsProxy.enable (
import ./tg-ws-proxy.nix {
inherit
lib
pkgs
packages
cfg
;
}
))
# SingBox dials SSH natively, so it needs no OpenSSH unit. XRay has no SSH
# outbound, and a standalone tunnel has no backend at all, so both keep it.
(lib.mkIf derived.sshProxyUnitEnabled (
import ./ssh-proxy.nix {
inherit
lib
pkgs
cfg
;
}
))
(lib.mkIf cfg.amneziaWg.enable (
import ./amnezia-wg.nix {
inherit
config
lib
pkgs
cfg
;
}
))
(lib.mkIf cfg.tray.enable (
import ./tray.nix {
inherit
config
lib
pkgs
packages
cfg
;
}
))
]
))
];
}
+166 -23
View File
@@ -6,36 +6,105 @@
let
proxyCfg = cfg.proxy;
singBoxCfg = proxyCfg // {
enable = proxyCfg.enable && proxyCfg.singBox.enable;
enable = singBoxEnabled;
package = proxyCfg.singBox.package;
clashApiPort = proxyCfg.singBox.clashApiPort;
urlTest = proxyCfg.urlTest // {
tolerance = proxyCfg.singBox.urlTest.tolerance;
};
};
xrayCfg = proxyCfg.xray;
proxyEnabled = proxyCfg.enable;
singBoxEnabled = proxyCfg.enable && proxyCfg.singBox.enable;
xrayEnabled = proxyCfg.enable && proxyCfg.xray.enable;
hybridEnabled = singBoxEnabled && xrayEnabled;
pureSingBoxEnabled = singBoxEnabled && !xrayEnabled;
pureXrayEnabled = xrayEnabled && !singBoxEnabled;
activeBackend =
if hybridEnabled then
"hybrid"
else if pureXrayEnabled then
"xray"
else if pureSingBoxEnabled then
"sing-box"
else
null;
# "hybrid" runs both; the pure* flags are what backend-specific code branches on.
singBoxEnabled = proxyEnabled && proxyCfg.backend != "xray";
xrayEnabled = proxyEnabled && proxyCfg.backend != "sing-box";
hybridEnabled = proxyEnabled && proxyCfg.backend == "hybrid";
pureSingBoxEnabled = proxyEnabled && proxyCfg.backend == "sing-box";
pureXrayEnabled = proxyEnabled && proxyCfg.backend == "xray";
activeBackend = if proxyEnabled then proxyCfg.backend else null;
perAppRoutingCfg = cfg.perAppRouting;
globalTun = proxyCfg.tun;
globalTproxy = proxyCfg.tproxy;
perAppRoutingTun = proxyCfg.tun.perApp;
perAppRoutingTproxy = proxyCfg.tproxy.perApp;
perAppZapretCfg = cfg.zapret.perApp;
perAppRoutingTun = cfg.perAppRouting.tun;
perAppRoutingTproxy = cfg.perAppRouting.tproxy;
zapretCfg = cfg.zapret;
zapretEngine = cfg.zapret.engine;
perAppZapretCfg = cfg.perAppRouting.zapret;
userControlCfg = cfg.userControl;
sshProxyCfg = cfg.sshProxy;
sshProxyOutboundTag = "ssh-proxy";
sshProxyOutboundEnabled = sshProxyCfg.enable && sshProxyCfg.asOutbound;
# Only sing-box dials SSH natively; XRay and standalone tunnels use the OpenSSH unit.
sshProxyNativeOutbound = sshProxyOutboundEnabled && !pureXrayEnabled;
sshProxyUnitEnabled = sshProxyCfg.enable && !sshProxyNativeOutbound;
proxyInboundsCfg = cfg.inbounds;
proxyInboundsEnabled = proxyInboundsCfg.enable;
# Listeners as a list, with `via` resolved against the default.
proxyInbounds = lib.mapAttrsToList (tag: listener: {
inherit tag listener;
via = if listener.via == null then proxyInboundsCfg.routing.via else listener.via;
}) proxyInboundsCfg.listeners;
# Whether any listener or inbounds.routing.proxy exception relays through the local SOCKS
# listener.
proxyInboundsNeedLocalProxy =
lib.any (ib: ib.via == "proxy") proxyInbounds
|| lib.any (field: proxyInboundsCfg.routing.proxy.${field} != [ ]) [
"domains"
"ips"
"geosites"
"geoips"
];
# Names pass unresolved unless XRay dials itself (a direct listener, or pure XRay).
proxyInboundsResolveInSingBox =
!pureXrayEnabled && !lib.any (ib: ib.via == "direct") proxyInbounds;
proxyInboundsGuardPrivate =
proxyInboundsEnabled
&& proxyInboundsCfg.routing.blockPrivate
&& proxyInboundsNeedLocalProxy
&& proxyInboundsResolveInSingBox;
# Other vias name static outbounds, rendered into the inbound service's own config.
proxyInboundViaTags = lib.unique (
builtins.filter (via: !builtins.elem via builtinTags) (map (ib: ib.via) proxyInbounds)
);
proxyInboundViaOutbounds = builtins.filter (
ob: builtins.elem ob.tag proxyInboundViaTags
) proxyCfg.outbounds;
proxyInboundUdpTypes = [
"shadowsocks"
"socks"
];
proxyInboundPorts = lib.unique (map (ib: ib.listener.port) proxyInbounds);
# Loopback listeners are fronted locally; their ports stay closed.
proxyInboundsPublic = builtins.filter (
ib:
!builtins.elem ib.listener.address [
"127.0.0.1"
"::1"
]
) proxyInbounds;
# h3-only xhttp listeners are UDP-only, leaving the TCP port to a web server.
proxyInboundIsH3Only =
l: l.type != null && l.transport.type == "xhttp" && l.tls.enable && l.tls.alpn == [ "h3" ];
proxyInboundFirewallPorts = lib.unique (
map (ib: ib.listener.port) (
builtins.filter (ib: !proxyInboundIsH3Only ib.listener) proxyInboundsPublic
)
);
# A raw-JSON listener could serve anything, so open both protocols for it.
proxyInboundFirewallUdpPorts = lib.unique (
map (ib: ib.listener.port) (
builtins.filter (
ib:
ib.listener.type == null
|| builtins.elem ib.listener.type proxyInboundUdpTypes
|| proxyInboundIsH3Only ib.listener
) proxyInboundsPublic
)
);
selectionMode = proxyCfg.selection;
builtinTags = [
@@ -44,19 +113,71 @@ let
"block"
];
outboundTags = map (ob: ob.tag) proxyCfg.outbounds;
effectiveOutboundTags = outboundTags ++ lib.optional sshProxyOutboundEnabled sshProxyOutboundTag;
subscriptionTags = map (sub: sub.tag) proxyCfg.subscriptions;
hasStaticOutbounds = proxyCfg.outbounds != [ ];
hasSubscriptions = proxyCfg.subscriptions != [ ];
hasAvailableOutbounds = hasStaticOutbounds || hasSubscriptions || sshProxyOutboundEnabled;
collapseNamedOutbounds = selectionMode == "first";
clashApiEnabled = (singBoxEnabled || hybridEnabled) && selectionMode != "first";
perAppZapretEnabled = perAppZapretCfg.enable;
userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable;
userControlEnabled = userControlCfg.allow != [ ];
constants = {
zapret2StateDir = "/var/lib/proxy-suite/zapret2";
# NFQUEUE of the global zapret instance, per engine. Both are the engine's own
# default, which proxy-suite never overrides; the per-app instance opens a
# second queue and must not land on this one.
zapretGlobalQnum = {
zapret-discord-youtube = 200;
zapret2 = 300;
};
autoProxyStateDir = "/var/lib/proxy-suite/autoproxy";
# Runtime outbound control. The spool dirs hold one proxy URL per file and are
# group-writable when userControl is on, so proxy-ctl edits them without sudo;
# the pin outlives a reboot, unlike the per-boot route-mode override.
priorityOutboundFile = "/var/lib/proxy-suite/priority-outbound";
runtimeOutboundsDir = "/var/lib/proxy-suite/outbounds.d";
runtimeSubscriptionsDir = "/var/lib/proxy-suite/subscriptions.d";
# Written by every backend start script; proxy-ctl reads the socks copy.
outboundInventoryFile = "/run/proxy-suite-socks/outbounds.json";
inboundStatsApiPort = 18536;
inboundStatsFile = "/var/lib/proxy-suite/inbound-stats.json";
tunAutoRouteTableIndex = 2022;
tunAutoRouteRulePriority = 9000;
xrayTunPerAppTproxyRulePriority = 8996;
xrayTunPerAppTunRulePriority = 8997;
xrayGlobalTunIPv6Address = "fd66:19::1/64";
xrayGlobalTunIPv6RoutePrefix = "fd66:19::/64";
xrayPerAppTunIPv6Address = "fd66:20::1/64";
xrayPerAppTunIPv6RoutePrefix = "fd66:20::/64";
xrayDnsBridgePorts = {
socks = 18533;
tun = 18534;
perAppTun = 18535;
};
xraySidecarBasePorts = {
socks = 33080;
tun = 33180;
perAppTun = 33280;
};
};
# Subscription tags are deliberately not accepted: they only exist at runtime.
invalidInboundViaTargets = builtins.filter (tag: !builtins.elem tag outboundTags) proxyInboundViaTags;
invalidRoutingTargets = lib.unique (
map (rule: rule.outbound) (
builtins.filter (
rule: !builtins.elem rule.outbound (builtinTags ++ outboundTags)
rule: !builtins.elem rule.outbound (builtinTags ++ effectiveOutboundTags)
) proxyCfg.routing.rules
)
);
@@ -78,16 +199,38 @@ in
globalTproxy
perAppRoutingTun
perAppRoutingTproxy
zapretCfg
zapretEngine
perAppZapretCfg
perAppZapretEnabled
userControlCfg
userControlEnabled
sshProxyCfg
sshProxyOutboundTag
sshProxyOutboundEnabled
sshProxyNativeOutbound
sshProxyUnitEnabled
proxyInboundsCfg
proxyInboundsEnabled
proxyInbounds
proxyInboundsNeedLocalProxy
proxyInboundsResolveInSingBox
proxyInboundsGuardPrivate
proxyInboundViaTags
proxyInboundViaOutbounds
invalidInboundViaTargets
proxyInboundPorts
proxyInboundFirewallPorts
proxyInboundFirewallUdpPorts
constants
selectionMode
builtinTags
outboundTags
effectiveOutboundTags
subscriptionTags
hasStaticOutbounds
hasSubscriptions
hasAvailableOutbounds
collapseNamedOutbounds
clashApiEnabled
invalidRoutingTargets
+14
View File
@@ -0,0 +1,14 @@
# Adds one reading of XRay's per-user counters ($q, taken with -reset) to the
# daily totals: {days: {"YYYY-MM-DD": {"<email>": {up, down}}}, at}.
#
# A counter is named user>>>EMAIL>>>traffic>>>uplink|downlink, and a user's
# email is their name. Its value may come as a string, and a counter still at
# zero comes without one. Down is what the user received, up what they sent.
# The last 366 days are kept.
reduce ($q.stat // [])[] as $s (.;
($s.name | split(">>>")) as $n
| if ($n | length) == 4 and $n[0] == "user" then
.days[$day][$n[1]][if $n[3] == "uplink" then "up" else "down" end] += (($s.value // 0) | tonumber)
else . end)
| .at = $now
| .days = ((.days // {}) | with_entries(select(.key >= ($now - 366 * 86400 | strftime("%Y-%m-%d")))))
+4 -4
View File
@@ -8,13 +8,13 @@
let
proxyCfg = cfg.proxy;
globalTproxy = proxyCfg.tproxy;
perAppTun = proxyCfg.tun.perApp;
perAppTproxy = proxyCfg.tproxy.perApp;
zapretApp = cfg.zapret.perApp;
perAppTun = cfg.perAppRouting.tun;
perAppTproxy = cfg.perAppRouting.tproxy;
zapretApp = cfg.perAppRouting.zapret;
tgWsProxyCfg = cfg.tgWsProxy;
tgWsProxyBypassEnabled = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy;
tgWsProxyBypassMarkLine = lib.optionalString tgWsProxyBypassEnabled ''
meta mark ${toString tgWsProxyCfg.routingMark} return
meta mark ${toString tgWsProxyCfg.fwmark} return
'';
# Shared across all three nftables rule files that do IPv4 routing.
@@ -0,0 +1,45 @@
{
config,
lib,
pkgs,
...
}:
let
inherit (lib)
mkEnableOption
mkOption
types
;
t = import ./types.nix { inherit lib; };
awgPackages = import ../../../pkgs/amneziawg.nix { inherit pkgs; };
in
{
options.services.proxy-suite.amneziaWg = {
enable = mkEnableOption "native AmneziaWG client profiles";
toolsPackage = mkOption {
type = types.package;
default = awgPackages.tools;
description = "AWG 3.1 package providing awg and awg-quick.";
};
userspacePackage = mkOption {
type = types.package;
default = awgPackages.userspace;
description = "AWG 3.1 userspace implementation used when the kernel interface is unavailable.";
};
kernelModulePackage = mkOption {
type = types.nullOr types.package;
default = awgPackages.kernelModule config.boot.kernelPackages;
description = "AWG 3.1 kernel module package. Set null to use userspace-only fallback.";
};
profiles = mkOption {
type = types.attrsOf t.profileType;
default = { };
description = "Named AmneziaWG client profiles. Only one global profile can be active.";
};
};
}
+18 -10
View File
@@ -1,16 +1,24 @@
# All option declarations for services.proxy-suite, split by feature area.
{ ... }:
{ lib, ... }:
{
imports = [
./other.nix
./legacy-sing-box.nix
./sing-box.nix
./sing-box-outbounds.nix
./sing-box-dns.nix
./sing-box-tun.nix
./sing-box-tproxy.nix
./sing-box-routing.nix
./removed.nix
./proxy.nix
./proxy-outbounds.nix
./proxy-dns.nix
./proxy-routing.nix
./proxy-tun.nix
./proxy-tproxy.nix
./inbounds.nix
./per-app-routing.nix
./zapret.nix
./zapret2.nix
./amnezia-wg.nix
./ssh-proxy.nix
./tg-ws-proxy.nix
./geodata.nix
./tray.nix
./user-control.nix
];
options.services.proxy-suite.enable = lib.mkEnableOption "proxy-suite";
}
+35
View File
@@ -0,0 +1,35 @@
{ lib, pkgs, ... }:
let
inherit (lib) literalExpression mkOption types;
in
{
# Shared by the client backends and the inbound service, so not under proxy.
options.services.proxy-suite.geodata = {
xray.assets = mkOption {
type = types.nullOr types.package;
default = pkgs.v2ray-rules-dat;
defaultText = literalExpression "pkgs.v2ray-rules-dat";
description = ''
Package with share/v2ray/{geoip,geosite}.dat for every XRay process. Null uses XRay's own
country-only data, where a tag like "geoip:telegram" stops XRay from starting.
'';
};
singBox = {
geoip = mkOption {
type = types.package;
default = pkgs.sing-geoip;
defaultText = literalExpression "pkgs.sing-geoip";
description = "Package with share/sing-box/rule-set/geoip-NAME.srs (country codes by default).";
};
geosite = mkOption {
type = types.package;
default = pkgs.sing-geosite;
defaultText = literalExpression "pkgs.sing-geosite";
description = "Package with share/sing-box/rule-set/geosite-NAME.srs.";
};
};
};
}
+111
View File
@@ -0,0 +1,111 @@
{ lib, proxySuiteUpstream, ... }:
let
inherit (lib)
literalExpression
literalMD
mkEnableOption
mkOption
types
;
t = import ./types.nix { inherit lib; };
bool =
default: description:
mkOption {
type = types.bool;
inherit default description;
};
in
{
options.services.proxy-suite.inbounds = {
enable = mkEnableOption "server inbounds that accept proxy connections from outside";
package = mkOption {
type = types.package;
default = proxySuiteUpstream.xray;
defaultText = literalMD "proxy-suite's `xray` (`pkgs/xray.nix`)";
example = literalExpression "pkgs.xray";
description = "XRay package serving the inbounds, whatever the client-side backend.";
};
serverAddress = mkOption {
type = types.nullOr (types.strMatching "[^[:space:]]+");
default = null;
description = "Public address clients connect to, used in share links. Null detects the uplink IPv4.";
example = "vpn.example.com";
};
openFirewall = bool true "Open every non-loopback listener port.";
shareLinks = bool true "Write client share links for `proxy-ctl inbounds link` (root and userControl.group only).";
subscriptions = {
enable = mkEnableOption "" // {
description = ''
Write one subscription file per user (their links from every listener, base64) to
/run/proxy-suite-inbounds/subscriptions/<token>. Serve that directory with a web server;
see the README.
'';
};
group = mkOption {
type = types.str;
default = "nginx";
description = "Group allowed to read the subscription files: the web server serving them.";
example = "caddy";
};
baseUrl = mkOption {
type = types.nullOr types.str;
default = null;
description = "URL the subscription directory is served at, for `proxy-ctl inbounds sub`.";
example = "https://vpn.example.com/sub";
};
};
# Mirrors proxy.routing, for traffic arriving from outside instead of from this host.
routing = {
via = mkOption {
type = types.str;
default = "proxy";
description = ''
Default egress of inbound traffic; listeners can override it:
- "proxy": through the local proxy and its current selection (needs proxy.enable).
- a proxy.outbounds tag: pinned to that server (url, urlFile or xrayJson outbounds only).
- "direct": out from this machine.
- "block": dropped.
'';
example = "direct";
};
proxy = t.routingFields;
blockRu = bool true ''Block Russian destinations (geosite "category-ru", geoip "ru").'';
blockPrivate = bool true "Block private and loopback destinations, so clients cannot reach this host's LAN or local services.";
zapretDirect = bool true "Send zapret's hostlist destinations direct, so this host's zapret unblocks them (default via only).";
};
listeners = mkOption {
type = types.attrsOf t.inboundType;
default = { };
description = "Listeners by tag.";
example = literalExpression ''
{
vless-reality = {
type = "vless";
port = 443;
users = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ];
flow = "xtls-rprx-vision";
reality = {
enable = true;
serverNames = [ "www.microsoft.com" ];
privateKeyFile = "/run/secrets/proxy-inbound-reality-key";
publicKey = "jNXH...";
shortIds = [ "0123abcd" ];
};
};
}
'';
};
};
}
@@ -1,72 +0,0 @@
{ lib, config, ... }:
let
inherit (lib) mkIf mkOption types;
cfg = config.services.proxy-suite;
legacy = cfg.singBox or { };
legacyUsed = legacy != { };
has = name: builtins.hasAttr name legacy;
hasNested = path: lib.hasAttrByPath path legacy;
getNested = path: lib.getAttrFromPath path legacy;
setIf = condition: value: lib.optionalAttrs condition value;
in
{
options.services.proxy-suite.singBox = mkOption {
type = types.submodule {
freeformType = types.anything;
};
default = { };
visible = false;
description = ''
Deprecated compatibility tree for the old services.proxy-suite.singBox
options. Use services.proxy-suite.proxy instead.
'';
};
config = mkIf legacyUsed {
warnings = [
''
services.proxy-suite.singBox is deprecated. Move shared options to
services.proxy-suite.proxy and SingBox-specific options to
services.proxy-suite.proxy.singBox.
''
];
services.proxy-suite.proxy = lib.mkMerge [
(setIf (!has "enable") {
enable = lib.mkDefault true;
singBox.enable = lib.mkDefault true;
})
(setIf (has "enable") {
enable = lib.mkDefault legacy.enable;
singBox.enable = lib.mkDefault legacy.enable;
})
(setIf (has "listenAddress") { listenAddress = lib.mkDefault legacy.listenAddress; })
(setIf (has "port") { port = lib.mkDefault legacy.port; })
(setIf (has "auth") { auth = lib.mkDefault legacy.auth; })
(setIf (has "proxyByDefault") { proxyByDefault = lib.mkDefault legacy.proxyByDefault; })
(setIf (has "outbounds") { outbounds = lib.mkDefault legacy.outbounds; })
(setIf (has "subscriptions") { subscriptions = lib.mkDefault legacy.subscriptions; })
(setIf (has "subscriptionUpdateInterval") {
subscriptionUpdateInterval = lib.mkDefault legacy.subscriptionUpdateInterval;
})
(setIf (has "selection") { selection = lib.mkDefault legacy.selection; })
(setIf (has "dns") { dns = lib.mkDefault legacy.dns; })
(setIf (has "routing") { routing = lib.mkDefault legacy.routing; })
(setIf (has "tun") { tun = lib.mkDefault legacy.tun; })
(setIf (has "tproxy") { tproxy = lib.mkDefault legacy.tproxy; })
(setIf (hasNested [ "urlTest" "url" ]) {
urlTest.url = lib.mkDefault (getNested [ "urlTest" "url" ]);
})
(setIf (hasNested [ "urlTest" "interval" ]) {
urlTest.interval = lib.mkDefault (getNested [ "urlTest" "interval" ]);
})
(setIf (hasNested [ "urlTest" "tolerance" ]) {
singBox.urlTest.tolerance = lib.mkDefault (getNested [ "urlTest" "tolerance" ]);
})
(setIf (has "package") { singBox.package = lib.mkDefault legacy.package; })
(setIf (has "clashApiPort") { singBox.clashApiPort = lib.mkDefault legacy.clashApiPort; })
];
};
}
-284
View File
@@ -1,284 +0,0 @@
# Top-level, userControl, tray, and tgWsProxy options.
{ lib, ... }:
let
inherit (lib) mkOption mkEnableOption types;
in
{
options.services.proxy-suite = {
enable = mkEnableOption "proxy suite (proxy backend + zapret + tg-ws-proxy)";
userControl = {
group = mkOption {
type = types.strMatching "^[a-z_][a-z0-9_-]*$";
default = "proxy-suite";
description = ''
Local group allowed to use passwordless polkit-backed `proxy-ctl`
commands when userControl.global.enable or userControl.perApp.enable
is turned on.
'';
example = "proxy-suite";
};
global.enable = (mkEnableOption "passwordless proxy-ctl control over global proxy-suite units") // {
default = true;
description = ''
Whether members of userControl.group may manage global
proxy-suite units without password prompts via commands like
`proxy-ctl tun on|off`, `proxy-ctl tproxy on|off`,
`proxy-ctl restart`, or `proxy-ctl subscription update`.
'';
};
perApp.enable = (mkEnableOption "passwordless proxy-ctl control over per-app routing helpers") // {
default = true;
description = ''
Whether members of userControl.group may start and stop the
app-scoped backend units used by `proxy-ctl wrap ...` for
route = "tun", route = "tproxy", or route = "zapret" profiles
without password prompts.
'';
};
};
tray = {
enable = mkEnableOption "system tray indicator for proxy-suite";
pollInterval = mkOption {
type = types.int;
default = 5;
description = ''
Tray status refresh interval in seconds.
Lower values make UI state changes appear faster, while higher values
reduce background polling overhead.
'';
example = 5;
};
autostart = mkOption {
type = types.bool;
default = true;
description = ''
Whether to install an XDG autostart entry for the tray application
for graphical users.
'';
example = true;
};
};
tgWsProxy = {
enable = mkEnableOption "Telegram MTProto WebSocket proxy";
port = mkOption {
type = types.port;
default = 1443;
description = ''
TCP listen port for tg-ws-proxy.
Telegram clients connect to this endpoint when using the local MTProto
WebSocket proxy.
'';
example = 1076;
};
host = mkOption {
type = types.str;
default = "127.0.0.1";
description = ''
Bind address for tg-ws-proxy.
Keep `127.0.0.1` for local-only usage; bind to `0.0.0.0` only when you
intentionally expose the proxy to other hosts.
'';
example = "127.0.0.1";
};
secret = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
MTProto proxy secret (hex string). Legacy inline form; this value ends up
in the Nix store. Prefer secretFile for real deployments.
Set exactly one of secret or secretFile when tgWsProxy.enable = true.
Generate one with: openssl rand -hex 16
'';
example = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
};
secretFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing the MTProto proxy secret.
Intended for use with secret managers so the secret stays out of the Nix store.
Set exactly one of secretFile or secret when tgWsProxy.enable = true.
'';
example = "/run/secrets/tg-ws-proxy-secret";
};
dcIps = mkOption {
type = types.attrsOf types.str;
default = { };
description = ''
Mapping of Telegram DC IDs to relay IPs.
Keys are DC IDs as strings and values are IPv4/IPv6 addresses used by
tg-ws-proxy for MTProto relay selection.
'';
example = {
"2" = "149.154.167.220";
"4" = "149.154.167.220";
"203" = "149.154.167.220";
};
};
verbose = mkOption {
type = types.bool;
default = false;
description = ''
Whether to enable debug logging in tg-ws-proxy.
'';
example = true;
};
logFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Optional path where tg-ws-proxy writes rotating logs.
When unset, tg-ws-proxy logs to stderr only.
'';
example = "/var/log/tg-ws-proxy.log";
};
logMaxMb = mkOption {
type = types.numbers.positive;
default = 5.0;
description = ''
Maximum tg-ws-proxy log file size in MiB before rotation.
Only used when tgWsProxy.logFile is set.
'';
example = 10.0;
};
logBackups = mkOption {
type = types.ints.positive;
default = 1;
description = ''
Number of rotated tg-ws-proxy log files to keep.
Only used when tgWsProxy.logFile is set.
'';
example = 3;
};
bufKb = mkOption {
type = types.ints.between 4 2147483647;
default = 256;
description = ''
Socket send and receive buffer size for tg-ws-proxy, in KiB.
'';
example = 512;
};
poolSize = mkOption {
type = types.ints.unsigned;
default = 4;
description = ''
WebSocket connection pool size per Telegram DC.
Set to 0 to disable connection pooling.
'';
example = 8;
};
cfProxyDomains = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
User-defined Cloudflare-proxied domains used by tg-ws-proxy for
WebSocket fallback. Each entry is passed as a separate
--cfproxy-domain argument.
'';
example = [
"cdn.example.com"
"edge.example.net"
];
};
cfProxyWorkerDomains = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Cloudflare Worker domains used by tg-ws-proxy for WebSocket fallback.
These are tried before other fallback methods.
'';
example = [ "worker.example.com" ];
};
cfProxyFallback = mkOption {
type = types.bool;
default = true;
description = ''
Whether to allow tg-ws-proxy to use Cloudflare proxy fallback when
direct WebSocket routing is unavailable.
'';
example = false;
};
fakeTlsDomain = mkOption {
type = types.nullOr (types.strMatching ".+");
default = null;
description = ''
Optional SNI domain used to enable tg-ws-proxy Fake TLS masking.
When set, tg-ws-proxy emits an ee-secret connection link.
'';
example = "www.example.com";
};
proxyProtocol = mkOption {
type = types.bool;
default = false;
description = ''
Whether tg-ws-proxy should accept a PROXY protocol v1 header from a
fronting reverse proxy such as nginx or HAProxy.
'';
example = true;
};
wsKeepalive = mkOption {
type = types.numbers.nonnegative;
default = 30.0;
description = ''
Seconds between upstream WebSocket keepalive pings.
Set to 0 to disable keepalive pings.
'';
example = 15.0;
};
bypassTransparentProxy = mkOption {
type = types.bool;
default = true;
description = ''
Whether to keep tg-ws-proxy's own relay connections out of proxy-suite
transparent routing backends.
When enabled and global TUN or TProxy mode is configured, the
tg-ws-proxy systemd service receives a packet mark and an earlier
policy-routing rule back to the main table. This prevents global TUN
from routing the local Telegram MTProto relay through the proxy backend again,
which can otherwise break tg-ws-proxy after enabling TUN mode.
'';
example = true;
};
routingMark = mkOption {
type = types.int;
default = 4;
description = ''
Packet mark used by tgWsProxy.bypassTransparentProxy to bypass
proxy-suite transparent routing. Override this only if it collides
with another local policy-routing mark on your host.
'';
example = 4;
};
};
};
}
+59 -61
View File
@@ -1,101 +1,99 @@
# Per-app routing options (backends and profiles).
{ lib, ... }:
let
inherit (lib) mkOption mkEnableOption types;
inherit (lib) mkEnableOption mkOption types;
t = import ./types.nix { inherit lib; };
int =
default: description:
mkOption {
type = types.int;
inherit default description;
};
localSubnets =
description:
mkOption {
type = types.listOf types.str;
default = [ "192.168.0.0/16" ];
inherit description;
example = [
"192.168.0.0/16"
"10.0.0.0/8"
];
};
in
{
options.services.proxy-suite.perAppRouting = {
enable = mkEnableOption "per-app routing helpers via proxy-ctl wrap";
enable = mkEnableOption "per-app routing (`proxy-ctl apps run`)";
createDefaultProfiles = mkOption {
type = types.bool;
default = false;
description = ''
Whether to automatically add curated perAppRouting profiles.
This is opt-in. Generated defaults are appended only when no
user-defined profile with the same name already exists.
Current curated defaults:
- `proxychains`: route = "proxychains"
- `tun`: route = "tun" when proxy.tun.perApp.enable = true
- `tproxy`: route = "tproxy" when proxy.tproxy.perApp.enable = true
- `zapret`: route = "zapret" when zapret.perApp.enable = true
This makes `proxy-ctl wrap proxychains -- <command>` available
without defining the profile manually, and similarly exposes
`proxy-ctl wrap tun -- <command>` or
`proxy-ctl wrap tproxy -- <command>` or
`proxy-ctl wrap zapret -- <command>` when the corresponding backend
is enabled.
Add a profile named after each enabled backend (proxychains, tun, tproxy, zapret) unless
one with that name already exists.
'';
example = true;
};
profiles = mkOption {
type = types.listOf t.perAppRoutingProfileType;
default = [ ];
description = ''
Named per-app route profiles consumed by `proxy-ctl wrap`.
This initial implementation supports:
- "direct" for running a command unchanged
- "proxychains" for TCP apps that can use an LD_PRELOAD wrapper
instead of global TUN or TProxy interception
- "tun" for per-app-scoped policy routing into the dedicated app TUN
backend
- "tproxy" for per-app-scoped transparent interception through the
dedicated app TProxy backend
- "zapret" for per-app-scoped zapret handling through a separate
zapret instance without changing the app's network path or exit IP
proxychains-based wrapping depends on proxy.enable = true and the
local proxy-suite proxy listener provided by the active backend. The
"tun" route depends on proxy.tun.perApp.enable = true. The "tproxy"
route depends on proxy.tproxy.perApp.enable = true. The "zapret"
route depends on zapret.perApp.enable = true.
When createDefaultProfiles = true, curated defaults are added on top
of this list unless a user-defined profile already uses the same
name.
'';
description = "Profiles for `proxy-ctl apps run <name> -- <command>`.";
example = [
{
name = "steam-browser";
route = "proxychains";
}
{
name = "native-direct";
route = "direct";
}
];
};
proxychains = {
enable = mkEnableOption "proxychains-backed perAppRouting profiles";
enable = mkEnableOption "the proxychains backend (TCP apps, through LD_PRELOAD)";
quiet = mkOption {
type = types.bool;
default = true;
description = ''
Whether generated proxychains wrappers should suppress their normal
startup chatter. This maps to proxychains-ng quiet_mode.
'';
example = true;
description = "Silence proxychains (quiet_mode).";
};
proxyDns = mkOption {
type = types.bool;
default = true;
description = ''
Whether generated proxychains wrappers should resolve DNS through
the proxy instead of the local resolver. This maps to proxychains-ng
proxy_dns.
'';
example = true;
description = "Resolve DNS through the proxy (proxy_dns).";
};
};
tun = {
enable = mkEnableOption "the per-app TUN backend";
fwmark = int 16 "Mark that steers wrapped apps into routeTable.";
routeTable = int 101 "Policy-routing table of the per-app TUN.";
localSubnets = localSubnets "Subnets wrapped apps reach directly.";
interface = mkOption {
type = types.str;
default = "psperapptun0";
description = "Per-app TUN interface name.";
};
address = mkOption {
type = types.str;
default = "172.20.0.1/30";
description = "Per-app TUN interface address (CIDR).";
};
mtu = int 1400 "Per-app TUN interface MTU.";
};
tproxy = {
enable = mkEnableOption "the per-app TProxy backend";
fwmark = int 17 "Mark that steers wrapped apps into routeTable.";
routeTable = int 102 "Policy-routing table of the per-app TProxy.";
localSubnets = localSubnets "Subnets that bypass interception (DNS excepted).";
};
zapret = {
enable = mkEnableOption "the per-app zapret backend: a second zapret instance for wrapped apps only";
filterMark = int 268435456 "Mark bit that selects wrapped app traffic.";
qnum = int 201 "NFQUEUE number. Must differ from the global instance's.";
};
};
}
+35
View File
@@ -0,0 +1,35 @@
{ lib, ... }:
let
inherit (lib) mkOption;
t = import ./types.nix { inherit lib; };
cloudflare = {
type = "udp";
address = "1.1.1.1";
port = 53;
};
in
{
options.services.proxy-suite.proxy.dns = {
local = mkOption {
type = t.dnsUpstreamType;
default = cloudflare;
description = "Resolver for direct traffic and the default domain resolver. Goes through the proxy in global TUN mode.";
example = {
type = "tcp";
address = "9.9.9.9";
};
};
remote = mkOption {
type = t.dnsUpstreamType;
default = cloudflare;
description = "Resolver used through the proxy; the DNS default when proxy.routing.default is proxy.";
example = {
type = "tls";
address = "1.1.1.1";
port = 853;
};
};
};
}
@@ -0,0 +1,94 @@
{ lib, ... }:
let
inherit (lib) mkOption types;
t = import ./types.nix { inherit lib; };
in
{
options.services.proxy-suite.proxy = {
outbounds = mkOption {
type = types.listOf t.outboundType;
default = [ ];
description = ''
Static proxy outbounds. The proxy needs at least one outbound or subscription to start;
`proxy-ctl proxy outbounds add` supplies one at runtime if none is declared here.
'';
example = [
{
tag = "de-vps";
urlFile = "/run/secrets/proxy-de-url";
}
{
tag = "nl-vps";
url = "hy2://password@example.com:443?sni=example.com";
}
];
};
subscriptions = mkOption {
type = types.listOf t.subscriptionType;
default = [ ];
description = ''
Subscription URLs serving a base64 or plain list of proxy URIs. Fetched on first start,
cached under /var/lib/proxy-suite/subscriptions, refreshed by a timer. Ones added with
`proxy-ctl proxy subs add` live in /var/lib/proxy-suite/subscriptions.d and refresh alongside.
'';
example = [
{
tag = "private";
urlFile = "/run/secrets/private-sub-url";
}
];
};
subscriptionUpdateInterval = mkOption {
type = types.str;
default = "1d";
description = "How often subscriptions are refreshed (systemd time span).";
example = "6h";
};
selection = mkOption {
type = types.enum [
"first"
"selector"
"urltest"
];
default = "first";
description = ''
How to pick among outbounds:
- "first": one at a time - the pinned outbound, or the first available.
- "selector": all of them, pick by hand.
- "urltest": all of them, ranked by latency unless one is pinned.
`proxy-ctl proxy select` pins an outbound in every mode, and the pin outlives a restart.
"selector" and "urltest" switch without restarting the backend (sing-box only); "first"
and XRay restart it.
'';
example = "urltest";
};
urlTest = {
url = mkOption {
type = types.str;
default = "https://www.gstatic.com/generate_204";
description = "URL fetched through each outbound to rank them. Pick one blocked in your region.";
example = "https://telegram.org";
};
interval = mkOption {
type = types.str;
default = "3m";
description = "How often outbounds are re-tested (Go duration).";
example = "1m";
};
tolerance = mkOption {
type = types.int;
default = 50;
description = "Milliseconds a faster outbound must win by to replace the current one (sing-box only).";
example = 100;
};
};
};
}
@@ -0,0 +1,71 @@
{ lib, ... }:
let
inherit (lib) mkOption types;
t = import ./types.nix { inherit lib; };
list =
description: example:
mkOption {
type = types.listOf types.str;
default = [ ];
inherit description example;
};
in
{
options.services.proxy-suite.proxy.routing = {
default = mkOption {
type = types.enum [
"proxy"
"direct"
];
default = "proxy";
description = "Where traffic no routing rule matches goes.";
example = "direct";
};
directRu = mkOption {
type = types.bool;
default = true;
description = ''Send geosite "category-ru" and geoip "ru" direct.'';
};
proxy = {
domains = list "Domain suffixes sent through the proxy." [ "youtube.com" ];
ips = list "IP CIDRs sent through the proxy." [ "1.1.1.0/24" ];
geosites = list "Geosite names sent through the proxy." [ "netflix" ];
geoips = list "Geoip names sent through the proxy." [ "us" ];
};
direct = {
domains = list "Domain suffixes sent direct. zapret hostlists join them when zapret.directSync.enable is on." [
"internal.example"
];
ips = list "IP CIDRs sent direct." [ "10.10.0.0/16" ];
geosites = list "Geosite names sent direct." [ "category-ru" ];
geoips = list "Geoip names sent direct." [ "ru" ];
};
block = {
domains = list "Domain suffixes blocked." [ "ads.example.com" ];
ips = list "IP CIDRs blocked." [ "203.0.113.0/24" ];
geosites = list "Geosite names blocked." [ "category-ads-all" ];
geoips = list "Geoip names blocked." [ "cn" ];
};
rules = mkOption {
type = types.listOf t.routingRuleType;
default = [ ];
description = "Rules checked before the proxy/direct/block lists, in order; the first match wins.";
example = [
{
outbound = "vps-de";
geosites = [ "netflix" ];
}
{
outbound = "direct";
domains = [ "internal.corp" ];
}
];
};
};
}
@@ -0,0 +1,44 @@
{ lib, ... }:
let
inherit (lib) mkEnableOption mkOption types;
in
{
options.services.proxy-suite.proxy.tproxy = {
enable = mkEnableOption "global TProxy mode (proxy-suite-tproxy)";
port = mkOption {
type = types.port;
default = 1085;
description = "Port of the TProxy inbound.";
};
fwmark = mkOption {
type = types.int;
default = 1;
description = "Mark of intercepted packets, routed through routeTable.";
};
proxyMark = mkOption {
type = types.int;
default = 2;
description = "Mark of the backend's own traffic, so it is not intercepted again.";
};
routeTable = mkOption {
type = types.int;
default = 100;
description = "Policy-routing table for intercepted traffic.";
};
localSubnets = mkOption {
type = types.listOf types.str;
default = [ "192.168.0.0/16" ];
description = "Subnets that bypass interception (DNS excepted): your LAN, VM bridges.";
example = [
"192.168.0.0/16"
"10.0.0.0/8"
];
};
};
}
+28
View File
@@ -0,0 +1,28 @@
{ lib, ... }:
let
inherit (lib) mkEnableOption mkOption types;
in
{
options.services.proxy-suite.proxy.tun = {
enable = mkEnableOption "global TUN mode (proxy-suite-tun)";
interface = mkOption {
type = types.str;
default = "singtun0";
description = "TUN interface name.";
};
address = mkOption {
type = types.str;
default = "172.19.0.1/30";
description = "TUN interface address (CIDR).";
};
mtu = mkOption {
type = types.int;
default = 1400;
description = "TUN interface MTU.";
};
};
}
+184
View File
@@ -0,0 +1,184 @@
{
lib,
proxySuiteUpstream,
...
}:
let
inherit (lib)
literalExpression
literalMD
mkEnableOption
mkOption
types
;
in
{
options.services.proxy-suite.proxy = {
enable = mkEnableOption "the local proxy";
backend = mkOption {
type = types.enum [
"sing-box"
"xray"
"hybrid"
];
default = "sing-box";
description = ''
Proxy backend. "hybrid" runs sing-box in front and hands XRay-only outbounds
(XHTTP, ECH) to XRay.
'';
example = "hybrid";
};
autostart = mkOption {
type = types.nullOr (
types.enum [
"tun"
"tproxy"
]
);
default = null;
description = ''
Transparent mode started at boot, or null for neither. The mode named here must
also be enabled (proxy.tun.enable or proxy.tproxy.enable).
'';
example = "tun";
};
listener = {
address = mkOption {
type = types.str;
default = "127.0.0.1";
description = ''Bind address of the local SOCKS5/HTTP proxy. Use "0.0.0.0" only to expose it to the network.'';
};
port = mkOption {
type = types.port;
default = 1080;
description = "Port of the local SOCKS5/HTTP proxy.";
};
auth = {
username = mkOption {
type = types.nullOr (types.strMatching "[^[:space:]]+");
default = null;
description = "Username the local proxy requires. Set together with password or passwordFile.";
example = "proxy-user";
};
password = mkOption {
type = types.nullOr (types.strMatching "[^[:space:]]+");
default = null;
description = "Inline local proxy password. Ends up in the Nix store; prefer passwordFile.";
example = "change-me";
};
passwordFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to the local proxy password. With perAppRouting.proxychains it must be a
single token, and it is readable by userControl.group through the proxychains config.
'';
example = "/run/secrets/proxy-suite-local-proxy-password";
};
};
};
autoProxy = {
enable = mkEnableOption "autoProxy" // {
description = ''
Probe each exit for the destinations clients dial, and route each one through the first
exit that reaches it for as long as it keeps working (`proxy-ctl proxy auto probe` shows a
verdict). Censor-side failures stay direct for zapret. Needs the sing-box backend, and
makes this host fetch every new destination itself.
'';
};
interval = mkOption {
type = types.str;
default = "10m";
description = "Time between probe runs. `proxy-ctl proxy auto learn` does not wait for it.";
example = "30m";
};
probesPerRun = mkOption {
type = types.ints.positive;
default = 200;
description = "Most destinations probed per run; the rest wait in a backlog, most-dialled first.";
};
maxExits = mkOption {
type = types.ints.positive;
default = 12;
description = ''
Most exits probed, direct included. The first round tries one exit per network (AS), a
second round the rest.
'';
};
ttlDays = mkOption {
type = types.ints.positive;
default = 30;
description = ''
Days a verdict stands, routed destinations included: a route is re-probed once this long
has passed. Everything is relearned when this host's public address changes, and
`proxy-ctl proxy auto learn <domain>` re-probes one destination right away.
'';
};
slowBelowKiBps = mkOption {
type = types.ints.unsigned;
default = 150;
description = ''
Also route destinations that work directly but crawl: at least 300 KiB in a 10 s sample,
never faster than this. 0 disables. Needs `selection` other than "first".
'';
example = 0;
};
exclude = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Domain suffixes never probed or auto-routed.";
example = [ "internal.example" ];
};
probeBasePort = mkOption {
type = types.port;
default = 18540;
description = ''
First loopback port of the per-exit probe listeners (one per exit, maxExits in total).
They are unauthenticated even when proxy.listener.auth is set.
'';
};
};
singBox = {
package = mkOption {
type = types.package;
default = proxySuiteUpstream.sing-box;
defaultText = literalMD "`sing-box` from proxy-suite's own `nixpkgs` input";
example = literalExpression "pkgs.sing-box";
description = ''sing-box package, used when backend is "sing-box" or "hybrid".'';
};
clashApiPort = mkOption {
type = types.port;
default = 9090;
description = ''Port of sing-box's Clash API, used with selection "selector" or "urltest".'';
};
};
xray = {
package = mkOption {
type = types.package;
default = proxySuiteUpstream.xray;
defaultText = literalMD "proxy-suite's `xray` (`pkgs/xray.nix`)";
example = literalExpression "pkgs.xray";
description = ''XRay package, used when backend is "xray" or "hybrid".'';
};
};
};
}
+75
View File
@@ -0,0 +1,75 @@
{ lib, ... }:
let
p = path: [ "services" "proxy-suite" ] ++ lib.splitString "." path;
rm = path: replacement: lib.mkRemovedOptionModule (p path) replacement;
# Top-level zapret options that moved under the engine namespace; the value is
# the leaf name they carry there.
zapretMoved = {
configName = "configName";
gameFilter = "gameFilter";
hostlistRules = "hostlistRules";
includeExtraUpstreamLists = "includeExtraUpstreamLists";
listGeneral = "domains";
listExclude = "excludeDomains";
ipsetAll = "ips";
ipsetExclude = "excludeIps";
};
in
{
imports = [
# These were aliases; they are removal notices now, so there is one
# compatibility policy instead of two.
(rm "proxyInbounds" "Use services.proxy-suite.inbounds.")
(rm "proxy.tun.perApp" "Use services.proxy-suite.perAppRouting.tun.")
(rm "proxy.tproxy.perApp" "Use services.proxy-suite.perAppRouting.tproxy.")
(rm "zapret.perApp" "Use services.proxy-suite.perAppRouting.zapret.")
(rm "proxy.singBox.urlTest.tolerance" "Use services.proxy-suite.proxy.urlTest.tolerance.")
(rm "tgWsProxy.host" "Use services.proxy-suite.tgWsProxy.listener.address.")
(rm "singBox" "Use services.proxy-suite.proxy, with sing-box-specific options under proxy.singBox.")
# proxy.
(rm "proxy.singBox.enable" ''Use services.proxy-suite.proxy.backend = "sing-box" (or "hybrid").'')
(rm "proxy.xray.enable" ''Use services.proxy-suite.proxy.backend = "xray" (or "hybrid").'')
(rm "proxy.listenAddress" "Use services.proxy-suite.proxy.listener.address.")
(rm "proxy.port" "Use services.proxy-suite.proxy.listener.port.")
(rm "proxy.auth.username" "Use services.proxy-suite.proxy.listener.auth.username.")
(rm "proxy.auth.password" "Use services.proxy-suite.proxy.listener.auth.password.")
(rm "proxy.auth.passwordFile" "Use services.proxy-suite.proxy.listener.auth.passwordFile.")
(rm "proxy.proxyByDefault" ''Use services.proxy-suite.proxy.routing.default = "proxy" or "direct".'')
(rm "proxy.routing.enableRuDirect" "Use services.proxy-suite.proxy.routing.directRu.")
(rm "proxy.tun.autostart" ''Use services.proxy-suite.proxy.autostart = "tun".'')
(rm "proxy.tproxy.autostart" ''Use services.proxy-suite.proxy.autostart = "tproxy".'')
# zapret. Both engines now spell their lists the same way.
(rm "zapret.syncDirectRouting" "Use services.proxy-suite.zapret.directSync.enable.")
(rm "zapret.syncDirectRoutingUpstreamIps" "Use services.proxy-suite.zapret.directSync.upstreamIps.")
(rm "zapret.syncDirectRoutingUserIps" "Use services.proxy-suite.zapret.directSync.userIps.")
# sshProxy splits into server (where it dials) and listener (what it opens).
(rm "sshProxy.user" "Use services.proxy-suite.sshProxy.server.user.")
(rm "sshProxy.host" "Use services.proxy-suite.sshProxy.server.host.")
(rm "sshProxy.sshPort" "Use services.proxy-suite.sshProxy.server.port.")
(rm "sshProxy.listenAddress" "Use services.proxy-suite.sshProxy.listener.address.")
(rm "sshProxy.listenPort" "Use services.proxy-suite.sshProxy.listener.port.")
# tgWsProxy groups its listener, Cloudflare and logging knobs.
(rm "tgWsProxy.port" "Use services.proxy-suite.tgWsProxy.listener.port.")
(rm "tgWsProxy.cfProxyDomains" "Use services.proxy-suite.tgWsProxy.cloudflare.domains.")
(rm "tgWsProxy.cfProxyWorkerDomains" "Use services.proxy-suite.tgWsProxy.cloudflare.workerDomains.")
(rm "tgWsProxy.cfProxyFallback" "Use services.proxy-suite.tgWsProxy.cloudflare.fallback.")
(rm "tgWsProxy.bufKb" "Use services.proxy-suite.tgWsProxy.bufferKiB.")
(rm "tgWsProxy.routingMark" "Use services.proxy-suite.tgWsProxy.fwmark.")
(rm "tgWsProxy.verbose" "Use services.proxy-suite.tgWsProxy.log.verbose.")
(rm "tgWsProxy.logFile" "Use services.proxy-suite.tgWsProxy.log.file.")
(rm "tgWsProxy.logMaxMb" "Use services.proxy-suite.tgWsProxy.log.maxSizeMiB.")
(rm "tgWsProxy.logBackups" "Use services.proxy-suite.tgWsProxy.log.keep.")
# userControl.
(rm "userControl.global.enable" ''Use services.proxy-suite.userControl.allow, which lists "global" by default.'')
(rm "userControl.perApp.enable" ''Use services.proxy-suite.userControl.allow, which lists "perApp" by default.'')
]
++ lib.mapAttrsToList (
old: new: rm "zapret.${old}" "Use services.proxy-suite.zapret.zapret-discord-youtube.${new}."
) zapretMoved;
}
@@ -1,52 +0,0 @@
{ lib, ... }:
let
inherit (lib) mkOption;
t = import ./types.nix { inherit lib; };
in
{
options.services.proxy-suite.proxy.dns = {
local = mkOption {
type = t.dnsUpstreamType;
default = {
type = "udp";
address = "1.1.1.1";
port = 53;
};
description = ''
DNS upstream used for the built-in "local" resolver role.
This resolver is also used as the backend's default domain resolver.
The module keeps detour policy automatic: in mixed/TProxy mode and
per-app-routing TUN mode, "local" stays on the direct path (without an
explicit detour); in global TUN mode, it is forced through the proxy to avoid
auto_redirect conflicts.
'';
example = {
type = "tcp";
address = "9.9.9.9";
port = 53;
};
};
remote = mkOption {
type = t.dnsUpstreamType;
default = {
type = "udp";
address = "1.1.1.1";
port = 53;
};
description = ''
DNS upstream used for the built-in "remote" resolver role.
This resolver always detours through the proxy and becomes the
generated dns.final target when proxy.proxyByDefault = true.
'';
example = {
type = "tls";
address = "1.1.1.1";
port = 853;
};
};
};
}
@@ -1,133 +0,0 @@
{ lib, ... }:
let
inherit (lib) mkOption types;
t = import ./types.nix { inherit lib; };
in
{
options.services.proxy-suite.proxy = {
outbounds = mkOption {
type = types.listOf t.outboundType;
default = [ ];
description = ''
List of static proxy outbounds.
Set exactly one of urlFile, url, singBoxJson, xrayJson, or the
deprecated json field per entry. Backend-specific raw JSON fields are
only valid with their matching backend.
At least one outbound or one subscription is required when
proxy.enable = true.
'';
example = [
{
tag = "de-vps";
urlFile = "/run/secrets/proxy-de-url";
}
{
tag = "nl-vps";
url = "hy2://password@example.com:443?sni=example.com";
}
];
};
subscriptions = mkOption {
type = types.listOf t.subscriptionType;
default = [ ];
description = ''
Subscription URLs that provide dynamic lists of proxy outbounds.
Each URL must return a base64-encoded newline-separated list of proxy URIs
(standard v2rayN / Clash subscription format) or plain text of the same.
On first service start, each subscription is fetched live and cached
under /var/lib/proxy-suite/subscriptions/<backend>/<tag>.json. Later restarts
reuse the cache, so ordinary service restarts do not need network access.
A systemd timer (proxy-suite-subscription-update) refreshes all caches
on the interval set by subscriptionUpdateInterval and restarts the
running proxy services after a successful refresh.
'';
example = [
{
tag = "community";
url = "https://example.com/sub/token";
}
{
tag = "private";
urlFile = "/run/secrets/private-sub-url";
}
];
};
subscriptionUpdateInterval = mkOption {
type = types.str;
default = "1d";
description = ''
How often the proxy-suite-subscription-update timer fires and refreshes
all subscription caches. Accepts any systemd time span string
(e.g. "1h", "6h", "1d", "12h").
Only used when proxy.subscriptions is non-empty. The timer also runs
once shortly after boot.
'';
example = "6h";
};
selection = mkOption {
type = types.enum [
"first"
"selector"
"urltest"
];
default = "first";
description = ''
How to pick between multiple proxy outbounds:
- "first": route through a single active outbound tagged "proxy".
The first static outbound is used, or the first subscription
outbound if only subscriptions are configured.
- "selector": create a Clash-compatible selector outbound tagged
"proxy" and keep all configured outbounds available for manual
switching via the Clash API.
- "urltest": create automatic latency testing tagged "proxy" and
keep all configured outbounds available so the active backend can
periodically probe and switch to a faster one.
proxy.singBox.clashApiPort is only used with "selector" or "urltest"
on the SingBox backend. "selector" is SingBox-only. "urltest" maps to
SingBox urltest or XRay observatory/balancer depending on backend.
urlTest.* options are only used with "urltest".
Per-outbound tags are only individually meaningful with "selector"
or "urltest".
'';
example = "urltest";
};
urlTest = {
url = mkOption {
type = types.str;
default = "https://www.gstatic.com/generate_204";
description = ''
URL that the active backend fetches through each proxy to measure latency.
Only used when selection = "urltest".
Set this to a URL that is actually blocked in your region (e.g.
"https://telegram.org") so that only proxies that bypass the
blocking get selected. If left at the default, any responding proxy
wins – including ones that might not unblock your target site.
'';
example = "https://telegram.org";
};
interval = mkOption {
type = types.str;
default = "3m";
description = ''
How often the active backend re-tests all outbounds. Accepts a Go
duration string (e.g. "1m", "3m", "10m").
Only used when selection = "urltest".
'';
example = "1m";
};
};
};
}
@@ -1,122 +0,0 @@
{ lib, ... }:
let
inherit (lib) mkOption types;
t = import ./types.nix { inherit lib; };
in
{
options.services.proxy-suite.proxy.routing = {
enableRuDirect = mkOption {
type = types.bool;
default = true;
description = ''
Automatically append "category-ru" to routing.direct.geosites and
"ru" to routing.direct.geoips.
This is additive: user-defined routing.direct.* entries still apply.
'';
example = true;
};
proxy = t.routingFields;
direct = {
domains = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Domain suffixes to send direct (bypass proxy).
Merged with zapret-synced direct domains when zapret direct sync
options are enabled.
'';
example = [ "internal.example" ];
};
ips = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
IP CIDRs to send direct.
Merged with zapret-synced direct IPs when the corresponding zapret
sync options are enabled.
'';
example = [ "10.10.0.0/16" ];
};
geosites = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
sing-geosite names to send direct.
"category-ru" is added automatically when enableRuDirect = true.
'';
example = [ "category-ru" ];
};
geoips = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
sing-geoip names to send direct.
"ru" is added automatically when enableRuDirect = true.
'';
example = [ "ru" ];
};
};
block = {
domains = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Domain suffixes to block entirely.";
example = [ "ads.example.com" ];
};
ips = mkOption {
type = types.listOf types.str;
default = [ ];
description = "IP CIDRs to block.";
example = [ "203.0.113.0/24" ];
};
geosites = mkOption {
type = types.listOf types.str;
default = [ ];
description = "sing-geosite names to block.";
example = [ "category-ads-all" ];
};
geoips = mkOption {
type = types.listOf types.str;
default = [ ];
description = "sing-geoip names to block.";
example = [ "cn" ];
};
};
rules = mkOption {
type = types.listOf t.routingRuleType;
default = [ ];
description = ''
Explicit routing rules evaluated before global proxy/direct/block lists.
Each rule routes matching traffic to a specific outbound tag.
The outbound can be a configured outbound tag (useful with selector/urltest),
or one of: "proxy" (active proxy), "direct", "block".
Order is preserved. The first matching rule wins in the active backend.
With selection = "first", non-built-in outbound tags are effectively
routed to the single active "proxy" outbound.
'';
example = [
{
outbound = "vps-de";
domains = [ "netflix.com" ];
geosites = [ "netflix" ];
}
{
outbound = "direct";
domains = [ "internal.corp" ];
}
{
outbound = "block";
domains = [ "ads.example.com" ];
}
];
};
};
}
@@ -1,119 +0,0 @@
{ lib, ... }:
let
inherit (lib) mkOption mkEnableOption types;
in
{
options.services.proxy-suite.proxy.tproxy = {
enable = mkEnableOption "global proxy TProxy mode service";
autostart = mkOption {
type = types.bool;
default = false;
description = ''
Whether to start proxy-suite-tproxy automatically during boot by
attaching it to multi-user.target.
Cannot be enabled together with proxy.tun.autostart.
'';
example = true;
};
port = mkOption {
type = types.port;
default = 1081;
description = ''
Local listen port for the proxy backend's TProxy inbound.
nftables redirection created by proxy-suite-tproxy sends intercepted
TCP/UDP traffic to this port.
'';
example = 1081;
};
fwmark = mkOption {
type = types.int;
default = 1;
description = ''
Mark applied to intercepted packets in global TProxy mode.
A matching `ip rule` routes this mark to
proxy.tproxy.routeTable, which points traffic to
loopback for local proxy processing.
'';
example = 1;
};
proxyMark = mkOption {
type = types.int;
default = 2;
description = ''
Mark applied to backend egress packets in global TProxy mode so
they bypass re-interception and do not loop back into the
transparent proxy path.
'';
example = 2;
};
routeTable = mkOption {
type = types.int;
default = 100;
description = ''
Policy-routing table number used for global TProxy interception flow.
The module installs a local default route in this table and binds it
to proxy.tproxy.fwmark.
'';
example = 100;
};
localSubnets = mkOption {
type = types.listOf types.str;
default = [ "192.168.0.0/16" ];
description = ''
Subnets whose traffic bypasses global TProxy interception, except
DNS (port 53).
Typically this should include your LAN subnet(s). VM bridge networks
should usually go here too, or use zapret.cidrExemption for
subnet-specific NFQUEUE exemption on the zapret side.
'';
example = [
"192.168.0.0/16"
"10.0.0.0/8"
];
};
perApp = {
enable = mkEnableOption "per-app-scoped proxy TProxy backend for perAppRouting profiles";
fwmark = mkOption {
type = types.int;
default = 17;
description = ''
Packet mark used to steer wrapped app traffic into the per-app-scoped
TProxy policy-routing table.
'';
example = 17;
};
routeTable = mkOption {
type = types.int;
default = 102;
description = ''
Policy-routing table used by the per-app-scoped TProxy backend.
'';
example = 102;
};
localSubnets = mkOption {
type = types.listOf types.str;
default = [ "192.168.0.0/16" ];
description = ''
Subnets whose traffic bypasses per-app-scoped TProxy interception,
except DNS (port 53).
'';
example = [
"192.168.0.0/16"
"10.0.0.0/8"
];
};
};
};
}
@@ -1,111 +0,0 @@
{ lib, ... }:
let
inherit (lib) mkOption mkEnableOption types;
mkTunCommonFields =
{
interfaceDefault,
interfaceDescription,
addressDefault,
addressDescription,
mtuDefault,
mtuDescription,
}:
{
interface = mkOption {
type = types.str;
default = interfaceDefault;
description = interfaceDescription;
example = interfaceDefault;
};
address = mkOption {
type = types.str;
default = addressDefault;
description = addressDescription;
example = addressDefault;
};
mtu = mkOption {
type = types.int;
default = mtuDefault;
description = mtuDescription;
example = mtuDefault;
};
};
in
{
options.services.proxy-suite.proxy.tun = {
enable = mkEnableOption "global proxy TUN mode service";
autostart = mkOption {
type = types.bool;
default = false;
description = ''
Whether to start proxy-suite-tun automatically during boot by
attaching it to multi-user.target.
Cannot be enabled together with proxy.tproxy.autostart.
'';
example = true;
};
perApp = {
enable = mkEnableOption "per-app-scoped proxy TUN backend for perAppRouting profiles";
fwmark = mkOption {
type = types.int;
default = 16;
description = ''
Packet mark used to steer wrapped app traffic into the per-app-scoped
TUN policy-routing table.
'';
example = 16;
};
routeTable = mkOption {
type = types.int;
default = 101;
description = ''
Policy-routing table used by the per-app-scoped TUN backend.
'';
example = 101;
};
localSubnets = mkOption {
type = types.listOf types.str;
default = [ "192.168.0.0/16" ];
description = ''
Destination subnets that should bypass the per-app-scoped TUN mark,
so wrapped apps can still reach local LAN resources directly.
'';
example = [
"192.168.0.0/16"
"10.0.0.0/8"
];
};
}
// mkTunCommonFields {
interfaceDefault = "psperapptun0";
interfaceDescription = ''
Name of the dedicated per-app-routing TUN interface used by
proxy-suite-per-app-tun.
'';
addressDefault = "172.20.0.1/30";
addressDescription = ''
Address assigned to the dedicated per-app-routing TUN interface in CIDR
notation.
'';
mtuDefault = 1400;
mtuDescription = "MTU for the dedicated per-app-routing TUN interface.";
};
}
// mkTunCommonFields {
interfaceDefault = "singtun0";
interfaceDescription = "Name of the TUN interface created by proxy-suite-tun.";
addressDefault = "172.19.0.1/30";
addressDescription = "Address assigned to the global TUN interface in CIDR notation.";
mtuDefault = 1400;
mtuDescription = "MTU for the global TUN interface created by proxy-suite-tun.";
};
}
-166
View File
@@ -1,166 +0,0 @@
# Core proxy options. Feature-area options live in sing-box-{outbounds,dns,tun,tproxy,routing}.nix.
{ lib, pkgs, ... }:
let
inherit (lib)
literalExpression
mkOption
mkEnableOption
types
;
in
{
options.services.proxy-suite.proxy = {
enable = mkOption {
type = types.bool;
default = false;
description = ''
Whether to configure and run the proxy backend services.
This is disabled by default; enable it explicitly and choose at least
one backend with proxy.singBox.enable or proxy.xray.enable. Enabling
both runs sing-box as the frontend and XRay as a sidecar for outbounds
that require XRay.
'';
};
listenAddress = mkOption {
type = types.str;
default = "127.0.0.1";
description = ''
Address for the local SOCKS5/HTTP inbound to bind to.
This affects the proxy-suite-socks service.
Use "0.0.0.0" only if you intentionally want to expose the proxy to
other machines on your network.
'';
example = "127.0.0.1";
};
port = mkOption {
type = types.port;
default = 1080;
description = ''
Listen port for the local SOCKS5/HTTP proxy inbound provided by
proxy-suite-socks. SingBox exposes SOCKS5 and HTTP on this port.
XRay's Socks inbound also accepts SOCKS and HTTP.
'';
example = 1080;
};
auth = {
username = mkOption {
type = types.nullOr (types.strMatching "[^[:space:]]+");
default = null;
description = ''
Optional username for the local SOCKS5/HTTP mixed inbound.
Set this together with exactly one of auth.password or
auth.passwordFile to require clients to authenticate before using the
local proxy. Leave unset to keep the local proxy unauthenticated.
'';
example = "proxy-user";
};
password = mkOption {
type = types.nullOr (types.strMatching "[^[:space:]]+");
default = null;
description = ''
Optional inline password for the local SOCKS5/HTTP mixed inbound.
Convenient for testing, but the password ends up in the Nix store.
Prefer auth.passwordFile for real deployments.
'';
example = "change-me";
};
passwordFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing the local proxy password.
Intended for use with secret managers so the password stays out of
the Nix store. The file is read when proxy-suite-socks starts.
If perAppRouting.proxychains.enable is also used, keep this password
as a single non-whitespace token so it can be written to the
proxychains-ng config format. The generated proxychains config is
readable by members of userControl.group.
'';
example = "/run/secrets/proxy-suite-local-proxy-password";
};
};
proxyByDefault = mkOption {
type = types.bool;
default = true;
description = ''
Whether traffic that does not match any explicit routing rule should
go through the proxy or go direct.
This affects the generated backend route final and DNS final in the
config.
'';
example = true;
};
singBox = {
enable = mkEnableOption "SingBox proxy backend";
package = mkOption {
type = types.package;
default = pkgs.sing-box;
defaultText = literalExpression "pkgs.sing-box";
example = literalExpression "pkgs.sing-box";
description = ''
sing-box package used by proxy-suite systemd services.
Override this to pin or test a specific sing-box build when upstream
protocol behavior changes.
'';
};
clashApiPort = mkOption {
type = types.port;
default = 9090;
description = ''
Port for the Clash-compatible REST API exposed by sing-box.
Only used when proxy.selection is "selector" or "urltest". Ignored
in "first" mode because there is no selector-style outbound to
control.
'';
example = 9090;
};
urlTest.tolerance = mkOption {
type = types.int;
default = 50;
description = ''
Latency tolerance in milliseconds for sing-box urltest. The current
proxy is only replaced when a competing one is faster by more than
this value.
Only used when proxy.selection = "urltest" and the SingBox backend
is active.
'';
example = 100;
};
};
xray = {
enable = mkEnableOption "XRay proxy backend";
package = mkOption {
type = types.package;
default = pkgs.xray;
defaultText = literalExpression "pkgs.xray";
example = literalExpression "pkgs.xray";
description = ''
XRay package used by proxy-suite systemd services.
Override this to pin or test a specific XRay build when upstream
protocol behavior changes.
'';
};
};
};
}
+124
View File
@@ -0,0 +1,124 @@
{ lib, ... }:
let
inherit (lib) mkEnableOption mkOption types;
token = types.nullOr (types.strMatching "[^[:space:]]+");
path =
description: example:
mkOption {
type = types.nullOr types.str;
default = null;
inherit description example;
};
in
{
options.services.proxy-suite.sshProxy = {
enable = mkEnableOption "an SSH dynamic SOCKS5 tunnel";
# Where the tunnel goes.
server = {
user = mkOption {
type = token;
default = null;
description = "SSH login user.";
example = "root";
};
host = mkOption {
type = token;
default = null;
description = "SSH server.";
example = "ssh.example.com";
};
port = mkOption {
type = types.port;
default = 22;
description = "SSH server port.";
};
};
asOutbound = mkOption {
type = types.bool;
default = false;
description = ''
Add the tunnel as an outbound tagged "ssh-proxy". sing-box dials SSH itself; XRay goes
through the OpenSSH unit's SOCKS listener.
'';
};
identityFile = path "Runtime path to the private key. Null uses the agent or OpenSSH defaults." "/run/secrets/proxy-suite-ssh-key";
hostKey = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Accepted host keys (sing-box). List every key `ssh-keyscan` prints: the algorithm is
negotiated. Empty accepts any key.
'';
example = [ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI..." ];
};
hostKeyFile = path "Known-hosts file to read hostKey from at runtime (sing-box). Wins over hostKey." "/root/.ssh/known_hosts";
# The rest only apply to the OpenSSH unit (XRay, or asOutbound = false).
knownHostsFile = path "Known-hosts file for OpenSSH." "/run/secrets/proxy-suite-ssh-known-hosts";
strictHostKeyChecking = mkOption {
type = types.enum [
"yes"
"accept-new"
"no"
];
default = "accept-new";
description = "OpenSSH host key policy.";
example = "yes";
};
# The local SOCKS5 listener the OpenSSH unit opens.
listener = {
address = mkOption {
type = types.strMatching "[^[:space:]]+";
default = "127.0.0.1";
description = "Address of the OpenSSH SOCKS5 listener.";
};
port = mkOption {
type = types.port;
default = 1091;
description = "Port of the OpenSSH SOCKS5 listener.";
};
};
serviceUser = mkOption {
type = token;
default = null;
description = "Unix user running the OpenSSH unit.";
example = "proxy";
};
extraArgs = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Extra OpenSSH arguments.";
example = [
"-J"
"jump.example.com"
];
};
domainStrategy = mkOption {
type = types.nullOr (
types.enum [
"prefer_ipv4"
"prefer_ipv6"
"ipv4_only"
"ipv6_only"
]
);
default = null;
description = "Resolve destinations locally before the tunnel (XRay only). Can break geo-steered CDNs.";
example = "prefer_ipv4";
};
};
}
+129
View File
@@ -0,0 +1,129 @@
{ lib, ... }:
let
inherit (lib) mkEnableOption mkOption types;
domains =
description: example:
mkOption {
type = types.listOf types.str;
default = [ ];
inherit description example;
};
in
{
options.services.proxy-suite.tgWsProxy = {
enable = mkEnableOption "the Telegram MTProto WebSocket proxy";
listener = {
address = mkOption {
type = types.str;
default = "127.0.0.1";
description = "Bind address.";
};
port = mkOption {
type = types.port;
default = 1443;
description = "Listen port.";
};
};
secret = mkOption {
type = types.nullOr types.str;
default = null;
description = "Inline MTProto secret (`openssl rand -hex 16`). Ends up in the Nix store; prefer secretFile.";
example = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
};
secretFile = mkOption {
type = types.nullOr types.str;
default = null;
description = "Runtime path to the MTProto secret.";
example = "/run/secrets/tg-ws-proxy-secret";
};
dcIps = mkOption {
type = types.attrsOf types.str;
default = { };
description = "Relay IP per Telegram DC ID.";
example = {
"2" = "149.154.167.220";
};
};
fakeTlsDomain = mkOption {
type = types.nullOr (types.strMatching ".+");
default = null;
description = "SNI for Fake TLS masking (ee-secret links).";
example = "www.example.com";
};
cloudflare = {
domains = domains "Cloudflare-proxied domains for WebSocket fallback." [ "cdn.example.com" ];
workerDomains = domains "Cloudflare Worker domains, tried first." [ "worker.example.com" ];
fallback = mkOption {
type = types.bool;
default = true;
description = "Fall back to Cloudflare when direct WebSocket fails.";
};
};
poolSize = mkOption {
type = types.ints.unsigned;
default = 4;
description = "WebSocket pool size per DC; 0 disables pooling.";
};
bufferKiB = mkOption {
type = types.ints.between 4 2147483647;
default = 256;
description = "Socket buffer size, in KiB.";
};
proxyProtocol = mkOption {
type = types.bool;
default = false;
description = "Accept a PROXY protocol v1 header from a fronting reverse proxy.";
};
bypassTransparentProxy = mkOption {
type = types.bool;
default = true;
description = "Keep the relay's own connections out of TUN/TProxy, which would otherwise loop them.";
};
fwmark = mkOption {
type = types.int;
default = 4;
description = "Packet mark bypassTransparentProxy uses.";
};
log = {
verbose = mkOption {
type = types.bool;
default = false;
description = "Debug logging.";
};
file = mkOption {
type = types.nullOr types.str;
default = null;
description = "Rotating log file. Null logs to stderr.";
example = "/var/log/tg-ws-proxy.log";
};
maxSizeMiB = mkOption {
type = types.numbers.positive;
default = 5.0;
description = "Log size before rotation, in MiB.";
};
keep = mkOption {
type = types.ints.positive;
default = 1;
description = "Rotated logs kept.";
};
};
};
}
+22
View File
@@ -0,0 +1,22 @@
{ lib, ... }:
let
inherit (lib) mkEnableOption mkOption types;
in
{
options.services.proxy-suite.tray = {
enable = mkEnableOption "the system tray indicator";
autostart = mkOption {
type = types.bool;
default = true;
description = "Start the tray in graphical sessions (XDG autostart).";
};
pollInterval = mkOption {
type = types.ints.positive;
default = 5;
description = "Status refresh interval, in seconds.";
};
};
}
+25 -324
View File
@@ -1,240 +1,34 @@
# Type submodule definitions shared across options sub-files.
{ lib }:
let
inherit (lib) mkOption types;
# Shared routing-rule fields (reused in both outboundType.routing and routing.rules entries)
list =
description: example:
mkOption {
type = types.listOf types.str;
default = [ ];
inherit description example;
};
routingFields = {
domains = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Domain suffixes to match in this routing rule.
Leave empty to skip domain-based matching for this rule entry.
'';
example = [
"youtube.com"
"discord.com"
];
};
ips = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
IP CIDRs to match in this routing rule.
Leave empty to skip IP-based matching for this rule entry.
'';
example = [ "1.1.1.0/24" ];
};
geosites = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
sing-geosite rule-set names to match in this routing rule.
Each name becomes a backend geosite rule-set reference.
'';
example = [
"netflix"
"google"
];
};
geoips = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
sing-geoip rule-set names to match in this routing rule.
Each name becomes a backend geoip rule-set reference.
'';
example = [
"us"
"de"
];
};
domains = list "Domain suffixes to match." [ "youtube.com" ];
ips = list "IP CIDRs to match." [ "1.1.1.0/24" ];
geosites = list "Geosite names to match (see geodata)." [ "netflix" ];
geoips = list "Geoip names to match (see geodata; the defaults are country codes only)." [ "us" ];
};
# An explicit routing rule – associates traffic patterns with a named outbound.
routingRuleType = types.submodule {
options = {
outbound = mkOption {
type = types.str;
description = ''
Target outbound tag. Can be a specific server tag (only useful with
selection = "selector" or "urltest"), or one of the built-in tags:
"proxy" (the active proxy outbound), "direct", "block".
With selection = "first", named proxy outbounds are collapsed into the
single active "proxy" outbound at runtime, so per-tag routing no longer
distinguishes between individual proxy servers.
'';
description = ''Outbound tag, or "proxy", "direct", "block". With selection = "first" every proxy tag means "proxy".'';
example = "vps-de";
};
}
// routingFields;
};
subscriptionType = types.submodule {
options = {
tag = mkOption {
type = types.strMatching "^[A-Za-z0-9][A-Za-z0-9._-]*$";
description = ''
Unique identifier for this subscription.
Used as a prefix for all outbound tags generated from its proxy list,
e.g. "my-sub" -> tags like "my-sub-Server-DE".
This value is also used as the subscription cache filename stem under
/var/lib/proxy-suite/subscriptions/<backend>/, so it must be a safe
identifier.
'';
example = "community-list";
};
url = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Literal subscription URL. The response must be a base64-encoded
newline-separated list of proxy URIs (standard v2rayN format) or
a plain-text list of the same.
This value is embedded in the Nix store. Prefer urlFile for private
subscription links or tokens.
'';
example = "https://example.com/sub/token123";
};
urlFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing the subscription URL.
Intended for use with secret managers (sops-nix, agenix, etc.).
The file is read at service start time and never lands in the Nix store.
Set exactly one of urlFile or url for each subscription entry.
'';
example = "/run/secrets/proxy-subscription-url";
};
};
};
outboundType = types.submodule {
options = {
tag = mkOption {
type = types.str;
description = ''
Outbound tag used in routing rules and multi-outbound selection.
With selection = "selector" or "urltest", each outbound keeps its own
tag and can be selected directly. With selection = "first", proxy-suite
routes through a single active outbound tagged "proxy", so individual
proxy tags are mainly useful for documentation and config structure.
'';
example = "vps-de";
};
urlFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing the proxy URL.
Intended for use with secret managers (sops-nix, agenix, etc.).
The file is read at service start time and never lands in the Nix store.
Set exactly one of urlFile, url, or json for each outbound.
'';
example = "/run/secrets/my-proxy-url";
};
url = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Literal proxy URL. Convenient for non-secret configs, but the URL
will end up in the Nix store.
Set exactly one of urlFile, url, or json for each outbound.
Prefer urlFile for real credentials.
'';
example = "hy2://password@example.com:443?sni=example.com";
};
backend = mkOption {
type = types.enum [
"auto"
"sing-box"
"xray"
];
default = "auto";
description = ''
Backend preference for this outbound when both SingBox and XRay are
enabled. "auto" uses SingBox when the URL or JSON can be represented
there and falls back to XRay for XRay-only transports such as XHTTP
or ECH. Ignored by single-backend configurations.
'';
example = "xray";
};
singBoxJson = mkOption {
type = types.nullOr types.attrs;
default = null;
description = ''
Raw sing-box outbound configuration as a Nix attribute set.
Embedded directly into the config at build time. The tag field
is overridden by the outbound's tag option.
Set exactly one of urlFile, url, singBoxJson, xrayJson, or json for
each outbound.
Use this when the proxy definition is easier to generate as native Nix
than as a single URL string. Only valid with the SingBox backend.
'';
example = {
type = "vless";
server = "example.com";
server_port = 443;
uuid = "...";
};
};
xrayJson = mkOption {
type = types.nullOr types.attrs;
default = null;
description = ''
Raw XRay outbound configuration as a Nix attribute set.
Embedded directly into the config at build time. The tag field is
overridden by the outbound's tag option.
Set exactly one of urlFile, url, singBoxJson, xrayJson, or json for
each outbound. Only valid with the XRay backend.
'';
example = {
protocol = "vless";
settings = {
address = "example.com";
port = 443;
id = "...";
encryption = "none";
};
};
};
json = mkOption {
type = types.nullOr types.attrs;
default = null;
visible = false;
description = ''
Deprecated alias for singBoxJson. Use singBoxJson instead.
'';
};
# Shorthand for attaching routing rules directly to an outbound definition.
# Traffic matching these patterns is sent to this specific outbound.
# Only meaningful when selection = "selector" or "urltest" (with "first",
# all proxy traffic goes to the single "proxy" outbound anyway).
routing = routingFields;
};
};
dnsUpstreamType = types.submodule {
options = {
type = mkOption {
@@ -244,94 +38,19 @@ let
"tls"
];
default = "udp";
description = ''
DNS transport type for this upstream resolver.
'';
example = "tls";
description = "DNS transport.";
};
address = mkOption {
type = types.strMatching ".+";
description = ''
Resolver address or hostname used for this DNS upstream.
'';
description = "Resolver address.";
example = "1.1.1.1";
};
port = mkOption {
type = types.port;
default = 53;
description = ''
Destination port for this DNS upstream.
'';
example = 853;
};
};
};
zapretPresetType = types.enum [
"general"
"google"
"instagram"
"soundcloud"
"twitter"
];
zapretHostlistRuleType = types.submodule {
options = {
name = mkOption {
type = types.strMatching "^[a-z0-9][a-z0-9-]*$";
description = ''
Custom hostlist name. Used to generate hostlists/list-<name>.txt
inside the derived zapret config directory.
'';
example = "cloudflare";
};
domains = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Domains written into the generated custom zapret hostlist file.
Must be non-empty for every hostlistRules entry.
'';
example = [
"example.com"
"example.de"
];
};
preset = mkOption {
type = types.nullOr zapretPresetType;
default = null;
description = ''
Clone the active zapret config's built-in NFQWS rule family for this
hostlist. Can be combined with nfqwsArgs for additional custom rules.
'';
example = "google";
};
nfqwsArgs = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Additional NFQWS argument fragments for this hostlist.
The module injects --hostlist=... and trailing --new automatically.
Each hostlistRules entry must define preset, nfqwsArgs, or both.
'';
example = [
"--filter-tcp=443 --dpi-desync=fake,multisplit"
];
};
enableDirectSync = mkOption {
type = types.bool;
default = true;
description = ''
Whether this custom hostlist should also be mirrored into proxy
direct domain routing when zapret.syncDirectRouting = true.
'';
description = "Resolver port.";
};
};
};
@@ -340,10 +59,7 @@ let
options = {
name = mkOption {
type = types.strMatching "^[a-z0-9][a-z0-9-]*$";
description = ''
Profile name used by `proxy-ctl wrap <name> -- <command>`.
Must be unique within perAppRouting.profiles.
'';
description = "Profile name, unique.";
example = "steam-browser";
};
@@ -357,37 +73,22 @@ let
];
default = "proxychains";
description = ''
Per-app route backend used by proxy-ctl wrap.
- "direct": run the command unchanged.
- "proxychains": run the command through proxychains-ng using the
local proxy-suite mixed SOCKS endpoint.
- "tun": launch the command in the dedicated per-app-routing TUN slice so
only that app's traffic is policy-routed into the app TUN backend.
- "tproxy": launch the command in the dedicated per-app-routing TProxy
slice so only that app's traffic is transparently intercepted by
the local proxy TProxy inbound.
- "zapret": launch the command in the dedicated per-app-routing zapret
slice so only that app's traffic is handled by the separate
per-app-scoped zapret instance.
Additional route backends may be added in the future.
Backend: "direct" (unchanged), "proxychains", or the per-app "tun", "tproxy" or "zapret"
backend of perAppRouting.
'';
example = "proxychains";
};
};
};
in
{
inherit
dnsUpstreamType
perAppRoutingProfileType
routingFields
routingRuleType
subscriptionType
outboundType
dnsUpstreamType
zapretPresetType
zapretHostlistRuleType
perAppRoutingProfileType
;
}
// import ./types/outbounds.nix { inherit lib routingFields; }
// import ./types/zapret.nix { inherit lib; }
// import ./types/inbounds.nix { inherit lib; }
// import ./types/amnezia-wg.nix { inherit lib; }
@@ -0,0 +1,308 @@
# AmneziaWG profile option types.
{ lib }:
let
inherit (lib) mkOption types;
optionalString = types.nullOr types.str;
optionalUnsigned = types.nullOr types.ints.unsigned;
rangeValue = types.oneOf [
types.ints.unsigned
(types.strMatching "^([0-9]+|[0-9]+-[0-9]+|\\(off\\))$")
];
optionalRange = types.nullOr rangeValue;
peerType = types.submodule {
options = {
publicKey = mkOption {
type = types.strMatching "[^[:space:]]+";
description = "AmneziaWG peer public key.";
};
presharedKey = mkOption {
type = optionalString;
default = null;
description = "Inline peer preshared key. Prefer presharedKeyFile for secrets.";
};
presharedKeyFile = mkOption {
type = optionalString;
default = null;
description = "Runtime path containing the peer preshared key.";
};
allowedIPs = mkOption {
type = types.listOf types.str;
description = "IP prefixes routed to and accepted from this peer.";
example = [
"0.0.0.0/0"
"::/0"
];
};
endpoint = mkOption {
type = optionalString;
default = null;
example = "vpn.example.com:51820";
description = "Optional peer endpoint in host:port form.";
};
persistentKeepalive = mkOption {
type = optionalRange;
default = null;
description = "Persistent keepalive seconds, optionally expressed as an AWG 3 range.";
};
advancedSecurity = mkOption {
type = types.nullOr types.bool;
default = null;
description = "Optional AWG peer AdvancedSecurity setting.";
};
};
};
obfuscationType = types.submodule {
options = {
jc = mkOption {
type = optionalUnsigned;
default = null;
description = "Junk packet count (Jc).";
};
jmin = mkOption {
type = optionalUnsigned;
default = null;
description = "Minimum junk packet size (Jmin).";
};
jmax = mkOption {
type = optionalUnsigned;
default = null;
description = "Maximum junk packet size (Jmax).";
};
s1 = mkOption {
type = optionalUnsigned;
default = null;
description = "Handshake-init padding (S1).";
};
s2 = mkOption {
type = optionalUnsigned;
default = null;
description = "Handshake-response padding (S2).";
};
s3 = mkOption {
type = optionalUnsigned;
default = null;
description = "Cookie-reply padding (S3).";
};
s4 = mkOption {
type = optionalUnsigned;
default = null;
description = "Transport-message padding (S4).";
};
h1 = mkOption {
type = optionalRange;
default = null;
description = "Handshake-init header or range (H1).";
};
h2 = mkOption {
type = optionalRange;
default = null;
description = "Handshake-response header or range (H2).";
};
h3 = mkOption {
type = optionalRange;
default = null;
description = "Cookie-reply header or range (H3).";
};
h4 = mkOption {
type = optionalRange;
default = null;
description = "Transport-message header or range (H4).";
};
i1 = mkOption {
type = optionalString;
default = null;
description = "First custom signature packet (I1).";
};
i2 = mkOption {
type = optionalString;
default = null;
description = "Second custom signature packet (I2).";
};
i3 = mkOption {
type = optionalString;
default = null;
description = "Third custom signature packet (I3).";
};
i4 = mkOption {
type = optionalString;
default = null;
description = "Fourth custom signature packet (I4).";
};
i5 = mkOption {
type = optionalString;
default = null;
description = "Fifth custom signature packet (I5).";
};
headerProtectionKey = mkOption {
type = optionalString;
default = null;
description = "Inline AWG 3 header-protection key. Prefer headerProtectionKeyFile.";
};
headerProtectionKeyFile = mkOption {
type = optionalString;
default = null;
description = "Runtime path containing the AWG 3 header-protection key.";
};
contentPaddingAddition = mkOption {
type = optionalRange;
default = null;
description = "AWG 3 content-padding addition or range.";
};
rekeyAfterTime = mkOption {
type = optionalRange;
default = null;
description = "AWG 3 rekey interval or range.";
};
rekeyTimeout = mkOption {
type = optionalRange;
default = null;
description = "AWG 3 rekey timeout or range.";
};
rejectAfterTime = mkOption {
type = optionalRange;
default = null;
description = "AWG 3 reject-after interval or range.";
};
keepaliveTimeout = mkOption {
type = optionalRange;
default = null;
description = "AWG 3 keepalive timeout or range.";
};
maxHandshakeAttempts = mkOption {
type = optionalRange;
default = null;
description = "AWG 3 maximum handshake attempts or range.";
};
randomTrailers = mkOption {
type = types.nullOr types.bool;
default = null;
description = "AWG 3 random transport trailers (RandomTrailers).";
};
disableCookies = mkOption {
type = types.nullOr types.bool;
default = null;
description = "AWG 3 cookie suppression (DisableCookies).";
};
};
};
settingsType = types.submodule {
options = {
addresses = mkOption {
type = types.listOf types.str;
default = [ ];
description = "IP prefixes assigned to the AWG interface.";
example = [ "10.8.0.2/32" ];
};
dns = mkOption {
type = types.listOf types.str;
default = [ ];
description = "DNS servers installed while this profile is active.";
};
privateKey = mkOption {
type = optionalString;
default = null;
description = "Inline client private key. Prefer privateKeyFile.";
};
privateKeyFile = mkOption {
type = optionalString;
default = null;
description = "Runtime path containing the client private key.";
};
listenPort = mkOption {
type = types.nullOr types.port;
default = null;
description = "Optional local UDP listen port.";
};
mtu = mkOption {
type = optionalUnsigned;
default = null;
description = "Optional interface MTU.";
};
table = mkOption {
type = optionalString;
default = null;
description = "wg-quick routing table name/number, auto, or off.";
};
obfuscation = mkOption {
type = obfuscationType;
default = { };
description = "AmneziaWG 1.x through 3.x obfuscation parameters.";
};
obfuscationFile = mkOption {
type = optionalString;
default = null;
example = "/run/secrets/awg-obfuscation.json";
description = ''
Runtime path to a partial JSON object using the same field names and
value types as obfuscation, excluding headerProtectionKeyFile.
Values are combined with public obfuscation settings at service startup
without putting the file contents in the Nix store. Omitted or null
fields are unset; duplicate JSON keys and fields set in both sources
are rejected. A file-provided headerProtectionKey also conflicts with
obfuscation.headerProtectionKeyFile. Private and preshared keys use
their existing file options. Restart the profile after secret rotation.
'';
};
peers = mkOption {
type = types.listOf peerType;
default = [ ];
description = "AmneziaWG peers.";
};
};
};
profileType = types.submodule (
{ name, ... }:
{
options = {
interfaceName = mkOption {
type = types.strMatching "^[A-Za-z0-9_.-]{1,15}$";
default = "awg-${name}";
description = "Linux interface name. It must fit Linux's 15-character limit.";
};
autostart = mkOption {
type = types.bool;
default = false;
description = "Whether to start this profile at boot. At most one profile may autostart.";
};
allowConfigHooks = mkOption {
type = types.bool;
default = false;
description = "Allow trusted imported configs to execute wg-quick hooks or use SaveConfig.";
};
vpnContainer = mkOption {
type = optionalString;
default = null;
description = "AWG container/protocol identifier to select when a vpn:// bundle is ambiguous.";
};
configFile = mkOption {
type = optionalString;
default = null;
description = "Runtime path to an AmneziaWG .conf file.";
};
vpnFile = mkOption {
type = optionalString;
default = null;
description = "Runtime path containing a self-contained vpn:// export.";
};
vpn = mkOption {
type = optionalString;
default = null;
description = "Inline self-contained vpn:// export. This value is stored in the Nix store.";
};
settings = mkOption {
type = types.nullOr settingsType;
default = null;
description = "Typed declarative AmneziaWG client configuration.";
};
};
}
);
in
{
inherit profileType;
}
@@ -0,0 +1,235 @@
{ lib }:
let
inherit (lib) mkOption types;
nullStr =
description: example:
mkOption {
type = types.nullOr types.str;
default = null;
inherit description example;
};
userType = types.submodule {
options = {
name = mkOption {
type = types.str;
default = "";
description = "Account label: the share link's name, and what subscriptions and stats group by.";
example = "phone";
};
uuid = nullStr "UUID (vless, vmess). Ends up in the Nix store; prefer uuidFile." "b831381d-6324-4d53-ad4f-8cda48b30811";
uuidFile = nullStr "Runtime path to the UUID." "/run/secrets/proxy-inbound-uuid";
password = nullStr "Password (trojan, shadowsocks, socks, http). Ends up in the Nix store; prefer passwordFile." "hunter2";
passwordFile = nullStr "Runtime path to the password." "/run/secrets/proxy-inbound-password";
};
};
transportType = types.submodule {
options = {
type = mkOption {
type = types.enum [
"raw"
"ws"
"grpc"
"httpupgrade"
"xhttp"
];
default = "raw";
description = ''Stream transport. "raw" is plain TCP, the usual choice for REALITY.'';
example = "ws";
};
path = mkOption {
type = types.str;
default = "/";
description = "Request path (ws, httpupgrade, xhttp).";
example = "/download";
};
host = nullStr "Expected Host header (ws, httpupgrade, xhttp). Null accepts any." "cdn.example.com";
mode = mkOption {
type = types.nullOr (
types.enum [
"auto"
"packet-up"
"stream-up"
"stream-one"
]
);
default = null;
description = ''xhttp mode. Null lets the client choose; behind an HTTP/1.1 proxy use "packet-up".'';
example = "packet-up";
};
serviceName = mkOption {
type = types.str;
default = "";
description = "gRPC service name.";
example = "GunService";
};
};
};
tlsType = types.submodule {
options = {
enable = mkOption {
type = types.bool;
default = false;
description = "Terminate TLS (always on for trojan). Exclusive with reality.";
};
certificateFile = nullStr "Runtime path to the PEM certificate chain." "/var/lib/acme/example.com/fullchain.pem";
keyFile = nullStr "Runtime path to the PEM private key." "/var/lib/acme/example.com/key.pem";
serverName = nullStr "SNI in share links. Defaults to inbounds.serverAddress." "example.com";
alpn = mkOption {
type = types.nullOr (
types.listOf (
types.enum [
"h3"
"h2"
"http/1.1"
]
)
);
default = null;
description = ''
ALPN offered and put in share links. [ "h3" ] alone makes an xhttp listener UDP-only, so
a web server can keep the TCP port.
'';
example = [ "h3" ];
};
};
};
realityType = types.submodule {
options = {
enable = mkOption {
type = types.bool;
default = false;
description = "Enable REALITY. Exclusive with tls.";
};
dest = mkOption {
type = types.str;
default = "www.microsoft.com:443";
description = "TLS 1.3 + HTTP/2 server that unauthenticated probes are forwarded to.";
};
serverNames = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Accepted SNIs, served by dest. The first goes into share links.";
example = [ "www.microsoft.com" ];
};
privateKeyFile = nullStr "Runtime path to the x25519 private key (`xray x25519`)." "/run/secrets/proxy-inbound-reality-key";
privateKey = nullStr "x25519 private key. Ends up in the Nix store; prefer privateKeyFile." "gG1Yz...";
publicKey = nullStr "x25519 public key, required for share links." "jNXH...";
shortIds = mkOption {
type = types.listOf types.str;
default = [ "" ];
description = "Accepted short IDs (hex). The first goes into share links.";
example = [ "0123abcd" ];
};
};
};
inboundType = types.submodule {
options = {
type = mkOption {
type = types.nullOr (
types.enum [
"vless"
"vmess"
"trojan"
"shadowsocks"
"socks"
"http"
]
);
default = null;
description = "Protocol. Set exactly one of type, xrayJson, or jsonFile.";
example = "vless";
};
port = mkOption {
type = types.port;
default = 443;
description = "Bound port.";
};
sharePort = mkOption {
type = types.nullOr types.port;
default = null;
description = "Port share links advertise, when something in front owns the public port. Null uses port.";
example = 443;
};
address = mkOption {
type = types.strMatching "[^[:space:]]+";
default = "::";
description = "Bound address. A loopback address keeps the port closed in the firewall.";
example = "127.0.0.1";
};
via = nullStr "Egress, as in inbounds.routing.via. Null inherits it." "nl-vps";
users = mkOption {
type = types.listOf userType;
default = [ ];
description = "Accepted accounts.";
example = [ { uuidFile = "/run/secrets/proxy-inbound-uuid"; } ];
};
flow = mkOption {
type = types.nullOr (types.enum [ "xtls-rprx-vision" ]);
default = null;
description = "VLESS flow; raw transport only.";
example = "xtls-rprx-vision";
};
method = mkOption {
type = types.str;
default = "2022-blake3-aes-128-gcm";
description = "Shadowsocks cipher. 2022 ciphers take a base64 key of matching length as password.";
example = "aes-128-gcm";
};
transport = mkOption {
type = transportType;
default = { };
description = "Stream transport.";
};
tls = mkOption {
type = tlsType;
default = { };
description = "TLS termination.";
};
reality = mkOption {
type = realityType;
default = { };
description = "REALITY.";
};
xrayJson = mkOption {
type = types.nullOr types.attrs;
default = null;
description = "Raw XRay inbound, built into the store; tag is overridden.";
example = {
protocol = "dokodemo-door";
settings.port = 8080;
};
};
jsonFile = nullStr "Runtime path to a raw XRay inbound (no share link); tag is overridden." "/run/secrets/proxy-inbound-vless.json";
};
};
in
{
inherit inboundType;
}
@@ -0,0 +1,82 @@
{ lib, routingFields }:
let
inherit (lib) mkOption types;
nullStr =
description: example:
mkOption {
type = types.nullOr types.str;
default = null;
inherit description example;
};
nullAttrs =
description: example:
mkOption {
type = types.nullOr types.attrs;
default = null;
inherit description example;
};
subscriptionType = types.submodule {
options = {
tag = mkOption {
type = types.strMatching "^[A-Za-z0-9][A-Za-z0-9._-]*$";
description = "Unique name; prefixes the tags of its outbounds and names its cache file.";
example = "community-list";
};
url = nullStr "Subscription URL. Ends up in the Nix store; prefer urlFile." "https://example.com/sub/token123";
urlFile = nullStr "Runtime path to the subscription URL." "/run/secrets/proxy-subscription-url";
};
};
outboundType = types.submodule {
options = {
tag = mkOption {
type = types.str;
description = "Outbound tag, for routing rules and selection.";
example = "vps-de";
};
url = nullStr "Proxy URL. Ends up in the Nix store; prefer urlFile." "hy2://password@example.com:443?sni=example.com";
urlFile = nullStr "Runtime path to the proxy URL." "/run/secrets/my-proxy-url";
singBoxJson = nullAttrs "Raw sing-box outbound (sing-box backend); tag is overridden." {
type = "vless";
server = "example.com";
server_port = 443;
};
xrayJson = nullAttrs "Raw XRay outbound (XRay backend); tag is overridden." {
protocol = "vless";
settings.address = "example.com";
};
json = mkOption {
type = types.nullOr types.attrs;
default = null;
visible = false;
description = "Deprecated alias for singBoxJson.";
};
backend = mkOption {
type = types.enum [
"auto"
"sing-box"
"xray"
];
default = "auto";
description = ''
Backend for this outbound when both run. "auto" prefers sing-box and falls back to XRay
for XRay-only transports (XHTTP, ECH).
'';
example = "xray";
};
# Destinations sent to this outbound (selection "selector" or "urltest").
routing = routingFields;
};
};
in
{
inherit subscriptionType outboundType;
}
@@ -0,0 +1,96 @@
{ lib }:
let
inherit (lib) mkOption types;
zapretPresetType = types.enum [
"general"
"google"
"instagram"
"soundcloud"
"twitter"
];
zapretDefaultDomainType = types.enum [
"general"
"google"
"discord"
"youtube"
"instagram"
"soundcloud"
"twitter"
];
zapretDefaultIpType = types.enum [ "all" ];
zapretHostlistRuleType = types.submodule {
options = {
name = mkOption {
type = types.strMatching "^[a-z0-9][a-z0-9-]*$";
description = "Hostlist name (hostlists/list-<name>.txt).";
example = "cloudflare";
};
domains = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Domains in this hostlist.";
example = [ "example.com" ];
};
defaultDomains = mkOption {
type = types.listOf zapretDefaultDomainType;
default = [ ];
description = ''
Upstream lists to include ("discord" = "general", "youtube" = "google"). Without preset,
use one per rule so the strategy family can be inferred.
'';
example = [ "google" ];
};
ips = mkOption {
type = types.listOf types.str;
default = [ ];
description = "IPs/CIDRs in this rule's ipset.";
example = [ "203.0.113.0/24" ];
};
defaultIps = mkOption {
type = types.listOf zapretDefaultIpType;
default = [ ];
description = ''Upstream ipsets to include ("all" is ipset-all.txt).'';
example = [ "all" ];
};
preset = mkOption {
type = types.nullOr zapretPresetType;
default = null;
description = "Strategy family to clone, from configName or the active config.";
example = "google";
};
configName = mkOption {
type = types.nullOr types.str;
default = null;
description = "Config to clone strategies from. Exclusive with nfqwsArgs.";
example = "general(ALT9)";
};
nfqwsArgs = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Raw NFQWS arguments; --hostlist and --new are added. Exclusive with configName.";
example = [ "--filter-tcp=443 --dpi-desync=fake,multisplit" ];
};
enableDirectSync = mkOption {
type = types.bool;
default = true;
description = "Include these domains in zapret.directSync.";
};
};
};
in
{
inherit zapretHostlistRuleType;
}
@@ -0,0 +1,34 @@
{ lib, ... }:
let
inherit (lib) mkOption types;
in
{
options.services.proxy-suite.userControl = {
group = mkOption {
type = types.strMatching "^[a-z_][a-z0-9_-]*$";
default = "proxy-suite";
description = "Group whose members may run privileged `proxy-ctl` commands without a password.";
};
allow = mkOption {
type = types.listOf (
types.enum [
"global"
"perApp"
]
);
default = [
"global"
"perApp"
];
description = ''
What userControl.group may control without a password:
- "global": the global units (proxy, tun, tproxy, zapret, restart, subs update).
- "perApp": the per-app backend units used by `proxy-ctl apps run`.
Empty grants no passwordless control.
'';
example = [ "global" ];
};
};
}
+79 -174
View File
@@ -1,193 +1,98 @@
# zapret DPI bypass options.
{ lib, ... }:
let
inherit (lib) mkOption mkEnableOption types;
inherit (lib) mkEnableOption mkOption types;
t = import ./types.nix { inherit lib; };
list =
description: example:
mkOption {
type = types.listOf types.str;
default = [ ];
inherit description example;
};
bool =
default: description:
mkOption {
type = types.bool;
inherit default description;
};
in
{
options.services.proxy-suite.zapret = {
enable = mkEnableOption "zapret DPI bypass";
perApp = {
enable = mkEnableOption "per-app-scoped zapret backend for perAppRouting profiles";
filterMark = mkOption {
type = types.int;
default = 268435456;
description = ''
Packet mark bit used to mark wrapped app traffic for the
dedicated per-app-scoped zapret instance.
'';
example = 268435456;
};
qnum = mkOption {
type = types.int;
default = 201;
description = ''
NFQUEUE number used by the dedicated per-app-scoped zapret instance.
This backend runs as a second zapret daemon and should use a
queue distinct from the global zapret instance.
'';
example = 201;
};
};
syncDirectRouting = mkOption {
type = types.bool;
default = true;
description = ''
When zapret.enable = true, mirror zapret's upstream domain hostlists
into proxy direct domain routing.
This includes the default zapret domain lists and any custom
hostlistRules entries with enableDirectSync = true.
'';
example = true;
};
syncDirectRoutingUpstreamIps = mkOption {
type = types.bool;
default = false;
description = ''
When zapret.enable = true, mirror zapret's upstream ipset ranges
(such as ipset-all.txt minus exclusions) into proxy direct IP routing.
'';
example = false;
};
syncDirectRoutingUserIps = mkOption {
type = types.bool;
default = true;
description = ''
When zapret.enable = true, mirror user-defined zapret.ipsetAll and
zapret.ipsetExclude entries into proxy direct IP routing.
'';
example = true;
};
configName = mkOption {
type = types.str;
default = "general(ALT)";
description = "zapret strategy preset name passed through to the generated zapret configuration.";
example = "general(ALT)";
};
gameFilter = mkOption {
type = types.str;
default = "null";
description = ''zapret game traffic filter mode: "all", "tcp", "udp", or "null" to disable.'';
example = "null";
};
listGeneral = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Extra domains to include in zapret's interception list.
When syncDirectRouting = true, these domains are also mirrored into
proxy direct routing.
'';
example = [ "youtube.com" ];
};
listExclude = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Domains to exclude from zapret interception.
When syncDirectRouting = true, these exclusions also remove matching
domains from the zapret-derived proxy direct-routing set.
'';
example = [ "music.youtube.com" ];
};
ipsetAll = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Extra IPs/CIDRs to add to zapret's ipset.
Mirrored into proxy direct IP routing when
syncDirectRoutingUserIps = true.
'';
example = [ "203.0.113.0/24" ];
};
ipsetExclude = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
IPs/CIDRs to exclude from zapret's ipset.
Also excluded from zapret-derived proxy direct IP routing when
syncDirectRoutingUserIps = true.
'';
example = [ "203.0.113.10/32" ];
};
includeExtraUpstreamLists = mkOption {
type = types.bool;
default = false;
description = ''
Automatically activate upstream list-instagram.txt, list-soundcloud.txt,
and list-twitter.txt in the generated zapret config when the selected
upstream preset does not already reference them.
When syncDirectRouting = true, domains from these extra lists are also
mirrored into proxy direct routing.
'';
example = false;
};
hostlistRules = mkOption {
type = types.listOf t.zapretHostlistRuleType;
default = [ ];
description = ''
Additional named zapret hostlists with per-list DPI mitigation rules.
Each entry generates hostlists/list-<name>.txt and can clone a built-in
zapret family, add custom NFQWS rule fragments, or both.
Each entry must define at least one domain and at least one of preset
or nfqwsArgs.
'';
example = [
{
name = "googlevideo";
domains = [
"googlevideo.com"
"ggpht.com"
];
preset = "google";
}
{
name = "example";
domains = [
"example.com"
"example.de"
];
preset = "general";
nfqwsArgs = [
"--filter-tcp=443 --dpi-desync=fake,multisplit"
];
}
engine = mkOption {
type = types.enum [
"zapret-discord-youtube"
"zapret2"
];
default = "zapret-discord-youtube";
description = ''
"zapret-discord-youtube": nfqws with curated presets and static hostlists (zapret.zapret-discord-youtube).
"zapret2": nfqws2, which learns blocked hosts at runtime (zapret.zapret2).
'';
example = "zapret2";
};
cidrExemption = {
enable = mkEnableOption "CIDR exemption from zapret NFQUEUE";
# What zapret feeds back into the client routing table.
directSync = {
enable = bool true "Add zapret's domain hostlists to proxy.routing.direct.";
upstreamIps = bool false "Add zapret's upstream ipsets to proxy.routing.direct.";
userIps = bool true "Add zapret-discord-youtube.ips, minus zapret-discord-youtube.excludeIps, to proxy.routing.direct.";
};
cidrs = mkOption {
type = types.listOf types.str;
default = [ ];
example = [
"192.168.123.0/24"
"10.0.0.0/8"
# Shared by both engines: a netfilter-level bypass, not an engine-specific concept.
cidrExemption = {
enable = mkEnableOption "exempting subnets from zapret, e.g. NATed VMs whose traffic it would break";
cidrs = list "Exempted subnets." [ "192.168.123.0/24" ];
};
zapret-discord-youtube = {
configName = mkOption {
type = types.str;
default = "general(ALT)";
description = "Upstream strategy preset. Names that differ only in whitespace match.";
example = "general (ALT9)";
};
gameFilter = mkOption {
type = types.enum [
"all"
"tcp"
"udp"
"null"
];
default = "null";
description = ''Game traffic filter, or "null" for off.'';
example = "all";
};
domains = list "Extra domains to bypass." [ "youtube.com" ];
excludeDomains = list "Domains never bypassed." [ "music.youtube.com" ];
ips = list "Extra IPs/CIDRs to bypass." [ "203.0.113.0/24" ];
excludeIps = list "IPs/CIDRs never bypassed." [ "203.0.113.10/32" ];
includeExtraUpstreamLists = bool false "Also use the upstream instagram, soundcloud and twitter lists.";
hostlistRules = mkOption {
type = types.listOf t.zapretHostlistRuleType;
default = [ ];
description = ''
Subnets to exempt from zapret's NFQUEUE mangle rules.
Useful when a VM (libvirt, etc.) is behind NAT and zapret
would corrupt its traffic through the host's nftables.
Extra named hostlists, each with its own strategy: cloned from a preset or configName,
or given as nfqwsArgs.
'';
example = [
{
name = "youtube-alt9";
defaultDomains = [ "youtube" ];
configName = "general(ALT9)";
}
{
name = "custom-sites";
domains = [ "example.com" ];
preset = "general";
}
];
};
};
};
+139
View File
@@ -0,0 +1,139 @@
{ lib, ... }:
let
inherit (lib) mkEnableOption mkOption types;
int =
default: description:
mkOption {
type = types.ints.positive;
inherit default description;
};
# Ported from nfqws2-keenetic. `circular` rotates strategy=1/2/3 per
# second-level domain whenever the failure detector fires.
defaultProfiles = [
''
--filter-tcp=443,80,1984,5222 --filter-l7=http,tls,mtproto <HOSTLIST>
--payload=tls_client_hello,mtproto_initial
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
--lua-desync=fake:blob=tls_clienthello:tls_mod=rnd,dupsid,sni=fonts.google.com:tcp_seq=10000:strategy=1
--lua-desync=multisplit:pos=1,midsld:seqovl=1:seqovl_pattern=tls_clienthello:tcp_ts_up:strategy=1
--lua-desync=fake:blob=0x00000000:tcp_ack=-66000:tls_mod=rnd,dupsid,sni=www.google.com:repeats=2:strategy=2
--lua-desync=multisplit:pos=1,midsld:strategy=2
--lua-desync=hostfakesplit:host=ozon.ru:midhost=host-2:seqovl=sniext+3:seqovl_pattern=tls_clienthello:badsum:tcp_md5:tcp_ts_up:strategy=3
--lua-desync=hostfakesplit:tcp_md5:tcp_ts_up:strategy=3
--payload=http_req
--lua-desync=http_methodeol:badsum
''
# QUIC reads the learned list but never adds to it: browsers retry over TCP.
''
--filter-udp=443 --filter-l7=quic <HOSTLIST_NOAUTO>
--payload=quic_initial
--lua-desync=fake:blob=quic_initial:repeats=11
''
# No hostlist: these protocols carry no SNI.
''
--filter-udp=590-600,1400,3478-3481,5349,19294-19344,49152-65535
--filter-l7=wireguard,stun,discord,mtproto,unknown
--out-range=<n2
--payload=wireguard_initiation,wireguard_response,wireguard_cookie,stun,discord_ip_discovery,mtproto_initial,unknown
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
--lua-desync=fake:repeats=6:strategy=1
--lua-desync=fake:blob=quic_initial:repeats=6:strategy=2
''
];
in
{
options.services.proxy-suite.zapret.zapret2 = {
profiles = mkOption {
type = types.listOf types.str;
default = defaultProfiles;
description = ''
nfqws2 profiles, joined with --new; first match wins. <HOSTLIST> expands to the hostlist
arguments, <HOSTLIST_NOAUTO> to the same without learning. --qnum, --fwmark and --lua-init
are added automatically.
'';
example = [
"--filter-tcp=443 --filter-l7=tls <HOSTLIST> --payload=tls_client_hello --lua-desync=multisplit:pos=1,midsld"
];
};
blobs = mkOption {
type = types.attrsOf types.str;
default = {
tls_clienthello = "tls_clienthello_www_google_com.bin";
quic_initial = "quic_initial_www_google_com.bin";
};
description = "Fake payloads by name (blob=<name>): a file in zapret2's files/fake, or an absolute path.";
example = {
tls_clienthello = "/etc/proxy-suite/my_clienthello.bin";
};
};
domains = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Domains always treated as blocked. At runtime: `proxy-ctl zapret auto add`.";
example = [ "rutracker.org" ];
};
excludeDomains = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Domains never touched or learned. At runtime: `proxy-ctl zapret auto exclude`.";
example = [ "bank.example.com" ];
};
ports = {
tcp = mkOption {
type = types.str;
default = "80,443,1984,2053,2083,2087,2096,5222,8443";
description = "TCP ports sent to NFQUEUE. Must cover every port a profile filters on.";
};
udp = mkOption {
type = types.str;
default = "443,590-600,1400,3478-3481,5349,19294-19344,49152-65535";
description = "UDP ports sent to NFQUEUE. Must cover every port a profile filters on.";
};
};
ipv6 = mkOption {
type = types.bool;
default = false;
description = "Intercept IPv6 as well as IPv4.";
};
autoHostlist = {
enable = mkEnableOption "learning blocked hosts at runtime" // {
default = true;
description = ''
Learn blocked hosts: after failThreshold failures (retransmissions, early RST, DPI
redirect, one-sided UDP) a host joins /var/lib/proxy-suite/zapret2/zapret-hosts-auto.txt.
Off, only zapret2.domains and `proxy-ctl zapret auto add` are acted on.
'';
};
failThreshold = int 3 "Failures before a host is learned.";
failTime = int 300 "Seconds allowed between two failures before the count resets.";
retransThreshold = int 3 "Retransmissions of the first request that count as one failure.";
retransReset = mkOption {
type = types.bool;
default = true;
description = "RST a stalled client once retransThreshold is hit, so failures are counted fast.";
};
retransMaxseq = int 32768 "Outgoing sequence number past which failure detection stops.";
incomingMaxseq = int 4096 "Incoming sequence number past which an RST or redirect is not a failure.";
udpOut = int 4 "Outgoing UDP packets before a one-sided exchange counts as a failure.";
udpIn = int 1 "Incoming UDP packets at or below which an exchange is one-sided.";
debugLog = mkOption {
type = types.bool;
default = false;
description = "Log why hosts are or are not learned to zapret-hosts-auto-debug.log.";
};
};
};
}
+120
View File
@@ -0,0 +1,120 @@
{
lib,
cfg,
zapret,
}:
let
r = cfg.proxy.routing;
zapretCfg = cfg.zapret;
zapretDomainGroups = import ./zapret-domain-groups.nix { inherit lib zapret; };
trim = lib.strings.trim;
hasPrefix = lib.strings.hasPrefix;
splitString = lib.strings.splitString;
zapretSrc = if builtins.isAttrs zapret && zapret ? outPath then zapret.outPath else zapret;
parseListFile =
path:
lib.unique (
builtins.filter (line: line != "" && !(hasPrefix "#" line)) (
map trim (splitString "\n" (builtins.replaceStrings [ "\r" ] [ "" ] (builtins.readFile path)))
)
);
subtractItems = items: exclusions: builtins.filter (item: !(builtins.elem item exclusions)) items;
syncZapretDirectDomains = zapretCfg.enable && zapretCfg.directSync.enable;
syncZapretDirectUpstreamIps = zapretCfg.enable && zapretCfg.directSync.upstreamIps;
syncZapretDirectUserIps = zapretCfg.enable && zapretCfg.directSync.userIps;
syncZapretDirectAnyIps = syncZapretDirectUpstreamIps || syncZapretDirectUserIps;
zapretDefaultDomainFiles = [
"list-general.txt"
"list-google.txt"
]
++ lib.optionals zapretCfg.zapret-discord-youtube.includeExtraUpstreamLists [
"list-instagram.txt"
"list-soundcloud.txt"
"list-twitter.txt"
];
zapretDefaultDomains =
if syncZapretDirectDomains then
lib.unique (
lib.concatMap (file: parseListFile "${zapretSrc}/hostlists/${file}") zapretDefaultDomainFiles
)
else
[ ];
zapretDefaultIps =
if syncZapretDirectUpstreamIps then parseListFile "${zapretSrc}/hostlists/ipset-all.txt" else [ ];
zapretUserIps = if syncZapretDirectUserIps then zapretCfg.zapret-discord-youtube.ips else [ ];
zapretCustomDomains =
if syncZapretDirectDomains then
lib.unique (
lib.concatMap (
rule: lib.optionals rule.enableDirectSync (zapretDomainGroups.effectiveRuleDomains rule)
) zapretCfg.zapret-discord-youtube.hostlistRules
)
else
[ ];
zapretCustomUserIps =
if syncZapretDirectUserIps then
lib.unique (
lib.concatMap (rule: lib.optionals rule.enableDirectSync rule.ips) zapretCfg.zapret-discord-youtube.hostlistRules
)
else
[ ];
zapretCustomDefaultIps =
if syncZapretDirectUpstreamIps then
lib.unique (
lib.concatMap (
rule: lib.optionals rule.enableDirectSync (zapretDomainGroups.expandDefaultIps rule.defaultIps)
) zapretCfg.zapret-discord-youtube.hostlistRules
)
else
[ ];
zapretExcludedDomains =
if syncZapretDirectDomains then parseListFile "${zapretSrc}/hostlists/list-exclude.txt" else [ ];
zapretExcludedIps = lib.unique (
(
if syncZapretDirectUpstreamIps then
parseListFile "${zapretSrc}/hostlists/ipset-exclude.txt"
else
[ ]
)
++ (if syncZapretDirectUserIps then zapretCfg.zapret-discord-youtube.excludeIps else [ ])
);
zapretDirectDomains =
if syncZapretDirectDomains then
subtractItems (lib.unique (zapretDefaultDomains ++ zapretCfg.zapret-discord-youtube.domains ++ zapretCustomDomains)) (
lib.unique (zapretExcludedDomains ++ zapretCfg.zapret-discord-youtube.excludeDomains)
)
else
[ ];
zapretDirectIps =
if syncZapretDirectAnyIps then
subtractItems (
lib.unique (zapretDefaultIps ++ zapretUserIps ++ zapretCustomUserIps ++ zapretCustomDefaultIps)
) zapretExcludedIps
else
[ ];
in
{
# The zapret-derived portion on its own. proxyInbounds routes these to the
# direct outbound so the host's own zapret handles the DPI bypass for inbound
# clients, instead of paying for a proxy hop it does not need.
zapretDirect = {
domains = zapretDirectDomains;
ips = zapretDirectIps;
};
direct = {
domains = lib.unique (r.direct.domains ++ zapretDirectDomains);
ips = lib.unique (r.direct.ips ++ zapretDirectIps);
geosites = lib.unique (r.direct.geosites ++ lib.optional r.directRu "category-ru");
geoips = lib.unique (r.direct.geoips ++ lib.optional r.directRu "ru");
};
}
+36 -318
View File
@@ -10,98 +10,17 @@ let
derived = import ./derived.nix { inherit lib cfg; };
r = cfg.proxy.routing;
proxyCfg = derived.proxyCfg;
zapretCfg = cfg.zapret;
tgWsProxyCfg = cfg.tgWsProxy;
trim = lib.strings.trim;
hasPrefix = lib.strings.hasPrefix;
splitString = lib.strings.splitString;
zapretSrc = if builtins.isAttrs zapret && zapret ? outPath then zapret.outPath else zapret;
parseListFile =
path:
lib.unique (
builtins.filter (line: line != "" && !(hasPrefix "#" line)) (
map trim (splitString "\n" (builtins.replaceStrings [ "\r" ] [ "" ] (builtins.readFile path)))
)
);
subtractItems = items: exclusions: builtins.filter (item: !(builtins.elem item exclusions)) items;
syncZapretDirectDomains = zapretCfg.enable && zapretCfg.syncDirectRouting;
syncZapretDirectUpstreamIps = zapretCfg.enable && zapretCfg.syncDirectRoutingUpstreamIps;
syncZapretDirectUserIps = zapretCfg.enable && zapretCfg.syncDirectRoutingUserIps;
syncZapretDirectAnyIps = syncZapretDirectUpstreamIps || syncZapretDirectUserIps;
zapretDefaultDomainFiles = [
"list-general.txt"
"list-google.txt"
]
++ lib.optionals zapretCfg.includeExtraUpstreamLists [
"list-instagram.txt"
"list-soundcloud.txt"
"list-twitter.txt"
];
zapretDefaultDomains =
if syncZapretDirectDomains then
lib.unique (
lib.concatMap (file: parseListFile "${zapretSrc}/hostlists/${file}") zapretDefaultDomainFiles
)
else
[ ];
zapretDefaultIps =
if syncZapretDirectUpstreamIps then parseListFile "${zapretSrc}/hostlists/ipset-all.txt" else [ ];
zapretUserIps = if syncZapretDirectUserIps then zapretCfg.ipsetAll else [ ];
zapretCustomDomains =
if syncZapretDirectDomains then
lib.unique (
lib.concatMap (rule: lib.optionals rule.enableDirectSync rule.domains) zapretCfg.hostlistRules
)
else
[ ];
zapretExcludedDomains =
if syncZapretDirectDomains then parseListFile "${zapretSrc}/hostlists/list-exclude.txt" else [ ];
zapretExcludedIps = lib.unique (
(
if syncZapretDirectUpstreamIps then
parseListFile "${zapretSrc}/hostlists/ipset-exclude.txt"
else
[ ]
)
++ (if syncZapretDirectUserIps then zapretCfg.ipsetExclude else [ ])
);
zapretDirectDomains =
if syncZapretDirectDomains then
subtractItems (lib.unique (zapretDefaultDomains ++ zapretCfg.listGeneral ++ zapretCustomDomains)) (
lib.unique (zapretExcludedDomains ++ zapretCfg.listExclude)
)
else
[ ];
zapretDirectIps =
if syncZapretDirectAnyIps then
subtractItems (lib.unique (zapretDefaultIps ++ zapretUserIps)) zapretExcludedIps
else
[ ];
direct = {
domains = lib.unique (r.direct.domains ++ zapretDirectDomains);
ips = lib.unique (r.direct.ips ++ zapretDirectIps);
geosites = lib.unique (r.direct.geosites ++ lib.optional r.enableRuDirect "category-ru");
geoips = lib.unique (r.direct.geoips ++ lib.optional r.enableRuDirect "ru");
zapretDirect = import ./rules-zapret-direct.nix {
inherit
lib
cfg
zapret
;
};
inherit (zapretDirect) direct;
zapretDirectRules = zapretDirect.zapretDirect;
mkRule =
field: tag: items:
lib.optional (items != [ ]) {
${field} = items;
outbound = tag;
};
mkDomainRule = mkRule "domain_suffix";
mkIPRule = mkRule "ip_cidr";
mkRulesetRule = mkRule "rule_set";
customRuleCategory =
outbound:
if outbound == "direct" then
@@ -149,238 +68,36 @@ let
customRules =
perOutboundRules ++ map (rule: rule // { outbound = resolveTag rule.outbound; }) r.rules;
# Build sing-box routing rule entries from a custom rule record.
mkCustomRuleEntries =
rule:
lib.flatten [
(mkDomainRule rule.outbound rule.domains)
(mkIPRule rule.outbound rule.ips)
(mkRulesetRule rule.outbound (map (s: "geosite-${s}") rule.geosites))
(mkRulesetRule rule.outbound (map (s: "geoip-${s}") rule.geoips))
];
# All geosite names referenced anywhere (for rule-set file definitions).
allGeositeNames = lib.unique (
r.proxy.geosites
++ direct.geosites
++ r.block.geosites
++ lib.concatMap (rule: rule.geosites) customRules
);
# All geoip names referenced anywhere.
allGeoIPNames = lib.unique (
r.proxy.geoips ++ direct.geoips ++ r.block.geoips ++ lib.concatMap (rule: rule.geoips) customRules
);
mkRuleSet = kind: pkg: name: {
tag = "${kind}-${name}";
type = "local";
format = "binary";
path = "${pkg}/share/sing-box/rule-set/${kind}-${name}.srs";
singBoxRules = import ./rules/sing-box.nix {
inherit
lib
r
direct
tgWsProxyCfg
customRules
customRuleCategory
;
inherit (cfg) geodata;
};
inherit (singBoxRules)
geositeRuleSets
geoIPRuleSets
singBoxRoutingRules
singBoxRouteModeRules
;
geositeRuleSets = map (mkRuleSet "geosite" pkgs.sing-geosite) allGeositeNames;
geoIPRuleSets = map (mkRuleSet "geoip" pkgs.sing-geoip) allGeoIPNames;
commonRules = [
{
network = [
"tcp"
"udp"
];
port = 53;
action = "hijack-dns";
}
{ action = "sniff"; }
];
customRouteRules = map (rule: {
category = customRuleCategory rule.outbound;
entries = mkCustomRuleEntries rule;
}) customRules;
proxyPrimaryRules = lib.flatten [
(mkDomainRule "proxy" r.proxy.domains)
(mkIPRule "proxy" r.proxy.ips)
];
directRules = lib.flatten [
(mkDomainRule "direct" direct.domains)
(mkIPRule "direct" direct.ips)
(mkRulesetRule "direct" (map (s: "geosite-${s}") direct.geosites))
(mkRulesetRule "direct" (map (s: "geoip-${s}") direct.geoips))
];
tgWsProxyRelayDirectRules =
lib.optional
(tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { })
{
ip_cidr = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps);
outbound = "direct";
};
safetyDirectRules = [
{
ip_is_private = true;
outbound = "direct";
}
]
++ tgWsProxyRelayDirectRules;
blockRules = lib.flatten [
(mkDomainRule "block" r.block.domains)
(mkIPRule "block" r.block.ips)
(mkRulesetRule "block" (map (s: "geosite-${s}") r.block.geosites))
(mkRulesetRule "block" (map (s: "geoip-${s}") r.block.geoips))
];
proxyGeoRules = lib.flatten [
(mkRulesetRule "proxy" (map (s: "geosite-${s}") r.proxy.geosites))
(mkRulesetRule "proxy" (map (s: "geoip-${s}") r.proxy.geoips))
];
singBoxRoutingRules =
commonRules
++ lib.concatMap (item: item.entries) customRouteRules
++ proxyPrimaryRules
++ directRules
++ safetyDirectRules
++ blockRules
++ proxyGeoRules;
singBoxRouteModeRules = {
common = commonRules;
custom = customRouteRules;
proxyPrimary = proxyPrimaryRules;
direct = directRules;
safetyDirect = safetyDirectRules;
block = blockRules;
proxyGeo = proxyGeoRules;
};
xrayTarget =
tag:
if tag == "proxy" && derived.selectionMode == "urltest" then
{ balancerTag = "proxy"; }
else
{ outboundTag = tag; };
mkXrayRule =
ruleTag: fields: tag:
(
{
type = "field";
inherit ruleTag;
}
// fields
// (xrayTarget tag)
);
xrayDomainRules =
ruleTag: tag: domains:
lib.optional (domains != [ ]) (
mkXrayRule ruleTag {
domain = map (domain: "domain:${domain}") domains;
} tag
);
xrayIPRules =
ruleTag: tag: ips:
lib.optional (ips != [ ]) (
mkXrayRule ruleTag {
ip = ips;
} tag
);
xrayGeositeRules =
ruleTag: tag: geosites:
lib.optional (geosites != [ ]) (
mkXrayRule ruleTag {
domain = map (name: "geosite:${name}") geosites;
} tag
);
xrayGeoIPRules =
ruleTag: tag: geoips:
lib.optional (geoips != [ ]) (
mkXrayRule ruleTag {
ip = map (name: "geoip:${name}") geoips;
} tag
);
xrayCustomRuleTag = category: kind: "custom-${category}-${kind}";
mkXrayCustomRuleEntries =
rule:
lib.flatten [
(xrayDomainRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "domain") rule.outbound
rule.domains
)
(xrayIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "ip") rule.outbound rule.ips)
(xrayGeositeRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geosite") rule.outbound
rule.geosites
)
(xrayGeoIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geoip") rule.outbound
rule.geoips
)
];
xrayCustomRouteRules = map (rule: {
category = customRuleCategory rule.outbound;
entries = mkXrayCustomRuleEntries rule;
}) customRules;
xrayProxyPrimaryRules = lib.flatten [
(xrayDomainRules "proxy-domain" "proxy" r.proxy.domains)
(xrayIPRules "proxy-ip" "proxy" r.proxy.ips)
];
xrayDirectRules = lib.flatten [
(xrayDomainRules "direct-domain" "direct" direct.domains)
(xrayIPRules "direct-ip" "direct" direct.ips)
(xrayGeositeRules "direct-geosite" "direct" direct.geosites)
(xrayGeoIPRules "direct-geoip" "direct" direct.geoips)
];
xraySafetyDirectRules = [
(mkXrayRule "direct-private" { ip = [ "geoip:private" ]; } "direct")
]
++
lib.optional
(tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { })
(
mkXrayRule "direct-tg-relay" { ip = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps); } "direct"
);
xrayBlockRules = lib.flatten [
(xrayDomainRules "block-domain" "block" r.block.domains)
(xrayIPRules "block-ip" "block" r.block.ips)
(xrayGeositeRules "block-geosite" "block" r.block.geosites)
(xrayGeoIPRules "block-geoip" "block" r.block.geoips)
];
xrayProxyGeoRules = lib.flatten [
(xrayGeositeRules "proxy-geosite" "proxy" r.proxy.geosites)
(xrayGeoIPRules "proxy-geoip" "proxy" r.proxy.geoips)
];
xrayRoutingRules =
lib.concatMap (item: item.entries) xrayCustomRouteRules
++ xrayProxyPrimaryRules
++ xrayDirectRules
++ xraySafetyDirectRules
++ xrayProxyGeoRules
++ xrayBlockRules;
xrayRouteModeRules = {
common = [ ];
custom = xrayCustomRouteRules;
proxyPrimary = xrayProxyPrimaryRules;
direct = xrayDirectRules;
safetyDirect = xraySafetyDirectRules;
block = xrayBlockRules;
proxyGeo = xrayProxyGeoRules;
xrayRules = import ./rules/xray.nix {
inherit
lib
r
direct
tgWsProxyCfg
customRules
customRuleCategory
;
inherit (derived) selectionMode;
};
inherit (xrayRules) xrayRoutingRules xrayRouteModeRules;
routingRules = singBoxRoutingRules;
routeModeRules = singBoxRouteModeRules;
@@ -389,6 +106,7 @@ in
{
inherit
direct
zapretDirectRules
geositeRuleSets
geoIPRuleSets
singBoxRoutingRules
@@ -0,0 +1,135 @@
# XRay routing for the inbound service. Separate from the client ruleset:
# "proxy" here is the client stack's SOCKS listener, so its selection applies.
{
lib,
proxyInboundsCfg,
proxyInbounds,
zapretDirectRules,
}:
let
defaultVia = proxyInboundsCfg.routing.via;
# Listeners on the default egress are covered by the final rule.
overrideInbounds = builtins.filter (ib: ib.via != defaultVia) proxyInbounds;
defaultInboundTags = map (ib: ib.tag) (builtins.filter (ib: ib.via == defaultVia) proxyInbounds);
blockPrivateRule = lib.optional proxyInboundsCfg.routing.blockPrivate {
type = "field";
ruleTag = "inbound-block-private";
ip = [ "geoip:private" ];
outboundTag = "block";
};
# 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.
serverAddressIsIp =
let
addr = proxyInboundsCfg.serverAddress;
in
addr != null
&& (lib.hasInfix ":" addr || builtins.match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+" addr != null);
serverAddressRule = lib.optional (proxyInboundsCfg.serverAddress != null) (
{
type = "field";
ruleTag = "inbound-server-address-direct";
outboundTag = "direct";
}
// (
if serverAddressIsIp then
{ ip = [ proxyInboundsCfg.serverAddress ]; }
else
{ domain = [ "full:${proxyInboundsCfg.serverAddress}" ]; }
)
);
blockRuRules = lib.optionals proxyInboundsCfg.routing.blockRu [
{
type = "field";
ruleTag = "inbound-block-ru-domain";
domain = [ "geosite:category-ru" ];
outboundTag = "block";
}
{
type = "field";
ruleTag = "inbound-block-ru-ip";
ip = [ "geoip:ru" ];
outboundTag = "block";
}
];
inboundProxy = proxyInboundsCfg.routing.proxy;
proxyDomainRule = lib.optional (inboundProxy.domains != [ ] || inboundProxy.geosites != [ ]) {
type = "field";
ruleTag = "inbound-proxy-domain";
domain =
map (domain: "domain:${domain}") inboundProxy.domains
++ map (name: "geosite:${name}") inboundProxy.geosites;
inboundTag = map (ib: ib.tag) proxyInbounds;
outboundTag = "proxy";
};
proxyIpRule = lib.optional (inboundProxy.ips != [ ] || inboundProxy.geoips != [ ]) {
type = "field";
ruleTag = "inbound-proxy-ip";
ip = inboundProxy.ips ++ map (name: "geoip:${name}") inboundProxy.geoips;
inboundTag = map (ib: ib.tag) proxyInbounds;
outboundTag = "proxy";
};
# Only when the default egress is a proxy, and only for its listeners.
zapretDirectEnabled =
proxyInboundsCfg.routing.zapretDirect
&& defaultInboundTags != [ ]
&& !builtins.elem defaultVia [
"direct"
"block"
];
mkZapretRule =
ruleTag: field: items:
lib.optional (zapretDirectEnabled && items != [ ]) {
type = "field";
inherit ruleTag;
${field} = items;
inboundTag = defaultInboundTags;
outboundTag = "direct";
};
zapretRules =
mkZapretRule "inbound-zapret-direct-domain" "domain" (
map (domain: "domain:${domain}") zapretDirectRules.domains
)
++ mkZapretRule "inbound-zapret-direct-ip" "ip" zapretDirectRules.ips;
overrideRules = map (ib: {
type = "field";
ruleTag = "inbound-via-${ib.tag}";
inboundTag = [ ib.tag ];
outboundTag = ib.via;
}) overrideInbounds;
finalRule = {
type = "field";
ruleTag = "inbound-final";
network = "tcp,udp";
outboundTag = defaultVia;
};
# Explicit proxy exceptions beat blockRu: RU-geolocated ranges (Telegram's,
# at times) would otherwise swallow them.
xrayInboundRules =
blockPrivateRule
++ serverAddressRule
++ proxyDomainRule
++ proxyIpRule
++ blockRuRules
++ zapretRules
++ overrideRules
++ [ finalRule ];
in
{
inherit xrayInboundRules;
}
+136
View File
@@ -0,0 +1,136 @@
# sing-box routing rules and local rule-set definitions.
{
lib,
r,
direct,
tgWsProxyCfg,
customRules,
customRuleCategory,
geodata,
}:
let
mkRule =
field: tag: items:
lib.optional (items != [ ]) {
${field} = items;
outbound = tag;
};
mkDomainRule = mkRule "domain_suffix";
mkIPRule = mkRule "ip_cidr";
mkRulesetRule = mkRule "rule_set";
mkCustomRuleEntries =
rule:
lib.flatten [
(mkDomainRule rule.outbound rule.domains)
(mkIPRule rule.outbound rule.ips)
(mkRulesetRule rule.outbound (map (s: "geosite-${s}") rule.geosites))
(mkRulesetRule rule.outbound (map (s: "geoip-${s}") rule.geoips))
];
allGeositeNames = lib.unique (
r.proxy.geosites
++ direct.geosites
++ r.block.geosites
++ lib.concatMap (rule: rule.geosites) customRules
);
allGeoIPNames = lib.unique (
r.proxy.geoips ++ direct.geoips ++ r.block.geoips ++ lib.concatMap (rule: rule.geoips) customRules
);
mkRuleSet = kind: pkg: name: {
tag = "${kind}-${name}";
type = "local";
format = "binary";
path = "${pkg}/share/sing-box/rule-set/${kind}-${name}.srs";
};
geositeRuleSets = map (mkRuleSet "geosite" geodata.singBox.geosite) allGeositeNames;
geoIPRuleSets = map (mkRuleSet "geoip" geodata.singBox.geoip) allGeoIPNames;
commonRules = [
{
network = [
"tcp"
"udp"
];
port = 53;
action = "hijack-dns";
}
{ action = "sniff"; }
];
customRouteRules = map (rule: {
category = customRuleCategory rule.outbound;
entries = mkCustomRuleEntries rule;
}) customRules;
proxyPrimaryRules = lib.flatten [
(mkDomainRule "proxy" r.proxy.domains)
(mkIPRule "proxy" r.proxy.ips)
];
directRules = lib.flatten [
(mkDomainRule "direct" direct.domains)
(mkIPRule "direct" direct.ips)
(mkRulesetRule "direct" (map (s: "geosite-${s}") direct.geosites))
(mkRulesetRule "direct" (map (s: "geoip-${s}") direct.geoips))
];
tgWsProxyRelayDirectRules =
lib.optional
(tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { })
{
ip_cidr = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps);
outbound = "direct";
};
safetyDirectRules = [
{
ip_is_private = true;
outbound = "direct";
}
]
++ tgWsProxyRelayDirectRules;
blockRules = lib.flatten [
(mkDomainRule "block" r.block.domains)
(mkIPRule "block" r.block.ips)
(mkRulesetRule "block" (map (s: "geosite-${s}") r.block.geosites))
(mkRulesetRule "block" (map (s: "geoip-${s}") r.block.geoips))
];
proxyGeoRules = lib.flatten [
(mkRulesetRule "proxy" (map (s: "geosite-${s}") r.proxy.geosites))
(mkRulesetRule "proxy" (map (s: "geoip-${s}") r.proxy.geoips))
];
singBoxRoutingRules =
commonRules
++ lib.concatMap (item: item.entries) customRouteRules
++ proxyPrimaryRules
++ directRules
++ safetyDirectRules
++ blockRules
++ proxyGeoRules;
singBoxRouteModeRules = {
common = commonRules;
custom = customRouteRules;
proxyPrimary = proxyPrimaryRules;
direct = directRules;
safetyDirect = safetyDirectRules;
block = blockRules;
proxyGeo = proxyGeoRules;
};
in
{
inherit
geositeRuleSets
geoIPRuleSets
singBoxRoutingRules
singBoxRouteModeRules
;
}
+142
View File
@@ -0,0 +1,142 @@
# XRay routing rule definitions.
{
lib,
r,
direct,
tgWsProxyCfg,
customRules,
customRuleCategory,
selectionMode,
}:
let
xrayTarget =
tag:
if tag == "proxy" && selectionMode == "urltest" then
{ balancerTag = "proxy"; }
else
{ outboundTag = tag; };
mkXrayRule =
ruleTag: fields: tag:
(
{
type = "field";
inherit ruleTag;
}
// fields
// (xrayTarget tag)
);
xrayDomainRules =
ruleTag: tag: domains:
lib.optional (domains != [ ]) (
mkXrayRule ruleTag {
domain = map (domain: "domain:${domain}") domains;
} tag
);
xrayIPRules =
ruleTag: tag: ips:
lib.optional (ips != [ ]) (
mkXrayRule ruleTag {
ip = ips;
} tag
);
xrayGeositeRules =
ruleTag: tag: geosites:
lib.optional (geosites != [ ]) (
mkXrayRule ruleTag {
domain = map (name: "geosite:${name}") geosites;
} tag
);
xrayGeoIPRules =
ruleTag: tag: geoips:
lib.optional (geoips != [ ]) (
mkXrayRule ruleTag {
ip = map (name: "geoip:${name}") geoips;
} tag
);
xrayCustomRuleTag = category: kind: "custom-${category}-${kind}";
mkXrayCustomRuleEntries =
rule:
lib.flatten [
(xrayDomainRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "domain") rule.outbound
rule.domains
)
(xrayIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "ip") rule.outbound rule.ips)
(xrayGeositeRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geosite") rule.outbound
rule.geosites
)
(xrayGeoIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geoip") rule.outbound
rule.geoips
)
];
xrayCustomRouteRules = map (rule: {
category = customRuleCategory rule.outbound;
entries = mkXrayCustomRuleEntries rule;
}) customRules;
xrayProxyPrimaryRules = lib.flatten [
(xrayDomainRules "proxy-domain" "proxy" r.proxy.domains)
(xrayIPRules "proxy-ip" "proxy" r.proxy.ips)
];
xrayDirectRules = lib.flatten [
(xrayDomainRules "direct-domain" "direct" direct.domains)
(xrayIPRules "direct-ip" "direct" direct.ips)
(xrayGeositeRules "direct-geosite" "direct" direct.geosites)
(xrayGeoIPRules "direct-geoip" "direct" direct.geoips)
];
xraySafetyDirectRules = [
(mkXrayRule "direct-private" { ip = [ "geoip:private" ]; } "direct")
]
++
lib.optional
(tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { })
(
mkXrayRule "direct-tg-relay" { ip = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps); } "direct"
);
xrayBlockRules = lib.flatten [
(xrayDomainRules "block-domain" "block" r.block.domains)
(xrayIPRules "block-ip" "block" r.block.ips)
(xrayGeositeRules "block-geosite" "block" r.block.geosites)
(xrayGeoIPRules "block-geoip" "block" r.block.geoips)
];
xrayProxyGeoRules = lib.flatten [
(xrayGeositeRules "proxy-geosite" "proxy" r.proxy.geosites)
(xrayGeoIPRules "proxy-geoip" "proxy" r.proxy.geoips)
];
xrayRoutingRules =
lib.concatMap (item: item.entries) xrayCustomRouteRules
++ xrayProxyPrimaryRules
++ xrayDirectRules
++ xraySafetyDirectRules
++ xrayProxyGeoRules
++ xrayBlockRules;
xrayRouteModeRules = {
common = [ ];
custom = xrayCustomRouteRules;
proxyPrimary = xrayProxyPrimaryRules;
direct = xrayDirectRules;
safetyDirect = xraySafetyDirectRules;
block = xrayBlockRules;
proxyGeo = xrayProxyGeoRules;
};
in
{
inherit
xrayRoutingRules
xrayRouteModeRules
;
}
+462 -299
View File
@@ -5,6 +5,7 @@
tgWsProxyCfg,
builtinTags,
outboundTags,
effectiveOutboundTags ? outboundTags,
subscriptionTags,
invalidRoutingTargets,
effectivePerAppRoutingProfileNames,
@@ -15,20 +16,9 @@
}:
let
assertions = import ./service/assertions-lib.nix { inherit lib; };
inherit (assertions)
mkAssertion
requireEnabled
requireAvailable
uniqueValues
notEqualWhen
forbiddenValues
exactlyOneOf
;
inherit (derived)
constants
proxyCfg
singBoxCfg
proxyEnabled
singBoxEnabled
xrayEnabled
@@ -40,39 +30,73 @@ let
perAppRoutingTun
perAppRoutingTproxy
perAppZapretCfg
zapretCfg
zapretEngine
;
globalTunAutoRouteTable = 2022;
mkAssertion = assertion: message: { inherit assertion message; };
requireEnabled =
featureEnabled: dependencyEnabled: message:
mkAssertion (!featureEnabled || dependencyEnabled) message;
requireAvailable =
featureUsed: dependencyEnabled: message:
mkAssertion (!featureUsed || dependencyEnabled) message;
uniqueValues =
condition: values: message:
mkAssertion (!condition || builtins.length values == builtins.length (lib.unique values)) message;
exactlyOneOf =
condition: values: message:
mkAssertion (
!condition || builtins.length (builtins.filter (value: value != null) values) == 1
) message;
notEqualWhen =
condition: left: right: message:
mkAssertion (!(condition && left == right)) message;
forbiddenValues =
condition: value: disallowed: message:
mkAssertion (!(condition && builtins.elem value disallowed)) message;
featureAssertions = [
(requireAvailable proxyCfg.singBox.enable proxyEnabled
"proxy-suite: proxy.singBox.enable requires proxy.enable = true"
)
(requireAvailable proxyCfg.xray.enable proxyEnabled
"proxy-suite: proxy.xray.enable requires proxy.enable = true"
)
(mkAssertion (!proxyEnabled || proxyCfg.singBox.enable || proxyCfg.xray.enable)
"proxy-suite: at least one of proxy.singBox.enable or proxy.xray.enable must be true when proxy.enable = true"
)
(requireAvailable proxyEnabled (
proxyCfg.outbounds != [ ] || proxyCfg.subscriptions != [ ]
) "proxy-suite: at least one outbound or subscription is required when proxy.enable = true")
(uniqueValues proxyEnabled outboundTags "proxy-suite: outbound tags must be unique")
# Declaring no outbound at all is legal: they can be added at runtime with
# `proxy-ctl proxy outbounds add`. Only a warning here; the backend still
# refuses to start with nothing to dial.
(uniqueValues proxyEnabled effectiveOutboundTags "proxy-suite: outbound tags must be unique")
(uniqueValues proxyEnabled subscriptionTags
"proxy-suite: subscription tags must be unique because they are used as cache keys and outbound tag prefixes"
)
(mkAssertion (
!proxyEnabled || builtins.all (tag: !builtins.elem tag builtinTags) outboundTags
!proxyEnabled || builtins.all (tag: !builtins.elem tag builtinTags) effectiveOutboundTags
) "proxy-suite: outbound tags must not use reserved names: proxy, direct, block")
(requireEnabled cfg.sshProxy.asOutbound cfg.sshProxy.enable
"proxy-suite: sshProxy.asOutbound requires sshProxy.enable = true"
)
(requireEnabled cfg.sshProxy.asOutbound proxyEnabled
"proxy-suite: sshProxy.asOutbound requires proxy.enable = true"
)
(requireEnabled proxyCfg.autoProxy.enable proxyEnabled
"proxy-suite: proxy.autoProxy.enable requires proxy.enable = true"
)
(mkAssertion (!(proxyCfg.autoProxy.enable && pureXrayEnabled))
"proxy-suite: proxy.autoProxy needs the sing-box backend: learned routes are local rule-sets that sing-box reloads from disk, and pure XRay has no equivalent"
)
(mkAssertion (
!cfg.sshProxy.enable || (cfg.sshProxy.server.user != null && cfg.sshProxy.server.host != null)
) "proxy-suite: sshProxy.server.user and sshProxy.server.host are required when sshProxy.enable = true")
# SingBox dials SSH itself and verifies host keys by value, with no
# knownHostsFile and no trust-on-first-use fallback. An empty list accepts
# any host key, so refuse rather than silently downgrade the tunnel.
(mkAssertion (
!derived.sshProxyNativeOutbound || cfg.sshProxy.hostKey != [ ] || cfg.sshProxy.hostKeyFile != null
) "proxy-suite: sshProxy.hostKey or sshProxy.hostKeyFile is required when sshProxy.asOutbound = true with a SingBox or hybrid backend, because SingBox verifies host keys by value and an empty list accepts any key. Point hostKeyFile at a known-hosts file, or list every key from `ssh-keyscan -p <server.port> <server.host>` in hostKey -- the host key algorithm is negotiated, so a single pinned key fails the handshake when the server picks another algorithm.")
(mkAssertion (!proxyEnabled || invalidRoutingTargets == [ ])
"proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}"
)
(mkAssertion (
!(pureXrayEnabled && proxyCfg.selection == "selector")
) "proxy-suite: proxy.selection = \"selector\" is only available with proxy.singBox.enable = true")
) "proxy-suite: proxy.selection = \"selector\" requires proxy.backend = \"sing-box\" or \"hybrid\"")
(mkAssertion
(!(pureXrayEnabled && (proxyCfg.dns.local.type == "tls" || proxyCfg.dns.remote.type == "tls")))
"proxy-suite: proxy.dns.*.type = \"tls\" is not supported with proxy.xray.enable = true; use udp/tcp DNS for XRay"
"proxy-suite: proxy.dns.*.type = \"tls\" is not supported with proxy.backend = \"xray\"; use udp/tcp DNS for XRay"
)
(requireEnabled globalTun.enable proxyEnabled
"proxy-suite: proxy.tun.enable requires proxy.enable = true"
@@ -80,15 +104,11 @@ let
(requireEnabled globalTproxy.enable proxyEnabled
"proxy-suite: proxy.tproxy.enable requires proxy.enable = true"
)
(requireEnabled globalTun.autostart globalTun.enable
"proxy-suite: proxy.tun.autostart requires proxy.tun.enable = true"
(requireEnabled (proxyCfg.autostart == "tun") globalTun.enable
''proxy-suite: proxy.autostart = "tun" requires proxy.tun.enable = true''
)
(requireEnabled globalTproxy.autostart globalTproxy.enable
"proxy-suite: proxy.tproxy.autostart requires proxy.tproxy.enable = true"
)
(mkAssertion
(!(globalTproxy.enable && globalTproxy.autostart && globalTun.enable && globalTun.autostart))
"proxy-suite: proxy.tproxy.autostart and proxy.tun.autostart cannot both be enabled at the same time"
(requireEnabled (proxyCfg.autostart == "tproxy") globalTproxy.enable
''proxy-suite: proxy.autostart = "tproxy" requires proxy.tproxy.enable = true''
)
];
@@ -112,232 +132,38 @@ let
"proxy-suite: route=proxychains in perAppRouting.profiles requires proxy.enable = true"
)
(requireEnabled perAppRoutingTun.enable perAppRoutingCfg.enable
"proxy-suite: proxy.tun.perApp.enable requires perAppRouting.enable = true"
"proxy-suite: perAppRouting.tun.enable requires perAppRouting.enable = true"
)
(requireEnabled perAppRoutingTun.enable proxyEnabled
"proxy-suite: proxy.tun.perApp.enable requires proxy.enable = true"
"proxy-suite: perAppRouting.tun.enable requires proxy.enable = true"
)
(requireAvailable hasTunProfiles perAppRoutingTun.enable
"proxy-suite: route=tun in perAppRouting.profiles requires proxy.tun.perApp.enable = true"
"proxy-suite: route=tun in perAppRouting.profiles requires perAppRouting.tun.enable = true"
)
(requireAvailable hasTunProfiles proxyEnabled
"proxy-suite: route=tun in perAppRouting.profiles requires proxy.enable = true"
)
(requireEnabled perAppRoutingTproxy.enable perAppRoutingCfg.enable
"proxy-suite: proxy.tproxy.perApp.enable requires perAppRouting.enable = true"
"proxy-suite: perAppRouting.tproxy.enable requires perAppRouting.enable = true"
)
(requireEnabled perAppRoutingTproxy.enable proxyEnabled
"proxy-suite: proxy.tproxy.perApp.enable requires proxy.enable = true"
"proxy-suite: perAppRouting.tproxy.enable requires proxy.enable = true"
)
(requireAvailable hasTproxyProfiles perAppRoutingTproxy.enable
"proxy-suite: route=tproxy in perAppRouting.profiles requires proxy.tproxy.perApp.enable = true"
"proxy-suite: route=tproxy in perAppRouting.profiles requires perAppRouting.tproxy.enable = true"
)
(requireAvailable hasTproxyProfiles proxyEnabled
"proxy-suite: route=tproxy in perAppRouting.profiles requires proxy.enable = true"
)
(requireEnabled perAppZapretCfg.enable perAppRoutingCfg.enable
"proxy-suite: zapret.perApp.enable requires perAppRouting.enable = true"
"proxy-suite: perAppRouting.zapret.enable requires perAppRouting.enable = true"
)
(requireAvailable hasZapretProfiles perAppZapretCfg.enable
"proxy-suite: route=zapret in perAppRouting.profiles requires zapret.perApp.enable = true"
"proxy-suite: route=zapret in perAppRouting.profiles requires perAppRouting.zapret.enable = true"
)
];
collisionAssertions = map (item: notEqualWhen item.condition item.left item.right item.message) [
{
condition = globalTun.enable && perAppRoutingTun.enable;
left = globalTun.interface;
right = perAppRoutingTun.interface;
message = "proxy-suite: proxy.tun.interface and proxy.tun.perApp.interface must differ";
}
{
condition = globalTun.enable && perAppRoutingTun.enable;
left = globalTun.address;
right = perAppRoutingTun.address;
message = "proxy-suite: proxy.tun.address and proxy.tun.perApp.address must differ";
}
{
condition = globalTun.enable && perAppRoutingTun.enable;
left = perAppRoutingTun.routeTable;
right = globalTunAutoRouteTable;
message = "proxy-suite: proxy.tun.perApp.routeTable must differ from the global TUN auto-route table 2022";
}
{
condition = perAppRoutingTun.enable && globalTproxy.enable;
left = perAppRoutingTun.fwmark;
right = globalTproxy.fwmark;
message = "proxy-suite: proxy.tun.perApp.fwmark must differ from proxy.tproxy.fwmark when global TProxy is enabled";
}
{
condition = perAppRoutingTun.enable && globalTproxy.enable;
left = perAppRoutingTun.fwmark;
right = globalTproxy.proxyMark;
message = "proxy-suite: proxy.tun.perApp.fwmark must differ from proxy.tproxy.proxyMark when global TProxy is enabled";
}
{
condition = perAppRoutingTun.enable && globalTproxy.enable;
left = perAppRoutingTun.routeTable;
right = globalTproxy.routeTable;
message = "proxy-suite: proxy.tun.perApp.routeTable must differ from proxy.tproxy.routeTable when global TProxy is enabled";
}
{
condition = perAppRoutingTproxy.enable;
left = perAppRoutingTproxy.fwmark;
right = globalTproxy.fwmark;
message = "proxy-suite: proxy.tproxy.perApp.fwmark must differ from proxy.tproxy.fwmark";
}
{
condition = perAppRoutingTproxy.enable;
left = perAppRoutingTproxy.fwmark;
right = globalTproxy.proxyMark;
message = "proxy-suite: proxy.tproxy.perApp.fwmark must differ from proxy.tproxy.proxyMark";
}
{
condition = perAppRoutingTproxy.enable;
left = perAppRoutingTproxy.routeTable;
right = globalTproxy.routeTable;
message = "proxy-suite: proxy.tproxy.perApp.routeTable must differ from proxy.tproxy.routeTable";
}
{
condition = perAppRoutingTun.enable && perAppRoutingTproxy.enable;
left = perAppRoutingTun.fwmark;
right = perAppRoutingTproxy.fwmark;
message = "proxy-suite: proxy.tun.perApp.fwmark and proxy.tproxy.perApp.fwmark must differ";
}
{
condition = perAppRoutingTun.enable && perAppRoutingTproxy.enable;
left = perAppRoutingTun.routeTable;
right = perAppRoutingTproxy.routeTable;
message = "proxy-suite: proxy.tun.perApp.routeTable and proxy.tproxy.perApp.routeTable must differ";
}
{
condition = perAppZapretCfg.enable;
left = perAppZapretCfg.filterMark;
right = globalTproxy.fwmark;
message = "proxy-suite: zapret.perApp.filterMark must differ from proxy.tproxy.fwmark";
}
{
condition = perAppZapretCfg.enable;
left = perAppZapretCfg.filterMark;
right = globalTproxy.proxyMark;
message = "proxy-suite: zapret.perApp.filterMark must differ from proxy.tproxy.proxyMark";
}
{
condition = perAppRoutingTun.enable && perAppZapretCfg.enable;
left = perAppRoutingTun.fwmark;
right = perAppZapretCfg.filterMark;
message = "proxy-suite: proxy.tun.perApp.fwmark and zapret.perApp.filterMark must differ";
}
{
condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable;
left = perAppRoutingTproxy.fwmark;
right = perAppZapretCfg.filterMark;
message = "proxy-suite: proxy.tproxy.perApp.fwmark and zapret.perApp.filterMark must differ";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && globalTproxy.enable;
left = tgWsProxyCfg.routingMark;
right = globalTproxy.fwmark;
message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tproxy.fwmark";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && globalTproxy.enable;
left = tgWsProxyCfg.routingMark;
right = globalTproxy.proxyMark;
message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tproxy.proxyMark";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTun.enable;
left = tgWsProxyCfg.routingMark;
right = perAppRoutingTun.fwmark;
message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tun.perApp.fwmark";
}
{
condition =
tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTproxy.enable;
left = tgWsProxyCfg.routingMark;
right = perAppRoutingTproxy.fwmark;
message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tproxy.perApp.fwmark";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppZapretCfg.enable;
left = tgWsProxyCfg.routingMark;
right = perAppZapretCfg.filterMark;
message = "proxy-suite: tgWsProxy.routingMark must differ from zapret.perApp.filterMark";
}
];
perAppZapretDesyncMarks = [
67108864
134217728
];
positiveNumberAssertions =
map (item: mkAssertion (!item.condition || item.value > 0) item.message)
[
{
condition = globalTun.enable;
value = globalTun.mtu;
message = "proxy-suite: proxy.tun.mtu must be greater than zero";
}
{
condition = perAppRoutingTun.enable;
value = perAppRoutingTun.mtu;
message = "proxy-suite: proxy.tun.perApp.mtu must be greater than zero";
}
{
condition = globalTproxy.enable;
value = globalTproxy.fwmark;
message = "proxy-suite: proxy.tproxy.fwmark must be greater than zero";
}
{
condition = globalTproxy.enable;
value = globalTproxy.proxyMark;
message = "proxy-suite: proxy.tproxy.proxyMark must be greater than zero";
}
{
condition = globalTproxy.enable;
value = globalTproxy.routeTable;
message = "proxy-suite: proxy.tproxy.routeTable must be greater than zero";
}
{
condition = perAppRoutingTun.enable;
value = perAppRoutingTun.fwmark;
message = "proxy-suite: proxy.tun.perApp.fwmark must be greater than zero";
}
{
condition = perAppRoutingTun.enable;
value = perAppRoutingTun.routeTable;
message = "proxy-suite: proxy.tun.perApp.routeTable must be greater than zero";
}
{
condition = perAppRoutingTproxy.enable;
value = perAppRoutingTproxy.fwmark;
message = "proxy-suite: proxy.tproxy.perApp.fwmark must be greater than zero";
}
{
condition = perAppRoutingTproxy.enable;
value = perAppRoutingTproxy.routeTable;
message = "proxy-suite: proxy.tproxy.perApp.routeTable must be greater than zero";
}
{
condition = perAppZapretCfg.enable;
value = perAppZapretCfg.filterMark;
message = "proxy-suite: zapret.perApp.filterMark must be greater than zero";
}
{
condition = perAppZapretCfg.enable;
value = perAppZapretCfg.qnum;
message = "proxy-suite: zapret.perApp.qnum must be greater than zero";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy;
value = tgWsProxyCfg.routingMark;
message = "proxy-suite: tgWsProxy.routingMark must be greater than zero";
}
];
localProxyAuthCfg = proxyCfg.auth;
localProxyAuthCfg = proxyCfg.listener.auth;
localProxyAuthUsed =
localProxyAuthCfg.username != null
|| localProxyAuthCfg.password != null
@@ -345,63 +171,13 @@ let
localProxyAuthAssertions = [
(mkAssertion (
!proxyEnabled || !localProxyAuthUsed || localProxyAuthCfg.username != null
) "proxy-suite: proxy.auth requires username when password or passwordFile is set")
) "proxy-suite: proxy.listener.auth requires username when password or passwordFile is set")
(exactlyOneOf (proxyEnabled && localProxyAuthUsed) [
localProxyAuthCfg.password
localProxyAuthCfg.passwordFile
] "proxy-suite: proxy.auth requires exactly one of password or passwordFile")
] "proxy-suite: proxy.listener.auth requires exactly one of password or passwordFile")
];
forbiddenValueAssertions =
map (item: forbiddenValues item.condition item.value item.disallowed item.message)
[
{
condition = perAppZapretCfg.enable;
value = perAppZapretCfg.filterMark;
disallowed = [
536870912
1073741824
];
message = "proxy-suite: zapret.perApp.filterMark must not use zapret internal desync mark bits";
}
{
condition = perAppZapretCfg.enable;
value = globalTproxy.fwmark;
disallowed = perAppZapretDesyncMarks;
message = "proxy-suite: proxy.tproxy.fwmark must not use per-app-zapret internal desync mark bits";
}
{
condition = perAppZapretCfg.enable;
value = globalTproxy.proxyMark;
disallowed = perAppZapretDesyncMarks;
message = "proxy-suite: proxy.tproxy.proxyMark must not use per-app-zapret internal desync mark bits";
}
{
condition = perAppRoutingTun.enable && perAppZapretCfg.enable;
value = perAppRoutingTun.fwmark;
disallowed = perAppZapretDesyncMarks;
message = "proxy-suite: proxy.tun.perApp.fwmark must not use per-app-zapret internal desync mark bits";
}
{
condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable;
value = perAppRoutingTproxy.fwmark;
disallowed = perAppZapretDesyncMarks;
message = "proxy-suite: proxy.tproxy.perApp.fwmark must not use per-app-zapret internal desync mark bits";
}
{
condition = perAppZapretCfg.enable;
value = perAppZapretCfg.filterMark;
disallowed = perAppZapretDesyncMarks;
message = "proxy-suite: zapret.perApp.filterMark must not use per-app-zapret internal desync mark bits";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppZapretCfg.enable;
value = tgWsProxyCfg.routingMark;
disallowed = perAppZapretDesyncMarks;
message = "proxy-suite: tgWsProxy.routingMark must not use per-app-zapret internal desync mark bits";
}
];
secretAssertions = [
(exactlyOneOf tgWsProxyCfg.enable [
tgWsProxyCfg.secret
@@ -422,31 +198,418 @@ let
)
(mkAssertion (
!singBoxEnabled || hybridEnabled || ob.xrayJson == null
) "proxy-suite: outbound '${ob.tag}': xrayJson is only available with proxy.xray.enable = true")
) "proxy-suite: outbound '${ob.tag}': xrayJson requires proxy.backend = xray or hybrid")
(mkAssertion (!xrayEnabled || hybridEnabled || (ob.singBoxJson == null && ob.json == null))
"proxy-suite: outbound '${ob.tag}': singBoxJson/json are only available with proxy.singBox.enable = true"
"proxy-suite: outbound '${ob.tag}': singBoxJson/json require proxy.backend = sing-box or hybrid"
)
(mkAssertion (
!(ob.backend == "xray") || xrayEnabled
) "proxy-suite: outbound '${ob.tag}': backend = \"xray\" requires proxy.xray.enable = true")
) "proxy-suite: outbound '${ob.tag}': backend = \"xray\" requires proxy.backend = xray or hybrid")
(mkAssertion (
!(ob.backend == "sing-box") || singBoxEnabled
) "proxy-suite: outbound '${ob.tag}': backend = \"sing-box\" requires proxy.singBox.enable = true")
) "proxy-suite: outbound '${ob.tag}': backend = \"sing-box\" requires proxy.backend = sing-box or hybrid")
]) proxyCfg.outbounds;
proxyInboundsCfg = derived.proxyInboundsCfg;
proxyInboundsEnabled = derived.proxyInboundsEnabled;
proxyInbounds = derived.proxyInbounds;
proxyInboundsNeedLocalProxy = proxyInboundsEnabled && derived.proxyInboundsNeedLocalProxy;
# A pinned outbound is rendered by the XRay renderer inside the inbound
# service, so a sing-box-only definition cannot serve as one.
singBoxOnlyPinnedTags = map (ob: ob.tag) (
builtins.filter (
ob: ob.singBoxJson != null || ob.json != null
) derived.proxyInboundViaOutbounds
);
proxyInboundAssertions =
[
(mkAssertion (!proxyInboundsEnabled || derived.invalidInboundViaTargets == [ ])
"proxy-suite: inbounds via targets are not defined in proxy.outbounds: ${lib.concatStringsSep ", " derived.invalidInboundViaTargets}. Subscription proxies cannot be named here because their tags only exist at runtime; use via = \"proxy\" to reach those."
)
(mkAssertion (!proxyInboundsEnabled || singBoxOnlyPinnedTags == [ ])
"proxy-suite: inbounds via targets a sing-box-only outbound: ${lib.concatStringsSep ", " singBoxOnlyPinnedTags}. The inbound service runs XRay, so a pinned outbound needs url, urlFile, or xrayJson."
)
(requireEnabled (proxyInboundsEnabled && derived.proxyInboundViaTags != [ ]) proxyEnabled
"proxy-suite: inbounds pins a listener to a proxy.outbounds tag, which requires proxy.enable = true"
)
(requireEnabled proxyInboundsEnabled (proxyInbounds != [ ])
"proxy-suite: inbounds.enable requires at least one entry in inbounds.listeners"
)
(requireEnabled proxyInboundsNeedLocalProxy proxyEnabled
"proxy-suite: inbounds.routing.via = \"proxy\" relays through the local proxy stack, which requires proxy.enable = true. Use via = \"direct\" for a plain exit node."
)
(requireEnabled proxyInboundsNeedLocalProxy derived.hasAvailableOutbounds
"proxy-suite: inbounds.routing.via = \"proxy\" relays through the local proxy stack, so at least one proxy.outbounds or proxy.subscriptions entry is required"
)
(uniqueValues proxyInboundsEnabled (map (ib: ib.listener.port) proxyInbounds)
"proxy-suite: inbounds.listeners must each use a distinct port"
)
(requireEnabled (proxyInboundsEnabled && proxyInboundsCfg.subscriptions.enable)
proxyInboundsCfg.shareLinks
"proxy-suite: inbounds.subscriptions are made of the share links, so they need inbounds.shareLinks = true"
)
(mkAssertion
(
!proxyInboundsEnabled
|| !proxyEnabled
|| !builtins.elem proxyCfg.listener.port derived.proxyInboundPorts
)
"proxy-suite: a proxyInbounds listener port collides with proxy.listener.port (${toString proxyCfg.listener.port})"
)
(mkAssertion
(
!proxyInboundsEnabled
|| !globalTproxy.enable
|| !builtins.elem globalTproxy.port derived.proxyInboundPorts
)
"proxy-suite: a proxyInbounds listener port collides with proxy.tproxy.port (${toString globalTproxy.port})"
)
]
++ lib.concatMap (
ib:
let
l = ib.listener;
prefix = "proxy-suite: inbounds listener '${ib.tag}'";
firstUser = if l.users == [ ] then null else builtins.head l.users;
needsUuid = builtins.elem l.type [
"vless"
"vmess"
];
needsPassword = builtins.elem l.type [
"trojan"
"shadowsocks"
"socks"
"http"
];
tlsTerminated = l.tls.enable || l.type == "trojan";
in
[
(exactlyOneOf proxyInboundsEnabled [
l.type
l.xrayJson
l.jsonFile
] "${prefix}: set exactly one of type, xrayJson, or jsonFile")
(mkAssertion (
!proxyInboundsEnabled || !(l.tls.enable && l.reality.enable)
) "${prefix}: tls.enable and reality.enable are mutually exclusive")
(mkAssertion (
!proxyInboundsEnabled || l.type == null || l.users != [ ]
) "${prefix}: at least one entry in users is required")
(exactlyOneOf (proxyInboundsEnabled && needsUuid && firstUser != null) [
firstUser.uuid
firstUser.uuidFile
] "${prefix}: ${toString l.type} users need exactly one of uuid or uuidFile")
(exactlyOneOf (proxyInboundsEnabled && needsPassword && firstUser != null) [
firstUser.password
firstUser.passwordFile
] "${prefix}: ${toString l.type} users need exactly one of password or passwordFile")
(exactlyOneOf (proxyInboundsEnabled && l.reality.enable) [
l.reality.privateKey
l.reality.privateKeyFile
] "${prefix}: reality needs exactly one of privateKey or privateKeyFile")
(mkAssertion (
!proxyInboundsEnabled || !l.reality.enable || l.reality.serverNames != [ ]
) "${prefix}: reality.serverNames must not be empty")
(requireAvailable (proxyInboundsEnabled && l.reality.enable && proxyInboundsCfg.shareLinks)
(l.reality.publicKey != null)
"${prefix}: reality.publicKey is required to generate share links. Run `xray x25519` to print it alongside the private key, or set inbounds.shareLinks = false."
)
(mkAssertion
(
!proxyInboundsEnabled
|| !tlsTerminated
|| l.reality.enable
|| (l.tls.certificateFile != null && l.tls.keyFile != null)
)
"${prefix}: TLS termination needs both tls.certificateFile and tls.keyFile"
)
(mkAssertion
(
!proxyInboundsEnabled
|| l.flow == null
|| (l.type == "vless" && l.transport.type == "raw")
)
"${prefix}: flow is only valid on a vless listener with transport.type = \"raw\""
)
(mkAssertion
(
!proxyInboundsEnabled
|| l.tls.alpn == null
|| !builtins.elem "h3" l.tls.alpn
|| (l.transport.type == "xhttp" && l.tls.enable && !l.reality.enable)
)
"${prefix}: tls.alpn \"h3\" is served only by the xhttp transport with tls.enable (not REALITY)"
)
]
) proxyInbounds;
subscriptionAssertions = lib.concatMap (sub: [
(exactlyOneOf proxyEnabled [
sub.urlFile
sub.url
] "proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url")
]) proxyCfg.subscriptions;
globalTunAutoRouteTable = constants.tunAutoRouteTableIndex;
globalZapretQnum = constants.zapretGlobalQnum.${zapretEngine};
collisionAssertions = map (item: notEqualWhen item.condition item.left item.right item.message) [
{
condition = globalTun.enable && perAppRoutingTun.enable;
left = globalTun.interface;
right = perAppRoutingTun.interface;
message = "proxy-suite: proxy.tun.interface and perAppRouting.tun.interface must differ";
}
{
condition = globalTun.enable && perAppRoutingTun.enable;
left = globalTun.address;
right = perAppRoutingTun.address;
message = "proxy-suite: proxy.tun.address and perAppRouting.tun.address must differ";
}
{
condition = globalTun.enable && perAppRoutingTun.enable;
left = perAppRoutingTun.routeTable;
right = globalTunAutoRouteTable;
message = "proxy-suite: perAppRouting.tun.routeTable must differ from the global TUN auto-route table ${toString globalTunAutoRouteTable}";
}
{
condition = perAppRoutingTun.enable && globalTproxy.enable;
left = perAppRoutingTun.fwmark;
right = globalTproxy.fwmark;
message = "proxy-suite: perAppRouting.tun.fwmark must differ from proxy.tproxy.fwmark when global TProxy is enabled";
}
{
condition = perAppRoutingTun.enable && globalTproxy.enable;
left = perAppRoutingTun.fwmark;
right = globalTproxy.proxyMark;
message = "proxy-suite: perAppRouting.tun.fwmark must differ from proxy.tproxy.proxyMark when global TProxy is enabled";
}
{
condition = perAppRoutingTun.enable && globalTproxy.enable;
left = perAppRoutingTun.routeTable;
right = globalTproxy.routeTable;
message = "proxy-suite: perAppRouting.tun.routeTable must differ from proxy.tproxy.routeTable when global TProxy is enabled";
}
{
condition = perAppZapretCfg.enable && zapretCfg.enable;
left = perAppZapretCfg.qnum;
right = globalZapretQnum;
message = "proxy-suite: perAppRouting.zapret.qnum must differ from the global zapret instance's NFQUEUE ${toString globalZapretQnum}";
}
{
condition = perAppRoutingTproxy.enable;
left = perAppRoutingTproxy.fwmark;
right = globalTproxy.fwmark;
message = "proxy-suite: perAppRouting.tproxy.fwmark must differ from proxy.tproxy.fwmark";
}
{
condition = perAppRoutingTproxy.enable;
left = perAppRoutingTproxy.fwmark;
right = globalTproxy.proxyMark;
message = "proxy-suite: perAppRouting.tproxy.fwmark must differ from proxy.tproxy.proxyMark";
}
{
condition = perAppRoutingTproxy.enable;
left = perAppRoutingTproxy.routeTable;
right = globalTproxy.routeTable;
message = "proxy-suite: perAppRouting.tproxy.routeTable must differ from proxy.tproxy.routeTable";
}
{
condition = perAppRoutingTun.enable && perAppRoutingTproxy.enable;
left = perAppRoutingTun.fwmark;
right = perAppRoutingTproxy.fwmark;
message = "proxy-suite: perAppRouting.tun.fwmark and perAppRouting.tproxy.fwmark must differ";
}
{
condition = perAppRoutingTun.enable && perAppRoutingTproxy.enable;
left = perAppRoutingTun.routeTable;
right = perAppRoutingTproxy.routeTable;
message = "proxy-suite: perAppRouting.tun.routeTable and perAppRouting.tproxy.routeTable must differ";
}
{
condition = perAppZapretCfg.enable;
left = perAppZapretCfg.filterMark;
right = globalTproxy.fwmark;
message = "proxy-suite: perAppRouting.zapret.filterMark must differ from proxy.tproxy.fwmark";
}
{
condition = perAppZapretCfg.enable;
left = perAppZapretCfg.filterMark;
right = globalTproxy.proxyMark;
message = "proxy-suite: perAppRouting.zapret.filterMark must differ from proxy.tproxy.proxyMark";
}
{
condition = perAppRoutingTun.enable && perAppZapretCfg.enable;
left = perAppRoutingTun.fwmark;
right = perAppZapretCfg.filterMark;
message = "proxy-suite: perAppRouting.tun.fwmark and perAppRouting.zapret.filterMark must differ";
}
{
condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable;
left = perAppRoutingTproxy.fwmark;
right = perAppZapretCfg.filterMark;
message = "proxy-suite: perAppRouting.tproxy.fwmark and perAppRouting.zapret.filterMark must differ";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && globalTproxy.enable;
left = tgWsProxyCfg.fwmark;
right = globalTproxy.fwmark;
message = "proxy-suite: tgWsProxy.fwmark must differ from proxy.tproxy.fwmark";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && globalTproxy.enable;
left = tgWsProxyCfg.fwmark;
right = globalTproxy.proxyMark;
message = "proxy-suite: tgWsProxy.fwmark must differ from proxy.tproxy.proxyMark";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTun.enable;
left = tgWsProxyCfg.fwmark;
right = perAppRoutingTun.fwmark;
message = "proxy-suite: tgWsProxy.fwmark must differ from perAppRouting.tun.fwmark";
}
{
condition =
tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTproxy.enable;
left = tgWsProxyCfg.fwmark;
right = perAppRoutingTproxy.fwmark;
message = "proxy-suite: tgWsProxy.fwmark must differ from perAppRouting.tproxy.fwmark";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppZapretCfg.enable;
left = tgWsProxyCfg.fwmark;
right = perAppZapretCfg.filterMark;
message = "proxy-suite: tgWsProxy.fwmark must differ from perAppRouting.zapret.filterMark";
}
];
perAppZapretDesyncMarks = [
67108864
134217728
];
positiveNumberAssertions =
map (item: mkAssertion (!item.condition || item.value > 0) item.message)
[
{
condition = globalTun.enable;
value = globalTun.mtu;
message = "proxy-suite: proxy.tun.mtu must be greater than zero";
}
{
condition = perAppRoutingTun.enable;
value = perAppRoutingTun.mtu;
message = "proxy-suite: perAppRouting.tun.mtu must be greater than zero";
}
{
condition = globalTproxy.enable;
value = globalTproxy.fwmark;
message = "proxy-suite: proxy.tproxy.fwmark must be greater than zero";
}
{
condition = globalTproxy.enable;
value = globalTproxy.proxyMark;
message = "proxy-suite: proxy.tproxy.proxyMark must be greater than zero";
}
{
condition = globalTproxy.enable;
value = globalTproxy.routeTable;
message = "proxy-suite: proxy.tproxy.routeTable must be greater than zero";
}
{
condition = perAppRoutingTun.enable;
value = perAppRoutingTun.fwmark;
message = "proxy-suite: perAppRouting.tun.fwmark must be greater than zero";
}
{
condition = perAppRoutingTun.enable;
value = perAppRoutingTun.routeTable;
message = "proxy-suite: perAppRouting.tun.routeTable must be greater than zero";
}
{
condition = perAppRoutingTproxy.enable;
value = perAppRoutingTproxy.fwmark;
message = "proxy-suite: perAppRouting.tproxy.fwmark must be greater than zero";
}
{
condition = perAppRoutingTproxy.enable;
value = perAppRoutingTproxy.routeTable;
message = "proxy-suite: perAppRouting.tproxy.routeTable must be greater than zero";
}
{
condition = perAppZapretCfg.enable;
value = perAppZapretCfg.filterMark;
message = "proxy-suite: perAppRouting.zapret.filterMark must be greater than zero";
}
{
condition = perAppZapretCfg.enable;
value = perAppZapretCfg.qnum;
message = "proxy-suite: perAppRouting.zapret.qnum must be greater than zero";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy;
value = tgWsProxyCfg.fwmark;
message = "proxy-suite: tgWsProxy.fwmark must be greater than zero";
}
];
forbiddenValueAssertions =
map (item: forbiddenValues item.condition item.value item.disallowed item.message)
[
{
condition = perAppZapretCfg.enable;
value = perAppZapretCfg.filterMark;
disallowed = [
536870912
1073741824
];
message = "proxy-suite: perAppRouting.zapret.filterMark must not use zapret internal desync mark bits";
}
{
condition = perAppZapretCfg.enable;
value = globalTproxy.fwmark;
disallowed = perAppZapretDesyncMarks;
message = "proxy-suite: proxy.tproxy.fwmark must not use per-app-zapret internal desync mark bits";
}
{
condition = perAppZapretCfg.enable;
value = globalTproxy.proxyMark;
disallowed = perAppZapretDesyncMarks;
message = "proxy-suite: proxy.tproxy.proxyMark must not use per-app-zapret internal desync mark bits";
}
{
condition = perAppRoutingTun.enable && perAppZapretCfg.enable;
value = perAppRoutingTun.fwmark;
disallowed = perAppZapretDesyncMarks;
message = "proxy-suite: perAppRouting.tun.fwmark must not use per-app-zapret internal desync mark bits";
}
{
condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable;
value = perAppRoutingTproxy.fwmark;
disallowed = perAppZapretDesyncMarks;
message = "proxy-suite: perAppRouting.tproxy.fwmark must not use per-app-zapret internal desync mark bits";
}
{
condition = perAppZapretCfg.enable;
value = perAppZapretCfg.filterMark;
disallowed = perAppZapretDesyncMarks;
message = "proxy-suite: perAppRouting.zapret.filterMark must not use per-app-zapret internal desync mark bits";
}
{
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppZapretCfg.enable;
value = tgWsProxyCfg.fwmark;
disallowed = perAppZapretDesyncMarks;
message = "proxy-suite: tgWsProxy.fwmark must not use per-app-zapret internal desync mark bits";
}
];
in
featureAssertions
++ perAppRoutingAssertions
++ collisionAssertions
++ positiveNumberAssertions
++ localProxyAuthAssertions
++ forbiddenValueAssertions
++ secretAssertions
++ outboundAssertions
++ proxyInboundAssertions
++ subscriptionAssertions
++ collisionAssertions
++ positiveNumberAssertions
++ forbiddenValueAssertions
@@ -1,31 +0,0 @@
{ lib }:
rec {
mkAssertion = assertion: message: { inherit assertion message; };
requireEnabled =
featureEnabled: dependencyEnabled: message:
mkAssertion (!featureEnabled || dependencyEnabled) message;
requireAvailable =
featureUsed: dependencyEnabled: message:
mkAssertion (!featureUsed || dependencyEnabled) message;
uniqueValues =
condition: values: message:
mkAssertion (!condition || builtins.length values == builtins.length (lib.unique values)) message;
notEqualWhen =
condition: left: right: message:
mkAssertion (!(condition && left == right)) message;
forbiddenValues =
condition: value: disallowed: message:
mkAssertion (!(condition && builtins.elem value disallowed)) message;
exactlyOneOf =
condition: values: message:
mkAssertion (
!condition || builtins.length (builtins.filter (value: value != null) values) == 1
) message;
}
+123
View File
@@ -142,4 +142,127 @@ rec {
execStop = "${pkgs.coreutils}/bin/true";
extraServiceConfig.Slice = sliceName;
};
cidrNetworkFunction = ''
cidr_network() {
local cidr="$1"
local addr="''${cidr%/*}"
local prefix="''${cidr#*/}"
local o1 o2 o3 o4 ip mask net
IFS=. read -r o1 o2 o3 o4 <<<"$addr"
ip=$(((o1 << 24) | (o2 << 16) | (o3 << 8) | o4))
if [ "$prefix" -eq 0 ]; then
mask=0
else
mask=$(((0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF))
fi
net=$((ip & mask))
printf '%d.%d.%d.%d/%s' \
$(((net >> 24) & 255)) \
$(((net >> 16) & 255)) \
$(((net >> 8) & 255)) \
$((net & 255)) \
"$prefix"
}
'';
mkDefaultUplinkIPv4Source =
{
ip,
awk,
errorMessage,
}:
''
uplink_addr="$(${ip} -4 route get 1.1.1.1 2>/dev/null | ${awk} '
/src/ {
for (i = 1; i <= NF; i++) {
if ($i == "src" && i + 1 <= NF) {
print $(i + 1)
exit
}
}
}
')"
if [ -z "$uplink_addr" ]; then
echo ${lib.escapeShellArg errorMessage} >&2
exit 1
fi
'';
mkNftDeleteTable =
{
nft,
family,
table,
}:
''
${nft} delete table ${family} ${table} 2>/dev/null || true
'';
mkIpRuleDeleteByFwmark =
{
ip,
family ? "",
fwmark,
table,
}:
''
while ${ip} ${
lib.optionalString (family != "") "${family} "
}rule del fwmark ${toString fwmark} table ${toString table} 2>/dev/null; do :; done
'';
mkIpRuleDeleteByTable =
{
ip,
family,
table,
}:
''
while ${ip} ${family} rule del table ${toString table} 2>/dev/null; do :; done
'';
mkIpRuleDeleteByPriority =
{
ip,
family,
priority,
}:
''
while ${ip} ${family} rule del pref ${toString priority} 2>/dev/null; do :; done
'';
mkIpRouteFlushTable =
{
ip,
family,
table,
}:
''
${ip} ${family} route flush table ${toString table} 2>/dev/null || true
'';
mkIpLocalDefaultRouteDelete =
{
ip,
table,
}:
''
${ip} route del local default dev lo table ${toString table} 2>/dev/null || true
'';
mkIpLinkDelete =
{
ip,
interface,
}:
''
${ip} link del dev ${lib.escapeShellArg interface} 2>/dev/null || true
'';
flushResolvedCaches = ''
${pkgs.systemd}/bin/resolvectl flush-caches 2>/dev/null || true
'';
}
+41 -5
View File
@@ -8,6 +8,8 @@
tunFile,
perAppTunFile,
routeModeRulesFile,
proxyInboundsFile,
proxyInboundsSpecFile,
perAppTunChainFile,
perAppTproxyRulesFile,
perAppZapretRulesFile,
@@ -17,6 +19,7 @@
let
derived = import ../derived.nix { inherit lib cfg; };
constants = derived.constants;
inherit (derived)
singBoxCfg
proxyCfg
@@ -33,6 +36,7 @@ let
perAppRoutingTun
perAppRoutingTproxy
perAppZapretCfg
zapretEngine
userControlCfg
selectionMode
builtinTags
@@ -40,7 +44,15 @@ let
subscriptionTags
invalidRoutingTargets
collapseNamedOutbounds
hasSubscriptions
sshProxyCfg
sshProxyOutboundEnabled
sshProxyUnitEnabled
proxyInboundsCfg
proxyInboundsEnabled
proxyInboundsNeedLocalProxy
proxyInboundsGuardPrivate
proxyInboundViaOutbounds
userControlEnabled
;
# Tool paths – defined once here and passed into sub-modules as needed.
@@ -54,12 +66,18 @@ let
headBin = "${pkgs.coreutils}/bin/head";
seqBin = "${pkgs.coreutils}/bin/seq";
findBin = "${pkgs.findutils}/bin/find";
amneziaWgProfileNamesFile = pkgs.writeText "proxy-suite-awg-profiles.json" (
builtins.toJSON (builtins.attrNames cfg.amneziaWg.profiles)
);
proxySuiteScriptsDir = ../../../scripts;
parserScriptsPythonPath = proxySuiteScriptsDir;
buildOutboundPy = "${proxySuiteScriptsDir}/build-outbound.py";
buildInboundPy = "${proxySuiteScriptsDir}/build-inbound.py";
fetchSubscriptionPy = "${proxySuiteScriptsDir}/fetch-subscription.py";
builders = import ./builders.nix { inherit lib pkgs; };
polkit = import ./polkit.nix {
inherit lib cfg userControlCfg;
};
@@ -70,18 +88,16 @@ let
pkgs
singBoxCfg
proxyCfg
proxyEnabled
singBoxEnabled
sshProxyCfg
xrayEnabled
hybridEnabled
pureXrayEnabled
activeBackend
perAppRoutingCfg
userControlCfg
perAppRoutingTun
selectionMode
collapseNamedOutbounds
hasSubscriptions
constants
;
inherit
jq
@@ -90,6 +106,7 @@ let
xray
parserScriptsPythonPath
buildOutboundPy
buildInboundPy
fetchSubscriptionPy
;
inherit
@@ -97,6 +114,16 @@ let
tunFile
perAppTunFile
routeModeRulesFile
proxyInboundsFile
proxyInboundsSpecFile
;
inherit
proxyInboundsCfg
proxyInboundsNeedLocalProxy
proxyInboundsGuardPrivate
proxyInboundViaOutbounds
userControlEnabled
builders
;
};
@@ -111,6 +138,7 @@ let
perAppRoutingCfg
perAppRoutingTun
perAppRoutingTproxy
constants
;
perAppZapretCfg = perAppZapretCfg;
inherit perAppTunChainFile perAppTproxyRulesFile perAppZapretRulesFile;
@@ -134,10 +162,17 @@ let
perAppRoutingTun
perAppRoutingTproxy
perAppZapretCfg
zapretEngine
constants
selectionMode
userControlCfg
;
inherit (scripts) subscriptionTagsFile subscriptionCacheDir;
inherit (scripts) routeModeStateFile;
inherit proxyInboundsEnabled;
inherit (scripts) proxyInboundsLinksFile proxyInboundsSubscriptionsFile;
proxyInboundsSubscriptionsBaseUrl = proxyInboundsCfg.subscriptions.baseUrl;
inherit amneziaWgProfileNamesFile;
inherit (perAppRouting)
perAppRoutingProfilesFile
proxychainsConfigFile
@@ -172,5 +207,6 @@ in
scripts
perAppRouting
control
amneziaWgProfileNamesFile
;
}
@@ -0,0 +1,152 @@
# Subscription refresh, route-mode and outbound control scripts.
{
lib,
pkgs,
proxyCfg,
clashApi,
routeModeStateFile,
priorityOutboundFile,
outboundInventoryFile,
subscriptionCacheDir,
subscriptionCacheHelpersBlock,
mkSubscriptionFetchBlock,
runtimeSubscriptionsFetchBlock,
jq,
}:
let
systemctl = "${pkgs.systemd}/bin/systemctl";
curl = "${pkgs.curl}/bin/curl";
restartActiveConfigConsumersBlock =
lib.concatMapStrings
(svc: ''
if ${systemctl} is-active --quiet ${svc}; then
${systemctl} restart ${svc}
fi
'')
[
"proxy-suite-socks"
"proxy-suite-tun"
"proxy-suite-per-app-tun"
];
subscriptionUpdateScript = pkgs.writeShellScript "proxy-suite-subscription-update" ''
set -euo pipefail
CACHE_DIR="${subscriptionCacheDir}"
mkdir -p "$CACHE_DIR"
FAILED=0
${subscriptionCacheHelpersBlock}
${lib.concatMapStrings mkSubscriptionFetchBlock proxyCfg.subscriptions}
${runtimeSubscriptionsFetchBlock}
if [ "$FAILED" -eq 0 ]; then
${restartActiveConfigConsumersBlock}
fi
exit "$FAILED"
'';
setRouteModeScript = pkgs.writeShellScript "proxy-suite-set-route-mode" ''
set -euo pipefail
mode="''${1:-}"
case "$mode" in
default)
;;
whitelist)
;;
blacklist)
;;
all-proxy)
;;
all-bypass)
;;
*)
echo "proxy-suite: route mode must be default, whitelist, blacklist, all-proxy, or all-bypass" >&2
exit 1
;;
esac
mkdir -p "$(dirname "${routeModeStateFile}")"
if [ "$mode" = "default" ]; then
rm -f "${routeModeStateFile}"
else
printf '%s\n' "$mode" > "${routeModeStateFile}"
fi
${restartActiveConfigConsumersBlock}
'';
# Pins the outbound the proxy prefers, or "auto" to hand the choice back to the
# configured selection. The pin is persisted either way; a live Clash API switch
# only saves the restart.
setPriorityOutboundScript = pkgs.writeShellScript "proxy-suite-set-priority-outbound" ''
set -euo pipefail
tag="''${1:-}"
if [ -z "$tag" ]; then
echo "proxy-suite: usage: proxy-suite-set-priority-outbound <tag|auto>" >&2
exit 1
fi
if [ "$tag" = "auto" ]; then
rm -f "${priorityOutboundFile}"
else
# The inventory only exists once the proxy has run. Without it there is
# nothing to check against, so accept the tag and let the start script warn
# if it turns out to name nothing.
if [ -r "${outboundInventoryFile}" ] \
&& ! ${jq} -e --arg t "$tag" '.tags | index($t) != null' "${outboundInventoryFile}" >/dev/null; then
echo "proxy-suite: unknown outbound '$tag'" >&2
exit 1
fi
mkdir -p "$(dirname "${priorityOutboundFile}")"
printf '%s\n' "$tag" > "${priorityOutboundFile}"
# Live switch when the running config exposes a selector; the persisted pin
# is what keeps it after the next restart.
if ${curl} -sf -X PUT "${clashApi}/proxies/proxy" \
-H "Content-Type: application/json" \
-d "$(${jq} -cn --arg name "$tag" '{name:$name}')" >/dev/null 2>&1; then
exit 0
fi
fi
${restartActiveConfigConsumersBlock}
'';
# Applies whatever is now in the runtime spool directories. A removed runtime
# subscription leaves a root-owned cache behind that the group cannot unlink,
# so the cache dir is reconciled against the sources here.
reloadOutboundsScript = pkgs.writeShellScript "proxy-suite-reload-outbounds" ''
set -euo pipefail
${subscriptionCacheHelpersBlock}
KEEP="|${
lib.concatMapStrings (sub: "${sub.tag}|") proxyCfg.subscriptions
}"
while IFS=$'\t' read -r TAG _; do
[ -n "$TAG" ] || continue
KEEP="$KEEP$TAG|"
done < <(_proxy_suite_runtime_subscriptions)
for CACHE in "$SUB_CACHE_DIR"/*.json; do
[ -e "$CACHE" ] || continue
TAG="''${CACHE##*/}"
TAG="''${TAG%.json}"
case "$KEEP" in
*"|$TAG|"*) ;;
*) rm -f "$CACHE" ;;
esac
done
${restartActiveConfigConsumersBlock}
'';
in
{
inherit
subscriptionUpdateScript
setRouteModeScript
setPriorityOutboundScript
reloadOutboundsScript
;
}
+28 -1
View File
@@ -7,13 +7,21 @@
perAppRoutingTun,
perAppRoutingTproxy,
perAppZapretCfg,
zapretEngine,
constants,
selectionMode,
userControlCfg,
subscriptionTagsFile,
subscriptionCacheDir,
perAppRoutingProfilesFile,
proxychainsConfigFile,
proxychainsQuietArg,
routeModeStateFile,
amneziaWgProfileNamesFile,
proxyInboundsEnabled,
proxyInboundsLinksFile,
proxyInboundsSubscriptionsFile,
proxyInboundsSubscriptionsBaseUrl,
}:
{
proxyCtl = packages.mkProxyCtl {
@@ -26,12 +34,31 @@
proxychainsConfigFile
proxychainsQuietArg
routeModeStateFile
amneziaWgProfileNamesFile
;
defaultRouteMode = if proxyCfg.proxyByDefault then "blacklist" else "whitelist";
defaultRouteMode = if (proxyCfg.routing.default == "proxy") then "blacklist" else "whitelist";
perAppRoutingEnabled = if perAppRoutingCfg.enable then "1" else "0";
perAppRoutingProxychainsEnabled = if perAppRoutingCfg.proxychains.enable then "1" else "0";
perAppRoutingTunEnabled = if perAppRoutingTun.enable then "1" else "0";
perAppRoutingTproxyEnabled = if perAppRoutingTproxy.enable then "1" else "0";
perAppRoutingZapretEnabled = if perAppZapretCfg.enable then "1" else "0";
zapretAutoEnabled = if zapretEngine == "zapret2" then "1" else "0";
zapretStateDir = constants.zapret2StateDir;
priorityOutboundFile = constants.priorityOutboundFile;
outboundInventoryFile = constants.outboundInventoryFile;
runtimeOutboundsDir = constants.runtimeOutboundsDir;
runtimeSubscriptionsDir = constants.runtimeSubscriptionsDir;
userControlGroup = userControlCfg.group;
inboundsEnabled = if proxyInboundsEnabled then "1" else "0";
inboundsLinksFile = proxyInboundsLinksFile;
inboundsStatsFile = constants.inboundStatsFile;
inboundsSubscriptionsFile = proxyInboundsSubscriptionsFile;
inboundsSubscriptionsBaseUrl =
if proxyInboundsSubscriptionsBaseUrl == null then "" else proxyInboundsSubscriptionsBaseUrl;
autoProxyEnabled = if proxyCfg.autoProxy.enable then "1" else "0";
autoProxyStateDir = constants.autoProxyStateDir;
localProxyUrl = "http://${
if proxyCfg.listener.address == "0.0.0.0" then "127.0.0.1" else proxyCfg.listener.address
}:${toString proxyCfg.listener.port}";
};
}
+158 -408
View File
@@ -9,6 +9,8 @@
tunFile,
perAppTunFile,
routeModeRulesFile,
proxyInboundsFile,
proxyInboundsSpecFile,
nftablesRulesFile,
perAppTproxyRulesFile,
perAppZapretRulesFile,
@@ -28,6 +30,8 @@ let
tunFile
perAppTunFile
routeModeRulesFile
proxyInboundsFile
proxyInboundsSpecFile
perAppTunChainFile
perAppTproxyRulesFile
perAppZapretRulesFile
@@ -37,13 +41,7 @@ let
};
builders = import ./builders.nix { inherit lib pkgs; };
inherit (builders)
mkNamedUnits
mkRestartingService
mkOneshotService
mkUserRuleService
mkAnchorService
;
inherit (builders) mkNamedUnits;
inherit (context)
derived
@@ -54,425 +52,177 @@ let
;
inherit (derived)
singBoxCfg
proxyCfg
proxyEnabled
xrayEnabled
hybridEnabled
pureXrayEnabled
activeBackend
perAppRoutingCfg
globalTun
globalTproxy
perAppRoutingTun
perAppRoutingTproxy
perAppZapretCfg
userControlCfg
userControlEnabled
perAppZapretEnabled
hasSubscriptions
sshProxyOutboundEnabled
sshProxyUnitEnabled
proxyInboundsEnabled
proxyInboundsNeedLocalProxy
proxyInboundFirewallPorts
proxyInboundFirewallUdpPorts
outboundTags
effectiveOutboundTags
subscriptionTags
invalidRoutingTargets
builtinTags
;
serviceNames = {
socks = "proxy-suite-socks";
tproxy = "proxy-suite-tproxy";
tun = "proxy-suite-tun";
perAppTun = "proxy-suite-per-app-tun";
perAppTproxy = "proxy-suite-per-app-tproxy";
perAppZapret = "proxy-suite-per-app-zapret";
subscriptionUpdate = "proxy-suite-subscription-update";
};
localProxyAuthEnabled =
proxyCfg.auth.username != null
&& (proxyCfg.auth.password != null || proxyCfg.auth.passwordFile != null);
# Must match the explicit iproute2_* indexes written to the global SingBox TUN
# template in config.nix. XRay uses the same table for manual Linux
# policy routing because XRay's autoSystemRoutingTable is not Linux-ready.
tunAutoRouteTableIndex = 2022;
tunAutoRouteRulePriority = 9000;
# Keep app-scoped marks ahead of the global XRay TUN catch-all. Without
# these priorities, iproute2's default priority lets global TUN capture
# packets intended for per-app routing tables.
xrayTunPerAppTproxyRulePriority = 8996;
xrayTunPerAppTunRulePriority = 8997;
xrayGlobalTunIPv6Address = "fd66:19::1/64";
xrayGlobalTunIPv6RoutePrefix = "fd66:19::/64";
xrayTunUpScript = pkgs.writeShellScript "proxy-suite-xray-tun-up" ''
set -euo pipefail
tun_cidr=${lib.escapeShellArg globalTun.address}
tun6_cidr=${lib.escapeShellArg xrayGlobalTunIPv6Address}
tun6_route_prefix=${lib.escapeShellArg xrayGlobalTunIPv6RoutePrefix}
tun_addr=""
tun_route_prefix=""
uplink_addr=""
cidr_network() {
local cidr="$1"
local addr="''${cidr%/*}"
local prefix="''${cidr#*/}"
local o1 o2 o3 o4 ip mask net
IFS=. read -r o1 o2 o3 o4 <<<"$addr"
ip=$(((o1 << 24) | (o2 << 16) | (o3 << 8) | o4))
if [ "$prefix" -eq 0 ]; then
mask=0
else
mask=$(((0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF))
fi
net=$((ip & mask))
printf '%d.%d.%d.%d/%s' \
$(((net >> 24) & 255)) \
$(((net >> 16) & 255)) \
$(((net >> 8) & 255)) \
$((net & 255)) \
"$prefix"
}
for _ in $(${pkgs.coreutils}/bin/seq 1 50); do
if ${ip} link show dev ${lib.escapeShellArg globalTun.interface} >/dev/null 2>&1; then
break
fi
${pkgs.coreutils}/bin/sleep 0.1
done
if ! ${ip} link show dev ${lib.escapeShellArg globalTun.interface} >/dev/null 2>&1; then
echo "proxy-suite: XRay TUN interface ${globalTun.interface} did not appear in time" >&2
exit 1
fi
uplink_addr="$(${ip} -4 route get 1.1.1.1 2>/dev/null | ${pkgs.gawk}/bin/awk '
/src/ {
for (i = 1; i <= NF; i++) {
if ($i == "src" && i + 1 <= NF) {
print $(i + 1)
exit
}
}
}
')"
if [ -z "$uplink_addr" ]; then
echo "proxy-suite: could not determine the default uplink IPv4 address for XRay TUN" >&2
exit 1
fi
while ${ip} -4 rule del pref ${toString xrayTunPerAppTproxyRulePriority} 2>/dev/null; do :; done
while ${ip} -4 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
while ${ip} -4 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done
while ${ip} -6 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
while ${ip} -6 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done
tun_addr="''${tun_cidr%%/*}"
tun_route_prefix="$(cidr_network "$tun_cidr")"
${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg globalTun.interface}
${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg globalTun.interface}
${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg globalTun.interface} src "$tun_addr" table ${toString tunAutoRouteTableIndex}
${ip} -4 route replace default dev ${lib.escapeShellArg globalTun.interface} src "$uplink_addr" table ${toString tunAutoRouteTableIndex}
${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
${ip} -6 route replace default dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
${lib.optionalString perAppRoutingTproxy.enable ''
${ip} -4 rule add pref ${toString xrayTunPerAppTproxyRulePriority} fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable}
''}
${lib.optionalString perAppRoutingTun.enable ''
${ip} -4 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
${ip} -6 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
''}
${ip} -4 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
${ip} -6 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
'';
tproxyUpScript = pkgs.writeShellScript "proxy-suite-tproxy-up" ''
set -euo pipefail
# Start from a clean policy-routing state. `ip rule add` permits duplicate
# rules on some iproute2 versions, and a stale rule can keep packets routed
# into a dead local table after a failed restart.
${nft} delete table ip singbox 2>/dev/null || true
while ${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null; do :; done
${ip} route del local default dev lo table ${toString globalTproxy.routeTable} 2>/dev/null || true
${nft} -f ${nftablesRulesFile}
${ip} route replace local default dev lo table ${toString globalTproxy.routeTable}
${ip} rule add fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable}
'';
tproxyDownScript = pkgs.writeShellScript "proxy-suite-tproxy-down" ''
set +e
${nft} delete table ip singbox 2>/dev/null || true
while ${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null; do :; done
${ip} route del local default dev lo table ${toString globalTproxy.routeTable} 2>/dev/null || true
'';
tunCleanupScript = pkgs.writeShellScript "proxy-suite-tun-cleanup" ''
set +e
# SingBox normally removes these on graceful shutdown, but stale
# auto_route/auto_redirect state leaves the host routing through a dead TUN
# interface after `proxy-ctl tun off` or an unclean service stop.
${nft} delete table inet sing-box 2>/dev/null || true
while ${ip} -4 rule del table ${toString tunAutoRouteTableIndex} 2>/dev/null; do :; done
while ${ip} -6 rule del table ${toString tunAutoRouteTableIndex} 2>/dev/null; do :; done
while ${ip} -4 rule del pref ${toString xrayTunPerAppTproxyRulePriority} 2>/dev/null; do :; done
while ${ip} -4 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
while ${ip} -6 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
${ip} -4 route flush table ${toString tunAutoRouteTableIndex} 2>/dev/null || true
${ip} -6 route flush table ${toString tunAutoRouteTableIndex} 2>/dev/null || true
${ip} link del dev ${lib.escapeShellArg globalTun.interface} 2>/dev/null || true
${pkgs.systemd}/bin/resolvectl flush-caches 2>/dev/null || true
'';
systemServiceEntries = [
{
enable = proxyEnabled;
name = serviceNames.socks;
value = mkRestartingService {
description = "${
if pureXrayEnabled then
"XRay"
else if hybridEnabled then
"sing-box + XRay sidecar"
else
"sing-box"
} proxy client (SOCKS + TProxy-ready)";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
execStart = scripts.startSocks;
runtimeDirectory = serviceNames.socks;
stateDirectory = "proxy-suite";
};
}
{
enable = proxyEnabled && globalTproxy.enable;
name = serviceNames.tproxy;
value = mkOneshotService {
description = "proxy-suite TProxy - nftables rules and policy routing";
after = [
"network.target"
"${serviceNames.socks}.service"
];
wantedBy = lib.optionals globalTproxy.autostart [ "multi-user.target" ];
requires = [ "${serviceNames.socks}.service" ];
conflicts = [
"${serviceNames.tun}.service"
"${serviceNames.perAppTproxy}.service"
];
execStart = tproxyUpScript;
execStop = tproxyDownScript;
};
}
{
enable = proxyEnabled && globalTun.enable;
name = serviceNames.tun;
value = mkRestartingService {
description = "${
if pureXrayEnabled then
"XRay"
else if hybridEnabled then
"sing-box + XRay sidecar"
else
"sing-box"
} TUN proxy client";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ];
conflicts = [ "${serviceNames.tproxy}.service" ];
execStartPre = tunCleanupScript;
execStart = scripts.startTun;
execStartPost = if pureXrayEnabled then xrayTunUpScript else null;
execStopPost = tunCleanupScript;
runtimeDirectory = serviceNames.tun;
stateDirectory = "proxy-suite";
};
}
{
enable = proxyEnabled && perAppRoutingTun.enable;
name = serviceNames.perAppTun;
value = mkRestartingService {
description = "proxy-suite per-app-routing TUN backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
execStartPre = perAppRouting.perAppTunDownScript;
execStart = scripts.startPerAppTun;
execStartPost = perAppRouting.perAppTunUpScript;
execStopPost = perAppRouting.perAppTunDownScript;
runtimeDirectory = serviceNames.perAppTun;
stateDirectory = "proxy-suite";
};
}
{
enable = proxyEnabled && perAppRoutingTun.enable;
name = "${serviceNames.perAppTun}-user@";
value = mkUserRuleService {
description = "Enable proxy-suite app TUN marking for user %i";
backendService = serviceNames.perAppTun;
execStart = "${perAppRouting.perAppTunUserRuleStart} %i";
execStop = "${perAppRouting.perAppTunUserRuleStop} %i";
};
}
{
enable = proxyEnabled && perAppRoutingTproxy.enable;
name = serviceNames.perAppTproxy;
value = mkOneshotService {
description = "proxy-suite per-app-routing TProxy backend";
after = [
"network.target"
"${serviceNames.socks}.service"
];
requires = [ "${serviceNames.socks}.service" ];
conflicts = [
"${serviceNames.tproxy}.service"
"${serviceNames.tun}.service"
];
execStart = perAppRouting.perAppTproxyUpScript;
execStop = perAppRouting.perAppTproxyDownScript;
};
}
{
enable = proxyEnabled && perAppRoutingTproxy.enable;
name = "${serviceNames.perAppTproxy}-user@";
value = mkUserRuleService {
description = "Enable proxy-suite app TProxy marking for user %i";
backendService = serviceNames.perAppTproxy;
execStart = "${perAppRouting.perAppTproxyUserRuleStart} %i";
execStop = "${perAppRouting.perAppTproxyUserRuleStop} %i";
};
}
{
enable = perAppZapretEnabled;
name = "${serviceNames.perAppZapret}-user@";
value = mkUserRuleService {
description = "Enable proxy-suite app zapret marking for user %i";
backendService = serviceNames.perAppZapret;
execStart = "${perAppRouting.perAppZapretUserRuleStart} %i";
execStop = "${perAppRouting.perAppZapretUserRuleStop} %i";
};
}
{
enable = proxyEnabled && hasSubscriptions;
name = serviceNames.subscriptionUpdate;
value = mkOneshotService {
description = "Refresh proxy-suite subscription caches";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
execStart = scripts.subscriptionUpdateScript;
stateDirectory = "proxy-suite";
};
}
{
enable = proxyEnabled;
name = "proxy-suite-route-mode@";
value = mkOneshotService {
description = "Set proxy-suite route mode to %i";
execStart = "${scripts.setRouteModeScript} %i";
extraServiceConfig.RemainAfterExit = false;
};
}
];
userServiceEntries = [
{
enable = perAppRoutingTun.enable;
name = "${serviceNames.perAppTun}-anchor";
value = mkAnchorService perAppRouting.perAppTunSliceName "Anchor service for proxy-suite app TUN slice";
}
{
enable = perAppRoutingTproxy.enable;
name = "${serviceNames.perAppTproxy}-anchor";
value = mkAnchorService perAppRouting.perAppTproxySliceName "Anchor service for proxy-suite app TProxy slice";
}
{
enable = perAppZapretEnabled;
name = "${serviceNames.perAppZapret}-anchor";
value = mkAnchorService perAppRouting.perAppZapretSliceName "Anchor service for proxy-suite app zapret slice";
}
];
timerEntries = [
{
enable = proxyEnabled && hasSubscriptions;
name = serviceNames.subscriptionUpdate;
value = {
description = "Periodic proxy-suite subscription refresh";
wantedBy = [ "timers.target" ];
timerConfig = {
OnBootSec = "5m";
OnUnitActiveSec = proxyCfg.subscriptionUpdateInterval;
};
};
}
];
in
{
environment.systemPackages = [ control.proxyCtl ];
# nftables must be on for transparent routing backends. Global TUN uses
# SingBox auto_redirect programs an `inet sing-box` nftables table.
networking.nftables.enable = lib.mkIf (
globalTun.enable
|| globalTproxy.enable
|| perAppRoutingTun.enable
|| perAppRoutingTproxy.enable
|| perAppZapretEnabled
) (lib.mkDefault true);
users.groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) {
"${userControlCfg.group}" = { };
};
security.polkit.enable = lib.mkIf (cfg.enable && userControlEnabled) true;
security.polkit.extraConfig = lib.mkIf (cfg.enable && userControlEnabled) (
lib.mkAfter ''
polkit.addRule(function(action, subject) {
if (!subject.isInGroup("${userControlCfg.group}")) {
return null;
}
if (action.id !== "org.freedesktop.systemd1.manage-units") {
return null;
}
var unit = action.lookup("unit");
${polkit.userControlPolkitRules}
return null;
});
''
);
systemd.user.services = mkNamedUnits userServiceEntries;
assertions = import ../service-assertions.nix {
inherit lib cfg derived;
tgWsProxyCfg = cfg.tgWsProxy;
constants = derived.constants;
routingScripts = import ./routing-scripts.nix {
inherit
builtinTags
outboundTags
subscriptionTags
invalidRoutingTargets
;
inherit (perAppRouting)
effectivePerAppRoutingProfileNames
hasProxychainsProfiles
hasTunProfiles
hasTproxyProfiles
hasZapretProfiles
lib
pkgs
builders
ip
nft
nftablesRulesFile
constants
globalTun
globalTproxy
perAppRoutingTun
perAppRoutingTproxy
;
};
systemd.services = mkNamedUnits systemServiceEntries;
serviceUnits = import ./units.nix {
inherit
lib
builders
proxyCfg
proxyEnabled
hybridEnabled
pureXrayEnabled
globalTun
globalTproxy
perAppRoutingTun
perAppRoutingTproxy
perAppZapretEnabled
sshProxyOutboundEnabled
sshProxyUnitEnabled
proxyInboundsEnabled
proxyInboundsNeedLocalProxy
scripts
perAppRouting
routingScripts
;
inherit (cfg) geodata;
};
inherit (serviceUnits)
localProxyAuthEnabled
systemServiceEntries
userServiceEntries
timerEntries
;
# autoProxy shells out to the built proxy-ctl, which only exists in this
# scope, so its units are merged in here rather than alongside the other
# feature modules in ../default.nix.
autoProxyUnits = lib.mkIf cfg.proxy.autoProxy.enable (
import ../autoproxy.nix {
inherit lib pkgs cfg;
inherit (control) proxyCtl;
inherit (constants) autoProxyStateDir;
}
);
in
lib.mkMerge [
autoProxyUnits
{
environment.systemPackages = [ control.proxyCtl ];
systemd.timers = mkNamedUnits timerEntries;
}
# nftables must be on for transparent routing backends. Global TUN uses
# SingBox auto_redirect programs an `inet sing-box` nftables table.
networking.nftables.enable = lib.mkIf (
globalTun.enable
|| globalTproxy.enable
|| perAppRoutingTun.enable
|| perAppRoutingTproxy.enable
|| perAppZapretEnabled
) (lib.mkDefault true);
# Inbound listeners are reached from outside, so their ports have to be open.
networking.firewall = lib.mkIf (proxyInboundsEnabled && cfg.inbounds.openFirewall) {
allowedTCPPorts = proxyInboundFirewallPorts;
allowedUDPPorts = proxyInboundFirewallUdpPorts;
};
users.groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) {
"${userControlCfg.group}" = { };
};
security.polkit.enable = lib.mkIf (cfg.enable && userControlEnabled) true;
security.polkit.extraConfig = lib.mkIf (cfg.enable && userControlEnabled) (
lib.mkAfter ''
polkit.addRule(function(action, subject) {
if (!subject.isInGroup("${userControlCfg.group}")) {
return null;
}
if (action.id !== "org.freedesktop.systemd1.manage-units") {
return null;
}
var unit = action.lookup("unit");
${polkit.userControlPolkitRules}
return null;
});
''
);
# Spool dirs for outbounds and subscriptions added at runtime. Setgid so the
# files proxy-ctl drops here inherit the group; without userControl only root
# writes them. tmpfiles rather than the start scripts, so the group can add an
# outbound before the proxy has ever run.
systemd.tmpfiles.rules = lib.mkIf (cfg.enable && proxyEnabled) (
map
(
dir:
"d ${dir} ${
if userControlEnabled then "2770 root ${userControlCfg.group}" else "0700 root root"
} -"
)
[
constants.runtimeOutboundsDir
constants.runtimeSubscriptionsDir
]
);
systemd.user.services = mkNamedUnits userServiceEntries;
assertions = import ../service-assertions.nix {
inherit lib cfg derived;
tgWsProxyCfg = cfg.tgWsProxy;
inherit
builtinTags
outboundTags
effectiveOutboundTags
subscriptionTags
invalidRoutingTargets
;
inherit (perAppRouting)
effectivePerAppRoutingProfileNames
hasProxychainsProfiles
hasTunProfiles
hasTproxyProfiles
hasZapretProfiles
;
};
warnings = lib.optional (proxyEnabled && !derived.hasAvailableOutbounds) (
"proxy-suite: no outbounds or subscriptions are declared; the proxy will not start"
+ " until one is added with `proxy-ctl proxy outbounds add`"
);
systemd.services = mkNamedUnits systemServiceEntries;
systemd.timers = mkNamedUnits timerEntries;
}
]
+69 -294
View File
@@ -9,6 +9,7 @@
perAppRoutingCfg,
perAppRoutingTun,
perAppRoutingTproxy,
constants,
perAppZapretCfg,
perAppTunChainFile,
perAppTproxyRulesFile,
@@ -31,305 +32,79 @@ let
perAppTproxySliceName = "proxy-suite-per-app-tproxy.slice";
perAppZapretSliceName = "proxy-suite-per-app-zapret.slice";
perAppRoutingProfileNames = map (profile: profile.name) perAppRoutingCfg.profiles;
defaultPerAppRoutingProfiles = lib.optionals perAppRoutingCfg.createDefaultProfiles (
[
{
name = "proxychains";
route = "proxychains";
}
]
++ lib.optionals perAppRoutingTun.enable [
{
name = "tun";
route = "tun";
}
]
++ lib.optionals perAppRoutingTproxy.enable [
{
name = "tproxy";
route = "tproxy";
}
]
++ lib.optionals perAppZapretCfg.enable [
{
name = "zapret";
route = "zapret";
}
]
);
effectivePerAppRoutingProfiles =
perAppRoutingCfg.profiles
++ builtins.filter (
profile: !(builtins.elem profile.name perAppRoutingProfileNames)
) defaultPerAppRoutingProfiles;
effectivePerAppRoutingProfileNames = map (profile: profile.name) effectivePerAppRoutingProfiles;
localProxyAuth = proxyCfg.auth;
localProxyAuthEnabled =
localProxyAuth.username != null
&& (localProxyAuth.password != null || localProxyAuth.passwordFile != null);
perAppRoutingProfilesFile = pkgs.writeText "proxy-suite-per-app-routing-profiles.json" (
builtins.toJSON effectivePerAppRoutingProfiles
);
proxychainsConfigFile =
if localProxyAuthEnabled then
"/run/proxy-suite-socks/proxychains.conf"
else
pkgs.writeText "proxy-suite-proxychains.conf" ''
strict_chain
${lib.optionalString perAppRoutingCfg.proxychains.quiet "quiet_mode"}
${lib.optionalString perAppRoutingCfg.proxychains.proxyDns "proxy_dns"}
tcp_read_time_out 15000
tcp_connect_time_out 8000
[ProxyList]
socks5 ${proxyCfg.listenAddress} ${toString proxyCfg.port}
'';
proxychainsQuietArg = lib.optionalString perAppRoutingCfg.proxychains.quiet "-q ";
hasProxychainsProfiles = builtins.any (
profile: profile.route == "proxychains"
) effectivePerAppRoutingProfiles;
hasTunProfiles = builtins.any (profile: profile.route == "tun") effectivePerAppRoutingProfiles;
hasTproxyProfiles = builtins.any (
profile: profile.route == "tproxy"
) effectivePerAppRoutingProfiles;
hasZapretProfiles = builtins.any (
profile: profile.route == "zapret"
) effectivePerAppRoutingProfiles;
xrayPerAppTunIPv6Address = "fd66:20::1/64";
xrayPerAppTunIPv6RoutePrefix = "fd66:20::/64";
perAppTunWaitForInterface = pkgs.writeShellScript "proxy-suite-per-app-tun-wait-for-interface" ''
set -euo pipefail
for _ in $(${seqBin} 1 50); do
if ${ip} link show dev ${lib.escapeShellArg perAppRoutingTun.interface} >/dev/null 2>&1; then
exit 0
fi
${sleepBin} 0.1
done
echo "proxy-suite: app TUN interface ${perAppRoutingTun.interface} did not appear in time" >&2
exit 1
'';
perAppTunUpScript = pkgs.writeShellScript "proxy-suite-per-app-tun-up" ''
set -euo pipefail
tun_cidr=${lib.escapeShellArg perAppRoutingTun.address}
tun6_cidr=${lib.escapeShellArg xrayPerAppTunIPv6Address}
tun6_route_prefix=${lib.escapeShellArg xrayPerAppTunIPv6RoutePrefix}
tun_addr=""
tun_route_prefix=""
uplink_addr=""
cidr_network() {
local cidr="$1"
local addr="''${cidr%/*}"
local prefix="''${cidr#*/}"
local o1 o2 o3 o4 ip mask net
IFS=. read -r o1 o2 o3 o4 <<<"$addr"
ip=$(((o1 << 24) | (o2 << 16) | (o3 << 8) | o4))
if [ "$prefix" -eq 0 ]; then
mask=0
else
mask=$(((0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF))
fi
net=$((ip & mask))
printf '%d.%d.%d.%d/%s' \
$(((net >> 24) & 255)) \
$(((net >> 16) & 255)) \
$(((net >> 8) & 255)) \
$((net & 255)) \
"$prefix"
}
${nft} delete table inet proxy_suite_per_app_tun 2>/dev/null || true
while ${ip} -4 rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null; do :; done
while ${ip} -6 rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null; do :; done
${ip} -4 route flush table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
${ip} -6 route flush table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
${nft} -f ${perAppTunChainFile}
${perAppTunWaitForInterface}
uplink_addr="$(${ip} -4 route get 1.1.1.1 2>/dev/null | ${awk} '
/src/ {
for (i = 1; i <= NF; i++) {
if ($i == "src" && i + 1 <= NF) {
print $(i + 1)
exit
}
}
}
')"
if [ -z "$uplink_addr" ]; then
echo "proxy-suite: could not determine the default uplink IPv4 address for app TUN" >&2
exit 1
fi
tun_addr="''${tun_cidr%%/*}"
tun_route_prefix="$(cidr_network "$tun_cidr")"
${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface}
${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$tun_addr" table ${toString perAppRoutingTun.routeTable}
${ip} -4 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$uplink_addr" table ${toString perAppRoutingTun.routeTable}
${ip} -4 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
${lib.optionalString pureXrayEnabled ''
${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface}
${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable}
${ip} -6 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable}
${ip} -6 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
''}
'';
perAppTunDownScript = pkgs.writeShellScript "proxy-suite-per-app-tun-down" ''
set +e
# Best-effort cleanup for graceful stops and for unclean previous exits.
${nft} delete table inet proxy_suite_per_app_tun 2>/dev/null || true
while ${ip} -4 rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null; do :; done
while ${ip} -6 rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null; do :; done
${ip} -4 route flush table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
${ip} -6 route flush table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
${ip} link del dev ${lib.escapeShellArg perAppRoutingTun.interface} 2>/dev/null || true
${pkgs.systemd}/bin/resolvectl flush-caches 2>/dev/null || true
'';
perAppTproxyUpScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-up" ''
set -euo pipefail
${nft} delete table ip proxy_suite_per_app_tproxy 2>/dev/null || true
while ${ip} rule del fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null; do :; done
${ip} route del local default dev lo table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true
${nft} -f ${perAppTproxyRulesFile}
${ip} route replace local default dev lo table ${toString perAppRoutingTproxy.routeTable}
${ip} rule add fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable}
'';
perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-down" ''
set +e
${nft} delete table ip proxy_suite_per_app_tproxy 2>/dev/null || true
while ${ip} rule del fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null; do :; done
${ip} route del local default dev lo table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true
'';
# Generate a "start" script that adds a per-user cgroup nftables mark rule.
mkUserRuleStart =
{
name,
nftFamily,
nftTable,
nftChain,
sliceName,
sliceLabel,
markRule,
}:
pkgs.writeShellScript "proxy-suite-${name}-user-start" ''
set -euo pipefail
uid="$1"
rule_comment_prefix="proxy-suite-${name}-user-$uid"
mark_comment="$rule_comment_prefix-mark"
cgroup_root="/sys/fs/cgroup/user.slice/user-$uid.slice/user@$uid.service"
if ! [ -d "$cgroup_root" ]; then
echo "proxy-suite: user cgroup root does not exist for uid $uid: $cgroup_root" >&2
exit 1
fi
cgroup_dir=$(${findBin} "$cgroup_root" -type d -name ${lib.escapeShellArg sliceName} | ${headBin} -n1 || true)
if [ -z "$cgroup_dir" ]; then
echo "proxy-suite: ${sliceLabel} slice cgroup does not exist for uid $uid under $cgroup_root" >&2
exit 1
fi
cgroup_path=''${cgroup_dir#/sys/fs/cgroup/}
cgroup_level=$(printf '%s' "$cgroup_path" | ${awk} -F/ '{ print NF }')
handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \
| ${grepBin} -F "comment \"$rule_comment_prefix" \
| ${awk} '{ print $NF }' || true)
if [ -n "$handles" ]; then
while IFS= read -r handle; do
[ -n "$handle" ] || continue
${nft} delete rule ${nftFamily} ${nftTable} ${nftChain} handle "$handle" || true
done <<< "$handles"
fi
printf '%s\n' \
"add rule ${nftFamily} ${nftTable} ${nftChain} socket cgroupv2 level $cgroup_level \"$cgroup_path\" ${markRule} comment \"$mark_comment\"" \
| ${nft} -f -
'';
# Generate a "stop" script that removes all per-user cgroup nftables mark rules.
mkUserRuleStop =
{
name,
nftFamily,
nftTable,
nftChain,
}:
pkgs.writeShellScript "proxy-suite-${name}-user-stop" ''
set -euo pipefail
uid="$1"
rule_comment_prefix="proxy-suite-${name}-user-$uid"
handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \
| ${grepBin} -F "comment \"$rule_comment_prefix" \
| ${awk} '{ print $NF }' || true)
if [ -n "$handles" ]; then
while IFS= read -r handle; do
[ -n "$handle" ] || continue
${nft} delete rule ${nftFamily} ${nftTable} ${nftChain} handle "$handle" || true
done <<< "$handles"
fi
'';
perAppTunUserRuleStart = mkUserRuleStart {
name = "per-app-tun";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_tun";
nftChain = "output";
sliceName = perAppTunSliceName;
sliceLabel = "app TUN";
markRule = "meta mark set ${toString perAppRoutingTun.fwmark} ct mark set ${toString perAppRoutingTun.fwmark}";
};
perAppTunUserRuleStop = mkUserRuleStop {
name = "per-app-tun";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_tun";
nftChain = "output";
profiles = import ./per-app-routing/profiles.nix {
inherit
lib
pkgs
proxyCfg
perAppRoutingCfg
perAppRoutingTun
perAppRoutingTproxy
perAppZapretCfg
;
};
inherit (profiles)
effectivePerAppRoutingProfiles
effectivePerAppRoutingProfileNames
perAppRoutingProfilesFile
proxychainsConfigFile
proxychainsQuietArg
hasProxychainsProfiles
hasTunProfiles
hasTproxyProfiles
hasZapretProfiles
;
perAppTproxyUserRuleStart = mkUserRuleStart {
name = "per-app-tproxy";
nftFamily = "ip";
nftTable = "proxy_suite_per_app_tproxy";
nftChain = "output";
sliceName = perAppTproxySliceName;
sliceLabel = "app TProxy";
markRule = "meta mark set ${toString perAppRoutingTproxy.fwmark} ct mark set ${toString perAppRoutingTproxy.fwmark}";
};
perAppTproxyUserRuleStop = mkUserRuleStop {
name = "per-app-tproxy";
nftFamily = "ip";
nftTable = "proxy_suite_per_app_tproxy";
nftChain = "output";
backendScripts = import ./per-app-routing/backend-scripts.nix {
inherit
lib
pkgs
builders
pureXrayEnabled
perAppRoutingTun
perAppRoutingTproxy
constants
perAppTunChainFile
perAppTproxyRulesFile
ip
nft
awk
seqBin
sleepBin
;
};
inherit (backendScripts)
perAppTunUpScript
perAppTunDownScript
perAppTproxyUpScript
perAppTproxyDownScript
;
perAppZapretUserRuleStart = mkUserRuleStart {
name = "per-app-zapret";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_zapret_mark";
nftChain = "output";
sliceName = perAppZapretSliceName;
sliceLabel = "app zapret";
markRule = "meta mark set meta mark or ${toString perAppZapretCfg.filterMark} ct mark set ct mark or ${toString perAppZapretCfg.filterMark}";
};
perAppZapretUserRuleStop = mkUserRuleStop {
name = "per-app-zapret";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_zapret_mark";
nftChain = "output";
userRules = import ./per-app-routing/user-rules.nix {
inherit
lib
pkgs
perAppRoutingTun
perAppRoutingTproxy
perAppZapretCfg
perAppTunSliceName
perAppTproxySliceName
perAppZapretSliceName
nft
awk
grepBin
findBin
headBin
;
};
inherit (userRules)
perAppTunUserRuleStart
perAppTunUserRuleStop
perAppTproxyUserRuleStart
perAppTproxyUserRuleStop
perAppZapretUserRuleStart
perAppZapretUserRuleStop
;
in
{
@@ -0,0 +1,144 @@
# Per-app TUN and TProxy backend lifecycle scripts.
{
lib,
pkgs,
builders,
pureXrayEnabled,
perAppRoutingTun,
perAppRoutingTproxy,
constants,
perAppTunChainFile,
perAppTproxyRulesFile,
ip,
nft,
awk,
seqBin,
sleepBin,
}:
let
defaultUplinkIPv4Source = builders.mkDefaultUplinkIPv4Source {
inherit ip awk;
errorMessage = "proxy-suite: could not determine the default uplink IPv4 address for app TUN";
};
inherit (constants)
xrayPerAppTunIPv6Address
xrayPerAppTunIPv6RoutePrefix
;
perAppTunWaitForInterface = pkgs.writeShellScript "proxy-suite-per-app-tun-wait-for-interface" ''
set -euo pipefail
for _ in $(${seqBin} 1 50); do
if ${ip} link show dev ${lib.escapeShellArg perAppRoutingTun.interface} >/dev/null 2>&1; then
exit 0
fi
${sleepBin} 0.1
done
echo "proxy-suite: app TUN interface ${perAppRoutingTun.interface} did not appear in time" >&2
exit 1
'';
perAppTunUpScript = pkgs.writeShellScript "proxy-suite-per-app-tun-up" ''
set -euo pipefail
tun_cidr=${lib.escapeShellArg perAppRoutingTun.address}
tun6_cidr=${lib.escapeShellArg xrayPerAppTunIPv6Address}
tun6_route_prefix=${lib.escapeShellArg xrayPerAppTunIPv6RoutePrefix}
tun_addr=""
tun_route_prefix=""
uplink_addr=""
${builders.cidrNetworkFunction}
${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "proxy_suite_per_app_tun"; }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
family = "-4";
fwmark = perAppRoutingTun.fwmark;
table = perAppRoutingTun.routeTable;
}}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
family = "-6";
fwmark = perAppRoutingTun.fwmark;
table = perAppRoutingTun.routeTable;
}}
${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = perAppRoutingTun.routeTable; }}
${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = perAppRoutingTun.routeTable; }}
${nft} -f ${perAppTunChainFile}
${perAppTunWaitForInterface}
${defaultUplinkIPv4Source}
tun_addr="''${tun_cidr%%/*}"
tun_route_prefix="$(cidr_network "$tun_cidr")"
${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface}
${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$tun_addr" table ${toString perAppRoutingTun.routeTable}
${ip} -4 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$uplink_addr" table ${toString perAppRoutingTun.routeTable}
${ip} -4 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
${lib.optionalString pureXrayEnabled ''
${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface}
${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable}
${ip} -6 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable}
${ip} -6 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
''}
'';
perAppTunDownScript = pkgs.writeShellScript "proxy-suite-per-app-tun-down" ''
set +e
# Best-effort cleanup for graceful stops and for unclean previous exits.
${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "proxy_suite_per_app_tun"; }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
family = "-4";
fwmark = perAppRoutingTun.fwmark;
table = perAppRoutingTun.routeTable;
}}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
family = "-6";
fwmark = perAppRoutingTun.fwmark;
table = perAppRoutingTun.routeTable;
}}
${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = perAppRoutingTun.routeTable; }}
${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = perAppRoutingTun.routeTable; }}
${builders.mkIpLinkDelete { inherit ip; interface = perAppRoutingTun.interface; }}
${builders.flushResolvedCaches}
'';
perAppTproxyUpScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-up" ''
set -euo pipefail
${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "proxy_suite_per_app_tproxy"; }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
fwmark = perAppRoutingTproxy.fwmark;
table = perAppRoutingTproxy.routeTable;
}}
${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = perAppRoutingTproxy.routeTable; }}
${nft} -f ${perAppTproxyRulesFile}
${ip} route replace local default dev lo table ${toString perAppRoutingTproxy.routeTable}
${ip} rule add fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable}
'';
perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-down" ''
set +e
${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "proxy_suite_per_app_tproxy"; }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
fwmark = perAppRoutingTproxy.fwmark;
table = perAppRoutingTproxy.routeTable;
}}
${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = perAppRoutingTproxy.routeTable; }}
'';
in
{
inherit
perAppTunUpScript
perAppTunDownScript
perAppTproxyUpScript
perAppTproxyDownScript
;
}
@@ -0,0 +1,95 @@
# Per-app routing profile expansion and proxychains config.
{
lib,
pkgs,
proxyCfg,
perAppRoutingCfg,
perAppRoutingTun,
perAppRoutingTproxy,
perAppZapretCfg,
}:
let
perAppRoutingProfileNames = map (profile: profile.name) perAppRoutingCfg.profiles;
defaultPerAppRoutingProfiles = lib.optionals perAppRoutingCfg.createDefaultProfiles (
[
{
name = "proxychains";
route = "proxychains";
}
]
++ lib.optionals perAppRoutingTun.enable [
{
name = "tun";
route = "tun";
}
]
++ lib.optionals perAppRoutingTproxy.enable [
{
name = "tproxy";
route = "tproxy";
}
]
++ lib.optionals perAppZapretCfg.enable [
{
name = "zapret";
route = "zapret";
}
]
);
effectivePerAppRoutingProfiles =
perAppRoutingCfg.profiles
++ builtins.filter (
profile: !(builtins.elem profile.name perAppRoutingProfileNames)
) defaultPerAppRoutingProfiles;
effectivePerAppRoutingProfileNames = map (profile: profile.name) effectivePerAppRoutingProfiles;
localProxyAuth = proxyCfg.listener.auth;
localProxyAuthEnabled =
localProxyAuth.username != null
&& (localProxyAuth.password != null || localProxyAuth.passwordFile != null);
perAppRoutingProfilesFile = pkgs.writeText "proxy-suite-per-app-routing-profiles.json" (
builtins.toJSON effectivePerAppRoutingProfiles
);
proxychainsConfigFile =
if localProxyAuthEnabled then
"/run/proxy-suite-socks/proxychains.conf"
else
pkgs.writeText "proxy-suite-proxychains.conf" ''
strict_chain
${lib.optionalString perAppRoutingCfg.proxychains.quiet "quiet_mode"}
${lib.optionalString perAppRoutingCfg.proxychains.proxyDns "proxy_dns"}
tcp_read_time_out 15000
tcp_connect_time_out 8000
[ProxyList]
socks5 ${proxyCfg.listener.address} ${toString proxyCfg.listener.port}
'';
proxychainsQuietArg = lib.optionalString perAppRoutingCfg.proxychains.quiet "-q ";
hasProxychainsProfiles = builtins.any (
profile: profile.route == "proxychains"
) effectivePerAppRoutingProfiles;
hasTunProfiles = builtins.any (profile: profile.route == "tun") effectivePerAppRoutingProfiles;
hasTproxyProfiles = builtins.any (
profile: profile.route == "tproxy"
) effectivePerAppRoutingProfiles;
hasZapretProfiles = builtins.any (
profile: profile.route == "zapret"
) effectivePerAppRoutingProfiles;
in
{
inherit
effectivePerAppRoutingProfiles
effectivePerAppRoutingProfileNames
perAppRoutingProfilesFile
proxychainsConfigFile
proxychainsQuietArg
hasProxychainsProfiles
hasTunProfiles
hasTproxyProfiles
hasZapretProfiles
;
}
@@ -0,0 +1,142 @@
# Per-user cgroup nftables mark-rule scripts for per-app routing backends.
{
lib,
pkgs,
perAppRoutingTun,
perAppRoutingTproxy,
perAppZapretCfg,
perAppTunSliceName,
perAppTproxySliceName,
perAppZapretSliceName,
nft,
awk,
grepBin,
findBin,
headBin,
}:
let
mkUserRuleStart =
{
name,
nftFamily,
nftTable,
nftChain,
sliceName,
sliceLabel,
markRule,
}:
pkgs.writeShellScript "proxy-suite-${name}-user-start" ''
set -euo pipefail
uid="$1"
rule_comment_prefix="proxy-suite-${name}-user-$uid"
mark_comment="$rule_comment_prefix-mark"
cgroup_root="/sys/fs/cgroup/user.slice/user-$uid.slice/user@$uid.service"
if ! [ -d "$cgroup_root" ]; then
echo "proxy-suite: user cgroup root does not exist for uid $uid: $cgroup_root" >&2
exit 1
fi
cgroup_dir=$(${findBin} "$cgroup_root" -type d -name ${lib.escapeShellArg sliceName} | ${headBin} -n1 || true)
if [ -z "$cgroup_dir" ]; then
echo "proxy-suite: ${sliceLabel} slice cgroup does not exist for uid $uid under $cgroup_root" >&2
exit 1
fi
cgroup_path=''${cgroup_dir#/sys/fs/cgroup/}
cgroup_level=$(printf '%s' "$cgroup_path" | ${awk} -F/ '{ print NF }')
handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \
| ${grepBin} -F "comment \"$rule_comment_prefix" \
| ${awk} '{ print $NF }' || true)
if [ -n "$handles" ]; then
while IFS= read -r handle; do
[ -n "$handle" ] || continue
${nft} delete rule ${nftFamily} ${nftTable} ${nftChain} handle "$handle" || true
done <<< "$handles"
fi
printf '%s\n' \
"add rule ${nftFamily} ${nftTable} ${nftChain} socket cgroupv2 level $cgroup_level \"$cgroup_path\" ${markRule} comment \"$mark_comment\"" \
| ${nft} -f -
'';
mkUserRuleStop =
{
name,
nftFamily,
nftTable,
nftChain,
}:
pkgs.writeShellScript "proxy-suite-${name}-user-stop" ''
set -euo pipefail
uid="$1"
rule_comment_prefix="proxy-suite-${name}-user-$uid"
handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \
| ${grepBin} -F "comment \"$rule_comment_prefix" \
| ${awk} '{ print $NF }' || true)
if [ -n "$handles" ]; then
while IFS= read -r handle; do
[ -n "$handle" ] || continue
${nft} delete rule ${nftFamily} ${nftTable} ${nftChain} handle "$handle" || true
done <<< "$handles"
fi
'';
perAppTunUserRuleStart = mkUserRuleStart {
name = "per-app-tun";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_tun";
nftChain = "output";
sliceName = perAppTunSliceName;
sliceLabel = "app TUN";
markRule = "meta mark set ${toString perAppRoutingTun.fwmark} ct mark set ${toString perAppRoutingTun.fwmark}";
};
perAppTunUserRuleStop = mkUserRuleStop {
name = "per-app-tun";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_tun";
nftChain = "output";
};
perAppTproxyUserRuleStart = mkUserRuleStart {
name = "per-app-tproxy";
nftFamily = "ip";
nftTable = "proxy_suite_per_app_tproxy";
nftChain = "output";
sliceName = perAppTproxySliceName;
sliceLabel = "app TProxy";
markRule = "meta mark set ${toString perAppRoutingTproxy.fwmark} ct mark set ${toString perAppRoutingTproxy.fwmark}";
};
perAppTproxyUserRuleStop = mkUserRuleStop {
name = "per-app-tproxy";
nftFamily = "ip";
nftTable = "proxy_suite_per_app_tproxy";
nftChain = "output";
};
perAppZapretUserRuleStart = mkUserRuleStart {
name = "per-app-zapret";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_zapret_mark";
nftChain = "output";
sliceName = perAppZapretSliceName;
sliceLabel = "app zapret";
markRule = "meta mark set meta mark or ${toString perAppZapretCfg.filterMark} ct mark set ct mark or ${toString perAppZapretCfg.filterMark}";
};
perAppZapretUserRuleStop = mkUserRuleStop {
name = "per-app-zapret";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_zapret_mark";
nftChain = "output";
};
in
{
inherit
perAppTunUserRuleStart
perAppTunUserRuleStop
perAppTproxyUserRuleStart
perAppTproxyUserRuleStop
perAppZapretUserRuleStart
perAppZapretUserRuleStop
;
}
+3 -3
View File
@@ -6,15 +6,15 @@
}:
let
userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable;
userControlEnabled = userControlCfg.allow != [ ];
userControlPolkitRules =
lib.optionalString userControlCfg.perApp.enable ''
lib.optionalString (builtins.elem "perApp" userControlCfg.allow) ''
if (unit.indexOf("proxy-suite-per-app-") === 0) {
return polkit.Result.YES;
}
''
+ lib.optionalString userControlCfg.global.enable ''
+ lib.optionalString (builtins.elem "global" userControlCfg.allow) ''
if ((unit.indexOf("proxy-suite-") === 0 &&
unit.indexOf("proxy-suite-per-app-") !== 0) ||
unit === "zapret-discord-youtube.service") {
@@ -0,0 +1,189 @@
# Start script of the inbound service: renders the listeners with their secrets into the
# template and runs XRay.
{
lib,
pkgs,
proxyCfg,
proxyInboundsCfg,
proxyInboundsNeedLocalProxy,
proxyInboundViaOutbounds,
userControlCfg,
userControlEnabled,
localProxyAuth,
localProxyAuthEnabled,
localProxyAuthPasswordSource,
jq,
python3,
parserScriptsPythonPath,
buildInboundPy,
buildOutboundPy,
proxyInboundsFile,
proxyInboundsSpecFile,
builders,
constants,
}:
let
runtimeDir = "/run/proxy-suite-inbounds";
linksFile = "${runtimeDir}/links.json";
subscriptionsFile = "${runtimeDir}/subscriptions.json";
subsCfg = proxyInboundsCfg.subscriptions;
xray = "${proxyInboundsCfg.package}/bin/xray";
needsLocalProxyAuth = proxyInboundsNeedLocalProxy && localProxyAuthEnabled;
serverAddressBlock =
if proxyInboundsCfg.serverAddress != null then
''SERVER_ADDRESS=${lib.escapeShellArg proxyInboundsCfg.serverAddress}''
else if proxyInboundsCfg.shareLinks then
''
${builders.mkDefaultUplinkIPv4Source {
ip = "${pkgs.iproute2}/bin/ip";
awk = "${pkgs.gawk}/bin/awk";
errorMessage = "proxy-suite: could not determine this host's uplink address for inbound share links; set inbounds.serverAddress";
}}
SERVER_ADDRESS="$uplink_addr"
''
else
''SERVER_ADDRESS=""'';
# Outbounds pinned with `via = "<tag>"`, rendered at start so urlFile contents stay
# out of the store.
mkViaOutboundBlock =
ob:
let
urlSource =
if ob.urlFile != null then
ob.urlFile
else if ob.url != null then
pkgs.writeText "proxy-suite-inbound-via-url-${ob.tag}" ob.url
else
null;
in
if urlSource == null then
''
# via outbound: ${ob.tag} (static xray json)
OB_JSON=$(cat ${
pkgs.writeText "proxy-suite-inbound-via-${ob.tag}.json" (
builtins.toJSON (ob.xrayJson // { inherit (ob) tag; })
)
})
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
''
else
''
# via outbound: ${ob.tag}
URL=$(cat ${lib.escapeShellArg urlSource})
OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} \
--backend xray --tag ${lib.escapeShellArg ob.tag})
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
'';
viaOutboundsBlock = lib.concatMapStrings mkViaOutboundBlock proxyInboundViaOutbounds;
writeLinksBlock = lib.optionalString proxyInboundsCfg.shareLinks ''
${jq} -c '.links' <<< "$RENDERED" > "${linksFile}"
${lib.optionalString userControlEnabled ''
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${linksFile}"
''}
chmod ${if userControlEnabled then "640" else "600"} "${linksFile}"
'';
# One file per user for the web server, plus a token index for proxy-ctl. Filled aside
# and swapped in whole; a missing group leaves them root-only.
writeSubscriptionsBlock = lib.optionalString (proxyInboundsCfg.shareLinks && subsCfg.enable) ''
SUB_DIR="${runtimeDir}/subscriptions"
rm -rf "$SUB_DIR.new"
mkdir -m 0750 "$SUB_DIR.new"
${jq} -r '.subscriptions[] | "\(.token)\t\(.body)"' <<< "$RENDERED" |
while IFS=$'\t' read -r token body; do
printf '%s' "$body" > "$SUB_DIR.new/$token"
done
chmod -R u=rwX,g=rX,o= "$SUB_DIR.new"
${pkgs.coreutils}/bin/chgrp -R ${lib.escapeShellArg subsCfg.group} "$SUB_DIR.new" ||
echo "proxy-suite: group ${subsCfg.group} cannot be given the subscriptions; they stay root-only" >&2
rm -rf "$SUB_DIR"
mv "$SUB_DIR.new" "$SUB_DIR"
${jq} -c '[.subscriptions[] | {user, token}]' <<< "$RENDERED" > "${subscriptionsFile}"
${lib.optionalString userControlEnabled ''
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${subscriptionsFile}"
''}
chmod ${if userControlEnabled then "640" else "600"} "${subscriptionsFile}"
'';
startInbounds = pkgs.writeShellScript "proxy-suite-start-inbounds" ''
set -euo pipefail
umask 077
RUNTIME_DIR="${runtimeDir}"
mkdir -p "$RUNTIME_DIR"
${serverAddressBlock}
RENDERED=$(PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildInboundPy} \
--spec ${proxyInboundsSpecFile} \
--server-address "$SERVER_ADDRESS")
INBOUNDS_JSON=$(${jq} -c '.inbounds' <<< "$RENDERED")
OUTBOUNDS_JSON='[]'
${viaOutboundsBlock}
${lib.optionalString needsLocalProxyAuth ''
LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")"
''}
${jq} \
--argjson ibs "$INBOUNDS_JSON" \
--argjson obs "$OUTBOUNDS_JSON" \
--argjson auth_enabled ${if needsLocalProxyAuth then "true" else "false"} \
--arg user ${if needsLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \
--arg password ${if needsLocalProxyAuth then "\"$LOCAL_PROXY_PASSWORD\"" else "''"} \
'.inbounds = $ibs
| .outbounds = $obs + .outbounds
| if $auth_enabled then
(.outbounds[] | select(.tag == "proxy") | .settings.servers[0].users)
= [{user:$user,pass:$password}]
else . end' \
${proxyInboundsFile} > "$RUNTIME_DIR/config.json"
chmod 600 "$RUNTIME_DIR/config.json"
${writeLinksBlock}
${writeSubscriptionsBlock}
exec ${xray} run -c "$RUNTIME_DIR/config.json"
'';
# Adds XRay's per-user counters to the daily totals, read and reset in one call.
# ponytail: a restart of the inbounds loses what was counted since the last run, at
# most one timer interval; collect from ExecStop if that matters.
collectInboundStats = pkgs.writeShellScript "proxy-suite-inbound-stats" ''
set -euo pipefail
file=${lib.escapeShellArg constants.inboundStatsFile}
if ! reading=$(${xray} api statsquery --server=127.0.0.1:${toString constants.inboundStatsApiPort} \
-pattern 'user>>>' -reset 2> /dev/null); then
echo "the inbounds' stats API is not answering; nothing collected"
exit 0
fi
[ -n "$reading" ] || reading='{}'
[ -s "$file" ] || echo '{}' > "$file"
tmp=$(${pkgs.coreutils}/bin/mktemp "$file.XXXXXX")
${jq} --argjson q "$reading" \
--arg day "$(${pkgs.coreutils}/bin/date +%F)" \
--argjson now "$(${pkgs.coreutils}/bin/date +%s)" \
-f ${../inbound-stats-add.jq} "$file" > "$tmp"
${lib.optionalString userControlEnabled ''
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$tmp" ||
echo "proxy-suite: group ${userControlCfg.group} cannot read the stats; they stay root-only" >&2
''}
chmod ${if userControlEnabled then "640" else "600"} "$tmp"
mv -f "$tmp" "$file"
'';
in
{
inherit
startInbounds
collectInboundStats
linksFile
subscriptionsFile
;
}
@@ -0,0 +1,144 @@
{
lib,
pkgs,
builders,
ip,
nft,
nftablesRulesFile,
constants,
globalTun,
globalTproxy,
perAppRoutingTun,
perAppRoutingTproxy,
}:
let
inherit (constants)
tunAutoRouteTableIndex
tunAutoRouteRulePriority
xrayTunPerAppTproxyRulePriority
xrayTunPerAppTunRulePriority
xrayGlobalTunIPv6Address
xrayGlobalTunIPv6RoutePrefix
;
defaultUplinkIPv4Source = builders.mkDefaultUplinkIPv4Source {
inherit ip;
awk = "${pkgs.gawk}/bin/awk";
errorMessage = "proxy-suite: could not determine the default uplink IPv4 address for XRay TUN";
};
in
{
xrayTunUpScript = pkgs.writeShellScript "proxy-suite-xray-tun-up" ''
set -euo pipefail
tun_cidr=${lib.escapeShellArg globalTun.address}
tun6_cidr=${lib.escapeShellArg xrayGlobalTunIPv6Address}
tun6_route_prefix=${lib.escapeShellArg xrayGlobalTunIPv6RoutePrefix}
tun_addr=""
tun_route_prefix=""
uplink_addr=""
${builders.cidrNetworkFunction}
for _ in $(${pkgs.coreutils}/bin/seq 1 50); do
if ${ip} link show dev ${lib.escapeShellArg globalTun.interface} >/dev/null 2>&1; then
break
fi
${pkgs.coreutils}/bin/sleep 0.1
done
if ! ${ip} link show dev ${lib.escapeShellArg globalTun.interface} >/dev/null 2>&1; then
echo "proxy-suite: XRay TUN interface ${globalTun.interface} did not appear in time" >&2
exit 1
fi
${defaultUplinkIPv4Source}
while ${ip} -4 rule del pref ${toString xrayTunPerAppTproxyRulePriority} 2>/dev/null; do :; done
while ${ip} -4 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
while ${ip} -4 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done
while ${ip} -6 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
while ${ip} -6 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done
tun_addr="''${tun_cidr%%/*}"
tun_route_prefix="$(cidr_network "$tun_cidr")"
${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg globalTun.interface}
${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg globalTun.interface}
${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg globalTun.interface} src "$tun_addr" table ${toString tunAutoRouteTableIndex}
${ip} -4 route replace default dev ${lib.escapeShellArg globalTun.interface} src "$uplink_addr" table ${toString tunAutoRouteTableIndex}
${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
${ip} -6 route replace default dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
${lib.optionalString perAppRoutingTproxy.enable ''
${ip} -4 rule add pref ${toString xrayTunPerAppTproxyRulePriority} fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable}
''}
${lib.optionalString perAppRoutingTun.enable ''
${ip} -4 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
${ip} -6 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
''}
${ip} -4 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
${ip} -6 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
'';
tproxyUpScript = pkgs.writeShellScript "proxy-suite-tproxy-up" ''
set -euo pipefail
# Start from a clean policy-routing state. `ip rule add` permits duplicate
# rules on some iproute2 versions, and a stale rule can keep packets routed
# into a dead local table after a failed restart.
${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "singbox"; }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
fwmark = globalTproxy.fwmark;
table = globalTproxy.routeTable;
}}
${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = globalTproxy.routeTable; }}
${nft} -f ${nftablesRulesFile}
${ip} route replace local default dev lo table ${toString globalTproxy.routeTable}
${ip} rule add fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable}
'';
tproxyDownScript = pkgs.writeShellScript "proxy-suite-tproxy-down" ''
set +e
${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "singbox"; }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
fwmark = globalTproxy.fwmark;
table = globalTproxy.routeTable;
}}
${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = globalTproxy.routeTable; }}
'';
tunCleanupScript = pkgs.writeShellScript "proxy-suite-tun-cleanup" ''
set +e
# SingBox normally removes these on graceful shutdown, but stale
# auto_route/auto_redirect state leaves the host routing through a dead TUN
# interface after `proxy-ctl proxy tun off` or an unclean service stop.
${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "sing-box"; }}
${builders.mkIpRuleDeleteByTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }}
${builders.mkIpRuleDeleteByTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }}
${builders.mkIpRuleDeleteByPriority {
inherit ip;
family = "-4";
priority = xrayTunPerAppTproxyRulePriority;
}}
${builders.mkIpRuleDeleteByPriority {
inherit ip;
family = "-4";
priority = xrayTunPerAppTunRulePriority;
}}
${builders.mkIpRuleDeleteByPriority {
inherit ip;
family = "-6";
priority = xrayTunPerAppTunRulePriority;
}}
${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }}
${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }}
${builders.mkIpLinkDelete { inherit ip; interface = globalTun.interface; }}
${builders.flushResolvedCaches}
'';
}
@@ -0,0 +1,117 @@
{
lib,
pureXrayEnabled,
selectionMode,
proxyInboundsGuardPrivate,
}:
if pureXrayEnabled then
''
def xray_bind_outbound($interface):
if $interface == "" or .protocol == "blackhole" or .protocol == "dns" then
.
else
.streamSettings = (.streamSettings // {})
| .streamSettings.sockopt = (.streamSettings.sockopt // {})
| if (.streamSettings.sockopt.interface? // "") == "" then
.streamSettings.sockopt.interface = $interface
else
.
end
end;
def xray_proxy_rule_target($single_tag):
if $single_tag != "" then
{outboundTag:$single_tag}
else
{balancerTag:"proxy"}
end;
def xray_rewrite_proxy_rule($single_tag):
if $single_tag != "" and (.balancerTag? // "") == "proxy" then
.outboundTag = $single_tag | del(.balancerTag)
else
.
end;
def xray_preserved_rules:
[.routing.rules[]
| select(((.ruleTag? // "") == "dns-hijack") or ((.ruleTag? // "") == "dns-upstream-direct"))];
def xray_final_rule($tag; $single_tag):
if $tag == "proxy" and "${selectionMode}" == "urltest" then
{type:"field",network:"tcp,udp",ruleTag:"final-default"} + xray_proxy_rule_target($single_tag)
else
{type:"field",network:"tcp,udp",ruleTag:"final-default",outboundTag:$tag}
end;
def xray_dns_server_order($dns_final):
if $dns_final == "" then
.dns.servers
else
([.dns.servers[] | select((.tag? // "") == "fakedns")]
+ [.dns.servers[] | select((.tag? // "") == $dns_final)]
+ [.dns.servers[] | select((.tag? // "") != "fakedns" and (.tag? // "") != $dns_final)])
end;
def xray_tun_dns_addresses($dns_final; $local_addr; $remote_addr):
if $dns_final == "local" then
[$local_addr, $remote_addr]
elif $dns_final == "remote" then
[$remote_addr, $local_addr]
else
[$remote_addr, $local_addr]
end;
.outbounds = (($obs + .outbounds) | map(xray_bind_outbound($xray_bind_interface)))
| if $xray_loglevel == "" then . else .log.loglevel = $xray_loglevel end
| if $auth_enabled then
(.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password"
| (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.accounts) = [{user:$user,pass:$password}]
else . end
| if $xray_tun_dns_runtime then
.dns.servers = xray_dns_server_order($dns_final)
| if $dns_final == "" then
.
else
(.inbounds[] | select(.protocol == "tun" and .tag == "tun-in") | .settings.dns) = xray_tun_dns_addresses($dns_final; $xray_dns_local_client; $xray_dns_remote_client)
end
else . end
| if $route_enabled then
.routing.rules = (xray_preserved_rules + $route_rules + [xray_final_rule($route_final; $xray_single_proxy_tag)])
else . end
| if $xray_single_proxy_tag == "" then
.
else
.routing.rules |= map(xray_rewrite_proxy_rule($xray_single_proxy_tag))
| del(.routing.balancers)
| del(.observatory)
end
''
else
''
def sing_box_preserved_rules:
[.route.rules[]
| select(((.action? // "") == "hijack-dns")
and (((.inbound? // []) | index("xray-dns-in")) != null))];
.outbounds = $obs + .outbounds
| if $auth_enabled then
(.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}]
else . end
| if $route_enabled then
.route.rules = (sing_box_preserved_rules + $route_rules)
| .route.final = $route_final
| .dns.final = $dns_final
| if $clear_dns_rules then .dns.rules = [] else . end
else . end
# autoProxy rules, after the route-mode replace so no mode drops them: pins first
# (they only match their own listener), learned rules last before final, so
# explicit rules win. All [] when off.
| .inbounds += $probe_inbounds
| .route.rule_set = ((.route.rule_set // []) + $autoproxy_rule_sets)
| .route.rules = ($probe_pin_rules + .route.rules + $autoproxy_rules)
''
+ lib.optionalString proxyInboundsGuardPrivate ''
# inbounds.routing.blockPrivate, enforced here because the listener passes names unresolved.
# Last, so only traffic falling through to a direct final is resolved. Local mixed-
# in clients lose names that resolve private.
| if (.route.final // "direct") == "direct" then
.route.rules += [
{inbound: ["mixed-in"], action: "resolve"},
{inbound: ["mixed-in"], ip_is_private: true, action: "reject"}
]
else . end
''
@@ -0,0 +1,111 @@
{
lib,
jq,
hybridEnabled,
xraySidecarRoutingMark,
}:
routingMark: xraySidecarBasePort: xrayDnsBridgePort:
lib.optionalString hybridEnabled ''
XRAY_OUTBOUNDS_JSON='[]'
XRAY_INBOUNDS_JSON='[]'
XRAY_ROUTE_RULES_JSON='[]'
XRAY_SIDECAR_NEXT_PORT=${toString xraySidecarBasePort}
XRAY_SIDECAR_DNS_PORT=${toString xrayDnsBridgePort}
_proxy_suite_add_sing_box_ob() {
local ob="$1"
OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
}
_proxy_suite_next_xray_sidecar_port() {
local port="$XRAY_SIDECAR_NEXT_PORT"
XRAY_SIDECAR_NEXT_PORT=$((XRAY_SIDECAR_NEXT_PORT + 1))
printf '%s\n' "$port"
}
_proxy_suite_add_xray_sidecar_ob() {
local ob="$1" tag="$2" port auth inbound_tag sing_ob inbound route_rule
port="$(_proxy_suite_next_xray_sidecar_port)"
auth="proxy-suite-xray-$port"
inbound_tag="$tag-inbound"
ob=$(${jq} \
--arg tag "$tag" \
--argjson mark ${toString xraySidecarRoutingMark} \
'.tag = $tag
| .streamSettings = (.streamSettings // {})
| .streamSettings.sockopt = (.streamSettings.sockopt // {})
| .streamSettings.sockopt.mark = $mark
| .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")' \
<<< "$ob")
XRAY_OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$XRAY_OUTBOUNDS_JSON")
inbound=$(${jq} -n \
--arg tag "$inbound_tag" \
--arg auth "$auth" \
--argjson port "$port" \
'{tag:$tag,listen:"127.0.0.1",port:$port,protocol:"socks",settings:{auth:"password",udp:true,accounts:[{user:$auth,pass:$auth}]}}')
XRAY_INBOUNDS_JSON=$(${jq} --argjson inbound "$inbound" '. + [$inbound]' <<< "$XRAY_INBOUNDS_JSON")
route_rule=$(${jq} -n \
--arg inbound "$inbound_tag" \
--arg outbound "$tag" \
'{type:"field",inboundTag:[$inbound],outboundTag:$outbound}')
XRAY_ROUTE_RULES_JSON=$(${jq} --argjson rule "$route_rule" '. + [$rule]' <<< "$XRAY_ROUTE_RULES_JSON")
sing_ob=$(${jq} -n \
--arg tag "$tag" \
--arg auth "$auth" \
--argjson port "$port" \
'{type:"socks",tag:$tag,server:"127.0.0.1",server_port:$port,version:"5",username:$auth,password:$auth${
lib.optionalString (routingMark != null) ",routing_mark:${toString routingMark}"
}}')
OUTBOUNDS_JSON=$(${jq} --argjson ob "$sing_ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
}
_proxy_suite_write_xray_sidecar_config() {
if [ "$(${jq} 'length' <<< "$XRAY_OUTBOUNDS_JSON")" -eq 0 ]; then
return 0
fi
${jq} -n \
--arg loglevel "$XRAY_LOGLEVEL" \
--arg bind_interface "$XRAY_TUN_BIND_INTERFACE" \
--argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \
--argjson inbounds "$XRAY_INBOUNDS_JSON" \
--argjson outbounds "$XRAY_OUTBOUNDS_JSON" \
--argjson route_rules "$XRAY_ROUTE_RULES_JSON" \
'
def bind_xray_sidecar($interface):
if $interface == "" then
.
else
.streamSettings = (.streamSettings // {})
| .streamSettings.sockopt = (.streamSettings.sockopt // {})
| if (.streamSettings.sockopt.interface? // "") == "" then
.streamSettings.sockopt.interface = $interface
else
.
end
end;
{
log: {
loglevel: (if $loglevel == "" then "warning" else $loglevel end),
access: "none"
},
dns: {
servers: [
{
address: "127.0.0.1",
port: $dns_port,
queryStrategy: "UseIP",
skipFallBack: true
}
]
},
inbounds: $inbounds,
outbounds: (($outbounds | map(bind_xray_sidecar($bind_interface))) + [{protocol:"freedom",tag:"direct"}]),
routing: {
domainStrategy: "AsIs",
rules: ($route_rules + [{type:"field",ip:["127.0.0.1"],port:$dns_port,outboundTag:"direct"}])
}
}' > "$RUNTIME_DIR/xray-sidecar.json"
}
''
@@ -0,0 +1,456 @@
{
lib,
pkgs,
singBoxCfg,
proxyCfg,
sshProxyCfg,
pureXrayEnabled,
hybridEnabled,
collapseNamedOutbounds,
selectionMode,
backend,
backendArg,
xraySidecarRoutingMark,
priorityOutboundFile,
runtimeOutboundsDir,
jq,
python3,
parserScriptsPythonPath,
buildOutboundPy,
mkSubscriptionBlock,
mkSubscriptionLoadHelperBlock,
runtimeSubscriptionsBlock,
}:
let
sshProxyTag = "ssh-proxy";
# sing-box domain strategies in XRay's names (UseIPv4v6 = prefer IPv4).
xrayDomainStrategies = {
prefer_ipv4 = "UseIPv4v6";
prefer_ipv6 = "UseIPv6v4";
ipv4_only = "UseIPv4";
ipv6_only = "UseIPv6";
};
rawOutboundJson =
ob: tag: routingMark:
let
backendRaw =
if pureXrayEnabled then
ob.xrayJson
else if ob.singBoxJson != null then
ob.singBoxJson
else
ob.json;
markAttrs =
if routingMark == null then
{ }
else if pureXrayEnabled then
{ streamSettings.sockopt.mark = routingMark; }
else
{ routing_mark = routingMark; };
taggedRaw = backendRaw // {
inherit tag;
};
in
if pureXrayEnabled then lib.recursiveUpdate taggedRaw markAttrs else taggedRaw // markAttrs;
# Every outbound that comes from a URL goes through these, whether it was
# declared in Nix or dropped into outbounds.d at runtime.
mkUrlOutboundHelpersBlock =
routingMark:
let
markArg = lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}";
parse = backendFlag: markFlag: ''
printf '%s' "$2" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} \
${backendFlag} --tag "$1"${markFlag}
'';
addBlock =
if hybridEnabled then
''
case "$pref" in
xray)
ob=$(_proxy_suite_parse_xray_url "$tag" "$url") || return 1
_proxy_suite_add_xray_sidecar_ob "$ob" "$tag"
;;
sing-box)
ob=$(_proxy_suite_parse_sing_box_url "$tag" "$url") || return 1
_proxy_suite_add_sing_box_ob "$ob"
;;
*)
if ob=$(_proxy_suite_parse_sing_box_url "$tag" "$url" 2>"$RUNTIME_DIR/sing-box-parser.err"); then
_proxy_suite_add_sing_box_ob "$ob"
elif ob=$(_proxy_suite_parse_xray_url "$tag" "$url"); then
_proxy_suite_add_xray_sidecar_ob "$ob" "$tag"
else
echo "proxy-suite: outbound '$tag' cannot be parsed by SingBox or XRay" >&2
if [ -s "$RUNTIME_DIR/sing-box-parser.err" ]; then
cat "$RUNTIME_DIR/sing-box-parser.err" >&2
fi
return 1
fi
;;
esac
''
else
''
ob=$(_proxy_suite_parse_url "$tag" "$url") || return 1
OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
'';
in
''
OUTBOUND_SOURCES_JSON='{}'
_proxy_suite_record_tag_source() {
OUTBOUND_SOURCES_JSON=$(${jq} --arg t "$1" --arg s "$2" '.[$t] = $s' <<< "$OUTBOUND_SOURCES_JSON")
}
# $1 source label, $2 array length before the add, $3 after. Subscriptions
# append an unknown number of outbounds, so they label them by range.
_proxy_suite_record_outbound_source() {
[ "$3" -gt "$2" ] || return 0
OUTBOUND_SOURCES_JSON=$(${jq} \
--argjson sources "$OUTBOUND_SOURCES_JSON" --arg s "$1" \
--argjson b "$2" --argjson a "$3" \
'reduce .[$b:$a][].tag as $t ($sources; .[$t] = $s)' <<< "$OUTBOUNDS_JSON")
}
${
if hybridEnabled then
''
_proxy_suite_parse_sing_box_url() {
${parse "--backend sing-box" markArg}
}
_proxy_suite_parse_xray_url() {
${parse "--backend xray" " --routing-mark ${toString xraySidecarRoutingMark}"}
}
''
else
''
_proxy_suite_parse_url() {
${parse backendArg markArg}
}
''
}
# $1 tag, $2 URL, $3 source label, $4 backend preference (auto|sing-box|xray).
# Returns non-zero when the URL cannot be parsed; the caller decides whether
# that is fatal.
_proxy_suite_add_url_outbound() {
local tag="$1" url="$2" source="$3" pref="''${4:-auto}" ob
${addBlock}
_proxy_suite_record_tag_source "$tag" "$source"
}
# Every runtime outbound, as "<tag>\t<url file>" lines. proxy-ctl refuses
# the reserved names, but the spool is group-writable, so check again here:
# a second outbound tagged "proxy" would quietly shadow the real one.
_proxy_suite_runtime_outbounds() {
local f tag
[ -d "${runtimeOutboundsDir}" ] || return 0
for f in "${runtimeOutboundsDir}"/*.url; do
[ -e "$f" ] || continue
tag="''${f##*/}"
tag="''${tag%.url}"
case "$tag" in
proxy | direct | block)
echo "proxy-suite: warning: ignoring runtime outbound '$tag': reserved name" >&2
continue
;;
esac
printf '%s\t%s\n' "$tag" "$f"
done
}
'';
mkOutboundBlock =
ob: routingMark: tag:
let
backendRaw =
if pureXrayEnabled then
ob.xrayJson
else if ob.singBoxJson != null then
ob.singBoxJson
else
ob.json;
in
if backendRaw != null then
let
outboundJson = builtins.toJSON (rawOutboundJson ob tag routingMark);
jsonFile = pkgs.writeText "proxy-suite-ob-${tag}.json" outboundJson;
in
''
# outbound: ${tag} (static ${backend} json)
OB_JSON=$(cat "${jsonFile}")
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
_proxy_suite_record_tag_source ${lib.escapeShellArg tag} static
''
else
let
urlSource =
if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url;
in
''
# outbound: ${tag}
_proxy_suite_add_url_outbound ${lib.escapeShellArg tag} "$(cat "${urlSource}")" static || exit 1
'';
singBoxRawOutboundJson =
ob: tag: routingMark:
let
backendRaw = if ob.singBoxJson != null then ob.singBoxJson else ob.json;
markAttrs = lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; };
in
backendRaw // { inherit tag; } // markAttrs;
xrayRawOutboundJson =
ob: tag:
lib.recursiveUpdate (ob.xrayJson // { inherit tag; }) {
streamSettings.sockopt = {
mark = xraySidecarRoutingMark;
domainStrategy = "UseIP";
};
};
mkHybridOutboundBlock =
ob: routingMark: tag:
if ob.xrayJson != null then
let
outboundJson = builtins.toJSON (xrayRawOutboundJson ob tag);
jsonFile = pkgs.writeText "proxy-suite-xray-sidecar-ob-${tag}.json" outboundJson;
in
''
# outbound: ${tag} (hybrid XRay json sidecar)
OB_JSON=$(cat "${jsonFile}")
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
_proxy_suite_record_tag_source ${lib.escapeShellArg tag} static
''
else if ob.singBoxJson != null || ob.json != null then
let
outboundJson = builtins.toJSON (singBoxRawOutboundJson ob tag routingMark);
jsonFile = pkgs.writeText "proxy-suite-sing-box-ob-${tag}.json" outboundJson;
in
''
# outbound: ${tag} (hybrid SingBox json)
OB_JSON=$(cat "${jsonFile}")
_proxy_suite_add_sing_box_ob "$OB_JSON"
_proxy_suite_record_tag_source ${lib.escapeShellArg tag} static
''
else
let
urlSource =
if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url;
in
''
# outbound: ${tag} (hybrid ${ob.backend})
_proxy_suite_add_url_outbound ${lib.escapeShellArg tag} "$(cat "${urlSource}")" static ${ob.backend} || exit 1
'';
mkSshProxyOutboundBlock =
routingMark:
let
singBoxOutbound = {
type = "ssh";
tag = sshProxyTag;
server = sshProxyCfg.server.host;
server_port = sshProxyCfg.server.port;
user = sshProxyCfg.server.user;
}
// lib.optionalAttrs (sshProxyCfg.identityFile != null) {
private_key_path = sshProxyCfg.identityFile;
}
// lib.optionalAttrs (sshProxyCfg.hostKey != [ ]) {
host_key = sshProxyCfg.hostKey;
}
// lib.optionalAttrs (routingMark != null) {
routing_mark = routingMark;
};
# XRay has no SSH outbound: it goes through the OpenSSH unit's listener.
xraySockopt =
lib.optionalAttrs (routingMark != null) { mark = routingMark; }
// lib.optionalAttrs (sshProxyCfg.domainStrategy != null) {
domainStrategy = xrayDomainStrategies.${sshProxyCfg.domainStrategy};
};
xrayOutbound = {
protocol = "socks";
tag = sshProxyTag;
settings = {
address = sshProxyCfg.listener.address;
port = sshProxyCfg.listener.port;
};
}
// lib.optionalAttrs (xraySockopt != { }) {
streamSettings.sockopt = xraySockopt;
};
outbound = if pureXrayEnabled then xrayOutbound else singBoxOutbound;
outboundJson = builtins.toJSON outbound;
jsonFile = pkgs.writeText "proxy-suite-ob-ssh-proxy-${backend}.json" outboundJson;
# Read at start so the known-hosts file stays out of the store.
knownHostsTarget =
if sshProxyCfg.server.port == 22 then
sshProxyCfg.server.host
else
"[${sshProxyCfg.server.host}]:${toString sshProxyCfg.server.port}";
hostKeyFileBlock =
lib.optionalString (!pureXrayEnabled && sshProxyCfg.hostKeyFile != null)
''
SSH_HOST_KEYS=$(${pkgs.openssh}/bin/ssh-keygen -F ${lib.escapeShellArg knownHostsTarget} \
-f ${lib.escapeShellArg sshProxyCfg.hostKeyFile} \
| ${jq} -R -s '[splits("\n")] | map(select(length > 0 and (startswith("#") | not))) | map(sub("^\\S+\\s+"; ""))')
if [ "$(${jq} 'length' <<< "$SSH_HOST_KEYS")" -eq 0 ]; then
echo "proxy-suite: no host keys for ${knownHostsTarget} in ${sshProxyCfg.hostKeyFile}" >&2
exit 1
fi
OB_JSON=$(${jq} --argjson hk "$SSH_HOST_KEYS" '.host_key = $hk' <<< "$OB_JSON")
'';
in
''
# outbound: ${sshProxyTag} (${if pureXrayEnabled then "OpenSSH SOCKS5 listener" else "native SSH"})
OB_JSON=$(cat "${jsonFile}")
${hostKeyFileBlock}
${
if hybridEnabled then
''_proxy_suite_add_sing_box_ob "$OB_JSON"''
else
''OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")''
}
_proxy_suite_record_tag_source ${sshProxyTag} ssh
'';
mkBackendOutboundBlock = if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock;
runtimeOutboundsBlock = ''
# outbounds added at runtime
while IFS=$'\t' read -r RUNTIME_OB_TAG RUNTIME_OB_SRC; do
[ -n "$RUNTIME_OB_TAG" ] || continue
_proxy_suite_add_url_outbound "$RUNTIME_OB_TAG" "$(cat "$RUNTIME_OB_SRC")" runtime \
|| echo "proxy-suite: warning: ignoring runtime outbound '$RUNTIME_OB_TAG'" >&2
done < <(_proxy_suite_runtime_outbounds)
'';
requireOutboundsBlock = ''
if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 0 ]; then
echo "proxy-suite: no proxy outbounds are available; declare one, or add one with 'proxy-ctl proxy outbounds add'" >&2
exit 1
fi
'';
# The pin names a user-facing tag, so it is resolved before the wrapper block
# renames anything. A pin that no longer matches any outbound - a subscription
# entry that went away, say - is dropped rather than left to break the config.
pinBlock = ''
OUTBOUND_TAGS_JSON=$(${jq} -c '[.[].tag]' <<< "$OUTBOUNDS_JSON")
PRIORITY_OUTBOUND=""
if [ -r "${priorityOutboundFile}" ]; then
PRIORITY_OUTBOUND="$(tr -d '\r\n[:space:]' < "${priorityOutboundFile}" 2>/dev/null || true)"
fi
if [ -n "$PRIORITY_OUTBOUND" ] \
&& ! ${jq} -e --arg t "$PRIORITY_OUTBOUND" 'index($t) != null' <<< "$OUTBOUND_TAGS_JSON" >/dev/null; then
echo "proxy-suite: warning: pinned outbound '$PRIORITY_OUTBOUND' is not available; picking automatically" >&2
PRIORITY_OUTBOUND=""
fi
'';
# proxy-ctl reads this unprivileged: tags, where each came from, and the pin.
inventoryBlock = ''
${jq} -n \
--argjson tags "$OUTBOUND_TAGS_JSON" \
--argjson sources "$OUTBOUND_SOURCES_JSON" \
--arg pinned "$PRIORITY_OUTBOUND" \
--arg selection ${lib.escapeShellArg selectionMode} \
'{tags: $tags, sources: $sources, pinned: $pinned, selection: $selection}' \
> "$RUNTIME_DIR/outbounds.json"
chmod 644 "$RUNTIME_DIR/outbounds.json"
'';
mkOutboundScript =
routingMark:
let
outboundBlocks = lib.concatMapStrings (
ob: mkBackendOutboundBlock ob routingMark ob.tag
) proxyCfg.outbounds;
subscriptionBlocks = lib.concatMapStrings (
sub: mkSubscriptionBlock sub routingMark
) proxyCfg.subscriptions;
sshProxyBlock = lib.optionalString sshProxyCfg.asOutbound (mkSshProxyOutboundBlock routingMark);
wrapperBlock =
if pureXrayEnabled && selectionMode == "urltest" then
''
OUTBOUNDS_JSON=$(${jq} 'map(.tag = ("proxy-suite-ob-" + .tag))' <<< "$OUTBOUNDS_JSON")
# XRay has no selector: a pin degrades the balancer to the one outbound,
# which is the same path a single-outbound config already takes.
if [ -n "$PRIORITY_OUTBOUND" ]; then
XRAY_SINGLE_PROXY_TAG="proxy-suite-ob-$PRIORITY_OUTBOUND"
elif [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 1 ]; then
XRAY_SINGLE_PROXY_TAG="$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")"
fi
''
else if collapseNamedOutbounds then
''
PROXY_TAG="$PRIORITY_OUTBOUND"
if [ -z "$PROXY_TAG" ]; then
PROXY_TAG=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")
fi
OUTBOUNDS_JSON=$(${jq} --arg t "$PROXY_TAG" \
'map(if .tag == $t then .tag = "proxy" else . end)' <<< "$OUTBOUNDS_JSON")
''
else if selectionMode == "selector" then
''
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
DEFAULT_TAG="$PRIORITY_OUTBOUND"
if [ -z "$DEFAULT_TAG" ]; then
DEFAULT_TAG=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")
fi
WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \
--arg default "$DEFAULT_TAG" \
'{type:"selector",tag:"proxy",outbounds:$tags,default:$default}')
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
''
else
''
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
if [ -n "$PRIORITY_OUTBOUND" ]; then
# A pin beats latency ranking: the same outbounds, behind a selector
# the Clash API can also switch live.
WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \
--arg default "$PRIORITY_OUTBOUND" \
'{type:"selector",tag:"proxy",outbounds:$tags,default:$default}')
else
WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
--arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \
--argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \
'{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:$interval,tolerance:$tolerance}')
fi
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
'';
# Real exits for autoProxy, taken after the wrapper may have renamed one to
# "proxy".
exitTagsBlock = ''
EXIT_TAGS_JSON=$(${jq} -c '[.[] | select(.type != "selector" and .type != "urltest") | .tag]' <<< "$OUTBOUNDS_JSON")
'';
in
mkUrlOutboundHelpersBlock routingMark
+ mkSubscriptionLoadHelperBlock routingMark
+ outboundBlocks
+ subscriptionBlocks
+ runtimeSubscriptionsBlock
+ runtimeOutboundsBlock
+ sshProxyBlock
+ requireOutboundsBlock
+ pinBlock
+ inventoryBlock
+ wrapperBlock
+ exitTagsBlock;
in
{
inherit mkOutboundScript rawOutboundJson;
}
@@ -0,0 +1,199 @@
# Subscription cache and outbound-loading script fragments.
#
# Everything is emitted as shell functions taking a tag and a file holding the
# subscription URL, so a subscription declared in Nix and one added at runtime
# under `subscriptions.d/` go through exactly the same code.
{
lib,
pkgs,
proxyCfg,
hybridEnabled,
mainBackend,
backend,
runtimeSubscriptionsDir,
jq,
python3,
parserScriptsPythonPath,
fetchSubscriptionPy,
routingMarkJq,
}:
let
subscriptionBackend = if hybridEnabled then "hybrid" else mainBackend;
subscriptionBackendArg = "--backend ${subscriptionBackend}";
subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/${backend}";
mkSubscriptionUrlSource =
sub:
if sub.urlFile != null then
sub.urlFile
else
pkgs.writeText "proxy-suite-sub-url-${sub.tag}" sub.url;
# Defined in every script that touches a cache: the start scripts and the
# update unit.
subscriptionCacheHelpersBlock = ''
SUB_CACHE_DIR="${subscriptionCacheDir}"
RUNTIME_SUBS_DIR="${runtimeSubscriptionsDir}"
_proxy_suite_valid_subscription_cache() {
[ -s "$1" ] && ${jq} -e ${
lib.escapeShellArg (
if hybridEnabled then
''type == "object" and (.singBox | type == "array") and (.xray | type == "array")''
else
''type == "array"''
)
} "$1" >/dev/null 2>&1
}
_proxy_suite_commit_subscription_cache() {
local tmp="$1" target="$2" tag="$3"
if _proxy_suite_valid_subscription_cache "$tmp"; then
mv "$tmp" "$target"
return 0
fi
rm -f "$tmp"
echo "proxy-suite: warning: subscription '$tag' produced an invalid cache; ignoring it" >&2
return 1
}
_proxy_suite_drop_invalid_subscription_cache() {
local target="$1" tag="$2"
if [ -f "$target" ] && ! _proxy_suite_valid_subscription_cache "$target"; then
rm -f "$target"
echo "proxy-suite: warning: removed invalid subscription cache for '$tag'" >&2
fi
}
# $1 tag, $2 file holding the subscription URL. Writes the cache atomically.
_proxy_suite_fetch_subscription() {
local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json"
mkdir -p "$SUB_CACHE_DIR"
if printf '%s' "$(cat "$src")" \
| PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} \
${subscriptionBackendArg} --tag-prefix "$tag" > "$cache.tmp"; then
_proxy_suite_commit_subscription_cache "$cache.tmp" "$cache" "$tag"
return
fi
rm -f "$cache.tmp"
echo "proxy-suite: failed to update subscription '$tag'" >&2
return 1
}
# Every runtime subscription, as "<tag>\t<url file>" lines.
_proxy_suite_runtime_subscriptions() {
local f tag
[ -d "$RUNTIME_SUBS_DIR" ] || return 0
for f in "$RUNTIME_SUBS_DIR"/*.url; do
[ -e "$f" ] || continue
tag="''${f##*/}"
tag="''${tag%.url}"
printf '%s\t%s\n' "$tag" "$f"
done
}
'';
# Merging a cache into OUTBOUNDS_JSON needs the routing mark, which differs per
# start script, so this one is emitted separately from the cache helpers.
mkSubscriptionLoadHelperBlock =
routingMark:
let
markFilter = routingMarkJq routingMark;
subVar = if hybridEnabled then "SUB_SING_BOX_JSON" else "SUB_JSON";
# Plain string concatenation: "$" next to an interpolation is exactly the
# spot where an indented string's escaping bites.
markBlock = lib.optionalString (routingMark != null) (
subVar + "=$(${jq} 'map(.${markFilter})' <<< \"$" + subVar + "\")\n"
);
mergeBlock =
if hybridEnabled then
''
SUB_SING_BOX_JSON=$(${jq} -c '.singBox' "$cache")
${markBlock}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_SING_BOX_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
while IFS= read -r SUB_XRAY_OB; do
SUB_XRAY_TAG="$(${jq} -r '.tag' <<< "$SUB_XRAY_OB")"
_proxy_suite_add_xray_sidecar_ob "$SUB_XRAY_OB" "$SUB_XRAY_TAG"
done < <(${jq} -c '.xray[]' "$cache")
''
else
''
SUB_JSON=$(cat "$cache")
${markBlock}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
'';
in
''
# $1 tag, $2 file holding the subscription URL. Fetches on a cold cache and
# merges whatever is cached; a subscription that cannot be fetched is a
# warning, never a failed start.
_proxy_suite_load_subscription() {
local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" before after
_proxy_suite_drop_invalid_subscription_cache "$cache" "$tag"
if [ ! -f "$cache" ]; then
_proxy_suite_fetch_subscription "$tag" "$src" \
|| echo "proxy-suite: warning: could not fetch subscription '$tag'" >&2
fi
[ -f "$cache" ] || return 0
before=$(${jq} 'length' <<< "$OUTBOUNDS_JSON")
${mergeBlock}
after=$(${jq} 'length' <<< "$OUTBOUNDS_JSON")
_proxy_suite_record_outbound_source "sub:$tag" "$before" "$after"
}
'';
mkSubscriptionBlock =
sub: _routingMark:
''
# subscription: ${sub.tag}
_proxy_suite_load_subscription ${lib.escapeShellArg sub.tag} ${
lib.escapeShellArg (mkSubscriptionUrlSource sub)
}
'';
runtimeSubscriptionsBlock = ''
# subscriptions added at runtime
while IFS=$'\t' read -r RUNTIME_SUB_TAG RUNTIME_SUB_SRC; do
[ -n "$RUNTIME_SUB_TAG" ] || continue
_proxy_suite_load_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC"
done < <(_proxy_suite_runtime_subscriptions)
'';
mkSubscriptionFetchBlock =
sub:
''
if _proxy_suite_fetch_subscription ${lib.escapeShellArg sub.tag} ${
lib.escapeShellArg (mkSubscriptionUrlSource sub)
}; then
echo "Updated subscription: ${sub.tag}"
else
FAILED=1
fi
'';
runtimeSubscriptionsFetchBlock = ''
while IFS=$'\t' read -r RUNTIME_SUB_TAG RUNTIME_SUB_SRC; do
[ -n "$RUNTIME_SUB_TAG" ] || continue
if _proxy_suite_fetch_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC"; then
echo "Updated subscription: $RUNTIME_SUB_TAG"
else
FAILED=1
fi
done < <(_proxy_suite_runtime_subscriptions)
'';
subscriptionTagsFile = pkgs.writeText "proxy-suite-subscription-tags.json" (
builtins.toJSON (map (sub: sub.tag) proxyCfg.subscriptions)
);
in
{
inherit
subscriptionCacheDir
subscriptionCacheHelpersBlock
mkSubscriptionLoadHelperBlock
mkSubscriptionBlock
runtimeSubscriptionsBlock
mkSubscriptionFetchBlock
runtimeSubscriptionsFetchBlock
subscriptionTagsFile
;
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,338 @@
# Backend startup script derivations.
{
lib,
pkgs,
proxyCfg,
perAppRoutingCfg,
userControlCfg,
globalTproxy,
xrayEnabled,
hybridEnabled,
pureXrayEnabled,
constants,
jq,
singBox,
xray,
backendBin,
routeModeStateFile,
routeModeRulesFile,
xrayLoglevelFile,
runtimeProxychainsConfig,
localProxyAuth,
localProxyAuthEnabled,
localProxyAuthPasswordSource,
backendJqFilterFile,
hybridRuntimeHelpersBlock,
subscriptionCacheHelpersBlock,
mkOutboundScript,
tproxyFile,
tunFile,
perAppTunFile,
}:
let
inherit (constants)
autoProxyStateDir
xrayDnsBridgePorts
xraySidecarBasePorts
;
autoProxyRender = import ../autoproxy-render.nix { inherit pkgs; };
routeModeBlacklistTail =
if pureXrayEnabled then
''
+ .proxyGeo
+ .block
''
else
''
+ .block
+ .proxyGeo
'';
routeModeCaseBlock = ''
if [ -r "$ROUTE_MODE_STATE_FILE" ]; then
ROUTE_MODE="$(tr -d '\r\n[:space:]' < "$ROUTE_MODE_STATE_FILE" 2>/dev/null || true)"
fi
case "$ROUTE_MODE" in
blacklist)
ROUTE_FINAL="proxy"
DNS_FINAL="remote"
ROUTE_MODE_ACTIVE=true
ROUTE_RULES_JSON=$(${jq} -c '
.common
+ (.custom | map(.entries) | add // [])
+ .proxyPrimary
+ .direct
+ .safetyDirect
${routeModeBlacklistTail}
' "${routeModeRulesFile}")
;;
whitelist)
ROUTE_FINAL="direct"
DNS_FINAL="local"
ROUTE_MODE_ACTIVE=true
ROUTE_RULES_JSON=$(${jq} -c '
.common
+ (.custom | map(.entries) | add // [])
+ .proxyPrimary
+ .direct
+ .safetyDirect
${routeModeBlacklistTail}
' "${routeModeRulesFile}")
;;
all-proxy)
ROUTE_FINAL="proxy"
DNS_FINAL="remote"
ROUTE_MODE_ACTIVE=true
CLEAR_DNS_RULES=true
ROUTE_RULES_JSON=$(${jq} -c '
.common
+ (.custom | map(select(.category == "proxy" or .category == "block") | .entries) | add // [])
+ .proxyPrimary
+ .safetyDirect
${routeModeBlacklistTail}
' "${routeModeRulesFile}")
;;
all-bypass)
ROUTE_FINAL="direct"
DNS_FINAL="local"
ROUTE_MODE_ACTIVE=true
CLEAR_DNS_RULES=true
ROUTE_RULES_JSON=$(${jq} -c '
.common
+ (.custom | map(select(.category == "block") | .entries) | add // [])
+ .safetyDirect
+ .block
' "${routeModeRulesFile}")
;;
*)
ROUTE_MODE=""
;;
esac
'';
writeProxychainsConfigBlock = ''
{
printf '%s\n' 'strict_chain'
${lib.optionalString perAppRoutingCfg.proxychains.quiet "printf '%s\\n' 'quiet_mode'"}
${lib.optionalString perAppRoutingCfg.proxychains.proxyDns "printf '%s\\n' 'proxy_dns'"}
printf '%s\n' 'tcp_read_time_out 15000'
printf '%s\n' 'tcp_connect_time_out 8000'
printf '\n%s\n' '[ProxyList]'
printf 'socks5 %s %s %s %s\n' \
${lib.escapeShellArg proxyCfg.listener.address} \
${lib.escapeShellArg (toString proxyCfg.listener.port)} \
${lib.escapeShellArg localProxyAuth.username} \
"$LOCAL_PROXY_PASSWORD"
} > "${runtimeProxychainsConfig}"
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${runtimeProxychainsConfig}"
chmod 640 "${runtimeProxychainsConfig}"
'';
mkStartScript =
{
name,
runtimeDir,
configFile,
routingMark ? null,
enableLocalProxyAuth ? false,
xrayTunEgressBinding ? false,
xrayTunDnsRuntime ? false,
xraySidecarBasePort ? xraySidecarBasePorts.socks,
xrayDnsBridgePort ? xrayDnsBridgePorts.socks,
enableAutoProxy ? false,
}:
pkgs.writeShellScript name ''
set -euo pipefail
RUNTIME_DIR="${runtimeDir}"
ROUTE_MODE_STATE_FILE="${routeModeStateFile}"
BACKEND_JQ_FILTER=${lib.escapeShellArg backendJqFilterFile}
XRAY_LOGLEVEL=""
XRAY_TUN_BIND_INTERFACE=""
XRAY_SINGLE_PROXY_TAG=""
mkdir -p "$RUNTIME_DIR"
OUTBOUNDS_JSON='[]'
ROUTE_MODE=""
ROUTE_FINAL=""
DNS_FINAL=""
ROUTE_RULES_JSON='[]'
ROUTE_MODE_ACTIVE=false
CLEAR_DNS_RULES=false
${hybridRuntimeHelpersBlock routingMark xraySidecarBasePort xrayDnsBridgePort}
${subscriptionCacheHelpersBlock}
${lib.optionalString enableLocalProxyAuth ''
umask 077
LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")"
${writeProxychainsConfigBlock}
''}
${lib.optionalString xrayEnabled ''
if [ -r "${xrayLoglevelFile}" ]; then
XRAY_LOGLEVEL="$(tr -d '\r\n[:space:]' < "${xrayLoglevelFile}" 2>/dev/null || true)"
fi
''}
${lib.optionalString xrayTunEgressBinding ''
XRAY_TUN_BIND_INTERFACE="$(${pkgs.iproute2}/bin/ip -4 route get 1.1.1.1 mark ${toString globalTproxy.proxyMark} 2>/dev/null | ${pkgs.gawk}/bin/awk '
/dev/ {
for (i = 1; i <= NF; i++) {
if ($i == "dev" && i + 1 <= NF) {
print $(i + 1)
exit
}
}
}
')"
if [ -z "$XRAY_TUN_BIND_INTERFACE" ]; then
echo "proxy-suite: could not determine the default uplink interface for XRay TUN" >&2
exit 1
fi
''}
${routeModeCaseBlock}
${mkOutboundScript routingMark}
${lib.optionalString hybridEnabled "_proxy_suite_write_xray_sidecar_config"}
# autoProxy: a loopback listener and a learned rule-set per exit, generated here
# because subscription tags only exist at runtime.
PROBE_INBOUNDS_JSON='[]'
PROBE_PIN_RULES_JSON='[]'
AUTOPROXY_RULE_SETS_JSON='[]'
AUTOPROXY_RULES_JSON='[]'
${lib.optionalString enableAutoProxy ''
AUTOPROXY_DIR=${lib.escapeShellArg autoProxyStateDir}
install -d -m 0750 "$AUTOPROXY_DIR"
[ -s "$AUTOPROXY_DIR/state.json" ] || echo '{"domains":{},"hosts":{},"exits":{},"backlog":{}}' > "$AUTOPROXY_DIR/state.json"
# direct is always exit 0; state is keyed by tag, so shifting indices are
# harmless.
PROBE_EXITS_JSON=$(${jq} -c \
--argjson max ${toString proxyCfg.autoProxy.maxExits} \
--argjson base ${toString proxyCfg.autoProxy.probeBasePort} \
--arg dir "$AUTOPROXY_DIR" '
(["direct"] + map(select(. != "direct")))[0:$max]
| to_entries
| map({i: .key, tag: .value, port: ($base + .key),
rule_set: ("autoproxy-" + (.key | tostring)),
path: ($dir + "/rs-" + (.key | tostring) + ".json")})
' <<< "$EXIT_TAGS_JSON")
printf '%s\n' "$PROBE_EXITS_JSON" > "$RUNTIME_DIR/probe-exits.json"
# proxy-ctl reads it unprivileged; it holds tags and loopback ports only.
chmod 644 "$RUNTIME_DIR/probe-exits.json"
${autoProxyRender} "$RUNTIME_DIR/probe-exits.json" "$AUTOPROXY_DIR/state.json"
PROBE_INBOUNDS_JSON=$(${jq} -c 'map({type: "mixed", tag: ("probe-in-" + (.i | tostring)),
listen: "127.0.0.1", listen_port: .port})' <<< "$PROBE_EXITS_JSON")
PROBE_PIN_RULES_JSON=$(${jq} -c 'map({inbound: ["probe-in-" + (.i | tostring)],
outbound: .tag})' <<< "$PROBE_EXITS_JSON")
AUTOPROXY_RULE_SETS_JSON=$(${jq} -c 'map({type: "local", format: "source",
tag: .rule_set, path: .path})' <<< "$PROBE_EXITS_JSON")
# all-bypass means everything direct; learned exits must not override it.
if [ "$ROUTE_MODE" != all-bypass ]; then
AUTOPROXY_RULES_JSON=$(${jq} -c 'map({rule_set: [.rule_set], outbound: .tag})' <<< "$PROBE_EXITS_JSON")
fi
''}
${jq} \
--argjson obs "$OUTBOUNDS_JSON" \
--argjson probe_inbounds "$PROBE_INBOUNDS_JSON" \
--argjson probe_pin_rules "$PROBE_PIN_RULES_JSON" \
--argjson autoproxy_rule_sets "$AUTOPROXY_RULE_SETS_JSON" \
--argjson autoproxy_rules "$AUTOPROXY_RULES_JSON" \
--argjson auth_enabled ${if enableLocalProxyAuth then "true" else "false"} \
--arg user ${if enableLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \
--arg password ${if enableLocalProxyAuth then "\"$LOCAL_PROXY_PASSWORD\"" else "''"} \
--argjson route_enabled "$ROUTE_MODE_ACTIVE" \
--argjson route_rules "$ROUTE_RULES_JSON" \
--arg route_final "$ROUTE_FINAL" \
--arg dns_final "$DNS_FINAL" \
--argjson clear_dns_rules "$CLEAR_DNS_RULES" \
--arg xray_loglevel "$XRAY_LOGLEVEL" \
--arg xray_bind_interface "$XRAY_TUN_BIND_INTERFACE" \
--arg xray_single_proxy_tag "$XRAY_SINGLE_PROXY_TAG" \
--argjson xray_tun_dns_runtime ${if xrayTunDnsRuntime then "true" else "false"} \
--arg xray_dns_local_client ${lib.escapeShellArg proxyCfg.dns.local.address} \
--arg xray_dns_remote_client ${lib.escapeShellArg proxyCfg.dns.remote.address} \
-f "$BACKEND_JQ_FILTER" \
"${configFile}" > "$RUNTIME_DIR/config.json"
${lib.optionalString enableLocalProxyAuth ''
chmod 600 "$RUNTIME_DIR/config.json"
''}
${
if hybridEnabled then
''
if [ -s "$RUNTIME_DIR/xray-sidecar.json" ]; then
XRAY_SIDECAR_PID=""
_proxy_suite_cleanup_xray_sidecar() {
if [ -n "$XRAY_SIDECAR_PID" ]; then
kill "$XRAY_SIDECAR_PID" 2>/dev/null || true
wait "$XRAY_SIDECAR_PID" 2>/dev/null || true
fi
}
trap _proxy_suite_cleanup_xray_sidecar EXIT
trap 'exit 143' INT TERM
${xray} run -c "$RUNTIME_DIR/xray-sidecar.json" &
XRAY_SIDECAR_PID="$!"
${pkgs.coreutils}/bin/sleep 0.2
if ! kill -0 "$XRAY_SIDECAR_PID" 2>/dev/null; then
XRAY_SIDECAR_STATUS=1
wait "$XRAY_SIDECAR_PID" || XRAY_SIDECAR_STATUS="$?"
exit "$XRAY_SIDECAR_STATUS"
fi
${singBox} run -c "$RUNTIME_DIR/config.json" &
SING_BOX_PID="$!"
SING_BOX_STATUS=0
wait "$SING_BOX_PID" || SING_BOX_STATUS="$?"
exit "$SING_BOX_STATUS"
fi
exec ${singBox} run -c "$RUNTIME_DIR/config.json"
''
else
''
exec ${backendBin} run -c "$RUNTIME_DIR/config.json"
''
}
'';
startSocks = mkStartScript {
name = "proxy-suite-start-socks";
runtimeDir = "/run/proxy-suite-socks";
configFile = tproxyFile;
routingMark = globalTproxy.proxyMark;
enableLocalProxyAuth = localProxyAuthEnabled;
xraySidecarBasePort = xraySidecarBasePorts.socks;
xrayDnsBridgePort = xrayDnsBridgePorts.socks;
# Only the socks unit: relayed traffic reaches it, and the prober needs one home.
enableAutoProxy = proxyCfg.autoProxy.enable && !pureXrayEnabled;
};
startTun = mkStartScript {
name = "proxy-suite-start-tun";
runtimeDir = "/run/proxy-suite-tun";
configFile = tunFile;
routingMark = if pureXrayEnabled then globalTproxy.proxyMark else null;
xrayTunEgressBinding = xrayEnabled;
xrayTunDnsRuntime = pureXrayEnabled;
xraySidecarBasePort = xraySidecarBasePorts.tun;
xrayDnsBridgePort = xrayDnsBridgePorts.tun;
};
startPerAppTun = mkStartScript {
name = "proxy-suite-start-per-app-tun";
runtimeDir = "/run/proxy-suite-per-app-tun";
configFile = perAppTunFile;
routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null;
xrayTunEgressBinding = xrayEnabled;
xrayTunDnsRuntime = pureXrayEnabled;
xraySidecarBasePort = xraySidecarBasePorts.perAppTun;
xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun;
};
in
{
inherit startSocks startTun startPerAppTun;
}
+320
View File
@@ -0,0 +1,320 @@
# Systemd unit definitions for proxy-suite services and timers.
{
lib,
builders,
proxyCfg,
proxyEnabled,
hybridEnabled,
pureXrayEnabled,
globalTun,
globalTproxy,
perAppRoutingTun,
perAppRoutingTproxy,
perAppZapretEnabled,
sshProxyOutboundEnabled,
sshProxyUnitEnabled,
proxyInboundsEnabled,
proxyInboundsNeedLocalProxy,
scripts,
perAppRouting,
routingScripts,
geodata,
}:
let
inherit (builders)
mkAnchorService
mkRestartingService
mkOneshotService
mkUserRuleService
;
inherit (routingScripts)
xrayTunUpScript
tproxyUpScript
tproxyDownScript
tunCleanupScript
;
serviceNames = {
socks = "proxy-suite-socks";
tproxy = "proxy-suite-tproxy";
tun = "proxy-suite-tun";
perAppTun = "proxy-suite-per-app-tun";
perAppTproxy = "proxy-suite-per-app-tproxy";
perAppZapret = "proxy-suite-per-app-zapret";
subscriptionUpdate = "proxy-suite-subscription-update";
inbounds = "proxy-suite-inbounds";
inboundStats = "proxy-suite-inbound-stats";
};
backendDescription =
if pureXrayEnabled then
"XRay"
else if hybridEnabled then
"sing-box + XRay sidecar"
else
"sing-box";
localProxyAuthEnabled =
proxyCfg.listener.auth.username != null
&& (proxyCfg.listener.auth.password != null || proxyCfg.listener.auth.passwordFile != null);
# XRay finds geoip.dat/geosite.dat through this; sing-box ignores it.
xrayAssetEnv = lib.optionalAttrs (geodata.xray.assets != null) {
Environment = [ "XRAY_LOCATION_ASSET=${geodata.xray.assets}/share/v2ray" ];
};
systemServiceEntries = [
{
enable = proxyEnabled;
name = serviceNames.socks;
value = mkRestartingService {
description = "${backendDescription} proxy client (SOCKS + TProxy-ready)";
# Only XRay goes through the OpenSSH unit's listener.
after = [
"network-online.target"
]
++ lib.optional (sshProxyOutboundEnabled && sshProxyUnitEnabled) "proxy-suite-ssh-proxy.service";
wants = [
"network-online.target"
]
++ lib.optional (sshProxyOutboundEnabled && sshProxyUnitEnabled) "proxy-suite-ssh-proxy.service";
wantedBy = [ "multi-user.target" ];
execStart = scripts.startSocks;
runtimeDirectory = serviceNames.socks;
stateDirectory = "proxy-suite";
extraServiceConfig = xrayAssetEnv;
};
}
{
enable = proxyInboundsEnabled;
name = serviceNames.inbounds;
value = mkRestartingService {
description = "XRay server inbounds (accept connections from outside)";
after = [
"network-online.target"
]
# After the client stack, but not `requires`: direct listeners keep serving
# without it.
++ lib.optional proxyInboundsNeedLocalProxy "${serviceNames.socks}.service";
wants = [
"network-online.target"
]
++ lib.optional proxyInboundsNeedLocalProxy "${serviceNames.socks}.service";
wantedBy = [ "multi-user.target" ];
execStart = scripts.startInbounds;
runtimeDirectory = serviceNames.inbounds;
extraServiceConfig = xrayAssetEnv;
};
}
{
enable = proxyInboundsEnabled;
name = serviceNames.inboundStats;
value = mkOneshotService {
description = "proxy-suite - add up per-user traffic through the inbounds";
after = [ "${serviceNames.inbounds}.service" ];
execStart = scripts.collectInboundStats;
stateDirectory = "proxy-suite";
# Run by a timer: a unit left "active" would never be started again.
extraServiceConfig.RemainAfterExit = false;
};
}
{
enable = proxyEnabled && globalTproxy.enable;
name = serviceNames.tproxy;
value = mkOneshotService {
description = "proxy-suite TProxy - nftables rules and policy routing";
after = [
"network.target"
"${serviceNames.socks}.service"
];
wantedBy = lib.optionals (proxyCfg.autostart == "tproxy") [ "multi-user.target" ];
requires = [ "${serviceNames.socks}.service" ];
conflicts = [
"${serviceNames.tun}.service"
"${serviceNames.perAppTproxy}.service"
];
execStart = tproxyUpScript;
execStop = tproxyDownScript;
};
}
{
enable = proxyEnabled && globalTun.enable;
name = serviceNames.tun;
value = mkRestartingService {
description = "${backendDescription} TUN proxy client";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = lib.optionals (proxyCfg.autostart == "tun") [ "multi-user.target" ];
conflicts = [ "${serviceNames.tproxy}.service" ];
execStartPre = tunCleanupScript;
execStart = scripts.startTun;
execStartPost = if pureXrayEnabled then xrayTunUpScript else null;
execStopPost = tunCleanupScript;
runtimeDirectory = serviceNames.tun;
stateDirectory = "proxy-suite";
};
}
{
enable = proxyEnabled && perAppRoutingTun.enable;
name = serviceNames.perAppTun;
value = mkRestartingService {
description = "proxy-suite per-app-routing TUN backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
execStartPre = perAppRouting.perAppTunDownScript;
execStart = scripts.startPerAppTun;
execStartPost = perAppRouting.perAppTunUpScript;
execStopPost = perAppRouting.perAppTunDownScript;
runtimeDirectory = serviceNames.perAppTun;
stateDirectory = "proxy-suite";
};
}
{
enable = proxyEnabled && perAppRoutingTun.enable;
name = "${serviceNames.perAppTun}-user@";
value = mkUserRuleService {
description = "Enable proxy-suite app TUN marking for user %i";
backendService = serviceNames.perAppTun;
execStart = "${perAppRouting.perAppTunUserRuleStart} %i";
execStop = "${perAppRouting.perAppTunUserRuleStop} %i";
};
}
{
enable = proxyEnabled && perAppRoutingTproxy.enable;
name = serviceNames.perAppTproxy;
value = mkOneshotService {
description = "proxy-suite per-app-routing TProxy backend";
after = [
"network.target"
"${serviceNames.socks}.service"
];
requires = [ "${serviceNames.socks}.service" ];
conflicts = [
"${serviceNames.tproxy}.service"
"${serviceNames.tun}.service"
];
execStart = perAppRouting.perAppTproxyUpScript;
execStop = perAppRouting.perAppTproxyDownScript;
};
}
{
enable = proxyEnabled && perAppRoutingTproxy.enable;
name = "${serviceNames.perAppTproxy}-user@";
value = mkUserRuleService {
description = "Enable proxy-suite app TProxy marking for user %i";
backendService = serviceNames.perAppTproxy;
execStart = "${perAppRouting.perAppTproxyUserRuleStart} %i";
execStop = "${perAppRouting.perAppTproxyUserRuleStop} %i";
};
}
{
enable = perAppZapretEnabled;
name = "${serviceNames.perAppZapret}-user@";
value = mkUserRuleService {
description = "Enable proxy-suite app zapret marking for user %i";
backendService = serviceNames.perAppZapret;
execStart = "${perAppRouting.perAppZapretUserRuleStart} %i";
execStop = "${perAppRouting.perAppZapretUserRuleStop} %i";
};
}
{
# Not gated on hasSubscriptions: runtime subscriptions need refreshing too.
enable = proxyEnabled;
name = serviceNames.subscriptionUpdate;
value = mkOneshotService {
description = "Refresh proxy-suite subscription caches";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
execStart = scripts.subscriptionUpdateScript;
stateDirectory = "proxy-suite";
};
}
{
enable = proxyEnabled;
name = "proxy-suite-route-mode@";
value = mkOneshotService {
description = "Set proxy-suite route mode to %i";
execStart = "${scripts.setRouteModeScript} %i";
extraServiceConfig.RemainAfterExit = false;
};
}
{
enable = proxyEnabled;
name = "proxy-suite-outbound-select@";
value = mkOneshotService {
description = "Pin the proxy-suite priority outbound to %i";
execStart = "${scripts.setPriorityOutboundScript} %i";
stateDirectory = "proxy-suite";
extraServiceConfig.RemainAfterExit = false;
};
}
{
enable = proxyEnabled;
name = "proxy-suite-outbound-reload";
value = mkOneshotService {
description = "Apply proxy-suite outbounds and subscriptions added at runtime";
execStart = scripts.reloadOutboundsScript;
stateDirectory = "proxy-suite";
extraServiceConfig.RemainAfterExit = false;
};
}
];
userServiceEntries = [
{
enable = perAppRoutingTun.enable;
name = "${serviceNames.perAppTun}-anchor";
value = mkAnchorService perAppRouting.perAppTunSliceName "Anchor service for proxy-suite app TUN slice";
}
{
enable = perAppRoutingTproxy.enable;
name = "${serviceNames.perAppTproxy}-anchor";
value = mkAnchorService perAppRouting.perAppTproxySliceName "Anchor service for proxy-suite app TProxy slice";
}
{
enable = perAppZapretEnabled;
name = "${serviceNames.perAppZapret}-anchor";
value = mkAnchorService perAppRouting.perAppZapretSliceName "Anchor service for proxy-suite app zapret slice";
}
];
timerEntries = [
{
enable = proxyEnabled;
name = serviceNames.subscriptionUpdate;
value = {
description = "Periodic proxy-suite subscription refresh";
wantedBy = [ "timers.target" ];
timerConfig = {
# OnActiveSec, not OnBootSec: see the autoProxy timer.
OnActiveSec = "5m";
OnUnitActiveSec = proxyCfg.subscriptionUpdateInterval;
};
};
}
{
enable = proxyInboundsEnabled;
name = serviceNames.inboundStats;
value = {
description = "proxy-suite per-user inbound traffic collection";
wantedBy = [ "timers.target" ];
timerConfig = {
# OnActiveSec, not OnBootSec: see the autoProxy timer.
OnActiveSec = "5m";
OnUnitActiveSec = "5m";
};
};
}
];
in
{
inherit
serviceNames
localProxyAuthEnabled
systemServiceEntries
userServiceEntries
timerEntries
;
}
+56
View File
@@ -0,0 +1,56 @@
# Native OpenSSH dynamic SOCKS5 proxy service.
{
lib,
pkgs,
cfg,
}:
let
s = cfg.sshProxy;
destination = if s.server.user == null then s.server.host else "${s.server.user}@${s.server.host}";
extraArgs = lib.concatMapStrings (arg: " args+=(${lib.escapeShellArg arg})\n") s.extraArgs;
startScript = pkgs.writeShellScript "proxy-suite-ssh-proxy-start" ''
set -euo pipefail
args=(
-N
-o BatchMode=yes
-o ExitOnForwardFailure=yes
-o ServerAliveInterval=15
-o ServerAliveCountMax=3
-o ConnectTimeout=10
-o StrictHostKeyChecking=${lib.escapeShellArg s.strictHostKeyChecking}
-D ${lib.escapeShellArg "${s.listener.address}:${toString s.listener.port}"}
)
${lib.optionalString (s.server.port != 22) "args+=(-p ${toString s.server.port})"}
${lib.optionalString (s.identityFile != null) "args+=(-i ${lib.escapeShellArg s.identityFile})"}
${lib.optionalString (
s.knownHostsFile != null
) "args+=(-o ${lib.escapeShellArg "UserKnownHostsFile=${s.knownHostsFile}"})"}
${extraArgs}
exec ${pkgs.openssh}/bin/ssh "''${args[@]}" ${lib.escapeShellArg destination}
'';
in
{
systemd.services.proxy-suite-ssh-proxy = {
description = "SSH dynamic SOCKS5 proxy";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
# Restart=always plus a server that refuses connections would otherwise hit
# the default 5-starts-in-10s limit and stay failed.
startLimitIntervalSec = 0;
serviceConfig = {
ExecStart = startScript;
# `ssh -N` exits 0 when the server closes the connection cleanly, which
# under on-failure left the tunnel down for good.
Restart = "always";
RestartSec = 5;
# One fd per forwarded channel; the 1024 default is low for a relay.
LimitNOFILE = 65536;
}
// lib.optionalAttrs (s.serviceUser != null) {
User = s.serviceUser;
};
};
}
+15 -15
View File
@@ -27,8 +27,8 @@ let
);
startScript = pkgs.writeShellScript "proxy-suite-tg-ws-proxy-start" ''
args=(
--port=${toString t.port}
--host=${lib.escapeShellArg t.host}
--port=${toString t.listener.port}
--host=${lib.escapeShellArg t.listener.address}
)
${
if t.secretFile != null then
@@ -36,15 +36,15 @@ let
else
"args+=(--secret=${lib.escapeShellArg t.secret})"
}
${dcArgs}${mkFlagArg t.verbose "--verbose"}${
mkOptionalValueArg (t.logFile != null) "--log-file" t.logFile
}${lib.optionalString (t.logFile != null) (mkRawValueArg "--log-max-mb" t.logMaxMb)}${
lib.optionalString (t.logFile != null) (mkRawValueArg "--log-backups" t.logBackups)
}${mkRawValueArg "--buf-kb" t.bufKb}${mkRawValueArg "--pool-size" t.poolSize}${mkRepeatedValueArgs "--cfproxy-domain" t.cfProxyDomains}${mkRepeatedValueArgs "--cfproxy-worker-domain" t.cfProxyWorkerDomains}${
mkFlagArg (!t.cfProxyFallback) "--no-cfproxy"
${dcArgs}${mkFlagArg t.log.verbose "--verbose"}${
mkOptionalValueArg (t.log.file != null) "--log-file" t.log.file
}${lib.optionalString (t.log.file != null) (mkRawValueArg "--log-max-mb" t.log.maxSizeMiB)}${
lib.optionalString (t.log.file != null) (mkRawValueArg "--log-backups" t.log.keep)
}${mkRawValueArg "--buf-kb" t.bufferKiB}${mkRawValueArg "--pool-size" t.poolSize}${mkRepeatedValueArgs "--cfproxy-domain" t.cloudflare.domains}${mkRepeatedValueArgs "--cfproxy-worker-domain" t.cloudflare.workerDomains}${
mkFlagArg (!t.cloudflare.fallback) "--no-cfproxy"
}${
mkOptionalValueArg (t.fakeTlsDomain != null) "--fake-tls-domain" t.fakeTlsDomain
}${mkFlagArg t.proxyProtocol "--proxy-protocol"}${mkRawValueArg "--ws-keepalive" t.wsKeepalive}
}${mkFlagArg t.proxyProtocol "--proxy-protocol"}
exec ${tgPkg}/bin/tg-ws-proxy "''${args[@]}"
'';
@@ -53,8 +53,8 @@ let
add_bypass_rule() {
local family="$1"
while ${ip} "$family" rule del pref ${toString bypassRulePriority} fwmark ${toString t.routingMark} lookup main 2>/dev/null; do :; done
${ip} "$family" rule add pref ${toString bypassRulePriority} fwmark ${toString t.routingMark} lookup main 2>/dev/null || true
while ${ip} "$family" rule del pref ${toString bypassRulePriority} fwmark ${toString t.fwmark} lookup main 2>/dev/null; do :; done
${ip} "$family" rule add pref ${toString bypassRulePriority} fwmark ${toString t.fwmark} lookup main 2>/dev/null || true
}
add_bypass_rule -4
@@ -64,8 +64,8 @@ let
bypassDownScript = pkgs.writeShellScript "proxy-suite-tg-ws-proxy-bypass-down" ''
set +e
while ${ip} -4 rule del pref ${toString bypassRulePriority} fwmark ${toString t.routingMark} lookup main 2>/dev/null; do :; done
while ${ip} -6 rule del pref ${toString bypassRulePriority} fwmark ${toString t.routingMark} lookup main 2>/dev/null; do :; done
while ${ip} -4 rule del pref ${toString bypassRulePriority} fwmark ${toString t.fwmark} lookup main 2>/dev/null; do :; done
while ${ip} -6 rule del pref ${toString bypassRulePriority} fwmark ${toString t.fwmark} lookup main 2>/dev/null; do :; done
'';
in
{
@@ -75,7 +75,7 @@ in
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
serviceConfig = {
ExecStart = "${startScript}";
ExecStart = startScript;
LoadCredential = lib.optional (t.secretFile != null) "tg_ws_proxy_secret:${t.secretFile}";
Restart = "on-failure";
RestartSec = 5;
@@ -83,7 +83,7 @@ in
// lib.optionalAttrs transparentBypassEnabled {
ExecStartPre = bypassUpScript;
ExecStopPost = bypassDownScript;
SocketMark = toString t.routingMark;
SocketMark = toString t.fwmark;
};
};
}
@@ -0,0 +1,111 @@
{
lib,
zapret,
}:
let
trim = lib.strings.trim;
hasPrefix = lib.strings.hasPrefix;
splitString = lib.strings.splitString;
zapretSrc = if builtins.isAttrs zapret && zapret ? outPath then zapret.outPath else zapret;
parseListFile =
path:
lib.unique (
builtins.filter (line: line != "" && !(hasPrefix "#" line)) (
map trim (splitString "\n" (builtins.replaceStrings [ "\r" ] [ "" ] (builtins.readFile path)))
)
);
upstreamHostlist = file: parseListFile "${zapretSrc}/hostlists/${file}";
generalDomains = upstreamHostlist "list-general.txt";
domainGroups = {
general = generalDomains;
google = upstreamHostlist "list-google.txt";
discord = generalDomains;
youtube = upstreamHostlist "list-google.txt";
instagram = upstreamHostlist "list-instagram.txt";
soundcloud = upstreamHostlist "list-soundcloud.txt";
twitter = upstreamHostlist "list-twitter.txt";
};
groupPresets = {
general = "general";
google = "google";
discord = "general";
youtube = "google";
instagram = "instagram";
soundcloud = "soundcloud";
twitter = "twitter";
};
ipGroups = {
all = upstreamHostlist "ipset-all.txt";
};
protocolGroups = {
general = [ "discord-voice" ];
discord = [ "discord-voice" ];
};
expandDefaultDomains =
groups:
lib.unique (
lib.concatMap (group: domainGroups.${group}) groups
);
expandDefaultIps =
groups:
lib.unique (
lib.concatMap (group: ipGroups.${group}) groups
);
inferPresets =
groups:
lib.unique (map (group: groupPresets.${group}) groups);
effectiveRuleDomains =
rule:
lib.unique (expandDefaultDomains rule.defaultDomains ++ rule.domains);
effectiveRuleIps =
rule:
lib.unique (expandDefaultIps rule.defaultIps ++ rule.ips);
effectiveRulePresets =
rule:
if rule.preset != null then [ rule.preset ] else inferPresets rule.defaultDomains;
effectiveRuleIpsetFamilies =
rule:
lib.optional (effectiveRuleIps rule != [ ]) "all";
effectiveRuleProtocolFamilies =
rule:
lib.optionals (rule.configName != null) (
lib.unique (
lib.concatMap (
group:
if builtins.hasAttr group protocolGroups then protocolGroups.${group} else [ ]
) rule.defaultDomains
)
);
in
{
inherit
domainGroups
groupPresets
ipGroups
protocolGroups
expandDefaultDomains
expandDefaultIps
inferPresets
effectiveRuleDomains
effectiveRuleIps
effectiveRulePresets
effectiveRuleIpsetFamilies
effectiveRuleProtocolFamilies
;
}
+23 -274
View File
@@ -1,4 +1,4 @@
# zapret DPI bypass configuration + optional CIDR exemption from NFQUEUE
# zapret DPI bypass services and optional CIDR exemption from NFQUEUE.
{
lib,
pkgs,
@@ -13,258 +13,26 @@ let
inherit (builders) mkOneshotService;
zapretCfg = cfg.zapret;
perAppZapretCfg = zapretCfg.perApp;
iptables = "${pkgs.iptables}/bin/iptables";
runtimeDeps = lib.attrValues {
inherit (pkgs)
iptables
ipset
nftables
coreutils
gawk
curl
wget
bash
kmod
findutils
gnused
gnugrep
procps
util-linux
perAppZapretCfg = cfg.perAppRouting.zapret;
awgServiceNames = map (name: "proxy-suite-awg-${name}.service") (
builtins.attrNames cfg.amneziaWg.profiles
);
zapretPackages = import ./zapret/packages.nix {
inherit
lib
pkgs
cfg
zapret
;
};
inherit (zapretPackages)
globalZapretPackage
perAppZapretPackage
globalZapretEnv
perAppZapretEnv
;
hostlistRuleNames = map (rule: rule.name) zapretCfg.hostlistRules;
baseZapretPackage =
let
upstreamPackages = zapret.packages.${pkgs.stdenv.hostPlatform.system};
in
if upstreamPackages ? zapret then upstreamPackages.zapret else upstreamPackages.default;
mkOptionalHostlistFile =
fileName: entries:
if entries != [ ] then pkgs.writeText fileName (lib.concatStringsSep "\n" entries + "\n") else null;
listGeneralFile = mkOptionalHostlistFile "proxy-suite-zapret-list-general-user.txt" zapretCfg.listGeneral;
listExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-list-exclude-user.txt" zapretCfg.listExclude;
ipsetAllFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-all.txt" zapretCfg.ipsetAll;
ipsetExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-exclude-user.txt" zapretCfg.ipsetExclude;
hostlistRuleSpec = pkgs.writeText "proxy-suite-zapret-hostlist-rules.json" (
builtins.toJSON {
includeExtraUpstreamLists = zapretCfg.includeExtraUpstreamLists;
entries = map (rule: {
inherit (rule)
name
preset
nfqwsArgs
;
}) zapretCfg.hostlistRules;
}
);
selectedConfigName = lib.strings.sanitizeDerivationName zapretCfg.configName;
patchConfigScriptSrc = builtins.path {
path = ../../scripts/patch-zapret-config.py;
name = "patch-zapret-config.py";
};
patchConfigScript = "${pkgs.python3}/bin/python3 ${patchConfigScriptSrc}";
mkGlobalBypassScript =
filterMark:
pkgs.writeText "proxy-suite-zapret-global-bypass.sh" ''
zapret_custom_firewall_nft() {
nft insert rule inet $ZAPRET_NFT_TABLE postrouting mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass"
nft insert rule inet $ZAPRET_NFT_TABLE postnat mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass"
nft insert rule inet $ZAPRET_NFT_TABLE prerouting mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass"
nft insert rule inet $ZAPRET_NFT_TABLE prenat mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass"
}
'';
mkDerivedZapretPackage =
{
packageName,
pidDir,
configName ? zapretCfg.configName,
gameFilter ? zapretCfg.gameFilter,
forceDisableFilterMark ? false,
filterMark ? null,
qnum ? null,
modeFilter ? null,
desyncMark ? null,
desyncMarkPostnat ? null,
nftTable ? null,
customScript ? null,
}:
pkgs.runCommand packageName
{
nativeBuildInputs = with pkgs; [
coreutils
gnused
python3
];
}
''
set -euo pipefail
mkdir -p "$out"
cp -a ${baseZapretPackage}/. "$out/"
chmod -R u+w "$out/opt/zapret" "$out/bin"
find "$out/opt/zapret/configs" -type f -exec ${pkgs.gnused}/bin/sed -i \
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
{} \;
find "$out/opt/zapret/hostlists" -type f -exec ${pkgs.gnused}/bin/sed -i \
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
{} \;
if [ -f "$out/opt/zapret/configs/${configName}" ]; then
cp "$out/opt/zapret/configs/${configName}" "$out/opt/zapret/config"
else
echo "proxy-suite: zapret config '${configName}' not found in curated package" >&2
ls -la "$out/opt/zapret/configs" >&2 || true
exit 1
fi
${pkgs.gnused}/bin/sed -i \
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
"$out/opt/zapret/config"
${pkgs.gnused}/bin/sed -i \
-e 's|^PIDDIR=.*$|PIDDIR=${pidDir}|' \
"$out/opt/zapret/init.d/sysv/functions"
append_list_file() {
local target="$1"
local extra_file="$2"
local tmp="$out/opt/zapret/hostlists/$target.tmp"
cat "$out/opt/zapret/hostlists/$target" > "$tmp"
${pkgs.gnused}/bin/sed -i -e '$a\' "$tmp"
cat "$extra_file" >> "$tmp"
mv "$tmp" "$out/opt/zapret/hostlists/$target"
}
set_config_var() {
local key="$1"
local value="$2"
if grep -Eq "^[#[:space:]]*$key=" "$out/opt/zapret/config"; then
${pkgs.gnused}/bin/sed -Ei "s|^[#[:space:]]*$key=.*$|$key=$value|" "$out/opt/zapret/config"
else
printf '\n%s=%s\n' "$key" "$value" >> "$out/opt/zapret/config"
fi
}
${lib.concatMapStrings
(
{ name, file }:
lib.optionalString (file != null) ''
append_list_file ${name} ${file}
''
)
[
{
name = "list-general-user.txt";
file = listGeneralFile;
}
{
name = "list-exclude-user.txt";
file = listExcludeFile;
}
{
name = "ipset-all.txt";
file = ipsetAllFile;
}
{
name = "ipset-exclude-user.txt";
file = ipsetExcludeFile;
}
]
}
rm -f "$out/opt/zapret/hostlists/.game_filter.enabled"
${lib.optionalString (gameFilter != "null") ''
echo "${gameFilter}" > "$out/opt/zapret/hostlists/.game_filter.enabled"
''}
${lib.concatMapStrings (
rule:
let
domainsFile = pkgs.writeText "proxy-suite-zapret-hostlist-${rule.name}.txt" (
lib.concatStringsSep "\n" (lib.unique rule.domains) + "\n"
);
in
''
cp ${domainsFile} "$out/opt/zapret/hostlists/list-${rule.name}.txt"
''
) zapretCfg.hostlistRules}
${patchConfigScript} --config "$out/opt/zapret/config" --spec ${hostlistRuleSpec}
${lib.optionalString forceDisableFilterMark ''
set_config_var FILTER_MARK ""
''}
${lib.concatMapStrings
(
{ var, value }:
lib.optionalString (value != null) ''
hex=$(printf '0x%x' ${toString value})
set_config_var ${var} "$hex"
''
)
[
{
var = "FILTER_MARK";
value = filterMark;
}
{
var = "DESYNC_MARK";
value = desyncMark;
}
{
var = "DESYNC_MARK_POSTNAT";
value = desyncMarkPostnat;
}
]
}
${lib.optionalString (qnum != null) ''
set_config_var QNUM ${toString qnum}
''}
${lib.optionalString (modeFilter != null) ''
set_config_var MODE_FILTER ${modeFilter}
''}
${lib.optionalString (nftTable != null) ''
set_config_var ZAPRET_NFT_TABLE ${nftTable}
''}
${lib.optionalString (customScript != null) ''
mkdir -p "$out/opt/zapret/init.d/sysv/custom.d"
cp ${customScript} "$out/opt/zapret/init.d/sysv/custom.d/50-proxy-suite-custom.sh"
chmod +x "$out/opt/zapret/init.d/sysv/custom.d/50-proxy-suite-custom.sh"
''}
'';
globalZapretPackage = mkDerivedZapretPackage {
packageName = "proxy-suite-zapret-${selectedConfigName}";
pidDir = "/run/proxy-suite-zapret";
gameFilter = zapretCfg.gameFilter;
forceDisableFilterMark = true;
customScript =
if perAppZapretCfg.enable then mkGlobalBypassScript (toString perAppZapretCfg.filterMark) else null;
};
perAppZapretPackage = mkDerivedZapretPackage {
packageName = "proxy-suite-per-app-zapret-${selectedConfigName}";
pidDir = "/run/proxy-suite-per-app-zapret";
gameFilter = "all";
filterMark = perAppZapretCfg.filterMark;
qnum = perAppZapretCfg.qnum;
modeFilter = "none";
desyncMark = 134217728;
desyncMarkPostnat = 67108864;
nftTable = "proxy_suite_per_app_zapret";
};
iptables = "${pkgs.iptables}/bin/iptables";
zapretCommonPreStart = package: ''
${package}/opt/zapret/init.d/sysv/zapret stop || true
@@ -278,13 +46,6 @@ let
fi
'';
mkZapretEnv = package: [
"ZAPRET_BASE=${package}/opt/zapret"
"PATH=${lib.makeBinPath runtimeDeps}"
];
globalZapretEnv = mkZapretEnv globalZapretPackage;
perAppZapretEnv = mkZapretEnv perAppZapretPackage;
perAppZapretMarkUpScript = pkgs.writeShellScript "proxy-suite-per-app-zapret-mark-up" ''
set -euo pipefail
${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true
@@ -315,22 +76,7 @@ let
'') zapretCfg.cidrExemption.cidrs;
in
{
assertions = [
{
assertion = builtins.length hostlistRuleNames == builtins.length (lib.unique hostlistRuleNames);
message = "proxy-suite: zapret.hostlistRules names must be unique";
}
{
assertion = builtins.all (rule: rule.domains != [ ]) zapretCfg.hostlistRules;
message = "proxy-suite: each zapret.hostlistRules entry must define at least one domain";
}
{
assertion = builtins.all (
rule: rule.preset != null || rule.nfqwsArgs != [ ]
) zapretCfg.hostlistRules;
message = "proxy-suite: each zapret.hostlistRules entry must set preset, nfqwsArgs, or both";
}
];
assertions = zapretPackages.assertions;
environment.systemPackages = lib.mkBefore (
lib.optionals zapretCfg.enable [ globalZapretPackage ]
@@ -341,6 +87,7 @@ in
description = "zapret DPI bypass";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = awgServiceNames;
wantedBy = [ "multi-user.target" ];
preStart = zapretCommonPreStart globalZapretPackage;
runtimeDirectory = "proxy-suite-zapret";
@@ -359,7 +106,8 @@ in
conflicts = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
];
]
++ awgServiceNames;
preStart = zapretCommonPreStart perAppZapretPackage;
runtimeDirectory = "proxy-suite-per-app-zapret";
execStart = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret start";
@@ -375,6 +123,7 @@ in
description = "Exempt CIDRs from zapret NFQUEUE";
after = [ "zapret-discord-youtube.service" ];
wants = [ "zapret-discord-youtube.service" ];
conflicts = awgServiceNames;
wantedBy = [ "multi-user.target" ];
execStart = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-start" exemptStart;
execStop = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-stop" exemptStop;
@@ -0,0 +1,273 @@
# Builds derived zapret packages from the curated upstream package.
{
lib,
pkgs,
zapretCfg,
baseZapretPackage,
effectiveHostlistRules,
listGeneralFile,
listExcludeFile,
ipsetAllFile,
ipsetExcludeFile,
hostlistRuleSpec,
patchConfigScript,
}:
let
mkBypassScript =
{
filterMark ? null,
tunInterfaces ? [ ],
scope ? "global",
}:
pkgs.writeText "proxy-suite-zapret-bypass.sh" ''
# Upstream presets can select iptables explicitly, in which case the nft
# hook below is never called. Use upstream helpers for idempotent start
# and stop, and distinct comments so each service owns its exemptions.
zapret_custom_firewall() {
local family rule_helper chain
for family in 4 6; do
if [ "$family" = 4 ]; then
[ "''${DISABLE_IPV4:-0}" != 1 ] || continue
rule_helper=ipt_add_del
else
[ "''${DISABLE_IPV6:-0}" != 1 ] || continue
rule_helper=ipt6_add_del
fi
${lib.optionalString (filterMark != null) ''
for chain in POSTROUTING INPUT FORWARD; do
"$rule_helper" "$1" "$chain" -t mangle -m mark ! --mark 0/${filterMark} -m comment --comment "proxy-suite ${scope} per-app-zapret bypass" -j RETURN
done
''}
${lib.concatMapStrings (interface: ''
"$rule_helper" "$1" POSTROUTING -t mangle -o ${lib.escapeShellArg interface} -m comment --comment "proxy-suite ${scope} TUN bypass" -j RETURN
"$rule_helper" "$1" INPUT -t mangle -i ${lib.escapeShellArg interface} -m comment --comment "proxy-suite ${scope} TUN bypass" -j RETURN
"$rule_helper" "$1" FORWARD -t mangle -i ${lib.escapeShellArg interface} -m comment --comment "proxy-suite ${scope} TUN bypass" -j RETURN
'') tunInterfaces}
done
return 0
}
zapret_custom_firewall_nft() {
${lib.optionalString (filterMark != null) ''
nft insert rule inet $ZAPRET_NFT_TABLE postrouting mark and ${filterMark} != 0 return comment '"proxy-suite per-app-zapret bypass"'
nft insert rule inet $ZAPRET_NFT_TABLE postnat mark and ${filterMark} != 0 return comment '"proxy-suite per-app-zapret bypass"'
nft insert rule inet $ZAPRET_NFT_TABLE prerouting mark and ${filterMark} != 0 return comment '"proxy-suite per-app-zapret bypass"'
nft insert rule inet $ZAPRET_NFT_TABLE prenat mark and ${filterMark} != 0 return comment '"proxy-suite per-app-zapret bypass"'
''}
# Desync packets must reach the physical network, never a TUN userspace
# TCP stack: fake TLS payloads there can break the proxied handshake.
${lib.concatMapStrings (interface: ''
nft insert rule inet $ZAPRET_NFT_TABLE postrouting oifname ${lib.escapeShellArg (builtins.toJSON interface)} return comment '"proxy-suite TUN bypass"'
nft insert rule inet $ZAPRET_NFT_TABLE postnat oifname ${lib.escapeShellArg (builtins.toJSON interface)} return comment '"proxy-suite TUN bypass"'
nft insert rule inet $ZAPRET_NFT_TABLE prerouting iifname ${lib.escapeShellArg (builtins.toJSON interface)} return comment '"proxy-suite TUN bypass"'
nft insert rule inet $ZAPRET_NFT_TABLE prenat iifname ${lib.escapeShellArg (builtins.toJSON interface)} return comment '"proxy-suite TUN bypass"'
'') tunInterfaces}
}
'';
mkDerivedZapretPackage =
{
packageName,
pidDir,
configName ? zapretCfg.zapret-discord-youtube.configName,
gameFilter ? zapretCfg.zapret-discord-youtube.gameFilter,
forceDisableFilterMark ? false,
filterMark ? null,
qnum ? null,
modeFilter ? null,
desyncMark ? null,
desyncMarkPostnat ? null,
nftTable ? null,
customScript ? null,
}:
pkgs.runCommand packageName
{
nativeBuildInputs = with pkgs; [
coreutils
gnused
python3
];
}
''
set -euo pipefail
mkdir -p "$out"
cp -a ${baseZapretPackage}/. "$out/"
chmod -R u+w "$out/opt/zapret" "$out/bin"
find "$out/opt/zapret/configs" -type f -exec ${pkgs.gnused}/bin/sed -i \
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
{} \;
find "$out/opt/zapret/hostlists" -type f -exec ${pkgs.gnused}/bin/sed -i \
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
{} \;
requested_config=${lib.escapeShellArg configName}
configs_dir="$out/opt/zapret/configs"
selected_config="$configs_dir/$requested_config"
config_name_key() {
printf '%s' "$1" | tr -d '[:space:]'
}
if [ ! -f "$selected_config" ]; then
requested_key=$(config_name_key "$requested_config")
matched_config=""
for candidate in "$configs_dir"/*; do
[ -f "$candidate" ] || continue
candidate_name="''${candidate##*/}"
if [ "$(config_name_key "$candidate_name")" = "$requested_key" ]; then
if [ -n "$matched_config" ]; then
echo "proxy-suite: zapret config '$requested_config' is ambiguous after whitespace normalization" >&2
echo "proxy-suite: matched '$matched_config' and '$candidate'" >&2
exit 1
fi
matched_config="$candidate"
fi
done
if [ -n "$matched_config" ]; then
selected_config="$matched_config"
fi
fi
if [ -f "$selected_config" ]; then
cp "$selected_config" "$out/opt/zapret/config"
else
echo "proxy-suite: zapret config '$requested_config' not found in curated package" >&2
ls -la "$out/opt/zapret/configs" >&2 || true
exit 1
fi
${pkgs.gnused}/bin/sed -i \
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
"$out/opt/zapret/config"
${pkgs.gnused}/bin/sed -i \
-e 's|^PIDDIR=.*$|PIDDIR=${pidDir}|' \
"$out/opt/zapret/init.d/sysv/functions"
append_list_file() {
local target="$1"
local extra_file="$2"
local tmp="$out/opt/zapret/hostlists/$target.tmp"
cat "$out/opt/zapret/hostlists/$target" > "$tmp"
${pkgs.gnused}/bin/sed -i -e '$a\' "$tmp"
cat "$extra_file" >> "$tmp"
mv "$tmp" "$out/opt/zapret/hostlists/$target"
}
set_config_var() {
local key="$1"
local value="$2"
if grep -Eq "^[#[:space:]]*$key=" "$out/opt/zapret/config"; then
${pkgs.gnused}/bin/sed -Ei "s|^[#[:space:]]*$key=.*$|$key=$value|" "$out/opt/zapret/config"
else
printf '\n%s=%s\n' "$key" "$value" >> "$out/opt/zapret/config"
fi
}
${lib.concatMapStrings
(
{ name, file }:
lib.optionalString (file != null) ''
append_list_file ${name} ${file}
''
)
[
{
name = "list-general-user.txt";
file = listGeneralFile;
}
{
name = "list-exclude-user.txt";
file = listExcludeFile;
}
{
name = "ipset-all.txt";
file = ipsetAllFile;
}
{
name = "ipset-exclude-user.txt";
file = ipsetExcludeFile;
}
]
}
rm -f "$out/opt/zapret/hostlists/.game_filter.enabled"
${lib.optionalString (gameFilter != "null") ''
echo "${gameFilter}" > "$out/opt/zapret/hostlists/.game_filter.enabled"
''}
${lib.concatMapStrings (
rule:
let
domainsFile = pkgs.writeText "proxy-suite-zapret-hostlist-${rule.name}.txt" (
lib.concatStringsSep "\n" (lib.unique rule.domains) + "\n"
);
ipsetFile = pkgs.writeText "proxy-suite-zapret-ipset-${rule.name}.txt" (
lib.concatStringsSep "\n" (lib.unique rule.ips) + "\n"
);
in
lib.optionalString (rule.domains != [ ]) ''
cp ${domainsFile} "$out/opt/zapret/hostlists/list-${rule.name}.txt"
''
+ lib.optionalString (rule.ips != [ ]) ''
cp ${ipsetFile} "$out/opt/zapret/hostlists/ipset-${rule.name}.txt"
''
) effectiveHostlistRules}
${patchConfigScript} --config "$out/opt/zapret/config" --spec ${hostlistRuleSpec}
${lib.optionalString forceDisableFilterMark ''
set_config_var FILTER_MARK ""
''}
${lib.concatMapStrings
(
{ var, value }:
lib.optionalString (value != null) ''
hex=$(printf '0x%x' ${toString value})
set_config_var ${var} "$hex"
''
)
[
{
var = "FILTER_MARK";
value = filterMark;
}
{
var = "DESYNC_MARK";
value = desyncMark;
}
{
var = "DESYNC_MARK_POSTNAT";
value = desyncMarkPostnat;
}
]
}
${lib.optionalString (qnum != null) ''
set_config_var QNUM ${toString qnum}
''}
${lib.optionalString (modeFilter != null) ''
set_config_var MODE_FILTER ${modeFilter}
''}
${lib.optionalString (nftTable != null) ''
set_config_var ZAPRET_NFT_TABLE ${nftTable}
''}
${lib.optionalString (customScript != null) ''
mkdir -p "$out/opt/zapret/init.d/sysv/custom.d"
cp ${customScript} "$out/opt/zapret/init.d/sysv/custom.d/50-proxy-suite-custom.sh"
chmod +x "$out/opt/zapret/init.d/sysv/custom.d/50-proxy-suite-custom.sh"
''}
'';
in
{
inherit
mkDerivedZapretPackage
mkBypassScript
;
}
+219
View File
@@ -0,0 +1,219 @@
# Derived zapret packages and validation.
{
lib,
pkgs,
cfg,
zapret,
}:
let
zapretCfg = cfg.zapret;
perAppZapretCfg = cfg.perAppRouting.zapret;
tunInterfaces = lib.unique (
lib.optional (cfg.proxy.enable && cfg.proxy.tun.enable) cfg.proxy.tun.interface
++ lib.optional (cfg.proxy.enable && cfg.perAppRouting.tun.enable) cfg.perAppRouting.tun.interface
);
zapretDomainGroups = import ../zapret-domain-groups.nix { inherit lib zapret; };
runtimeDeps = lib.attrValues {
inherit (pkgs)
iptables
ipset
nftables
coreutils
gawk
curl
wget
bash
kmod
findutils
gnused
gnugrep
procps
util-linux
;
};
effectiveHostlistRules = map (
rule:
rule
// {
domains = zapretDomainGroups.effectiveRuleDomains rule;
ips = zapretDomainGroups.effectiveRuleIps rule;
presets = zapretDomainGroups.effectiveRulePresets rule;
ipsets = zapretDomainGroups.effectiveRuleIpsetFamilies rule;
protocols = zapretDomainGroups.effectiveRuleProtocolFamilies rule;
}
) zapretCfg.zapret-discord-youtube.hostlistRules;
hostlistRuleNames = map (rule: rule.name) zapretCfg.zapret-discord-youtube.hostlistRules;
baseZapretPackage =
let
upstreamPackages = zapret.packages.${pkgs.stdenv.hostPlatform.system};
in
if upstreamPackages ? zapret then upstreamPackages.zapret else upstreamPackages.default;
mkOptionalHostlistFile =
fileName: entries:
if entries != [ ] then pkgs.writeText fileName (lib.concatStringsSep "\n" entries + "\n") else null;
listGeneralFile = mkOptionalHostlistFile "proxy-suite-zapret-list-general-user.txt" zapretCfg.zapret-discord-youtube.domains;
listExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-list-exclude-user.txt" zapretCfg.zapret-discord-youtube.excludeDomains;
ipsetAllFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-all.txt" zapretCfg.zapret-discord-youtube.ips;
ipsetExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-exclude-user.txt" zapretCfg.zapret-discord-youtube.excludeIps;
hostlistRuleSpec = pkgs.writeText "proxy-suite-zapret-hostlist-rules.json" (
builtins.toJSON {
includeExtraUpstreamLists = zapretCfg.zapret-discord-youtube.includeExtraUpstreamLists;
entries = map (rule: {
inherit (rule)
name
configName
nfqwsArgs
ipsets
presets
protocols
;
hasDomains = rule.domains != [ ];
hasIps = rule.ips != [ ];
}) effectiveHostlistRules;
}
);
selectedConfigName = lib.strings.sanitizeDerivationName zapretCfg.zapret-discord-youtube.configName;
patchConfigScriptSrc = builtins.path {
path = ../../../scripts/patch-zapret-config.py;
name = "patch-zapret-config.py";
};
patchConfigScript = "${pkgs.python3}/bin/python3 ${patchConfigScriptSrc}";
packageBuilder = import ./package-builder.nix {
inherit
lib
pkgs
zapretCfg
baseZapretPackage
effectiveHostlistRules
listGeneralFile
listExcludeFile
ipsetAllFile
ipsetExcludeFile
hostlistRuleSpec
patchConfigScript
;
};
inherit (packageBuilder)
mkDerivedZapretPackage
mkBypassScript
;
globalZapretPackage = mkDerivedZapretPackage {
packageName = "proxy-suite-zapret-${selectedConfigName}";
pidDir = "/run/proxy-suite-zapret";
gameFilter = zapretCfg.zapret-discord-youtube.gameFilter;
forceDisableFilterMark = true;
customScript =
if perAppZapretCfg.enable || tunInterfaces != [ ] then
mkBypassScript {
inherit tunInterfaces;
filterMark = if perAppZapretCfg.enable then toString perAppZapretCfg.filterMark else null;
}
else
null;
};
perAppZapretPackage = mkDerivedZapretPackage {
packageName = "proxy-suite-per-app-zapret-${selectedConfigName}";
pidDir = "/run/proxy-suite-per-app-zapret";
gameFilter = "all";
filterMark = perAppZapretCfg.filterMark;
qnum = perAppZapretCfg.qnum;
modeFilter = "none";
desyncMark = 134217728;
desyncMarkPostnat = 67108864;
nftTable = "proxy_suite_per_app_zapret";
customScript =
if tunInterfaces != [ ] then
mkBypassScript {
inherit tunInterfaces;
scope = "per-app";
}
else
null;
};
mkZapretEnv = package: [
"ZAPRET_BASE=${package}/opt/zapret"
"PATH=${lib.makeBinPath runtimeDeps}"
];
assertions = [
{
assertion = builtins.length hostlistRuleNames == builtins.length (lib.unique hostlistRuleNames);
message = "proxy-suite: zapret.zapret-discord-youtube.hostlistRules names must be unique";
}
{
assertion = builtins.all (
rule:
zapretDomainGroups.effectiveRuleDomains rule != [ ]
|| zapretDomainGroups.effectiveRuleIps rule != [ ]
) zapretCfg.zapret-discord-youtube.hostlistRules;
message = "proxy-suite: each zapret.zapret-discord-youtube.hostlistRules entry must define domains, defaultDomains, ips, or defaultIps";
}
{
assertion = builtins.all (
rule:
rule.preset != null
|| rule.defaultDomains != [ ]
|| rule.ips != [ ]
|| rule.defaultIps != [ ]
|| rule.nfqwsArgs != [ ]
) zapretCfg.zapret-discord-youtube.hostlistRules;
message = "proxy-suite: each zapret.zapret-discord-youtube.hostlistRules entry must set preset, defaultDomains, ips/defaultIps, nfqwsArgs, or a valid configName source";
}
{
assertion = builtins.all (
rule:
zapretDomainGroups.effectiveRuleDomains rule == [ ]
|| rule.preset != null
|| rule.defaultDomains != [ ]
|| rule.nfqwsArgs != [ ]
) zapretCfg.zapret-discord-youtube.hostlistRules;
message = "proxy-suite: zapret.zapret-discord-youtube.hostlistRules entries with domains require preset, defaultDomains, or nfqwsArgs";
}
{
assertion = builtins.all (
rule: rule.preset != null || builtins.length rule.defaultDomains <= 1
) zapretCfg.zapret-discord-youtube.hostlistRules;
message = "proxy-suite: zapret.zapret-discord-youtube.hostlistRules entries without preset may infer a rule family from only one defaultDomains entry; split groups into separate rules or set preset";
}
{
assertion = builtins.all (
rule: !(rule.configName != null && rule.nfqwsArgs != [ ])
) zapretCfg.zapret-discord-youtube.hostlistRules;
message = "proxy-suite: zapret.zapret-discord-youtube.hostlistRules.*.configName cannot be used together with nfqwsArgs";
}
{
assertion = builtins.all (
rule:
rule.configName == null
|| rule.preset != null
|| rule.defaultDomains != [ ]
|| rule.ips != [ ]
|| rule.defaultIps != [ ]
) zapretCfg.zapret-discord-youtube.hostlistRules;
message = "proxy-suite: zapret.zapret-discord-youtube.hostlistRules.*.configName requires preset, defaultDomains, ips, or defaultIps";
}
];
in
{
inherit
globalZapretPackage
perAppZapretPackage
;
globalZapretEnv = mkZapretEnv globalZapretPackage;
perAppZapretEnv = mkZapretEnv perAppZapretPackage;
inherit assertions;
}
+131
View File
@@ -0,0 +1,131 @@
# zapret2 (nfqws2) services, under the zapret v1 unit and table names.
{
lib,
pkgs,
cfg,
packages,
perAppZapretRulesFile,
nft,
}:
let
builders = import ./service/builders.nix { inherit lib pkgs; };
inherit (builders) mkOneshotService;
zapretCfg = cfg.zapret;
perAppZapretCfg = cfg.perAppRouting.zapret;
inherit (import ./derived.nix { inherit lib cfg; }) constants;
awgServiceNames = map (name: "proxy-suite-awg-${name}.service") (
builtins.attrNames cfg.amneziaWg.profiles
);
runtime = import ./zapret2/runtime.nix {
inherit
lib
pkgs
cfg
packages
;
};
tunInterfaces = lib.unique (
lib.optional (cfg.proxy.enable && cfg.proxy.tun.enable) cfg.proxy.tun.interface
++ lib.optional (cfg.proxy.enable && cfg.perAppRouting.tun.enable) cfg.perAppRouting.tun.interface
);
globalRuntime = runtime.mkRuntime {
name = "proxy-suite-zapret2";
qnum = constants.zapretGlobalQnum.zapret2;
desyncMark = 1073741824; # 0x40000000
desyncMarkPostnat = 536870912; # 0x20000000
nftTable = "zapret2";
modeFilter = if zapretCfg.zapret2.autoHostlist.enable then "autohostlist" else "hostlist";
customScript =
let
exemptCidrs = lib.optionals zapretCfg.cidrExemption.enable zapretCfg.cidrExemption.cidrs;
in
if perAppZapretCfg.enable || tunInterfaces != [ ] || exemptCidrs != [ ] then
runtime.mkCustomScript {
inherit tunInterfaces exemptCidrs;
excludeMark = if perAppZapretCfg.enable then perAppZapretCfg.filterMark else null;
}
else
null;
};
# Wrapped apps opted in: MODE_FILTER=none applies every profile to all their traffic.
perAppRuntime = runtime.mkRuntime {
name = "proxy-suite-per-app-zapret2";
qnum = perAppZapretCfg.qnum;
desyncMark = 134217728; # 0x8000000
desyncMarkPostnat = 67108864; # 0x4000000
filterMark = perAppZapretCfg.filterMark;
nftTable = "proxy_suite_per_app_zapret";
modeFilter = "none";
customScript =
if tunInterfaces != [ ] then runtime.mkCustomScript { inherit tunInterfaces; } else null;
};
# nfqws2 and proxy-ctl expect the list files to exist.
mkPreStart = ''
${lib.getExe' pkgs.kmod "modprobe"} nfnetlink_queue 2>/dev/null || true
install -d -m 0755 ${runtime.stateDir}
touch ${runtime.autoHostlistFile} ${runtime.userHostlistFile} ${runtime.excludeHostlistFile}
'';
perAppZapretMarkUpScript = pkgs.writeShellScript "proxy-suite-per-app-zapret2-mark-up" ''
set -euo pipefail
${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true
${nft} -f ${perAppZapretRulesFile}
'';
perAppZapretMarkDownScript = pkgs.writeShellScript "proxy-suite-per-app-zapret2-mark-down" ''
set -euo pipefail
${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true
'';
in
{
environment.systemPackages = lib.mkBefore [ runtime.package ];
systemd.services.zapret-discord-youtube = lib.mkIf zapretCfg.enable (mkOneshotService {
description = "zapret2 DPI bypass";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = awgServiceNames;
wantedBy = [ "multi-user.target" ];
preStart = mkPreStart;
runtimeDirectory = "proxy-suite-zapret";
stateDirectory = "proxy-suite";
execStart = "${runtime.initScript} start";
execStop = "${runtime.initScript} stop";
extraServiceConfig = {
ExecReload = "${runtime.initScript} restart";
Environment = runtime.mkEnv {
runtime = globalRuntime;
pidDir = "/run/proxy-suite-zapret";
};
};
});
systemd.services.proxy-suite-per-app-zapret = lib.mkIf perAppZapretCfg.enable (mkOneshotService {
description = "proxy-suite per-app-routing zapret2 backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
]
++ awgServiceNames;
preStart = mkPreStart;
runtimeDirectory = "proxy-suite-per-app-zapret";
stateDirectory = "proxy-suite";
execStart = "${runtime.initScript} start";
execStop = "${runtime.initScript} stop";
execStartPre = "${perAppZapretMarkUpScript}";
execStopPost = "${perAppZapretMarkDownScript}";
extraServiceConfig.Environment = runtime.mkEnv {
runtime = perAppRuntime;
pidDir = "/run/proxy-suite-per-app-zapret";
};
});
}
+232
View File
@@ -0,0 +1,232 @@
# Per-instance zapret2 runtime: a generated config and custom.d hook, no package copy.
{
lib,
pkgs,
cfg,
packages,
}:
let
zapret2Cfg = cfg.zapret.zapret2;
autoCfg = zapret2Cfg.autoHostlist;
package = packages.zapret2;
zapretBase = "${package}/opt/zapret2";
# Shared by both instances: what the global one learns applies per-app too.
inherit (import ../derived.nix { inherit lib cfg; }) constants;
stateDir = constants.zapret2StateDir;
autoHostlistFile = "${stateDir}/zapret-hosts-auto.txt";
userHostlistFile = "${stateDir}/zapret-hosts-user.txt";
excludeHostlistFile = "${stateDir}/zapret-hosts-user-exclude.txt";
runtimeDeps = lib.attrValues {
inherit (pkgs)
coreutils
findutils
gawk
gnugrep
gnused
iproute2
iptables
ipset
kmod
nftables
procps
util-linux
;
};
toHex = value: "0x" + lib.toHexString value;
blobPath = file: if lib.hasPrefix "/" file then file else "${zapretBase}/files/fake/${file}";
blobArgs = lib.mapAttrsToList (name: file: "--blob=${name}:@${blobPath file}") zapret2Cfg.blobs;
hostlistMarkers = [
"<HOSTLIST>"
"<HOSTLIST_NOAUTO>"
];
# Static domain filters join every profile that uses a hostlist marker.
staticListArgs =
lib.optional (
zapret2Cfg.domains != [ ]
) "--hostlist-domains=${lib.concatStringsSep "," zapret2Cfg.domains}"
++ lib.optional (
zapret2Cfg.excludeDomains != [ ]
) "--hostlist-exclude-domains=${lib.concatStringsSep "," zapret2Cfg.excludeDomains}";
renderProfile =
profile:
let
suffix = lib.concatMapStrings (arg: " " + arg) staticListArgs;
in
lib.replaceStrings hostlistMarkers (map (marker: marker + suffix) hostlistMarkers) (
lib.trim profile
);
nfqwsOpt = lib.concatStringsSep " " (
blobArgs ++ [ (lib.concatStringsSep " --new " (map renderProfile zapret2Cfg.profiles)) ]
);
# The NFQUEUE window must exceed the retransmission threshold it counts.
packetWindow = {
tcpOut = 6 + autoCfg.retransThreshold;
tcpIn = 15;
udpOut = 6 + autoCfg.retransThreshold;
udpIn = 3;
};
mkConfig =
{
qnum,
desyncMark,
desyncMarkPostnat,
nftTable,
filterMark ? null,
modeFilter,
}:
pkgs.writeText "proxy-suite-zapret2-config" (
lib.concatStringsSep "\n" (
[
"# Generated by proxy-suite. Do not edit."
"WS_USER=root"
"FWTYPE=nftables"
"INIT_APPLY_FW=1"
"QNUM=${toString qnum}"
"DESYNC_MARK=${toHex desyncMark}"
"DESYNC_MARK_POSTNAT=${toHex desyncMarkPostnat}"
"ZAPRET_NFT_TABLE=${nftTable}"
]
++ lib.optional (filterMark != null) "FILTER_MARK=${toHex filterMark}"
++ lib.optional (!zapret2Cfg.ipv6) "DISABLE_IPV6=1"
++ [
"NFQWS2_ENABLE=1"
"NFQWS2_PORTS_TCP=${zapret2Cfg.ports.tcp}"
"NFQWS2_PORTS_UDP=${zapret2Cfg.ports.udp}"
"NFQWS2_TCP_PKT_OUT=${toString packetWindow.tcpOut}"
"NFQWS2_TCP_PKT_IN=${toString packetWindow.tcpIn}"
"NFQWS2_UDP_PKT_OUT=${toString packetWindow.udpOut}"
"NFQWS2_UDP_PKT_IN=${toString packetWindow.udpIn}"
"MODE_FILTER=${modeFilter}"
"AUTOHOSTLIST_FAIL_THRESHOLD=${toString autoCfg.failThreshold}"
"AUTOHOSTLIST_FAIL_TIME=${toString autoCfg.failTime}"
"AUTOHOSTLIST_RETRANS_THRESHOLD=${toString autoCfg.retransThreshold}"
"AUTOHOSTLIST_RETRANS_RESET=${if autoCfg.retransReset then "1" else "0"}"
"AUTOHOSTLIST_RETRANS_MAXSEQ=${toString autoCfg.retransMaxseq}"
"AUTOHOSTLIST_INCOMING_MAXSEQ=${toString autoCfg.incomingMaxseq}"
"AUTOHOSTLIST_UDP_OUT=${toString autoCfg.udpOut}"
"AUTOHOSTLIST_UDP_IN=${toString autoCfg.udpIn}"
"AUTOHOSTLIST_DEBUGLOG=${if autoCfg.debugLog then "1" else "0"}"
"NFQWS2_OPT=${lib.escapeShellArg nfqwsOpt}"
""
]
)
);
# Keep desync off TUN interfaces (it breaks proxied handshakes), off per-app
# traffic, and off exempted subnets (e.g. NATed VMs whose traffic it would break).
mkCustomScript =
{
tunInterfaces ? [ ],
excludeMark ? null,
exemptCidrs ? [ ],
}:
let
chains = [
{
name = "postrouting";
direction = "oifname";
ipMatch = "daddr";
}
{
name = "postnat";
direction = "oifname";
ipMatch = "daddr";
}
{
name = "prerouting";
direction = "iifname";
ipMatch = "saddr";
}
{
name = "prenat";
direction = "iifname";
ipMatch = "saddr";
}
];
nftFamily = cidr: if lib.hasInfix ":" cidr then "ip6" else "ip";
mkRule =
chain: match: comment:
" nft insert rule inet $ZAPRET_NFT_TABLE ${chain} ${match} return comment '\"${comment}\"'";
rules = lib.concatMap (
chain:
lib.optional (excludeMark != null) (
mkRule chain.name "mark and ${toHex excludeMark} != 0" "proxy-suite per-app-zapret bypass"
)
++ map (
interface: mkRule chain.name "${chain.direction} '\"${interface}\"'" "proxy-suite TUN bypass"
) tunInterfaces
++ map (
cidr:
mkRule chain.name "${nftFamily cidr} ${chain.ipMatch} ${cidr}" "proxy-suite CIDR exemption"
) exemptCidrs
) chains;
in
pkgs.writeText "proxy-suite-zapret2-custom.sh" (
lib.concatStringsSep "\n" (
[ "zapret_custom_firewall_nft() {" ]
++ rules
++ [
" return 0"
"}"
""
]
)
);
mkRuntime =
{
name,
customScript ? null,
...
}@args:
pkgs.runCommand name { } ''
mkdir -p "$out/init.d/sysv/custom.d"
cp ${
mkConfig (
builtins.removeAttrs args [
"name"
"customScript"
]
)
} "$out/config"
${lib.optionalString (customScript != null) ''
cp ${customScript} "$out/init.d/sysv/custom.d/50-proxy-suite-custom.sh"
''}
'';
mkEnv =
{ runtime, pidDir }:
[
"ZAPRET_BASE=${zapretBase}"
"ZAPRET_RW=${runtime}"
"HOSTLIST_BASE=${stateDir}"
"PIDDIR=${pidDir}"
"PATH=${lib.makeBinPath runtimeDeps}"
];
in
{
inherit
package
stateDir
autoHostlistFile
userHostlistFile
excludeHostlistFile
mkCustomScript
mkRuntime
mkEnv
;
initScript = "${zapretBase}/init.d/sysv/zapret2";
}
+26 -3508
View File
File diff suppressed because it is too large. Load diff
+143
View File
@@ -0,0 +1,143 @@
{
pkgs,
nixpkgs,
proxySuiteModule,
}:
let
keys = import "${nixpkgs}/nixos/tests/wireguard/snakeoil-keys.nix";
awgPackages = import ../../pkgs/amneziawg.nix { inherit pkgs; };
obfuscation = {
jc = 5;
jmin = 10;
jmax = 42;
s1 = 60;
s2 = 90;
};
network = address: {
networking.useDHCP = false;
networking.interfaces.eth1.ipv4.addresses = [
{
inherit address;
prefixLength = 24;
}
];
};
client =
address: userspaceOnly:
{
imports = [ proxySuiteModule ];
services.proxy-suite = {
enable = true;
amneziaWg = {
enable = true;
kernelModulePackage = if userspaceOnly then null else awgPackages.kernelModule pkgs.linuxPackages;
profiles.test = {
interfaceName = "awg-test";
settings = {
addresses = [ "10.23.42.2/32" ];
privateKey = keys.peer1.privateKey;
obfuscation = { inherit (obfuscation) s1 s2; };
obfuscationFile = "/run/awg-obfuscation.json";
peers = [
{
publicKey = keys.peer0.publicKey;
endpoint = "192.168.0.1:23542";
allowedIPs = [ "10.23.42.1/32" ];
persistentKeepalive = 5;
}
];
};
};
profiles.broken = {
interfaceName = "awg-broken";
settings = {
addresses = [ "10.99.42.2/32" ];
privateKey = keys.peer1.privateKey;
inherit obfuscation;
peers = [
{
publicKey = keys.peer0.publicKey;
endpoint = "192.168.0.254:23542";
allowedIPs = [ "10.99.42.1/32" ];
}
];
};
};
};
};
}
// network address;
in
pkgs.testers.runNixOSTest {
name = "proxy-suite-amneziawg-runtime";
nodes = {
server =
{ ... }:
{
imports = [ (network "192.168.0.1") ];
networking.firewall.allowedUDPPorts = [ 23542 ];
networking.wg-quick.interfaces.awg-server = {
type = "amneziawg";
address = [ "10.23.42.1/32" ];
listenPort = 23542;
privateKey = keys.peer0.privateKey;
extraOptions = {
Jc = obfuscation.jc;
Jmin = obfuscation.jmin;
Jmax = obfuscation.jmax;
S1 = obfuscation.s1;
S2 = obfuscation.s2;
};
peers = [
{
publicKey = keys.peer1.publicKey;
allowedIPs = [ "10.23.42.2/32" ];
}
];
};
};
kernel = client "192.168.0.2" false;
userspace = client "192.168.0.3" true;
};
testScript = ''
start_all()
server.wait_for_unit("wg-quick-awg-server.service")
# Provision the partial secret after boot, outside the generated manifest.
for machine in (kernel, userspace):
machine.succeed("""umask 077; echo '${
builtins.toJSON { inherit (obfuscation) jc jmin jmax; }
}' > /run/awg-obfuscation.json""")
with subtest("packaged kernel module"):
kernel.succeed("systemctl start proxy-suite-awg-test.service")
kernel.succeed("test $(stat -c %a /run/proxy-suite-awg-test/awg-test.conf) = 600")
kernel.succeed("test $(stat -c %a /run/proxy-suite-awg-test) = 700")
kernel.succeed("ip -d link show awg-test | grep -q amneziawg")
kernel.succeed("ping -c 5 10.23.42.1")
kernel.succeed("test $(awg show awg-test latest-handshakes | awk '{print $2}') -gt 0")
kernel.succeed("systemctl stop proxy-suite-awg-test.service")
kernel.fail("ip link show awg-test")
with subtest("automatic userspace fallback"):
userspace.fail("modprobe -n amneziawg")
userspace.succeed("systemctl start proxy-suite-awg-test.service")
userspace.succeed("test $(stat -c %a /run/proxy-suite-awg-test/awg-test.conf) = 600")
userspace.succeed("test $(stat -c %a /run/proxy-suite-awg-test) = 700")
userspace.succeed("test -r /sys/class/net/awg-test/tun_flags")
userspace.succeed("ping -c 5 10.23.42.1")
userspace.succeed("test $(awg show awg-test latest-handshakes | awk '{print $2}') -gt 0")
userspace.succeed("systemctl stop proxy-suite-awg-test.service")
userspace.fail("ip link show awg-test")
with subtest("failed handshake rolls back userspace routing"):
userspace.fail("systemctl start proxy-suite-awg-broken.service")
userspace.fail("ip link show awg-broken")
userspace.fail("ip route show table all | grep -F awg-broken")
userspace.fail("ip -6 route show table all | grep -F awg-broken")
'';
}
+352
View File
@@ -0,0 +1,352 @@
{
pkgs,
evalProxySuite,
mkBadProxySuiteFixture,
mkFailingAssertions,
mkProxyCtlDerived,
}:
let
generated = import ./read-generated.nix;
defaultPackages = evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
amneziaWg = {
enable = true;
profiles.home.configFile = "/run/secrets/awg.conf";
};
};
}
];
awgOnly = evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
amneziaWg = {
enable = true;
kernelModulePackage = null;
profiles = {
home = {
autostart = true;
settings = {
addresses = [ "10.8.0.2/32" ];
privateKeyFile = "/run/secrets/awg-private";
obfuscationFile = "/run/secrets/awg-obfuscation.json";
obfuscation = {
s1 = 12;
s2 = 12;
s3 = 12;
s4 = 12;
h1 = "100-200";
headerProtectionKeyFile = "/run/secrets/awg-header";
rekeyAfterTime = "120-180";
};
peers = [
{
publicKey = "public";
presharedKeyFile = "/run/secrets/awg-psk";
allowedIPs = [
"0.0.0.0/0"
"::/0"
];
endpoint = "vpn.example.com:51820";
persistentKeepalive = "20-30";
advancedSecurity = true;
}
];
};
};
work = {
configFile = "/run/secrets/work-awg.conf";
};
};
};
};
}
];
homeService = awgOnly.config.systemd.services.proxy-suite-awg-home;
workService = awgOnly.config.systemd.services.proxy-suite-awg-work;
ctl = mkProxyCtlDerived awgOnly;
sourceFixture = evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
amneziaWg = {
enable = true;
kernelModulePackage = null;
profiles = {
conf.configFile = "/run/secrets/client.conf";
file.vpnFile = "/run/secrets/client.vpn";
inline.vpn = "vpn://ZW1iZWRkZWQ";
nix.settings = {
addresses = [ "10.0.0.2/32" ];
privateKey = "inline-private";
peers = [
{
publicKey = "public";
allowedIPs = [ "10.0.0.1/32" ];
}
];
};
};
};
};
}
];
fakeTools = pkgs.writeShellScriptBin "awg-quick" "exit 0";
fakeUserspace = pkgs.writeShellScriptBin "amneziawg-go" "exit 0";
fakeKernelModule = pkgs.runCommand "fake-amneziawg-module" { } ''
mkdir -p "$out/lib/modules"
'';
overrideFixture = evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
amneziaWg = {
enable = true;
toolsPackage = fakeTools;
userspacePackage = fakeUserspace;
kernelModulePackage = fakeKernelModule;
profiles.home.configFile = "/run/secrets/client.conf";
};
};
}
];
withGlobalTun = evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
backend = "sing-box";
outbounds = [
{
tag = "primary";
url = "http://proxy.example.com:8080";
}
];
tun.enable = true;
tproxy.enable = true;
};
zapret.enable = true;
perAppRouting.zapret.enable = true;
amneziaWg = {
enable = true;
kernelModulePackage = null;
profiles.home.configFile = "/run/secrets/awg.conf";
};
};
}
];
withGlobalAwgService = withGlobalTun.config.systemd.services.proxy-suite-awg-home;
withGlobalAwgStartPre = withGlobalAwgService.serviceConfig.ExecStartPre;
withGlobalAwgBypassUp = generated.readDerivation (builtins.elemAt withGlobalAwgStartPre 1);
withGlobalAwgBypassDown = generated.readDerivation withGlobalAwgService.serviceConfig.ExecStopPost;
in
{
manifest = pkgs.runCommand "amneziawg-secret-manifest-check" { } ''
${pkgs.python3}/bin/python3 - <<'PY'
import json
import shlex
from pathlib import Path
prepare = Path("${builtins.head homeService.serviceConfig.ExecStartPre}").read_text()
args = shlex.split(prepare)
manifest = json.loads(Path(args[args.index("--manifest") + 1]).read_text())
assert manifest["kind"] == "settings"
assert manifest["settings"]["obfuscationFile"] == "/run/secrets/awg-obfuscation.json"
assert manifest["settings"]["obfuscation"]["s1"] == 12
assert manifest["settings"]["obfuscation"]["i1"] is None
PY
touch "$out"
'';
assertions = [
(
assert !awgOnly.config.services.proxy-suite.proxy.enable;
assert homeService.serviceConfig.RuntimeDirectoryMode == "0700";
assert homeService.serviceConfig.UMask == "0077";
assert
awgOnly.config.services.proxy-suite.amneziaWg.profiles.home.settings.obfuscationFile
== "/run/secrets/awg-obfuscation.json";
assert
sourceFixture.config.services.proxy-suite.amneziaWg.profiles.nix.settings.obfuscationFile == null;
assert builtins.elem "multi-user.target" homeService.wantedBy;
assert builtins.elem "proxy-suite-awg-work.service" homeService.conflicts;
assert builtins.elem "proxy-suite-tun.service" homeService.conflicts;
assert builtins.elem "proxy-suite-tproxy.service" homeService.conflicts;
assert builtins.elem "zapret-discord-youtube.service" homeService.conflicts;
assert builtins.elem "proxy-suite-per-app-zapret.service" homeService.conflicts;
assert workService.wantedBy == [ ];
assert homeService.serviceConfig.NoNewPrivileges;
assert builtins.length homeService.serviceConfig.ExecStartPre == 1;
assert !(homeService.serviceConfig ? ExecStopPost);
true
)
(
assert builtins.elem awgOnly.config.services.proxy-suite.amneziaWg.toolsPackage
awgOnly.config.environment.systemPackages;
assert builtins.elem awgOnly.config.services.proxy-suite.amneziaWg.userspacePackage
awgOnly.config.environment.systemPackages;
assert awgOnly.config.services.proxy-suite.amneziaWg.toolsPackage.version == "3.1.20260812";
assert awgOnly.config.services.proxy-suite.amneziaWg.userspacePackage.version == "3.1.20260828";
assert pkgs.lib.hasInfix "cmd_awg" ctl.script;
assert
ctl.awgProfiles == [
"home"
"work"
];
true
)
(
assert defaultPackages.config.services.proxy-suite.amneziaWg.toolsPackage.version == "3.1.20260812";
assert
defaultPackages.config.services.proxy-suite.amneziaWg.userspacePackage.version == "3.1.20260828";
assert
defaultPackages.config.services.proxy-suite.amneziaWg.kernelModulePackage.version == "3.1.20260812";
true
)
(
assert
sourceFixture.config.services.proxy-suite.amneziaWg.profiles.conf.configFile
== "/run/secrets/client.conf";
assert
sourceFixture.config.services.proxy-suite.amneziaWg.profiles.file.vpnFile
== "/run/secrets/client.vpn";
assert
sourceFixture.config.services.proxy-suite.amneziaWg.profiles.inline.vpn == "vpn://ZW1iZWRkZWQ";
assert
sourceFixture.config.services.proxy-suite.amneziaWg.profiles.nix.settings.privateKey
== "inline-private";
assert builtins.elem fakeTools overrideFixture.config.environment.systemPackages;
assert builtins.elem fakeUserspace overrideFixture.config.environment.systemPackages;
assert builtins.elem fakeKernelModule overrideFixture.config.boot.extraModulePackages;
assert pkgs.lib.hasInfix "unit.indexOf(\"proxy-suite-\") === 0"
awgOnly.config.security.polkit.extraConfig;
true
)
(
assert builtins.elem "proxy-suite-awg-home.service"
withGlobalTun.config.systemd.services.proxy-suite-tun.conflicts;
assert builtins.elem "proxy-suite-awg-home.service"
withGlobalTun.config.systemd.services.proxy-suite-tproxy.conflicts;
assert builtins.elem "proxy-suite-awg-home.service"
withGlobalTun.config.systemd.services.zapret-discord-youtube.conflicts;
assert builtins.elem "proxy-suite-awg-home.service"
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.wants;
assert builtins.length withGlobalAwgStartPre == 2;
assert pkgs.lib.hasInfix "rule add" withGlobalAwgBypassUp;
assert pkgs.lib.hasInfix "pref 8998" withGlobalAwgBypassUp;
assert pkgs.lib.hasInfix "fwmark 2 lookup main" withGlobalAwgBypassUp;
assert pkgs.lib.hasInfix "unable to install the AWG proxy-backend bypass rule"
withGlobalAwgBypassUp;
assert pkgs.lib.hasInfix "rule del" withGlobalAwgBypassDown;
assert pkgs.lib.hasInfix "pref 8998" withGlobalAwgBypassDown;
assert pkgs.lib.hasInfix "fwmark 2 lookup main" withGlobalAwgBypassDown;
true
)
]
++ mkFailingAssertions mkBadProxySuiteFixture [
{
enable = true;
amneziaWg.enable = true;
}
{
enable = true;
amneziaWg = {
enable = true;
kernelModulePackage = null;
profiles.home = {
configFile = "/run/a.conf";
vpnFile = "/run/a.vpn";
};
};
}
{
enable = true;
amneziaWg = {
enable = true;
kernelModulePackage = null;
profiles = {
one = {
autostart = true;
configFile = "/run/one.conf";
};
two = {
autostart = true;
configFile = "/run/two.conf";
};
};
};
}
{
enable = true;
amneziaWg = {
enable = true;
kernelModulePackage = null;
profiles = {
one = {
interfaceName = "awg-shared";
configFile = "/run/one.conf";
};
two = {
interfaceName = "awg-shared";
configFile = "/run/two.conf";
};
};
};
}
{
enable = true;
amneziaWg = {
enable = true;
kernelModulePackage = null;
profiles.home.settings = {
addresses = [ "10.8.0.2/32" ];
peers = [
{
publicKey = "public";
allowedIPs = [ "0.0.0.0/0" ];
}
];
};
};
}
{
enable = true;
proxy = {
enable = true;
backend = "sing-box";
outbounds = [
{
tag = "primary";
url = "http://proxy.example.com:8080";
}
];
tun = {
enable = true;
autostart = true;
};
};
amneziaWg = {
enable = true;
kernelModulePackage = null;
profiles.home = {
autostart = true;
configFile = "/run/home.conf";
};
};
}
];
}
+82
View File
@@ -0,0 +1,82 @@
{
pkgs,
evalProxySuite,
baseModule,
minimal,
mkRoutingRules,
mkTProxyConfig,
hasRuleSet,
dnsHasRuleSet,
dnsServerByTag,
mkBadFixtureRaw,
mkFailingAssertions,
}:
let
fixtures = import ./core-proxy/fixtures.nix {
inherit
pkgs
evalProxySuite
baseModule
minimal
mkRoutingRules
mkTProxyConfig
mkBadFixtureRaw
mkFailingAssertions
;
};
inherit (fixtures)
customSingBoxPackageBin
customSingBoxPackageStartScript
ruDefaultRules
ruDefaultConfig
ruDisabledRules
ruDisabledConfig
ruExplicitConfig
dnsLocalOverrideConfig
dnsRemoteOverrideConfig
proxyDirectConfig
urlTestCustomStartScript
noProxyBackendDefaultFixture
invalidCoreProxyAssertions
blockGeoRules
routingOrDomainRules
routingOrGeoIPRules
;
routingDnsChecks = import ./core-proxy/routing-dns.nix {
inherit
hasRuleSet
dnsHasRuleSet
dnsServerByTag
ruDefaultRules
ruDefaultConfig
ruDisabledRules
ruDisabledConfig
ruExplicitConfig
dnsLocalOverrideConfig
dnsRemoteOverrideConfig
blockGeoRules
routingOrDomainRules
routingOrGeoIPRules
;
};
serviceDefaultChecks = import ./core-proxy/service-defaults.nix {
inherit
pkgs
minimal
customSingBoxPackageBin
customSingBoxPackageStartScript
proxyDirectConfig
ruDefaultConfig
urlTestCustomStartScript
noProxyBackendDefaultFixture
invalidCoreProxyAssertions
;
};
in
{
inherit ruDefaultConfig;
assertions = routingDnsChecks.assertions ++ serviceDefaultChecks.assertions;
}
+196
View File
@@ -0,0 +1,196 @@
{
pkgs,
evalProxySuite,
baseModule,
minimal,
mkRoutingRules,
mkTProxyConfig,
mkBadFixtureRaw,
mkFailingAssertions,
}:
let
generated = import ../read-generated.nix;
customSingBoxPackage = pkgs.writeShellScriptBin "sing-box" ''
exit 0
'';
customSingBoxPackageFixture = evalProxySuite [
baseModule
{
services.proxy-suite.proxy.singBox.package = customSingBoxPackage;
}
];
customSingBoxPackageBin = "${builtins.unsafeDiscardStringContext (toString customSingBoxPackage)}/bin/sing-box";
customSingBoxPackageStartScript = generated.readDerivation (
customSingBoxPackageFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart
);
routingOrFixture = evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
backend = "sing-box";
outbounds = [
{
tag = "primary";
url = "http://proxy.example.com:8080";
}
];
routing.rules = [
{
outbound = "primary";
domains = [ "example.com" ];
geoips = [ "us" ];
}
];
};
};
}
];
ruDefaultRules = mkRoutingRules minimal;
ruDefaultConfig = mkTProxyConfig minimal;
ruDisabledFixture = evalProxySuite [
baseModule
{
services.proxy-suite.proxy.routing.directRu = false;
}
];
ruDisabledRules = mkRoutingRules ruDisabledFixture;
ruDisabledConfig = mkTProxyConfig ruDisabledFixture;
ruExplicitConfig = mkTProxyConfig (evalProxySuite [
baseModule
{
services.proxy-suite.proxy.routing = {
directRu = false;
direct.geosites = [ "category-ru" ];
};
}
]);
dnsLocalOverrideConfig = mkTProxyConfig (evalProxySuite [
baseModule
{
services.proxy-suite.proxy.dns.local = {
type = "tcp";
address = "9.9.9.9";
port = 5353;
};
}
]);
dnsRemoteOverrideConfig = mkTProxyConfig (evalProxySuite [
baseModule
{
services.proxy-suite.proxy.dns.remote = {
type = "tls";
address = "1.0.0.1";
port = 853;
};
}
]);
proxyDirectConfig = mkTProxyConfig (evalProxySuite [
baseModule
{
services.proxy-suite.proxy.routing.default = "direct";
}
]);
urlTestCustomFixture = evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
backend = "sing-box";
outbounds = [
{
tag = "test-proxy";
url = "http://proxy.example.com:8080";
}
];
selection = "urltest";
urlTest = {
url = "https://telegram.org";
interval = "1m";
tolerance = 100;
};
};
};
}
];
urlTestCustomStartScript = generated.readDerivation (
urlTestCustomFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart
);
noProxyBackendDefaultFixture = evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite.enable = true;
}
];
invalidCoreProxyAssertions = mkFailingAssertions mkBadFixtureRaw [
[
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
backend = "sing-box";
};
};
}
]
];
blockGeoRules = mkRoutingRules (evalProxySuite [
baseModule
{
services.proxy-suite.proxy.routing.block = {
geosites = [ "category-ads-all" ];
geoips = [ "cn" ];
};
}
]);
routingOrRules = mkRoutingRules routingOrFixture;
routingOrDomainRules = builtins.filter (
rule: (rule ? domain_suffix) && rule.domain_suffix == [ "example.com" ]
) routingOrRules;
routingOrGeoIPRules = builtins.filter (
rule: (rule ? rule_set) && rule.rule_set == [ "geoip-us" ]
) routingOrRules;
in
{
inherit
customSingBoxPackageBin
customSingBoxPackageStartScript
ruDefaultRules
ruDefaultConfig
ruDisabledRules
ruDisabledConfig
ruExplicitConfig
dnsLocalOverrideConfig
dnsRemoteOverrideConfig
proxyDirectConfig
urlTestCustomFixture
urlTestCustomStartScript
noProxyBackendDefaultFixture
invalidCoreProxyAssertions
blockGeoRules
routingOrDomainRules
routingOrGeoIPRules
;
}
+114
View File
@@ -0,0 +1,114 @@
{
hasRuleSet,
dnsHasRuleSet,
dnsServerByTag,
ruDefaultRules,
ruDefaultConfig,
ruDisabledRules,
ruDisabledConfig,
ruExplicitConfig,
dnsLocalOverrideConfig,
dnsRemoteOverrideConfig,
blockGeoRules,
routingOrDomainRules,
routingOrGeoIPRules,
}:
{
assertions = [
# -- routing rule entries with domains and geoips preserve both matchers --
(
assert builtins.length routingOrDomainRules == 1;
true
)
(
assert builtins.length routingOrGeoIPRules == 1;
true
)
(
assert (builtins.head routingOrDomainRules).outbound == "proxy";
true
)
(
assert (builtins.head routingOrGeoIPRules).outbound == "proxy";
true
)
# -- default RU direct route and DNS rules are generated --
(
let
localDns = dnsServerByTag ruDefaultConfig "local";
remoteDns = dnsServerByTag ruDefaultConfig "remote";
in
assert localDns.type == "udp";
assert localDns.server == "1.1.1.1";
assert localDns.server_port == 53;
assert !(localDns ? detour);
assert remoteDns.type == "udp";
assert remoteDns.server == "1.1.1.1";
assert remoteDns.server_port == 53;
assert remoteDns.detour == "proxy";
true
)
(
assert hasRuleSet ruDefaultRules "direct" "geosite-category-ru";
true
)
(
assert hasRuleSet ruDefaultRules "direct" "geoip-ru";
true
)
(
assert dnsHasRuleSet ruDefaultConfig.dns.rules "geosite-category-ru";
true
)
(
assert !(hasRuleSet ruDisabledRules "direct" "geosite-category-ru");
true
)
(
assert !(hasRuleSet ruDisabledRules "direct" "geoip-ru");
true
)
(
assert !(dnsHasRuleSet ruDisabledConfig.dns.rules "geosite-category-ru");
true
)
(
assert dnsHasRuleSet ruExplicitConfig.dns.rules "geosite-category-ru";
true
)
# -- DNS overrides map to sing-box server entries --
(
let
localDns = dnsServerByTag dnsLocalOverrideConfig "local";
in
assert localDns.type == "tcp";
assert localDns.server == "9.9.9.9";
assert localDns.server_port == 5353;
assert !(localDns ? detour);
true
)
(
let
remoteDns = dnsServerByTag dnsRemoteOverrideConfig "remote";
in
assert remoteDns.type == "tls";
assert remoteDns.server == "1.0.0.1";
assert remoteDns.server_port == 853;
assert remoteDns.detour == "proxy";
true
)
# -- block route geosite and geoip sets are emitted --
(
assert hasRuleSet blockGeoRules "block" "geosite-category-ads-all";
true
)
(
assert hasRuleSet blockGeoRules "block" "geoip-cn";
true
)
];
}
Loaded 100 of 179 files, more files were not shown because too many files have changed in this diff. Show more