78 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
FUFSoB 22ebfa171d chore: remove xray warning 2026-06-20 18:05:50 +05:00
FUFSoB 190ba24ce6 feat: update tg-ws-proxy and its options 2026-06-20 17:48:22 +05:00
FUFSoB 1f5e050cb2 fix: various fixes 2026-06-20 17:11:35 +05:00
FUFSoB 5b5598d12e fix: attempt to mitigate client<-server dropped packages 2026-06-18 20:15:05 +05:00
FUFSoB ce86e5669b fix: different xray fixes 2026-06-18 12:53:35 +05:00
FUFSoB 759bde8b29 fix: xhttp-reality parsing 2026-06-18 12:19:17 +05:00
FUFSoB 433a13ccad fix: truly fixing xray tun 2026-06-09 19:35:48 +05:00
FUFSoB f060c4cd5e fix: tun not working on xray backend 2026-06-08 00:00:08 +05:00
FUFSoB 39ce4d6be2 feat(wip): xray proxy backend 2026-06-07 18:15:37 +05:00
FUFSoB 377d974a18 fix: remove global zapret enable req for perApp zapret 2026-06-07 13:21:09 +05:00
FUFSoB 32bf2266c0 fix: vless fixes 2026-06-06 13:47:59 +05:00
github-actions[bot]andFUFSoB 334755fd0e chore(deps): refresh flakes and external pins (#4)
Co-authored-by: FUFSoB <32937947+FUFSoB@users.noreply.github.com>
2026-06-05 08:32:58 +05:00
FUFSoB 6025e463a5 fix: zapret and other services started before network was fully established 2026-05-30 18:31:48 +05:00
FUFSoB 110e33bc27 fix: tun not working 2026-05-18 18:25:08 +05:00
FUFSoB 86e229ff4c other fixes 2026-05-18 11:03:10 +05:00
FUFSoB 70c0454446 various fixes 2026-05-18 09:18:21 +05:00
github-actions[bot]andFUFSoB 1198a63f3e chore(deps): refresh flakes and external pins (#3)
Co-authored-by: FUFSoB <32937947+FUFSoB@users.noreply.github.com>
2026-05-13 23:08:42 +05:00
FUFSoB fc95f71292 feat: toggle current proxy mode 2026-04-30 19:49:58 +05:00
github-actions[bot]andFUFSoB 148f2bf2a2 chore(deps): refresh flakes and external pins (#2)
Co-authored-by: FUFSoB <32937947+FUFSoB@users.noreply.github.com>
2026-04-27 13:33:01 +05:00
FUFSoB bcc64b3a1b add license file 2026-04-26 21:18:22 +05:00
FUFSoB 43935daeb1 add optional user/password for sing-box 2026-04-22 17:29:12 +05:00
FUFSoB b696821d8c small fixes 2026-04-22 16:02:31 +05:00
FUFSoB 65e815e6dc change tunnel tray icon color 2026-04-19 14:02:57 +05:00
FUFSoB 676fa65747 small fixup 2026-04-19 13:46:47 +05:00
FUFSoB 4d6802e194 formatting 2026-04-19 12:11:01 +05:00
FUFSoB 744a769e73 extra refactoring 2026-04-19 12:09:21 +05:00
FUFSoB 078367d919 another round of refactoring 2026-04-19 11:02:55 +05:00
FUFSoB 716fe4b18d other improvements 2026-04-18 15:12:55 +05:00
FUFSoB 189cf4412d packages improvement 2026-04-18 13:36:35 +05:00
FUFSoB af2121412b proxy-ctl movement, generate help message 2026-04-18 12:47:38 +05:00
FUFSoB d6cbea79bf change default tg-ws-proxy port 2026-04-18 12:06:47 +05:00
FUFSoB 93e792f2e5 breaking options changes, refactor 2026-04-16 23:27:05 +05:00
FUFSoB ba7560bfac second refactor 2026-04-16 18:09:34 +05:00
FUFSoB b6bde24d2d refactor 2026-04-16 12:45:27 +05:00
FUFSoB 1860928c9c add curated default config 2026-04-15 19:00:04 +05:00
FUFSoB 415336e618 small fix 2026-04-15 18:11:57 +05:00
github-actions[bot]andFUFSoB f77f306acb chore(deps): refresh flakes and external pins (#1)
Co-authored-by: FUFSoB <32937947+FUFSoB@users.noreply.github.com>
2026-04-15 17:59:39 +05:00
FUFSoB 476b3fc21e fix gh actions 2026-04-15 17:43:23 +05:00
FUFSoB 5e69502382 small tray refine 2026-04-15 15:43:36 +05:00
FUFSoB d3ef8257ab github actions 2026-04-15 15:29:23 +05:00
FUFSoB f54ae974ef more internal updates 2026-04-15 14:49:13 +05:00
FUFSoB d3c68f7a9a some simplifications and improvements 2026-04-15 13:43:18 +05:00
FUFSoB fe41f56cc5 update system tray 2026-04-15 13:07:42 +05:00
FUFSoB eeea6c161d move userControl to root options 2026-04-15 11:07:46 +05:00
FUFSoB 8d4779481c allow using all privileged proxy-ctl command for group proxy-suite 2026-04-14 22:57:41 +05:00
FUFSoB de33512c88 update docs on per-app 2026-04-14 22:51:31 +05:00
FUFSoB 435c908663 per-app zapret 2026-04-14 22:50:27 +05:00
FUFSoB c3f4088458 per-app tproxy 2026-04-14 18:40:03 +05:00
FUFSoB 14557eba82 per-app tun 2026-04-14 18:17:27 +05:00
FUFSoB 181f3355c1 proxychains integration, proxy-ctl wrap 2026-04-14 14:49:32 +05:00
FUFSoB e6c7b1a817 Fix README 2026-04-14 10:59:16 +05:00
FUFSoB 981745bafb more docs improvements 2026-04-13 18:39:08 +05:00
FUFSoB 215958b367 make dns configurable 2026-04-13 17:26:48 +05:00
FUFSoB 5f45041e4c small readme clarification 2026-04-13 17:11:35 +05:00
FUFSoB 2ba1167d69 make default tg-ws-proxy host local-only 2026-04-13 17:03:51 +05:00
FUFSoB b8496a5737 add tproxy/tun autostart option 2026-04-13 16:58:33 +05:00
FUFSoB aac8e8d17d refined docs 2026-04-13 16:48:40 +05:00
FUFSoB 1eebbfdc21 update tg-ws-proxy package 2026-04-12 20:24:52 +05:00
186 changed files with 31588 additions and 4580 deletions

No files matched your search

+121
View File
@@ -0,0 +1,121 @@
name: Dependency updates
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
pull-requests: write
concurrency:
group: dependency-updates
cancel-in-progress: false
jobs:
update-dependencies:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Install Nix
uses: DeterminateSystems/nix-installer-action@v22
- name: Decide whether nixpkgs should be updated
id: nixpkgs_gate
run: |
set -euo pipefail
scripts/check-nixpkgs-relevance.sh >> "$GITHUB_OUTPUT"
- name: Update flake inputs
run: |
set -euo pipefail
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 update zapret
- name: Update pinned sources
env:
GITHUB_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
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; 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 --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'
uses: peter-evans/create-pull-request@v8
with:
branch: ci/update-dependencies
delete-branch: false
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
- name: No dependency changes
if: steps.changes.outputs.has_changes != 'true'
run: echo "No dependency updates detected."
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 FUFSoB
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+108 -497
View File
@@ -1,531 +1,142 @@
# proxy-suite-flake
Declarative proxy stack for NixOS. One flake, one module, done.
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), [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, throne and their ilk – 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` by default – always running, always available to apps
- **Transparent proxy (TProxy)** – redirect all system traffic through sing-box without configuring each app; start/stop on demand
- **TUN mode** – full tunnel via a virtual network interface; useful when TProxy doesn't cover something
- **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, TUIC v5, socks5, socks4, http/https proxy
- **`proxy-ctl`** – control script for managing services, switching outbounds, and following logs
- **DPI bypass** via zapret – handles YouTube, Discord, and other sites that are blocked by packet inspection rather than IP
- **Telegram proxy** – 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
imports = [ inputs.proxy-suite.nixosModules.default ];
modules = [ inputs.proxy-suite.nixosModules.default ];
```
---
## Basic configuration
Starter config:
```nix
services.proxy-suite = {
enable = true;
singBox = {
outbounds = [
{
tag = "vps";
# Runtime secret – not in the nix store.
# Works with sops-nix, agenix, or anything that gives you a file path.
urlFile = config.sops.secrets.proxy_url.path;
}
];
routing = {
# Default: send RU geosite/geoip traffic direct.
enableRuDirect = true;
direct.domains = [ "reddit.com" ];
};
routing.proxy.geosites = [ "google" ];
};
zapret = {
proxy = {
enable = true;
# Default: mirror zapret domain lists into sing-box direct routing.
syncDirectRouting = true;
# Upstream zapret IP ranges are much broader, so keep them opt-in.
syncDirectRoutingUpstreamIps = false;
# User-defined ipsetAll/ipsetExclude still map into sing-box by default.
syncDirectRoutingUserIps = true;
backend = "sing-box"; # or "xray", or "hybrid"
# 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
tproxy.enable = true;
tun.enable = true;
};
};
```
After `nixos-rebuild switch`, you have a SOCKS proxy at `localhost:1080`.
If you intentionally want to expose it on another interface, set:
```nix
services.proxy-suite.singBox.listenAddress = "0.0.0.0";
```
To also start transparent proxying:
```bash
systemctl start proxy-suite-tproxy
```
TProxy installs its own nftables interception rules and can coexist with the NixOS firewall.
---
## Outbound formats
Each outbound needs exactly one of `urlFile`, `url`, or `json`.
### urlFile (recommended for real credentials)
```nix
outbounds = [{
tag = "vps";
urlFile = config.sops.secrets.my_vps_url.path;
}];
```
The URL is read at service start time. Never touches the nix store.
### url (convenient, not secret)
```nix
outbounds = [{
tag = "vps";
url = "hy2://yourpassword@your-server.com:443?sni=your-server.com";
}];
```
The URL string ends up in `/nix/store`. Fine for non-sensitive configs or testing.
### json (full sing-box outbound attrset)
```nix
outbounds = [{
tag = "vps";
json = {
type = "vless";
server = "your-server.com";
server_port = 443;
uuid = "your-uuid";
tls = {
enabled = true;
server_name = "your-server.com";
reality = {
enabled = true;
public_key = "your-public-key";
short_id = "abc123";
};
};
};
}];
```
Embedded at build time. Good when you generate the config programmatically.
---
## Multiple outbounds
```nix
singBox = {
outbounds = [
{ tag = "de"; urlFile = config.sops.secrets.vps_de.path; }
{ tag = "nl"; urlFile = config.sops.secrets.vps_nl.path; }
];
# Auto-select the fastest (checks every 3 minutes)
selection = "urltest";
# Or expose a Clash-compatible API for manual switching:
# selection = "selector";
# clashApiPort = 9090; # then use a Clash controller UI
};
```
---
## Subscription URLs
A subscription URL is an HTTP endpoint that returns a base64-encoded newline-separated list of proxy URIs — the standard format used by v2rayN, Clash, and similar clients. All supported proxy schemes (VLESS, VMess, Trojan, Shadowsocks, Hysteria2, TUIC, SOCKS5, HTTP…) can appear in the same subscription.
```nix
singBox = {
subscriptions = [
{
tag = "community";
url = "https://example.com/sub/your-token";
}
];
# urltest is strongly recommended for subscriptions: sing-box probes all proxies
# concurrently and routes through the fastest working one. With selection = "first"
# a single dead server in position 0 breaks everything.
selection = "urltest";
subscriptionUpdateInterval = "6h"; # refresh every 6 hours (default: 1d)
# Optional: test against a URL that is actually blocked in your region.
# Only proxies that bypass the block will win — not just any reachable server.
# Defaults to https://www.gstatic.com/generate_204 (reachability check only).
urlTest.url = "https://telegram.org/";
};
```
Use `urlFile` instead of `url` to keep the subscription URL out of the nix store:
```nix
subscriptions = [{
tag = "private";
urlFile = config.sops.secrets.sub_url.path;
}];
```
### How it works
**First start:** the service fetches the subscription URL live and writes the parsed outbounds to `/var/lib/proxy-suite/subscriptions/<tag>.json`.
**Subsequent starts:** the cache file is used directly — no network access on restart.
**Periodic refresh:** a systemd timer (`proxy-suite-subscription-update`) fires on boot (after 5 minutes) and then every `subscriptionUpdateInterval`. On success it updates the cache files and restarts `proxy-suite-socks` (and `proxy-suite-tun` if it is active).
### urltest startup behavior
When `selection = "urltest"`, sing-box starts probing all proxies **concurrently** the moment the service comes up. Until the first test result arrives (typically within a few seconds), traffic uses the first proxy in the list. As tests complete, sing-box progressively switches to faster winners. Dead proxies are skipped as their tests time out.
**Practical consequence:** the first few requests after a (re)start may go through a slow or unreachable proxy. This resolves quickly — usually within 5–20 seconds — without any manual action.
To minimize this window, set `urlTest.url` to a URL that must actually be reachable through a working proxy (e.g. a blocked site in your region). This way the first working test result corresponds to a proxy that genuinely serves your traffic, not just any reachable server.
### Tag generation
Each proxy URI in the subscription gets a sing-box outbound tag derived from its `#remark` fragment:
```
<subscription-tag>-<slugified-remark>
```
For example, a subscription with `tag = "sub"` and a proxy remarked `Server DE #1` becomes `sub-Server-DE--1`. URIs without a remark get `sub-0`, `sub-1`, etc. Duplicate tags are suffixed with `-2`, `-3`, and so on.
### Routing domains through subscription proxies
Routing rules that point to `"proxy"` automatically use whatever subscription proxy is currently active. With `selection = "urltest"`, the fastest subscription proxy handles those domains. With `selection = "selector"`, the manually chosen one does.
```nix
singBox = {
subscriptions = [{ tag = "community"; url = "https://example.com/sub/token"; }];
selection = "urltest";
# These domains go through whichever community proxy wins the latency test.
routing.proxy.domains = [ "telegram.org" "twitter.com" ];
};
```
You **cannot** route specific domains to "a named group of proxies from subscription X" — subscription tags are generated at runtime and are unknown at Nix eval time. If you need to pin a domain to a specific proxy, use `selection = "selector"`, switch to that proxy via `proxy-ctl select <tag>`, and all routing rules pointing to `"proxy"` will follow.
### Mixing subscriptions with static outbounds
Subscriptions and static outbound declarations can coexist. Subscription outbounds are appended after static ones, so with `selection = "selector"` or `"urltest"` all of them are available:
```nix
singBox = {
outbounds = [
{ tag = "own-vps"; urlFile = config.sops.secrets.vps.path; }
];
subscriptions = [
{ tag = "backup"; url = "https://example.com/sub/token"; }
];
selection = "urltest";
};
```
### `selection = "first"` with subscriptions
With `selection = "first"` and static outbounds, the first static outbound is used (as usual). With `selection = "first"` and **subscriptions only**, the first proxy from the first subscription is used as `proxy`.
---
## Per-outbound routing
By default all proxied traffic goes to whatever the active outbound is (the selector, urltest winner, or single "first" outbound). You can override this per-outbound or with explicit rules to send specific traffic to a specific server.
Global direct routing also has two built-in behaviors:
- `singBox.routing.enableRuDirect = true` sends `geosite-category-ru` and `geoip-ru` direct by default.
- If `zapret.enable = true`, then `zapret.syncDirectRouting = true` mirrors zapret's upstream domain hostlists into sing-box direct rules. `zapret.syncDirectRoutingUpstreamIps = false` by default, so upstream zapret IP ranges are not mirrored unless you opt in, while `zapret.syncDirectRoutingUserIps = true` keeps user `ipsetAll`/`ipsetExclude` mirrored by default.
**Attached to an outbound:**
```nix
outbounds = [
{
tag = "de";
urlFile = config.sops.secrets.vps_de.path;
# Only meaningful with selection = "selector" or "urltest"
routing.geosites = [ "netflix" ];
routing.geoips = [ "us" ];
routing.domains = [ "hulu.com" "peacocktv.com" ];
}
{
tag = "nl";
urlFile = config.sops.secrets.vps_nl.path;
routing.domains = [ "discord.com" "discordapp.com" ];
}
];
```
**Explicit rules list** – also works for `direct` and `block`, in any selection mode:
```nix
singBox.routing.rules = [
# Block ad networks before anything else
{ outbound = "block"; geosites = [ "category-ads-all" ]; }
# Internal traffic goes direct
{ outbound = "direct"; domains = [ "corp.internal" ]; ips = [ "10.0.0.0/8" ]; }
# Route US ips and Netflix to a specific server
{ outbound = "de"; geoips = [ "us" ]; geosites = [ "netflix" ]; }
];
```
Rules from `outbound.routing` and `routing.rules` are evaluated **before** the global `routing.proxy` / `routing.direct` / `routing.block` lists, so they always take priority.
Within a single rule, `domains`, `ips`, `geosites`, and `geoips` are treated as independent matches. In practice that means one rule with multiple fields behaves like OR, not AND.
In `first` selection mode, per-outbound tags are resolved to `"proxy"` automatically (there's only one proxy outbound in that mode, so routing to a specific tag doesn't make sense).
---
## proxy-ctl
A control script is installed into your system packages automatically. Run it as root or with the right polkit permissions.
```
proxy-ctl status show status of all proxy-suite services
proxy-ctl tproxy on|off enable/disable TProxy transparent mode
proxy-ctl tun on|off enable/disable TUN mode
proxy-ctl restart restart proxy-suite-socks, and proxy-suite-tun if it is active
proxy-ctl logs [service] follow logs (default: proxy-suite-socks)
proxy-ctl outbounds list outbounds and current selection (needs Clash API)
proxy-ctl select <tag> switch to a specific outbound (selector mode)
proxy-ctl subscription list show subscriptions, cache age, and proxy count
proxy-ctl subscription update force-refresh all subscription caches and restart
```
`outbounds` works with `selection = "selector"` or `"urltest"`. `select` requires `selection = "selector"` and talks to the Clash-compatible REST API embedded in sing-box.
`subscription list` and `subscription update` are only meaningful when `singBox.subscriptions` is non-empty.
---
## Protocol URL formats
| Protocol | Example URL |
| --------------- | ------------------------------------------------------------------------------------------------ |
| VLESS + Reality | `vless://uuid@host:443?security=reality&pbk=KEY&fp=chrome&sni=SNI&sid=abc&flow=xtls-rprx-vision` |
| VLESS + TLS | `vless://uuid@host:443?security=tls&sni=SNI&type=ws&path=/path` |
| VMess | `vmess://BASE64_JSON` (standard V2 link format) |
| Trojan | `trojan://password@host:443?sni=SNI&fp=chrome` |
| Shadowsocks | `ss://BASE64(method:password)@host:port` or `ss://method:password@host:port` |
| Hysteria2 | `hy2://password@host:443?sni=SNI` |
| TUIC v5 | `tuic://uuid:password@host:443?sni=SNI&congestion_control=bbr` |
| SOCKS5 | `socks5://user:pass@host:1080` or `socks5://host:1080` |
| SOCKS4 | `socks4://host:1080` |
| HTTP proxy | `http://user:pass@host:8080` |
| HTTPS proxy | `https://host:8080` (HTTP CONNECT over TLS) |
---
## Zapret
zapret handles DPI-based blocking by mangling packets at the netfilter level. It's separate from the proxy, but by default this module also mirrors zapret-covered domains into sing-box direct routing so the proxy does not fight zapret for the same traffic.
```nix
zapret = {
enable = true;
configName = "general(ALT)";
syncDirectRouting = true; # default: sync upstream domain lists
syncDirectRoutingUpstreamIps = false; # default: do not sync upstream IP ranges
syncDirectRoutingUserIps = true; # default: do sync user ipsetAll/ipsetExclude
# Extra domains beyond zapret's built-in list
listGeneral = [ "pixiv.net" "pximg.net" ];
};
```
When `syncDirectRouting = true`, the module always reuses zapret's upstream `hostlists/list-general.txt` and `list-google.txt`, adds your `listGeneral`, and subtracts both upstream and user domain exclusions before generating sing-box direct rules. If `zapret.includeExtraUpstreamLists = true`, it also includes upstream `list-instagram.txt`, `list-soundcloud.txt`, and `list-twitter.txt` in both zapret handling and sing-box direct sync.
Custom `zapret.hostlistRules` domains also join this direct-domain sync by default. Set `enableDirectSync = false` on a custom hostlist if you want zapret to handle it but do not want sing-box direct-routing rules generated from it.
The generated zapret config can also auto-activate upstream `list-instagram.txt`, `list-soundcloud.txt`, and `list-twitter.txt` when the selected upstream preset does not already reference them. They are attached using the active config's `general` rule family so those hostlists are actually handled by zapret instead of just existing on disk. This is disabled by default; set `zapret.includeExtraUpstreamLists = true;` to opt in.
When `syncDirectRoutingUpstreamIps = true`, the module also mirrors zapret's upstream `ipset-all.txt`. This is disabled by default because the upstream IP set is intentionally broad.
When `syncDirectRoutingUserIps = true`, the module mirrors your `ipsetAll` and `ipsetExclude` values into sing-box direct routing even if upstream IP sync stays disabled. This is enabled by default.
If zapret corrupts traffic for some subnet (e.g. a VM behind a libvirt bridge):
```nix
zapret.cidrExemption = {
enable = true;
cidrs = [ "192.168.123.0/24" ]; # your VM's bridge network(s)
};
```
You can also define custom zapret hostlists with per-list rules:
```nix
zapret.hostlistRules = [
{
name = "googlevideo";
domains = [ "googlevideo.com" "ggpht.com" ];
preset = "google";
}
{
name = "example";
domains = [ "example.com" "example.de" ];
nfqwsArgs = [
"--filter-tcp=443 --dpi-desync=fake,multisplit"
];
}
{
name = "social-extra";
domains = [ "x.example" ];
preset = "twitter";
nfqwsArgs = [
"--filter-udp=443 --dpi-desync=fake --dpi-desync-repeats=6"
];
}
];
```
Each entry generates `hostlists/list-<name>.txt`. `preset` clones the active zapret config's matching family rules for that hostlist, while `nfqwsArgs` appends custom NFQWS rule fragments. The module injects the generated `--hostlist=...`, standard zapret exclude files, and trailing `--new` automatically.
---
## Telegram proxy
Runs a WebSocket MTProto relay. Useful for sharing with others on mobile or for clients that need a dedicated Telegram proxy.
```nix
tgWsProxy = {
enable = true;
# Generate a secret: openssl rand -hex 16
secretFile = config.sops.secrets.tg_ws_proxy_secret.path;
port = 1076;
host = "0.0.0.0"; # configurable bind address
};
```
`secretFile` is the recommended form because it keeps the secret out of the nix store. The legacy inline `secret = "...";` form still works for testing.
---
## Services
| Service | Auto-starts | Description |
| --------------------------------- | ------------------ | ------------------------------------------------ |
| `proxy-suite-socks` | yes | SOCKS5/HTTP proxy, always running |
| `proxy-suite-tproxy` | no | TProxy transparent mode (start manually) |
| `proxy-suite-tun` | no | TUN mode (start manually, conflicts with tproxy) |
| `proxy-suite-tg-ws-proxy` | yes (if enabled) | Telegram proxy |
| `proxy-suite-zapret-vm-exempt` | yes (if enabled) | VM subnet exemption |
| `proxy-suite-subscription-update` | timer (if sub set) | Refresh subscription caches and restart |
TProxy and TUN are mutually exclusive. Start one, the other refuses to start.
---
## Secret management
This module doesn't care how you manage secrets. Anything that gives you a file path works:
**sops-nix:**
```nix
sops.secrets.proxy_url.sopsFile = ./secrets/proxy.yaml;
services.proxy-suite.singBox.outbounds = [{
tag = "vps";
urlFile = config.sops.secrets.proxy_url.path;
}];
```
**agenix:**
```nix
age.secrets.proxy_url.file = ./secrets/proxy_url.age;
services.proxy-suite.singBox.outbounds = [{
tag = "vps";
urlFile = config.age.secrets.proxy_url.path;
}];
```
**Plain file (not recommended but works):**
```nix
# Create /run/proxy-url with your URL, ensure it's readable by root
urlFile = "/run/proxy-url";
```
---
## System tray
Optional tray indicator for desktop environments. Shows proxy status and provides quick toggles.
```nix
services.proxy-suite = {
tray = {
perAppRouting = {
enable = true;
autostart = true; # Install XDG autostart for all graphical users (default)
pollInterval = 5; # Status refresh interval in seconds
createDefaultProfiles = true;
proxychains.enable = true;
tun.enable = true;
tproxy.enable = true;
zapret.enable = true;
};
zapret.enable = true;
sshProxy = {
enable = 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;
secretFile = "/run/secrets/tg-ws-proxy-secret";
};
tray.enable = true;
};
```
Features:
---
- **Status icon**: `network-vpn` (active), `network-vpn-acquiring` (partial), `network-vpn-disconnected` (stopped)
- **Quick controls window**: Opens on secondary activation and on hosts that emit StatusNotifier `Activate` on left-click (including niri)
- **Enable/Disable Proxy**: Toggles `proxy-suite-socks`; disabling proxy also stops active TProxy/TUN first
- **Toggle TProxy/TUN**: Only shown if the service is enabled in your config
- **Close window**: Hides the floating controls window without exiting the tray
- **Update Subscriptions**: Triggers `proxy-suite-subscription-update` to re-fetch all subscription caches; only shown when subscriptions are configured
- **Restart services**: Restarts `proxy-suite-socks`, and `proxy-suite-tun` if it is active
- **Polkit authentication**: Prompts for password when toggling services
## Options
When enabled, the tray app is installed system-wide and autostarts for all graphical users via XDG autostart unless you set `tray.autostart = false;`.
See the [options reference](./docs/options/index.md), one page per option group. Regenerate it and the help below with `nix run .#update-docs`.
The tray uses libayatana-appindicator and requires StatusNotifier/AppIndicator support. KDE generally works out of the box; GNOME may need shell support or an extension that exposes AppIndicators.
## `proxy-ctl help`
To enable TProxy/TUN toggles in the tray, you need to enable the services in your config:
<!-- proxy-ctl-help:start -->
```text
Usage: proxy-ctl <group> [verb] [args]
A group without a verb shows its status or list.
```nix
services.proxy-suite.singBox = {
tproxy.enable = true; # Show TProxy toggle
tun.enable = true; # Show TUN toggle
};
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 -->
+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": 1775710090,
"narHash": "sha256-ar3rofg+awPB8QXDaFJhJ2jJhu+KqN/PRCXeyuXR76E=",
"lastModified": 1788614874,
"narHash": "sha256-7QYjT2vHLuX9Z1pdxHXDKCbh1CR3D/2rywB9Tx0MPRg=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "4c1018dae018162ec878d42fec712642d214fdfa",
"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": 1775231936,
"narHash": "sha256-jvyi6D2Ps0zicpIcn24tacIymQOyUVY6lr6B5RLQkx8=",
"lastModified": 1788726932,
"narHash": "sha256-MehJgJpN7BGMaDES9I0aj/YG6JkRlSj5RiZDZfclNpc=",
"owner": "kartavkun",
"repo": "zapret-discord-youtube",
"rev": "b3e3f854f8d9cf35ddbcbfa7a03cb0a1334dd7eb",
"rev": "64a8ee76f4f2e4a8d2751cb732f13448ee1e4fcf",
"type": "github"
},
"original": {
@@ -80,11 +46,11 @@
"zapret-flowseal": {
"flake": false,
"locked": {
"lastModified": 1775228068,
"narHash": "sha256-LAbCZRwoGxQcgO1nio33NlxBXIdsTQJxHQxu1RWctIA=",
"lastModified": 1788121958,
"narHash": "sha256-WMpxbtA2OH340e4uuXR0tcUW0D6V9Kzs0KI1iKqkXBM=",
"owner": "Flowseal",
"repo": "zapret-discord-youtube",
"rev": "22a9ca3bc067441789c83bd80c00d38e54be51c4",
"rev": "6cec828910d0809863205702182a3557d9d0e8c3",
"type": "github"
},
"original": {
+93 -7
View File
@@ -1,5 +1,5 @@
{
description = "NixOS proxy suite – sing-box, 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,18 @@
];
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;
};
mkReadmeDoc = import ./nix/readme-doc.nix {
inherit
nixpkgs
pkgsFor
proxySuiteModule
zapret
;
};
in
{
# Main module – bakes in the zapret flake so consumers don't need it as a separate input.
@@ -32,13 +43,86 @@
nixosModules.zapret = zapret.nixosModules.default;
overlays.default = final: prev: {
tg-ws-proxy = import ./pkgs/tg-ws-proxy.nix { pkgs = final; };
proxy-suite-tray = import ./pkgs/proxy-suite-tray.nix { pkgs = final; };
inherit (import ./pkgs/default.nix { pkgs = final; })
amneziawg-tools
amneziawg-go
mkProxyCtl
mkProxySuiteTray
mkTgWsProxy
tg-ws-proxy
proxy-suite-tray
zapret2
;
};
packages = forAll (system: {
tg-ws-proxy = import ./pkgs/tg-ws-proxy.nix { pkgs = pkgsFor system; };
proxy-suite-tray = import ./pkgs/proxy-suite-tray.nix { pkgs = pkgsFor system; };
packages = forAll (
system:
let
pkgs = pkgsFor system;
suitePkgs = import ./pkgs/default.nix { inherit pkgs; };
updateDocs = pkgs.writeShellApplication {
name = "update-docs";
runtimeInputs = [
pkgs.coreutils
pkgs.git
pkgs.nix
];
text = ''
set -euo pipefail
repo_root="$(git rev-parse --show-toplevel 2>/dev/null || true)"
if [[ -z "''${repo_root}" || ! -f "''${repo_root}/flake.nix" ]]; then
echo "run this helper from inside the proxy-suite-flake repository" >&2
exit 1
fi
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")"
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/"
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;
update-options-doc = pkgs.writeShellApplication {
name = "update-options-doc";
runtimeInputs = [ updateDocs ];
text = ''
exec ${updateDocs}/bin/update-docs "$@"
'';
};
}
);
apps = forAll (system: {
update-docs = {
type = "app";
program = "${self.packages.${system}.update-docs}/bin/update-docs";
meta.description = "Update generated docs and README help from current NixOS module outputs";
};
update-options-doc = {
type = "app";
program = "${self.packages.${system}.update-options-doc}/bin/update-options-doc";
meta.description = "Compatibility alias for update-docs";
};
});
checks = forAll (
@@ -50,6 +134,8 @@
proxySuiteModule
zapret
;
generatedOptionsDoc = mkOptionsDoc system;
generatedReadmeDoc = mkReadmeDoc system;
}
);
};
+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;
};
}
+74 -113
View File
@@ -1,5 +1,5 @@
# Build-time sing-box configuration templates.
# The proxy outbound(s) are injected at service start time, not here.
# Build-time proxy backend configuration templates.
# Proxy outbounds are injected at service start time, not here.
{
lib,
pkgs,
@@ -8,126 +8,87 @@
}:
let
sb = cfg.singBox;
direct = rules.direct;
clashApiBlock = lib.optionalAttrs (sb.selection != "first") {
experimental = {
clash_api = {
external_controller = "127.0.0.1:${toString sb.clashApiPort}";
};
};
derived = import ./derived.nix { inherit lib cfg; };
singBoxTemplates = import ./config-templates/sing-box.nix {
inherit
lib
derived
rules
;
};
xrayTemplates = import ./config-templates/xray.nix {
inherit
lib
derived
rules
;
};
dnsConfig = {
servers = [
{
tag = "remote";
type = "udp";
server = "1.1.1.1";
detour = "proxy";
}
{
tag = "local";
type = "udp";
server = "1.1.1.1";
# In TUN mode, routing DNS through direct can conflict with auto_redirect.
# In TProxy/mixed mode, direct is fine for local traffic.
detour = "direct";
}
];
rules =
lib.optional (builtins.elem "google" sb.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 sb.proxyByDefault then "remote" else "local";
inboundRules = import ./rules/proxy-inbounds.nix {
inherit lib;
inherit (derived) proxyInboundsCfg proxyInbounds;
inherit (rules) zapretDirectRules;
};
dnsConfigTun = dnsConfig // {
servers = map (s: if s.tag == "local" then s // { detour = "proxy"; } else s) dnsConfig.servers;
proxyInboundsTemplate = import ./config-templates/proxy-inbounds.nix {
inherit lib derived inboundRules;
inherit (xrayTemplates) mkDnsServer;
};
mkConfig =
{
enableMixed ? false,
enableTProxy ? false,
enableTun ? false,
useOutboundRoutingMark ? false,
}:
{
log.level = "warn";
dns = if enableTun then dnsConfigTun else dnsConfig;
inbounds =
lib.optional enableMixed {
type = "mixed";
tag = "mixed-in";
listen = sb.listenAddress;
listen_port = sb.port;
}
++ lib.optional enableTProxy {
type = "tproxy";
tag = "tproxy-in";
listen = "127.0.0.1";
listen_port = sb.tproxyPort;
}
++ lib.optional enableTun {
type = "tun";
tag = "tun-in";
interface_name = sb.tun.interface;
address = [ sb.tun.address ];
mtu = sb.tun.mtu;
auto_route = true;
auto_redirect = true;
strict_route = true;
stack = "mixed";
};
# proxy outbound(s) are prepended at runtime by the start script
outbounds = [
(
{
type = "direct";
tag = "direct";
}
// lib.optionalAttrs useOutboundRoutingMark { routing_mark = sb.proxyMark; }
)
{
type = "block";
tag = "block";
}
];
route = {
default_domain_resolver = "local";
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets;
rules = rules.routingRules;
final = if sb.proxyByDefault then "proxy" else "direct";
}
// lib.optionalAttrs enableTun { auto_detect_interface = true; };
}
// clashApiBlock;
tproxyTemplate = mkConfig {
enableMixed = true;
enableTProxy = true;
useOutboundRoutingMark = true;
# 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;
};
tunTemplate = mkConfig {
enableTun = true;
};
tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (builtins.toJSON tproxyTemplate);
tunFile = pkgs.writeText "proxy-suite-tun-template.json" (builtins.toJSON tunTemplate);
selectedTemplates = if derived.pureXrayEnabled then xrayTemplates else singBoxTemplates;
routeModeRules =
if derived.pureXrayEnabled then rules.xrayRouteModeRules else rules.singBoxRouteModeRules;
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 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 tproxyFile tunFile;
inherit
tproxyFile
tunFile
perAppTunFile
routeModeRulesFile
proxyInboundsFile
proxyInboundsSpecFile
;
}
+126 -51
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,
@@ -11,72 +12,146 @@
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.nix
# Always import the zapret module so its options are available,
# but we only activate services when cfg.zapret.enable = true.
zapret.nixosModules.default
./options
];
config = lib.mkIf cfg.enable (
lib.mkMerge [
(lib.mkIf cfg.singBox.enable (
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
rules = import ./rules.nix {
inherit
lib
pkgs
cfg
zapret
;
};
configs = import ./config.nix {
inherit
lib
pkgs
cfg
rules
;
};
nftr = import ./nftables.nix { inherit lib pkgs cfg; };
upstream = nixpkgs.legacyPackages.${pkgs.stdenv.hostPlatform.system};
in
import ./service.nix {
inherit
config
lib
pkgs
cfg
;
inherit (configs) tproxyFile tunFile;
inherit (nftr) nftablesRulesFile ip nft;
}
))
{
xray = import ../../pkgs/xray.nix { pkgs = upstream; };
inherit (upstream) sing-box;
};
}
(lib.mkIf cfg.zapret.enable (
import ./zapret.nix {
(lib.mkIf cfg.enable (
let
rules = import ./rules.nix {
inherit
lib
pkgs
cfg
zapret
;
}
))
(lib.mkIf cfg.tgWsProxy.enable (import ./tg-ws-proxy.nix { inherit lib pkgs cfg; }))
(lib.mkIf cfg.tray.enable (
import ./tray.nix {
};
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
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
;
}
))
]
))
];
}
+238
View File
@@ -0,0 +1,238 @@
{
lib,
cfg,
}:
let
proxyCfg = cfg.proxy;
singBoxCfg = proxyCfg // {
enable = singBoxEnabled;
package = proxyCfg.singBox.package;
clashApiPort = proxyCfg.singBox.clashApiPort;
};
xrayCfg = proxyCfg.xray;
proxyEnabled = proxyCfg.enable;
# "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 = 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 = [
"proxy"
"direct"
"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.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 ++ effectiveOutboundTags)
) proxyCfg.routing.rules
)
);
in
{
inherit
proxyCfg
singBoxCfg
xrayCfg
proxyEnabled
singBoxEnabled
xrayEnabled
hybridEnabled
pureSingBoxEnabled
pureXrayEnabled
activeBackend
perAppRoutingCfg
globalTun
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")))))
+114 -35
View File
@@ -6,46 +6,118 @@
}:
let
sb = cfg.singBox;
proxyCfg = cfg.proxy;
globalTproxy = proxyCfg.tproxy;
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.fwmark} return
'';
localSubnetLines = lib.concatMapStrings (cidr: ''
ip daddr ${cidr} tcp dport != 53 return
ip daddr ${cidr} udp dport != 53 return
'') sb.tproxy.localSubnets;
# Shared across all three nftables rule files that do IPv4 routing.
reservedIpBlock = ''
define RESERVED_IP = {
10.0.0.0/8,
100.64.0.0/10,
127.0.0.0/8,
169.254.0.0/16,
172.16.0.0/12,
192.0.0.0/24,
224.0.0.0/4,
240.0.0.0/4,
255.255.255.255/32
}
'';
mkLocalSubnetLines =
subnets:
lib.concatMapStrings (cidr: ''
ip daddr ${cidr} tcp dport != 53 return
ip daddr ${cidr} udp dport != 53 return
'') subnets;
tproxyLocalSubnetLines = mkLocalSubnetLines globalTproxy.localSubnets;
perAppTproxyLocalSubnetLines = mkLocalSubnetLines perAppTproxy.localSubnets;
nftablesRulesFile = pkgs.writeText "proxy-suite-tproxy.nft" ''
define RESERVED_IP = {
10.0.0.0/8,
100.64.0.0/10,
127.0.0.0/8,
169.254.0.0/16,
172.16.0.0/12,
192.0.0.0/24,
224.0.0.0/4,
240.0.0.0/4,
255.255.255.255/32
}
${reservedIpBlock}
table ip singbox {
chain prerouting {
type filter hook prerouting priority mangle; policy accept;
ip daddr $RESERVED_IP return
# Packets re-entering via loopback after output marking should not
# be skipped just because the host has an RFC1918 source address.
iifname != "lo" ip saddr $RESERVED_IP return
${tproxyLocalSubnetLines}
ip protocol tcp tproxy to 127.0.0.1:${toString globalTproxy.port} meta mark set ${toString globalTproxy.fwmark}
ip protocol udp tproxy to 127.0.0.1:${toString globalTproxy.port} meta mark set ${toString globalTproxy.fwmark}
}
chain output {
type route hook output priority mangle; policy accept;
ip daddr $RESERVED_IP return
${tproxyLocalSubnetLines}
meta mark ${toString globalTproxy.proxyMark} return
${tgWsProxyBypassMarkLine}${lib.optionalString perAppTun.enable " meta mark ${toString perAppTun.fwmark} return\n"}${lib.optionalString perAppTproxy.enable " meta mark ${toString perAppTproxy.fwmark} return\n"} ip protocol tcp meta mark set ${toString globalTproxy.fwmark}
ip protocol udp meta mark set ${toString globalTproxy.fwmark}
}
}
'';
table ip singbox {
chain prerouting {
type filter hook prerouting priority mangle; policy accept;
ip daddr $RESERVED_IP return
# Packets re-entering via loopback after output marking should not
# be skipped just because the host has an RFC1918 source address.
iifname != "lo" ip saddr $RESERVED_IP return
${localSubnetLines}
ip protocol tcp tproxy to 127.0.0.1:${toString sb.tproxyPort} meta mark set ${toString sb.fwmark}
ip protocol udp tproxy to 127.0.0.1:${toString sb.tproxyPort} meta mark set ${toString sb.fwmark}
perAppTproxyRulesFile = pkgs.writeText "proxy-suite-per-app-tproxy.nft" ''
${reservedIpBlock}
table ip proxy_suite_per_app_tproxy {
chain prerouting {
type filter hook prerouting priority mangle; policy accept;
ip daddr $RESERVED_IP return
iifname != "lo" ip saddr $RESERVED_IP return
${perAppTproxyLocalSubnetLines}
ct mark ${toString perAppTproxy.fwmark} meta mark set ${toString perAppTproxy.fwmark}
meta mark ${toString perAppTproxy.fwmark} ip protocol tcp tproxy to 127.0.0.1:${toString globalTproxy.port}
meta mark ${toString perAppTproxy.fwmark} ip protocol udp tproxy to 127.0.0.1:${toString globalTproxy.port}
}
chain output {
type route hook output priority mangle; policy accept;
ip daddr $RESERVED_IP return
${perAppTproxyLocalSubnetLines}
meta mark ${toString globalTproxy.proxyMark} return
${lib.optionalString perAppTun.enable " meta mark ${toString perAppTun.fwmark} return\n"} ct mark ${toString perAppTproxy.fwmark} meta mark set ${toString perAppTproxy.fwmark}
meta mark ${toString perAppTproxy.fwmark} return
}
}
chain output {
type route hook output priority mangle; policy accept;
ip daddr $RESERVED_IP return
${localSubnetLines}
meta mark ${toString sb.proxyMark} return
ip protocol tcp meta mark set ${toString sb.fwmark}
ip protocol udp meta mark set ${toString sb.fwmark}
'';
perAppZapretRulesFile = pkgs.writeText "proxy-suite-per-app-zapret.nft" ''
table inet proxy_suite_per_app_zapret_mark {
chain prerouting {
type filter hook prerouting priority -103; policy accept;
ct mark and ${toString zapretApp.filterMark} == ${toString zapretApp.filterMark} meta mark set meta mark or ${toString zapretApp.filterMark}
}
chain output {
type route hook output priority -103; policy accept;
ct mark and ${toString zapretApp.filterMark} == ${toString zapretApp.filterMark} meta mark set meta mark or ${toString zapretApp.filterMark}
meta mark and ${toString zapretApp.filterMark} == ${toString zapretApp.filterMark} return
}
}
'';
perAppTunChainFile = pkgs.writeText "proxy-suite-per-app-tun-chain.nft" ''
${reservedIpBlock}
table inet proxy_suite_per_app_tun {
chain output {
type route hook output priority mangle; policy accept;
ip daddr $RESERVED_IP return
${lib.concatMapStrings (cidr: ''
ip daddr ${cidr} return
'') perAppTun.localSubnets}
ct mark ${toString perAppTun.fwmark} meta mark set ${toString perAppTun.fwmark}
meta mark ${toString perAppTun.fwmark} return
}
}
}
'';
ip = "${pkgs.iproute2}/bin/ip";
@@ -53,5 +125,12 @@ let
in
{
inherit nftablesRulesFile ip nft;
inherit
nftablesRulesFile
perAppTproxyRulesFile
perAppZapretRulesFile
perAppTunChainFile
ip
nft
;
}
-686
View File
@@ -1,686 +0,0 @@
# All option declarations for services.proxy-suite
{ config, lib, ... }:
let
inherit (lib) mkOption mkEnableOption types;
# Shared routing-rule fields (reused in both outboundType.routing and routing.rules entries)
routingFields = {
domains = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Domain suffixes to match.";
example = [
"youtube.com"
"discord.com"
];
};
ips = mkOption {
type = types.listOf types.str;
default = [ ];
description = "IP CIDRs to match.";
example = [ "1.1.1.0/24" ];
};
geosites = mkOption {
type = types.listOf types.str;
default = [ ];
description = "sing-geosite rule-set names to match.";
example = [
"netflix"
"google"
];
};
geoips = mkOption {
type = types.listOf types.str;
default = [ ];
description = "sing-geoip rule-set names to match.";
example = [
"us"
"de"
];
};
};
# 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".
'';
example = "vps-de";
};
}
// routingFields;
};
subscriptionType = types.submodule {
options = {
tag = mkOption {
type = types.str;
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".
'';
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.
The URL will end up in the nix store. Use urlFile for actual secrets.
'';
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.
'';
example = "/run/secrets/my-sub-url";
};
};
};
outboundType = types.submodule {
options = {
tag = mkOption {
type = types.str;
description = "Outbound tag. Used in routing rules and multi-outbound selection.";
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.
Example with sops-nix:
urlFile = config.sops.secrets.my_proxy_url.path;
'';
};
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. Use urlFile for actual credentials.
'';
example = "hy2://password@example.com:443?sni=example.com";
};
json = 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.
'';
example = {
type = "vless";
server = "example.com";
server_port = 443;
uuid = "...";
};
};
# 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;
};
};
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 list-<name>.txt.";
example = "cloudflare";
};
domains = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Domains written into the generated custom zapret hostlist.";
example = [
"example.com"
"example.de"
];
};
preset = mkOption {
type = types.nullOr zapretPresetType;
default = null;
description = "Clone the active zapret config's built-in rule family for this hostlist.";
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.
'';
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 sing-box direct domain routing.";
};
};
};
in
{
options.services.proxy-suite = {
enable = mkEnableOption "proxy suite (sing-box + zapret + tg-ws-proxy)";
singBox = {
enable = mkOption {
type = types.bool;
default = true;
description = "Whether to configure and run sing-box.";
};
outbounds = mkOption {
type = types.listOf outboundType;
default = [ ];
description = ''
List of proxy outbounds. Set exactly one of urlFile, url, or json per entry.
At least one outbound (or one subscription) is required when singBox.enable = true.
'';
};
subscriptions = mkOption {
type = types.listOf 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 the subscription is fetched live. Subsequent starts
use the on-disk cache under /var/lib/proxy-suite/subscriptions/.
A systemd timer (proxy-suite-subscription-update) refreshes all caches on
the interval set by subscriptionUpdateInterval and restarts the service.
'';
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 subscriptions is non-empty.
'';
example = "6h";
};
selection = mkOption {
type = types.enum [
"first"
"selector"
"urltest"
];
default = "first";
description = ''
How to pick between multiple outbounds:
- "first": use the first outbound only (no overhead, simplest)
- "selector": expose a Clash-compatible API for manual switching
- "urltest": measure latency periodically and auto-switch to the fastest
'';
};
urlTest = {
url = mkOption {
type = types.str;
default = "https://www.gstatic.com/generate_204";
description = ''
URL that sing-box 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 sing-box re-tests all outbounds. Accepts a Go duration
string (e.g. "1m", "3m", "10m"). Only used when selection = "urltest".
'';
example = "1m";
};
tolerance = mkOption {
type = types.int;
default = 50;
description = ''
Latency tolerance in milliseconds. The current proxy is only replaced
when a competing one is faster by more than this value.
Only used when selection = "urltest".
'';
example = 100;
};
};
clashApiPort = mkOption {
type = types.port;
default = 9090;
description = "Port for the Clash-compatible REST API. Only used when selection is selector or urltest.";
};
listenAddress = mkOption {
type = types.str;
default = "127.0.0.1";
description = ''
Address for the SOCKS5/HTTP mixed inbound to bind to.
Use "0.0.0.0" only if you intentionally want to expose the proxy.
'';
};
port = mkOption {
type = types.port;
default = 1080;
description = "SOCKS5/HTTP mixed inbound listen port.";
};
tproxyPort = mkOption {
type = types.port;
default = 1081;
description = "Transparent proxy (TProxy) inbound listen port.";
};
fwmark = mkOption {
type = types.int;
default = 1;
description = "Netfilter mark set on packets intercepted by TProxy for policy routing.";
};
proxyMark = mkOption {
type = types.int;
default = 2;
description = "Netfilter mark set on sing-box's own outbound packets so they bypass TProxy re-interception.";
};
routeTable = mkOption {
type = types.int;
default = 100;
description = "Policy routing table used to redirect TProxy-marked packets to the loopback interface.";
};
proxyByDefault = mkOption {
type = types.bool;
default = true;
description = "If true, traffic not matching any routing rule goes through the proxy. If false, it goes direct.";
};
tun = {
enable = mkEnableOption "TUN mode service (opt-in, mutually exclusive with proxy-suite-tproxy)";
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.";
};
};
tproxy = {
enable = mkEnableOption "TProxy mode service (opt-in, transparent proxy via nftables)";
localSubnets = mkOption {
type = types.listOf types.str;
default = [ "192.168.0.0/16" ];
description = ''
Subnets whose traffic bypasses TProxy interception, except DNS (port 53).
Typically your LAN subnet(s). VM bridge networks should go here too,
or use zapret.cidrExemption for subnet-specific NFQUEUE exemption.
'';
example = [
"192.168.0.0/16"
"10.0.0.0/8"
];
};
};
routing = {
enableRuDirect = mkOption {
type = types.bool;
default = true;
description = "Automatically send sing-geosite category-ru and sing-geoip ru traffic direct.";
};
proxy = routingFields;
direct = {
domains = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Domain suffixes to send direct (bypass proxy).";
};
ips = mkOption {
type = types.listOf types.str;
default = [ ];
description = "IP CIDRs to send direct.";
};
geosites = mkOption {
type = types.listOf types.str;
default = [ ];
description = "sing-geosite names to send direct.";
};
geoips = mkOption {
type = types.listOf types.str;
default = [ ];
description = "sing-geoip names to send direct.";
};
};
block = {
domains = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Domain suffixes to block entirely.";
};
ips = mkOption {
type = types.listOf types.str;
default = [ ];
description = "IP CIDRs to block.";
};
geosites = mkOption {
type = types.listOf types.str;
default = [ ];
description = "sing-geosite names to block.";
};
geoips = mkOption {
type = types.listOf types.str;
default = [ ];
description = "sing-geoip names to block.";
};
};
# Per-outbound and per-action routing rules.
# These are evaluated before the global proxy/direct/block lists above.
# Use this for fine-grained control: route specific services to specific
# servers, or override the default for particular domains/IPs/geos.
#
# Alternatively, attach routing directly to an outbound via outbound.routing.*
# which is equivalent to adding an entry here with outbound = <that tag>.
#
# Order within this list is preserved (first matching rule wins in sing-box).
rules = mkOption {
type = types.listOf 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".
'';
example = [
{
outbound = "vps-de";
geosites = [ "netflix" ];
geoips = [ "us" ];
}
{
outbound = "direct";
domains = [ "internal.corp" ];
}
{
outbound = "block";
domains = [ "ads.example.com" ];
}
];
};
};
};
zapret = {
enable = mkEnableOption "zapret DPI bypass";
syncDirectRouting = mkOption {
type = types.bool;
default = true;
description = "When zapret is enabled, mirror its upstream domain hostlists into sing-box direct routing.";
};
syncDirectRoutingUpstreamIps = mkOption {
type = types.bool;
default = false;
description = "When zapret is enabled, mirror its upstream ipset ranges into sing-box direct routing.";
};
syncDirectRoutingUserIps = mkOption {
type = types.bool;
default = true;
description = "When zapret is enabled, mirror user-defined ipsetAll/ipsetExclude entries into sing-box direct routing.";
};
configName = mkOption {
type = types.str;
default = "general(ALT)";
description = "zapret strategy preset name.";
};
gameFilter = mkOption {
type = types.str;
default = "null";
description = ''zapret game traffic filter mode: "all", "tcp", "udp", or "null" to disable.'';
};
listGeneral = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Extra domains to include in zapret's interception list.";
};
listExclude = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Domains to exclude from zapret interception.";
};
ipsetAll = mkOption {
type = types.listOf types.str;
default = [ ];
description = "Extra IPs/CIDRs to add to zapret's ipset.";
};
ipsetExclude = mkOption {
type = types.listOf types.str;
default = [ ];
description = "IPs/CIDRs to exclude from zapret's ipset.";
};
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.
'';
};
hostlistRules = mkOption {
type = types.listOf 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.
'';
example = [
{
name = "googlevideo";
domains = [
"googlevideo.com"
"ggpht.com"
];
preset = "google";
}
{
name = "example";
domains = [
"example.com"
"example.de"
];
nfqwsArgs = [
"--filter-tcp=443 --dpi-desync=fake,multisplit"
];
}
];
};
cidrExemption = {
enable = mkEnableOption "CIDR exemption from zapret NFQUEUE";
cidrs = mkOption {
type = types.listOf types.str;
default = [ ];
example = [
"192.168.123.0/24"
"10.0.0.0/8"
];
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.
'';
};
};
};
tray = {
enable = mkEnableOption "system tray indicator for proxy-suite";
pollInterval = mkOption {
type = types.int;
default = 5;
description = "Status polling interval in seconds.";
};
autostart = mkOption {
type = types.bool;
default = true;
description = "Whether to autostart the tray application for all graphical users via XDG desktop autostart.";
};
};
tgWsProxy = {
enable = mkEnableOption "Telegram MTProto WebSocket proxy";
port = mkOption {
type = types.port;
default = 1076;
description = "Port to listen on.";
};
host = mkOption {
type = types.str;
default = "0.0.0.0";
description = "Address to bind to.";
};
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.
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.
'';
example = "/run/secrets/tg-ws-proxy-secret";
};
dcIps = mkOption {
type = types.attrsOf types.str;
default = {
"2" = "149.154.167.220";
"4" = "149.154.167.220";
};
description = "Map of Telegram DC ID to IP address for relay.";
example = {
"1" = "149.154.175.50";
"2" = "149.154.167.51";
"3" = "149.154.175.100";
"4" = "149.154.167.91";
"5" = "91.108.56.130";
};
};
};
};
}
@@ -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.";
};
};
}
+24
View File
@@ -0,0 +1,24 @@
{ lib, ... }:
{
imports = [
./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" ];
};
};
}
'';
};
};
}
@@ -0,0 +1,99 @@
{ lib, ... }:
let
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 (`proxy-ctl apps run`)";
createDefaultProfiles = mkOption {
type = types.bool;
default = false;
description = ''
Add a profile named after each enabled backend (proxychains, tun, tproxy, zapret) unless
one with that name already exists.
'';
};
profiles = mkOption {
type = types.listOf t.perAppRoutingProfileType;
default = [ ];
description = "Profiles for `proxy-ctl apps run <name> -- <command>`.";
example = [
{
name = "steam-browser";
route = "proxychains";
}
];
};
proxychains = {
enable = mkEnableOption "the proxychains backend (TCP apps, through LD_PRELOAD)";
quiet = mkOption {
type = types.bool;
default = true;
description = "Silence proxychains (quiet_mode).";
};
proxyDns = mkOption {
type = types.bool;
default = 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;
}
+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.";
};
};
}
+94
View File
@@ -0,0 +1,94 @@
{ lib }:
let
inherit (lib) mkOption types;
list =
description: example:
mkOption {
type = types.listOf types.str;
default = [ ];
inherit description example;
};
routingFields = {
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" ];
};
routingRuleType = types.submodule {
options = {
outbound = mkOption {
type = types.str;
description = ''Outbound tag, or "proxy", "direct", "block". With selection = "first" every proxy tag means "proxy".'';
example = "vps-de";
};
}
// routingFields;
};
dnsUpstreamType = types.submodule {
options = {
type = mkOption {
type = types.enum [
"udp"
"tcp"
"tls"
];
default = "udp";
description = "DNS transport.";
};
address = mkOption {
type = types.strMatching ".+";
description = "Resolver address.";
example = "1.1.1.1";
};
port = mkOption {
type = types.port;
default = 53;
description = "Resolver port.";
};
};
};
perAppRoutingProfileType = types.submodule {
options = {
name = mkOption {
type = types.strMatching "^[a-z0-9][a-z0-9-]*$";
description = "Profile name, unique.";
example = "steam-browser";
};
route = mkOption {
type = types.enum [
"direct"
"proxychains"
"tun"
"tproxy"
"zapret"
];
default = "proxychains";
description = ''
Backend: "direct" (unchanged), "proxychains", or the per-app "tun", "tproxy" or "zapret"
backend of perAppRouting.
'';
};
};
};
in
{
inherit
dnsUpstreamType
perAppRoutingProfileType
routingFields
routingRuleType
;
}
// 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" ];
};
};
}
+99
View File
@@ -0,0 +1,99 @@
{ lib, ... }:
let
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";
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";
};
# 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.";
};
# 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 = ''
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");
};
}
+69 -181
View File
@@ -7,119 +7,44 @@
}:
let
r = cfg.singBox.routing;
sb = cfg.singBox;
z = cfg.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 = z.enable && z.syncDirectRouting;
syncZapretDirectUpstreamIps = z.enable && z.syncDirectRoutingUpstreamIps;
syncZapretDirectUserIps = z.enable && z.syncDirectRoutingUserIps;
syncZapretDirectAnyIps = syncZapretDirectUpstreamIps || syncZapretDirectUserIps;
zapretDefaultDomainFiles = [
"list-general.txt"
"list-google.txt"
]
++ lib.optionals z.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 z.ipsetAll else [ ];
zapretCustomDomains =
if syncZapretDirectDomains then
lib.unique (lib.concatMap (rule: lib.optionals rule.enableDirectSync rule.domains) z.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 z.ipsetExclude else [ ])
);
zapretDirectDomains =
if syncZapretDirectDomains then
subtractItems (lib.unique (zapretDefaultDomains ++ z.listGeneral ++ zapretCustomDomains)) (
lib.unique (zapretExcludedDomains ++ z.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");
derived = import ./derived.nix { inherit lib cfg; };
r = cfg.proxy.routing;
proxyCfg = derived.proxyCfg;
tgWsProxyCfg = cfg.tgWsProxy;
zapretDirect = import ./rules-zapret-direct.nix {
inherit
lib
cfg
zapret
;
};
inherit (zapretDirect) direct;
zapretDirectRules = zapretDirect.zapretDirect;
mkDomainRule =
tag: domains:
lib.optional (domains != [ ]) {
domain_suffix = domains;
outbound = tag;
};
mkIPRule =
tag: ips:
lib.optional (ips != [ ]) {
ip_cidr = ips;
outbound = tag;
};
mkRulesetRule =
tag: tags:
lib.optional (tags != [ ]) {
rule_set = tags;
outbound = tag;
};
customRuleCategory =
outbound:
if outbound == "direct" then
"direct"
else if outbound == "block" then
"block"
else
"proxy";
# In "first" mode the start script renames the first outbound to "proxy",
# so any per-outbound routing tag that isn't direct/block/proxy must map
# to "proxy" instead of the original tag (which won't exist in sing-box).
builtinTags = [
"proxy"
"direct"
"block"
];
resolveTag =
tag: if sb.selection == "first" && !builtins.elem tag builtinTags then "proxy" else tag;
tag:
if derived.collapseNamedOutbounds && !builtins.elem tag derived.builtinTags then
"proxy"
else if
derived.pureXrayEnabled
&& derived.selectionMode == "urltest"
&& !builtins.elem tag derived.builtinTags
then
"proxy-suite-ob-${tag}"
else
tag;
# Collect per-outbound routing attached directly to outbound definitions.
perOutboundRules = lib.concatMap (
@@ -137,95 +62,58 @@ let
geoips
;
}
) sb.outbounds;
) proxyCfg.outbounds;
# All custom rules in priority order: per-outbound first, then explicit routing.rules.
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))
];
singBoxRules = import ./rules/sing-box.nix {
inherit
lib
r
direct
tgWsProxyCfg
customRules
customRuleCategory
;
inherit (cfg) geodata;
};
inherit (singBoxRules)
geositeRuleSets
geoIPRuleSets
singBoxRoutingRules
singBoxRouteModeRules
;
# 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
);
xrayRules = import ./rules/xray.nix {
inherit
lib
r
direct
tgWsProxyCfg
customRules
customRuleCategory
;
inherit (derived) selectionMode;
};
inherit (xrayRules) xrayRoutingRules xrayRouteModeRules;
# All geoip names referenced anywhere.
allGeoIPNames = lib.unique (
r.proxy.geoips ++ direct.geoips ++ r.block.geoips ++ lib.concatMap (rule: rule.geoips) customRules
);
geositeRuleSets = map (name: {
tag = "geosite-${name}";
type = "local";
format = "binary";
path = "${pkgs.sing-geosite}/share/sing-box/rule-set/geosite-${name}.srs";
}) allGeositeNames;
geoIPRuleSets = map (name: {
tag = "geoip-${name}";
type = "local";
format = "binary";
path = "${pkgs.sing-geoip}/share/sing-box/rule-set/geoip-${name}.srs";
}) allGeoIPNames;
routingRules = lib.flatten [
{
network = [
"tcp"
"udp"
];
port = 53;
action = "hijack-dns";
}
{ action = "sniff"; }
# Per-outbound and explicit rules come first – they take priority.
(lib.concatMap mkCustomRuleEntries customRules)
# Global proxy lists
(mkDomainRule "proxy" r.proxy.domains)
(mkIPRule "proxy" r.proxy.ips)
# Global direct lists
(mkDomainRule "direct" direct.domains)
(mkIPRule "direct" direct.ips)
(mkRulesetRule "direct" (map (s: "geosite-${s}") direct.geosites))
(mkRulesetRule "direct" (map (s: "geoip-${s}") direct.geoips))
{
ip_is_private = true;
outbound = "direct";
}
# Block (before proxy geosets so block can override them)
(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))
# Global proxy geo lists
(mkRulesetRule "proxy" (map (s: "geosite-${s}") r.proxy.geosites))
(mkRulesetRule "proxy" (map (s: "geoip-${s}") r.proxy.geoips))
];
routingRules = singBoxRoutingRules;
routeModeRules = singBoxRouteModeRules;
in
{
inherit
direct
zapretDirectRules
geositeRuleSets
geoIPRuleSets
singBoxRoutingRules
singBoxRouteModeRules
xrayRoutingRules
xrayRouteModeRules
routeModeRules
routingRules
;
}
@@ -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
;
}
+615
View File
@@ -0,0 +1,615 @@
{
lib,
cfg,
derived,
tgWsProxyCfg,
builtinTags,
outboundTags,
effectiveOutboundTags ? outboundTags,
subscriptionTags,
invalidRoutingTargets,
effectivePerAppRoutingProfileNames,
hasProxychainsProfiles,
hasTunProfiles,
hasTproxyProfiles,
hasZapretProfiles,
}:
let
inherit (derived)
constants
proxyCfg
proxyEnabled
singBoxEnabled
xrayEnabled
hybridEnabled
pureXrayEnabled
perAppRoutingCfg
globalTun
globalTproxy
perAppRoutingTun
perAppRoutingTproxy
perAppZapretCfg
zapretCfg
zapretEngine
;
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 = [
# 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) 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\" 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.backend = \"xray\"; use udp/tcp DNS for XRay"
)
(requireEnabled globalTun.enable proxyEnabled
"proxy-suite: proxy.tun.enable requires proxy.enable = true"
)
(requireEnabled globalTproxy.enable proxyEnabled
"proxy-suite: proxy.tproxy.enable requires proxy.enable = true"
)
(requireEnabled (proxyCfg.autostart == "tun") globalTun.enable
''proxy-suite: proxy.autostart = "tun" requires proxy.tun.enable = true''
)
(requireEnabled (proxyCfg.autostart == "tproxy") globalTproxy.enable
''proxy-suite: proxy.autostart = "tproxy" requires proxy.tproxy.enable = true''
)
];
perAppRoutingAssertions = [
(requireAvailable (perAppRoutingCfg.profiles != [ ]) perAppRoutingCfg.enable
"proxy-suite: perAppRouting.profiles requires perAppRouting.enable = true"
)
(requireEnabled perAppRoutingCfg.proxychains.enable perAppRoutingCfg.enable
"proxy-suite: perAppRouting.proxychains.enable requires perAppRouting.enable = true"
)
(requireEnabled perAppRoutingCfg.proxychains.enable proxyEnabled
"proxy-suite: perAppRouting.proxychains.enable requires proxy.enable = true"
)
(uniqueValues true effectivePerAppRoutingProfileNames
"proxy-suite: perAppRouting profile names must be unique"
)
(requireAvailable hasProxychainsProfiles perAppRoutingCfg.proxychains.enable
"proxy-suite: route=proxychains in perAppRouting.profiles requires perAppRouting.proxychains.enable = true"
)
(requireAvailable hasProxychainsProfiles proxyEnabled
"proxy-suite: route=proxychains in perAppRouting.profiles requires proxy.enable = true"
)
(requireEnabled perAppRoutingTun.enable perAppRoutingCfg.enable
"proxy-suite: perAppRouting.tun.enable requires perAppRouting.enable = true"
)
(requireEnabled perAppRoutingTun.enable proxyEnabled
"proxy-suite: perAppRouting.tun.enable requires proxy.enable = true"
)
(requireAvailable hasTunProfiles perAppRoutingTun.enable
"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: perAppRouting.tproxy.enable requires perAppRouting.enable = true"
)
(requireEnabled perAppRoutingTproxy.enable proxyEnabled
"proxy-suite: perAppRouting.tproxy.enable requires proxy.enable = true"
)
(requireAvailable hasTproxyProfiles perAppRoutingTproxy.enable
"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: perAppRouting.zapret.enable requires perAppRouting.enable = true"
)
(requireAvailable hasZapretProfiles perAppZapretCfg.enable
"proxy-suite: route=zapret in perAppRouting.profiles requires perAppRouting.zapret.enable = true"
)
];
localProxyAuthCfg = proxyCfg.listener.auth;
localProxyAuthUsed =
localProxyAuthCfg.username != null
|| localProxyAuthCfg.password != null
|| localProxyAuthCfg.passwordFile != null;
localProxyAuthAssertions = [
(mkAssertion (
!proxyEnabled || !localProxyAuthUsed || localProxyAuthCfg.username != null
) "proxy-suite: proxy.listener.auth requires username when password or passwordFile is set")
(exactlyOneOf (proxyEnabled && localProxyAuthUsed) [
localProxyAuthCfg.password
localProxyAuthCfg.passwordFile
] "proxy-suite: proxy.listener.auth requires exactly one of password or passwordFile")
];
secretAssertions = [
(exactlyOneOf tgWsProxyCfg.enable [
tgWsProxyCfg.secret
tgWsProxyCfg.secretFile
] "proxy-suite: tgWsProxy requires exactly one of secret or secretFile")
];
outboundAssertions = lib.concatMap (ob: [
(exactlyOneOf proxyEnabled
[
ob.urlFile
ob.url
ob.singBoxJson
ob.xrayJson
ob.json
]
"proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, singBoxJson, xrayJson, or json"
)
(mkAssertion (
!singBoxEnabled || hybridEnabled || ob.xrayJson == null
) "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 require proxy.backend = sing-box or hybrid"
)
(mkAssertion (
!(ob.backend == "xray") || xrayEnabled
) "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.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
++ localProxyAuthAssertions
++ secretAssertions
++ outboundAssertions
++ proxyInboundAssertions
++ subscriptionAssertions
++ collisionAssertions
++ positiveNumberAssertions
++ forbiddenValueAssertions
-547
View File
@@ -1,547 +0,0 @@
# Systemd services for sing-box
{
config,
lib,
pkgs,
cfg,
tproxyFile,
tunFile,
nftablesRulesFile,
ip,
nft,
}:
let
sb = cfg.singBox;
t = cfg.tgWsProxy;
builtinTags = [
"proxy"
"direct"
"block"
];
outboundTags = map (ob: ob.tag) sb.outbounds;
invalidRoutingTargets = lib.unique (
map (rule: rule.outbound) (
builtins.filter (rule: !builtins.elem rule.outbound (builtinTags ++ outboundTags)) sb.routing.rules
)
);
jq = "${pkgs.jq}/bin/jq";
python3 = "${pkgs.python3}/bin/python3";
singBox = "${pkgs.sing-box}/bin/sing-box";
fetchSubscriptionPy = ../../scripts/fetch-subscription.py;
# Build the shell code block for a single outbound entry.
# tag overrides ob.tag (used in "first" mode to force tag = "proxy").
# routingMark is null or an int; added to outbound JSON if set.
mkOutboundBlock =
ob: routingMark: tag:
let
markArg = lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}";
in
if ob.json != null then
let
outboundJson = builtins.toJSON (
ob.json // { tag = tag; } // lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; }
);
jsonFile = pkgs.writeText "proxy-suite-ob-${tag}.json" outboundJson;
in
''
# outbound: ${tag} (static json)
OB_JSON=$(cat ${lib.escapeShellArg jsonFile})
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
''
else
let
urlSource =
if ob.urlFile != null then
ob.urlFile
else
# Literal URL – write to nix store so the script can cat it.
# Less secret than urlFile, but convenient for non-sensitive configs.
"${pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url}";
in
''
# outbound: ${tag}
URL=$(cat ${lib.escapeShellArg urlSource})
OB_JSON=$(printf '%s' "$URL" | ${python3} ${../../scripts/build-outbound.py} --tag ${lib.escapeShellArg tag}${markArg})
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
'';
# Build the shell code block for a single subscription entry.
# Fetches subscription into the cache on first run; subsequent starts use the cache.
mkSubscriptionBlock =
sub: routingMark:
let
urlSource =
if sub.urlFile != null then
sub.urlFile
else
"${pkgs.writeText "proxy-suite-sub-url-${sub.tag}" sub.url}";
in
''
# subscription: ${sub.tag}
CACHE_DIR="/var/lib/proxy-suite/subscriptions"
CACHE_FILE="$CACHE_DIR/${lib.escapeShellArg sub.tag}.json"
if [ ! -f "$CACHE_FILE" ]; then
mkdir -p "$CACHE_DIR"
SUB_URL=$(cat ${lib.escapeShellArg urlSource})
if printf '%s' "$SUB_URL" \
| ${python3} ${fetchSubscriptionPy} --tag-prefix ${lib.escapeShellArg sub.tag} \
> "$CACHE_FILE.tmp"; then
mv "$CACHE_FILE.tmp" "$CACHE_FILE"
else
rm -f "$CACHE_FILE.tmp"
echo "proxy-suite: warning: could not fetch subscription '${sub.tag}'" >&2
fi
fi
if [ -f "$CACHE_FILE" ]; then
SUB_JSON=$(cat "$CACHE_FILE")
${lib.optionalString (routingMark != null) ''
SUB_JSON=$(${jq} --argjson m ${toString routingMark} 'map(. + {routing_mark: $m})' <<< "$SUB_JSON")
''}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
fi
'';
# Shell code that builds all outbounds, then optionally adds a selector/urltest wrapper.
mkOutboundScript =
routingMark:
let
outboundBlocks =
if sb.selection == "first" && sb.outbounds != [ ] then
# Only the first static outbound, tagged "proxy" so sing-box routes to it.
mkOutboundBlock (builtins.head sb.outbounds) routingMark "proxy"
else
lib.concatMapStrings (ob: mkOutboundBlock ob routingMark ob.tag) sb.outbounds;
subscriptionBlocks =
lib.concatMapStrings (sub: mkSubscriptionBlock sub routingMark) sb.subscriptions;
wrapperBlock =
if sb.selection == "first" then
# When there are no static outbounds, subscription outbounds keep their
# real tags. Rename the first one to "proxy" so routing rules resolve.
lib.optionalString (sb.outbounds == [ ] && sb.subscriptions != [ ]) ''
FIRST_TAG=$(${jq} -r 'if length > 0 then .[0].tag else "" end' <<< "$OUTBOUNDS_JSON")
if [ -n "$FIRST_TAG" ]; then
OUTBOUNDS_JSON=$(${jq} --arg t "$FIRST_TAG" \
'map(if .tag == $t then .tag = "proxy" else . end)' <<< "$OUTBOUNDS_JSON")
fi
''
else if sb.selection == "selector" then
''
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
FIRST=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")
WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \
--arg default "$FIRST" \
'{type:"selector",tag:"proxy",outbounds:$tags,default:$default}')
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
''
else
# urltest
''
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \
--arg url ${lib.escapeShellArg sb.urlTest.url} \
--arg interval ${lib.escapeShellArg sb.urlTest.interval} \
--argjson tolerance ${toString sb.urlTest.tolerance} \
'{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:$interval,tolerance:$tolerance}')
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
'';
in
outboundBlocks + subscriptionBlocks + wrapperBlock;
mkStartScript =
{
name,
runtimeDir,
configFile,
routingMark ? null,
}:
pkgs.writeShellScript name ''
set -euo pipefail
RUNTIME_DIR="${runtimeDir}"
mkdir -p "$RUNTIME_DIR"
OUTBOUNDS_JSON='[]'
${mkOutboundScript routingMark}
${jq} --argjson obs "$OUTBOUNDS_JSON" \
'.outbounds = $obs + .outbounds' \
"${configFile}" > "$RUNTIME_DIR/config.json"
exec ${singBox} run -c "$RUNTIME_DIR/config.json"
'';
startSocks = mkStartScript {
name = "proxy-suite-start-socks";
runtimeDir = "/run/proxy-suite-socks";
configFile = tproxyFile;
routingMark = sb.proxyMark;
};
startTun = mkStartScript {
name = "proxy-suite-start-tun";
runtimeDir = "/run/proxy-suite-tun";
configFile = tunFile;
routingMark = null;
};
clashApi = "http://127.0.0.1:${toString sb.clashApiPort}";
selection = sb.selection;
# Shell code to fetch a single subscription into the cache (used in update service).
mkSubscriptionFetchBlock =
sub:
let
urlSource =
if sub.urlFile != null then
sub.urlFile
else
"${pkgs.writeText "proxy-suite-sub-url-${sub.tag}" sub.url}";
in
''
SUB_URL=$(cat ${lib.escapeShellArg urlSource})
if printf '%s' "$SUB_URL" \
| ${python3} ${fetchSubscriptionPy} --tag-prefix ${lib.escapeShellArg sub.tag} \
> "$CACHE_DIR/${lib.escapeShellArg sub.tag}.json.tmp"; then
mv "$CACHE_DIR/${lib.escapeShellArg sub.tag}.json.tmp" \
"$CACHE_DIR/${lib.escapeShellArg sub.tag}.json"
echo "Updated subscription: ${sub.tag}"
else
rm -f "$CACHE_DIR/${lib.escapeShellArg sub.tag}.json.tmp"
echo "proxy-suite: failed to update subscription '${sub.tag}'" >&2
FAILED=1
fi
'';
subscriptionUpdateScript = pkgs.writeShellScript "proxy-suite-subscription-update" ''
set -euo pipefail
CACHE_DIR="/var/lib/proxy-suite/subscriptions"
mkdir -p "$CACHE_DIR"
FAILED=0
${lib.concatMapStrings mkSubscriptionFetchBlock sb.subscriptions}
if [ "$FAILED" -eq 0 ]; then
systemctl restart proxy-suite-socks
systemctl is-active --quiet proxy-suite-tun && systemctl restart proxy-suite-tun || true
fi
exit "$FAILED"
'';
# Subscription tags embedded at build time for proxy-ctl.
subscriptionTagsList = lib.concatStringsSep " " (map (sub: lib.escapeShellArg sub.tag) sb.subscriptions);
hasSubscriptions = sb.subscriptions != [ ];
proxyCtl = pkgs.writeShellApplication {
name = "proxy-ctl";
runtimeInputs = with pkgs; [
curl
jq
];
text = ''
# Embedded at build time from module config
CLASH_API="${clashApi}"
SELECTION="${selection}"
SUB_TAGS=(${subscriptionTagsList})
ALL_SERVICES=(
proxy-suite-socks
proxy-suite-tproxy
proxy-suite-tun
proxy-suite-tg-ws-proxy
proxy-suite-zapret-vm-exempt
zapret-discord-youtube
)
_usage() {
echo "Usage: proxy-ctl <command> [args]"
echo ""
echo "Commands:"
echo " status show status of all proxy-suite services"
echo " tproxy on|off enable/disable TProxy transparent mode"
echo " tun on|off enable/disable TUN mode"
echo " restart restart proxy-suite-socks and proxy-suite-tun if active"
echo " logs [service] follow service logs (default: proxy-suite-socks)"
echo " outbounds list outbounds and current selection"
echo " select <tag> switch to a specific outbound (selector mode)"
echo " subscription list show subscriptions, cache age, and proxy count"
echo " subscription update force-refresh all subscription caches and restart"
exit 1
}
_svc_status() {
local svc="$1"
if ! systemctl cat "$svc" &>/dev/null; then
return
fi
local state
state=$(systemctl is-active "$svc" 2>/dev/null || true)
printf " %-44s %s\n" "$svc" "$state"
}
cmd="''${1:-status}"
shift || true
case "$cmd" in
status)
echo "proxy-suite services:"
for svc in "''${ALL_SERVICES[@]}"; do
_svc_status "$svc"
done
;;
tproxy)
case "''${1:-on}" in
on) systemctl start proxy-suite-tproxy ;;
off) systemctl stop proxy-suite-tproxy ;;
*) echo "Usage: proxy-ctl tproxy on|off"; exit 1 ;;
esac
;;
tun)
case "''${1:-on}" in
on) systemctl start proxy-suite-tun ;;
off) systemctl stop proxy-suite-tun ;;
*) echo "Usage: proxy-ctl tun on|off"; exit 1 ;;
esac
;;
restart)
systemctl restart proxy-suite-socks
if systemctl is-active --quiet proxy-suite-tun; then
systemctl restart proxy-suite-tun
fi
;;
logs)
svc="''${1:-proxy-suite-socks}"
shift || true
exec journalctl -fu "$svc" "$@"
;;
outbounds)
data=$(curl -sf "$CLASH_API/proxies/proxy" 2>/dev/null) || {
echo "Clash API not available."
echo " - Make sure proxy-suite-socks is running"
echo " - selection must be 'selector' or 'urltest' (currently: $SELECTION)"
exit 1
}
now=$(echo "$data" | jq -r '.now // "n/a"')
ob_type=$(echo "$data" | jq -r '.type // "n/a"')
echo "Type: $ob_type"
echo "Current: $now"
echo ""
echo "Available:"
echo "$data" | jq -r '.all[]? | " " + .'
;;
select)
tag="''${1:?Usage: proxy-ctl select <outbound-tag>}"
if [ "$SELECTION" != "selector" ]; then
echo "selection must be 'selector' (currently: $SELECTION)"
exit 1
fi
payload=$(jq -cn --arg name "$tag" '{name:$name}')
if curl -sf -X PUT "$CLASH_API/proxies/proxy" \
-H "Content-Type: application/json" \
-d "$payload" >/dev/null; then
echo "Switched to: $tag"
else
echo "Failed – is proxy-suite-socks running with selector mode?"
exit 1
fi
;;
subscription)
subcmd="''${1:-list}"
shift || true
case "$subcmd" in
list)
CACHE_DIR="/var/lib/proxy-suite/subscriptions"
if [ ''${#SUB_TAGS[@]} -eq 0 ]; then
echo "No subscriptions configured."
else
printf " %-30s %-22s %s\n" "TAG" "LAST UPDATED" "PROXIES"
for t in "''${SUB_TAGS[@]}"; do
cache="$CACHE_DIR/$t.json"
if [ -f "$cache" ]; then
age=$(date -r "$cache" "+%Y-%m-%d %H:%M:%S" 2>/dev/null || echo "unknown")
count=$(jq 'length' "$cache" 2>/dev/null || echo "?")
else
age="(no cache)"
count="-"
fi
printf " %-30s %-22s %s\n" "$t" "$age" "$count"
done
fi
;;
update)
systemctl start proxy-suite-subscription-update
echo "Subscription update triggered. Follow with: proxy-ctl logs proxy-suite-subscription-update"
;;
*)
echo "Usage: proxy-ctl subscription list|update"; exit 1 ;;
esac
;;
*)
_usage
;;
esac
'';
};
in
{
environment.systemPackages = [ proxyCtl ];
# nftables must be on for TProxy to work.
networking.nftables.enable = lib.mkIf sb.tproxy.enable (lib.mkDefault true);
assertions = [
{
assertion = !sb.enable || (sb.outbounds != [ ] || sb.subscriptions != [ ]);
message = "proxy-suite: at least one outbound or subscription is required when singBox.enable = true";
}
{
assertion = builtins.length outboundTags == builtins.length (lib.unique outboundTags);
message = "proxy-suite: outbound tags must be unique";
}
{
assertion = builtins.all (tag: !builtins.elem tag builtinTags) outboundTags;
message = "proxy-suite: outbound tags must not use reserved names: proxy, direct, block";
}
{
assertion = invalidRoutingTargets == [ ];
message = "proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}";
}
{
assertion =
!t.enable
||
builtins.length (
builtins.filter (x: x != null) [
t.secret
t.secretFile
]
) == 1;
message = "proxy-suite: tgWsProxy requires exactly one of secret or secretFile";
}
]
++ lib.concatMap (ob: [
{
assertion =
builtins.length (
builtins.filter (x: x != null) [
ob.urlFile
ob.url
ob.json
]
) == 1;
message = "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, or json";
}
]) sb.outbounds
++ lib.concatMap (sub: [
{
assertion =
builtins.length (
builtins.filter (x: x != null) [
sub.urlFile
sub.url
]
) == 1;
message = "proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url";
}
]) sb.subscriptions;
systemd.services = {
# Always-on: SOCKS5/HTTP mixed inbound, also ready for TProxy interception.
proxy-suite-socks = {
description = "sing-box proxy client (SOCKS + TProxy-ready)";
after = [ "network.target" ];
wantedBy = [ "multi-user.target" ];
serviceConfig = {
ExecStart = "${startSocks}";
Restart = "on-failure";
RestartSec = 5;
RuntimeDirectory = "proxy-suite-socks";
StateDirectory = "proxy-suite";
};
};
}
// lib.optionalAttrs sb.tproxy.enable {
# Opt-in transparent proxy. Start/stop with:
# systemctl start proxy-suite-tproxy
# systemctl stop proxy-suite-tproxy
proxy-suite-tproxy = {
description = "sing-box TProxy – nftables rules and policy routing";
after = [
"network.target"
"proxy-suite-socks.service"
];
requires = [ "proxy-suite-socks.service" ];
conflicts = [ "proxy-suite-tun.service" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = pkgs.writeShellScript "proxy-suite-tproxy-up" ''
${nft} delete table ip singbox 2>/dev/null || true
${nft} -f ${nftablesRulesFile}
${ip} route add local default dev lo table ${toString sb.routeTable}
${ip} rule add fwmark ${toString sb.fwmark} table ${toString sb.routeTable}
'';
ExecStop = pkgs.writeShellScript "proxy-suite-tproxy-down" ''
${nft} delete table ip singbox 2>/dev/null || true
${ip} route del local default dev lo table ${toString sb.routeTable} 2>/dev/null || true
${ip} rule del fwmark ${toString sb.fwmark} table ${toString sb.routeTable} 2>/dev/null || true
'';
};
};
}
// lib.optionalAttrs sb.tun.enable {
# Opt-in TUN mode (full tunnel, no nftables needed). Start/stop with:
# systemctl start proxy-suite-tun
# systemctl stop proxy-suite-tun
proxy-suite-tun = {
description = "sing-box TUN proxy client";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = [ "proxy-suite-tproxy.service" ];
serviceConfig = {
ExecStart = "${startTun}";
Restart = "on-failure";
RestartSec = 5;
RuntimeDirectory = "proxy-suite-tun";
StateDirectory = "proxy-suite";
};
};
}
// lib.optionalAttrs hasSubscriptions {
proxy-suite-subscription-update = {
description = "Refresh proxy-suite subscription caches";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
serviceConfig = {
Type = "oneshot";
StateDirectory = "proxy-suite";
ExecStart = "${subscriptionUpdateScript}";
};
};
};
systemd.timers = lib.optionalAttrs hasSubscriptions {
proxy-suite-subscription-update = {
description = "Periodic proxy-suite subscription refresh";
wantedBy = [ "timers.target" ];
timerConfig = {
OnBootSec = "5m";
OnUnitActiveSec = sb.subscriptionUpdateInterval;
};
};
};
}
+268
View File
@@ -0,0 +1,268 @@
{
lib,
pkgs,
}:
let
mkOptionalTopLevel =
{
description,
after ? [ ],
wantedBy ? [ ],
wants ? [ ],
requires ? [ ],
conflicts ? [ ],
preStart ? null,
}:
{
inherit
description
after
wantedBy
wants
requires
conflicts
;
}
// lib.optionalAttrs (preStart != null) { inherit preStart; };
in
rec {
mkNamedUnits =
entries:
lib.listToAttrs (
map (entry: lib.nameValuePair entry.name entry.value) (
builtins.filter (entry: entry.enable) entries
)
);
mkRestartingService =
{
description,
execStart,
runtimeDirectory,
stateDirectory ? null,
after ? [ ],
wantedBy ? [ ],
wants ? [ ],
requires ? [ ],
conflicts ? [ ],
execStartPre ? null,
execStartPost ? null,
execStopPost ? null,
extraServiceConfig ? { },
preStart ? null,
}:
(mkOptionalTopLevel {
inherit
description
after
wantedBy
wants
requires
conflicts
preStart
;
})
// {
serviceConfig = {
ExecStart = execStart;
Restart = "on-failure";
RestartSec = 5;
RuntimeDirectory = runtimeDirectory;
}
// lib.optionalAttrs (stateDirectory != null) { StateDirectory = stateDirectory; }
// lib.optionalAttrs (execStartPre != null) { ExecStartPre = execStartPre; }
// lib.optionalAttrs (execStartPost != null) { ExecStartPost = execStartPost; }
// lib.optionalAttrs (execStopPost != null) { ExecStopPost = execStopPost; }
// extraServiceConfig;
};
mkOneshotService =
{
description,
execStart,
execStop ? null,
execStartPre ? null,
execStartPost ? null,
execStopPost ? null,
runtimeDirectory ? null,
stateDirectory ? null,
after ? [ ],
wantedBy ? [ ],
wants ? [ ],
requires ? [ ],
conflicts ? [ ],
extraServiceConfig ? { },
preStart ? null,
}:
(mkOptionalTopLevel {
inherit
description
after
wantedBy
wants
requires
conflicts
preStart
;
})
// {
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = execStart;
}
// lib.optionalAttrs (execStop != null) { ExecStop = execStop; }
// lib.optionalAttrs (execStartPre != null) { ExecStartPre = execStartPre; }
// lib.optionalAttrs (execStartPost != null) { ExecStartPost = execStartPost; }
// lib.optionalAttrs (execStopPost != null) { ExecStopPost = execStopPost; }
// lib.optionalAttrs (runtimeDirectory != null) { RuntimeDirectory = runtimeDirectory; }
// lib.optionalAttrs (stateDirectory != null) { StateDirectory = stateDirectory; }
// extraServiceConfig;
};
mkUserRuleService =
{
description,
backendService,
execStart,
execStop,
}:
mkOneshotService {
inherit description execStart execStop;
requires = [ "${backendService}.service" ];
after = [ "${backendService}.service" ];
};
mkAnchorService =
sliceName: description:
mkOneshotService {
inherit description;
execStart = "${pkgs.coreutils}/bin/true";
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
'';
}
+212
View File
@@ -0,0 +1,212 @@
# Shared service-layer assembly used by runtime module and docs generation.
{
lib,
pkgs,
packages,
cfg,
tproxyFile,
tunFile,
perAppTunFile,
routeModeRulesFile,
proxyInboundsFile,
proxyInboundsSpecFile,
perAppTunChainFile,
perAppTproxyRulesFile,
perAppZapretRulesFile,
ip,
nft,
}:
let
derived = import ../derived.nix { inherit lib cfg; };
constants = derived.constants;
inherit (derived)
singBoxCfg
proxyCfg
xrayCfg
proxyEnabled
singBoxEnabled
xrayEnabled
hybridEnabled
pureXrayEnabled
activeBackend
perAppRoutingCfg
globalTun
globalTproxy
perAppRoutingTun
perAppRoutingTproxy
perAppZapretCfg
zapretEngine
userControlCfg
selectionMode
builtinTags
outboundTags
subscriptionTags
invalidRoutingTargets
collapseNamedOutbounds
sshProxyCfg
sshProxyOutboundEnabled
sshProxyUnitEnabled
proxyInboundsCfg
proxyInboundsEnabled
proxyInboundsNeedLocalProxy
proxyInboundsGuardPrivate
proxyInboundViaOutbounds
userControlEnabled
;
# Tool paths – defined once here and passed into sub-modules as needed.
jq = "${pkgs.jq}/bin/jq";
python3 = "${pkgs.python3}/bin/python3";
singBox = "${singBoxCfg.package}/bin/sing-box";
xray = "${xrayCfg.package}/bin/xray";
grepBin = "${pkgs.gnugrep}/bin/grep";
awk = "${pkgs.gawk}/bin/awk";
sleepBin = "${pkgs.coreutils}/bin/sleep";
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;
};
scripts = import ./scripts.nix {
inherit
lib
pkgs
singBoxCfg
proxyCfg
sshProxyCfg
xrayEnabled
hybridEnabled
pureXrayEnabled
activeBackend
perAppRoutingCfg
userControlCfg
selectionMode
collapseNamedOutbounds
constants
;
inherit
jq
python3
singBox
xray
parserScriptsPythonPath
buildOutboundPy
buildInboundPy
fetchSubscriptionPy
;
inherit
tproxyFile
tunFile
perAppTunFile
routeModeRulesFile
proxyInboundsFile
proxyInboundsSpecFile
;
inherit
proxyInboundsCfg
proxyInboundsNeedLocalProxy
proxyInboundsGuardPrivate
proxyInboundViaOutbounds
userControlEnabled
builders
;
};
perAppRouting = import ./per-app-routing.nix {
inherit
lib
pkgs
cfg
singBoxCfg
proxyCfg
pureXrayEnabled
perAppRoutingCfg
perAppRoutingTun
perAppRoutingTproxy
constants
;
perAppZapretCfg = perAppZapretCfg;
inherit perAppTunChainFile perAppTproxyRulesFile perAppZapretRulesFile;
inherit ip nft;
inherit
awk
grepBin
findBin
headBin
seqBin
sleepBin
;
};
control = import ./control.nix {
inherit
packages
singBoxCfg
proxyCfg
perAppRoutingCfg
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
proxychainsQuietArg
;
};
in
{
inherit
derived
singBoxCfg
proxyCfg
xrayCfg
proxyEnabled
singBoxEnabled
xrayEnabled
hybridEnabled
pureXrayEnabled
activeBackend
perAppRoutingCfg
globalTun
globalTproxy
perAppRoutingTun
perAppRoutingTproxy
perAppZapretCfg
userControlCfg
builtinTags
outboundTags
subscriptionTags
invalidRoutingTargets
polkit
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
;
}
+64
View File
@@ -0,0 +1,64 @@
# Builds proxy-ctl from global proxy-suite state and per-app routing metadata.
{
packages,
singBoxCfg,
proxyCfg,
perAppRoutingCfg,
perAppRoutingTun,
perAppRoutingTproxy,
perAppZapretCfg,
zapretEngine,
constants,
selectionMode,
userControlCfg,
subscriptionTagsFile,
subscriptionCacheDir,
perAppRoutingProfilesFile,
proxychainsConfigFile,
proxychainsQuietArg,
routeModeStateFile,
amneziaWgProfileNamesFile,
proxyInboundsEnabled,
proxyInboundsLinksFile,
proxyInboundsSubscriptionsFile,
proxyInboundsSubscriptionsBaseUrl,
}:
{
proxyCtl = packages.mkProxyCtl {
clashApi = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}";
selection = selectionMode;
inherit
subscriptionTagsFile
subscriptionCacheDir
perAppRoutingProfilesFile
proxychainsConfigFile
proxychainsQuietArg
routeModeStateFile
amneziaWgProfileNamesFile
;
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}";
};
}
+228
View File
@@ -0,0 +1,228 @@
# Assembles proxy-suite systemd services from the sub-modules.
{
config,
lib,
pkgs,
packages,
cfg,
tproxyFile,
tunFile,
perAppTunFile,
routeModeRulesFile,
proxyInboundsFile,
proxyInboundsSpecFile,
nftablesRulesFile,
perAppTproxyRulesFile,
perAppZapretRulesFile,
perAppTunChainFile,
ip,
nft,
}:
let
context = import ./context.nix {
inherit
lib
pkgs
packages
cfg
tproxyFile
tunFile
perAppTunFile
routeModeRulesFile
proxyInboundsFile
proxyInboundsSpecFile
perAppTunChainFile
perAppTproxyRulesFile
perAppZapretRulesFile
ip
nft
;
};
builders = import ./builders.nix { inherit lib pkgs; };
inherit (builders) mkNamedUnits;
inherit (context)
derived
polkit
scripts
perAppRouting
control
;
inherit (derived)
proxyCfg
proxyEnabled
hybridEnabled
pureXrayEnabled
globalTun
globalTproxy
perAppRoutingTun
perAppRoutingTproxy
userControlCfg
userControlEnabled
perAppZapretEnabled
sshProxyOutboundEnabled
sshProxyUnitEnabled
proxyInboundsEnabled
proxyInboundsNeedLocalProxy
proxyInboundFirewallPorts
proxyInboundFirewallUdpPorts
outboundTags
effectiveOutboundTags
subscriptionTags
invalidRoutingTargets
builtinTags
;
constants = derived.constants;
routingScripts = import ./routing-scripts.nix {
inherit
lib
pkgs
builders
ip
nft
nftablesRulesFile
constants
globalTun
globalTproxy
perAppRoutingTun
perAppRoutingTproxy
;
};
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 ];
# 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;
}
]
@@ -0,0 +1,136 @@
# App routing backend infrastructure (TUN, TProxy, zapret).
{
lib,
pkgs,
cfg,
singBoxCfg,
proxyCfg,
pureXrayEnabled,
perAppRoutingCfg,
perAppRoutingTun,
perAppRoutingTproxy,
constants,
perAppZapretCfg,
perAppTunChainFile,
perAppTproxyRulesFile,
perAppZapretRulesFile,
ip,
nft,
awk,
grepBin,
findBin,
headBin,
seqBin,
sleepBin,
}:
let
builders = import ./builders.nix { inherit lib pkgs; };
inherit (builders) mkAnchorService;
perAppTunSliceName = "proxy-suite-per-app-tun.slice";
perAppTproxySliceName = "proxy-suite-per-app-tproxy.slice";
perAppZapretSliceName = "proxy-suite-per-app-zapret.slice";
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
;
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
;
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
{
inherit
perAppTunSliceName
perAppTproxySliceName
perAppZapretSliceName
perAppTunUpScript
perAppTunDownScript
perAppTproxyUpScript
perAppTproxyDownScript
perAppTunUserRuleStart
perAppTunUserRuleStop
perAppTproxyUserRuleStart
perAppTproxyUserRuleStop
perAppZapretUserRuleStart
perAppZapretUserRuleStop
mkAnchorService
effectivePerAppRoutingProfiles
effectivePerAppRoutingProfileNames
perAppRoutingProfilesFile
proxychainsConfigFile
proxychainsQuietArg
hasProxychainsProfiles
hasTunProfiles
hasTproxyProfiles
hasZapretProfiles
;
}
@@ -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
;
}
+27
View File
@@ -0,0 +1,27 @@
# Polkit rules granting proxy-suite group members passwordless control over services.
{
lib,
cfg,
userControlCfg,
}:
let
userControlEnabled = userControlCfg.allow != [ ];
userControlPolkitRules =
lib.optionalString (builtins.elem "perApp" userControlCfg.allow) ''
if (unit.indexOf("proxy-suite-per-app-") === 0) {
return polkit.Result.YES;
}
''
+ 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") {
return polkit.Result.YES;
}
'';
in
{
inherit userControlEnabled userControlPolkitRules;
}
@@ -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
;
}
+261
View File
@@ -0,0 +1,261 @@
# Assembles proxy backend startup and control scripts.
{
lib,
pkgs,
singBoxCfg,
proxyCfg,
sshProxyCfg,
xrayEnabled,
hybridEnabled,
pureXrayEnabled,
activeBackend,
perAppRoutingCfg,
userControlCfg,
selectionMode,
collapseNamedOutbounds,
constants,
jq,
python3,
singBox,
xray,
parserScriptsPythonPath,
buildOutboundPy,
fetchSubscriptionPy,
tproxyFile,
tunFile,
perAppTunFile,
routeModeRulesFile,
proxyInboundsCfg,
proxyInboundsNeedLocalProxy,
proxyInboundsGuardPrivate,
proxyInboundViaOutbounds,
userControlEnabled,
buildInboundPy,
proxyInboundsFile,
proxyInboundsSpecFile,
builders,
}:
let
globalTproxy = proxyCfg.tproxy;
backend = if activeBackend == null then "sing-box" else activeBackend;
mainBackend = if pureXrayEnabled then "xray" else "sing-box";
backendArg = "--backend ${mainBackend}";
backendBin = if pureXrayEnabled then xray else singBox;
localProxyAuth = proxyCfg.listener.auth;
localProxyAuthEnabled =
localProxyAuth.username != null
&& (localProxyAuth.password != null || localProxyAuth.passwordFile != null);
localProxyAuthPasswordSource =
if localProxyAuth.passwordFile != null then
localProxyAuth.passwordFile
else if localProxyAuth.password != null then
pkgs.writeText "proxy-suite-local-proxy-password" localProxyAuth.password
else
null;
routeModeStateFile = "/run/proxy-suite/route-mode";
inherit (constants)
priorityOutboundFile
runtimeOutboundsDir
runtimeSubscriptionsDir
outboundInventoryFile
;
clashApi = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}";
xrayLoglevelFile = "/run/proxy-suite/xray-loglevel";
runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf";
xraySidecarRoutingMark = globalTproxy.proxyMark;
routingMarkJq =
routingMark:
if routingMark == null then
""
else if pureXrayEnabled then
" | .streamSettings.sockopt.mark = ${toString routingMark}"
else
" | .routing_mark = ${toString routingMark}";
subscriptionScripts = import ./script-blocks/subscriptions.nix {
inherit
lib
pkgs
proxyCfg
hybridEnabled
mainBackend
backend
runtimeSubscriptionsDir
jq
python3
parserScriptsPythonPath
fetchSubscriptionPy
routingMarkJq
;
};
inherit (subscriptionScripts)
subscriptionCacheDir
subscriptionCacheHelpersBlock
mkSubscriptionLoadHelperBlock
mkSubscriptionBlock
runtimeSubscriptionsBlock
mkSubscriptionFetchBlock
runtimeSubscriptionsFetchBlock
subscriptionTagsFile
;
outboundScripts = import ./script-blocks/outbounds.nix {
inherit
lib
pkgs
singBoxCfg
proxyCfg
sshProxyCfg
pureXrayEnabled
hybridEnabled
collapseNamedOutbounds
selectionMode
backend
backendArg
xraySidecarRoutingMark
priorityOutboundFile
runtimeOutboundsDir
jq
python3
parserScriptsPythonPath
buildOutboundPy
mkSubscriptionBlock
mkSubscriptionLoadHelperBlock
runtimeSubscriptionsBlock
;
};
inherit (outboundScripts) mkOutboundScript;
hybridRuntimeHelpersBlock = import ./script-blocks/hybrid-runtime-helpers.nix {
inherit
lib
jq
hybridEnabled
xraySidecarRoutingMark
;
};
backendJqFilter = import ./script-blocks/backend-jq-filter.nix {
inherit
lib
pureXrayEnabled
selectionMode
proxyInboundsGuardPrivate
;
};
backendJqFilterFile = pkgs.writeText "proxy-suite-${backend}-backend-filter.jq" backendJqFilter;
startScripts = import ./start-scripts.nix {
inherit
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
;
};
inherit (startScripts) startSocks startTun startPerAppTun;
proxyInboundsScripts = import ./proxy-inbounds-scripts.nix {
inherit
lib
pkgs
proxyCfg
proxyInboundsCfg
proxyInboundsNeedLocalProxy
proxyInboundViaOutbounds
userControlCfg
userControlEnabled
localProxyAuth
localProxyAuthEnabled
localProxyAuthPasswordSource
jq
python3
parserScriptsPythonPath
buildInboundPy
buildOutboundPy
proxyInboundsFile
proxyInboundsSpecFile
builders
constants
;
};
inherit (proxyInboundsScripts) startInbounds collectInboundStats;
proxyInboundsLinksFile = proxyInboundsScripts.linksFile;
proxyInboundsSubscriptionsFile = proxyInboundsScripts.subscriptionsFile;
controlScripts = import ./control-scripts.nix {
inherit
lib
pkgs
proxyCfg
clashApi
routeModeStateFile
priorityOutboundFile
outboundInventoryFile
subscriptionCacheDir
subscriptionCacheHelpersBlock
mkSubscriptionFetchBlock
runtimeSubscriptionsFetchBlock
jq
;
};
inherit (controlScripts)
subscriptionUpdateScript
setRouteModeScript
setPriorityOutboundScript
reloadOutboundsScript
;
in
{
inherit
startSocks
startTun
startPerAppTun
startInbounds
collectInboundStats
;
inherit
proxyInboundsLinksFile
proxyInboundsSubscriptionsFile
routeModeStateFile
setRouteModeScript
setPriorityOutboundScript
reloadOutboundsScript
subscriptionUpdateScript
subscriptionTagsFile
subscriptionCacheDir
runtimeProxychainsConfig
priorityOutboundFile
runtimeOutboundsDir
runtimeSubscriptionsDir
outboundInventoryFile
clashApi
;
}
@@ -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;
};
};
}
+65 -13
View File
@@ -2,36 +2,88 @@
{
lib,
pkgs,
packages,
cfg,
}:
let
t = cfg.tgWsProxy;
tgPkg = import ../../pkgs/tg-ws-proxy.nix { inherit pkgs; };
tgPkg = packages.tg-ws-proxy;
ip = "${pkgs.iproute2}/bin/ip";
dcArgs = lib.concatMapStrings (id: " --dc-ip=${id}:${t.dcIps.${id}}") (builtins.attrNames t.dcIps);
transparentBypassEnabled =
t.bypassTransparentProxy && cfg.proxy.enable && (cfg.proxy.tun.enable || cfg.proxy.tproxy.enable);
bypassRulePriority = 8999;
mkValueArg = name: value: " args+=(${name}=${lib.escapeShellArg value})\n";
mkRawValueArg = name: value: " args+=(${name}=${toString value})\n";
mkFlagArg = condition: name: lib.optionalString condition " args+=(${name})\n";
mkOptionalValueArg =
condition: name: value:
lib.optionalString condition (mkValueArg name value);
mkRepeatedValueArgs = name: values: lib.concatMapStrings (value: mkValueArg name value) values;
dcArgs = lib.concatMapStrings (id: mkValueArg "--dc-ip" "${id}:${t.dcIps.${id}}") (
builtins.attrNames t.dcIps
);
startScript = pkgs.writeShellScript "proxy-suite-tg-ws-proxy-start" ''
exec ${tgPkg}/bin/tg-ws-proxy \
--port=${toString t.port} \
--host=${t.host} \
${
if t.secretFile != null then
"--secret-file=$CREDENTIALS_DIRECTORY/tg_ws_proxy_secret"
else
"--secret=${t.secret}"
}${dcArgs}
args=(
--port=${toString t.listener.port}
--host=${lib.escapeShellArg t.listener.address}
)
${
if t.secretFile != null then
''args+=(--secret-file="$CREDENTIALS_DIRECTORY/tg_ws_proxy_secret")''
else
"args+=(--secret=${lib.escapeShellArg t.secret})"
}
${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"}
exec ${tgPkg}/bin/tg-ws-proxy "''${args[@]}"
'';
bypassUpScript = pkgs.writeShellScript "proxy-suite-tg-ws-proxy-bypass-up" ''
set -euo pipefail
add_bypass_rule() {
local family="$1"
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
add_bypass_rule -6
'';
bypassDownScript = pkgs.writeShellScript "proxy-suite-tg-ws-proxy-bypass-down" ''
set +e
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
{
systemd.services.proxy-suite-tg-ws-proxy = {
description = "Telegram MTProto WebSocket proxy";
after = [ "network.target" ];
after = [ "network-online.target" ];
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;
}
// lib.optionalAttrs transparentBypassEnabled {
ExecStartPre = bypassUpScript;
ExecStopPost = bypassDownScript;
SocketMark = toString t.fwmark;
};
};
}
+2 -2
View File
@@ -3,14 +3,14 @@
config,
lib,
pkgs,
packages,
cfg,
}:
let
tray = cfg.tray;
proxyTray = import ../../pkgs/proxy-suite-tray.nix {
inherit pkgs;
proxyTray = packages.mkProxySuiteTray {
pollInterval = tray.pollInterval;
};
@@ -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
;
}
+106 -217
View File
@@ -1,242 +1,131 @@
# zapret DPI bypass configuration + optional CIDR exemption from NFQUEUE
# zapret DPI bypass services and optional CIDR exemption from NFQUEUE.
{
lib,
pkgs,
cfg,
zapret,
perAppZapretRulesFile,
nft,
}:
let
z = cfg.zapret;
builders = import ./service/builders.nix { inherit lib pkgs; };
inherit (builders) mkOneshotService;
zapretCfg = cfg.zapret;
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
;
iptables = "${pkgs.iptables}/bin/iptables";
runtimeDeps = lib.attrValues {
inherit (pkgs)
iptables
ipset
coreutils
gawk
curl
wget
bash
kmod
findutils
gnused
gnugrep
procps
util-linux
;
};
zapretCommonPreStart = package: ''
${package}/opt/zapret/init.d/sysv/zapret stop || true
hostlistRuleNames = map (rule: rule.name) z.hostlistRules;
${lib.getExe' pkgs.kmod "modprobe"} xt_NFQUEUE 2>/dev/null || true
${lib.getExe' pkgs.kmod "modprobe"} xt_connbytes 2>/dev/null || true
${lib.getExe' pkgs.kmod "modprobe"} xt_multiport 2>/dev/null || true
upstreamZapretPackage =
let
upstreamPackages = zapret.packages.${pkgs.stdenv.hostPlatform.system};
in
if upstreamPackages ? zapret then upstreamPackages.zapret else upstreamPackages.default;
if ! ${pkgs.ipset}/bin/ipset list nozapret >/dev/null 2>&1; then
${pkgs.ipset}/bin/ipset create nozapret hash:net
fi
'';
listGeneralFile =
if z.listGeneral != [ ] then
pkgs.writeText "proxy-suite-zapret-list-general-user.txt" (
lib.concatStringsSep "\n" z.listGeneral + "\n"
)
else
null;
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
${nft} -f ${perAppZapretRulesFile}
'';
listExcludeFile =
if z.listExclude != [ ] then
pkgs.writeText "proxy-suite-zapret-list-exclude-user.txt" (
lib.concatStringsSep "\n" z.listExclude + "\n"
)
else
null;
perAppZapretMarkDownScript = pkgs.writeShellScript "proxy-suite-per-app-zapret-mark-down" ''
set -euo pipefail
${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true
'';
ipsetAllFile =
if z.ipsetAll != [ ] then
pkgs.writeText "proxy-suite-zapret-ipset-all.txt" (lib.concatStringsSep "\n" z.ipsetAll + "\n")
else
null;
ipsetExcludeFile =
if z.ipsetExclude != [ ] then
pkgs.writeText "proxy-suite-zapret-ipset-exclude-user.txt" (
lib.concatStringsSep "\n" z.ipsetExclude + "\n"
)
else
null;
hostlistRuleSpec = pkgs.writeText "proxy-suite-zapret-hostlist-rules.json" (
builtins.toJSON {
includeExtraUpstreamLists = z.includeExtraUpstreamLists;
entries = map (rule: {
inherit (rule)
name
preset
nfqwsArgs
;
}) z.hostlistRules;
}
);
selectedConfigName = lib.strings.sanitizeDerivationName z.configName;
patchConfigScriptSrc = builtins.path {
path = ../../scripts/patch-zapret-config.py;
name = "patch-zapret-config.py";
};
patchConfigScript = "${pkgs.python3}/bin/python3 ${patchConfigScriptSrc}";
customZapretPackage =
pkgs.runCommand "proxy-suite-zapret-${selectedConfigName}"
{
nativeBuildInputs = with pkgs; [
coreutils
gnused
python3
];
}
''
set -euo pipefail
mkdir -p "$out"
cp -a ${upstreamZapretPackage}/. "$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|${upstreamZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
{} \;
if [ -f "$out/opt/zapret/configs/${z.configName}" ]; then
cp "$out/opt/zapret/configs/${z.configName}" "$out/opt/zapret/config"
else
echo "proxy-suite: zapret config '${z.configName}' not found in upstream package" >&2
ls -la "$out/opt/zapret/configs" >&2 || true
exit 1
fi
${pkgs.gnused}/bin/sed -i \
-e 's|${upstreamZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
"$out/opt/zapret/config"
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"
}
${lib.optionalString (listGeneralFile != null) ''
append_list_file list-general-user.txt ${listGeneralFile}
''}
${lib.optionalString (listExcludeFile != null) ''
append_list_file list-exclude-user.txt ${listExcludeFile}
''}
${lib.optionalString (ipsetAllFile != null) ''
append_list_file ipset-all.txt ${ipsetAllFile}
''}
${lib.optionalString (ipsetExcludeFile != null) ''
append_list_file ipset-exclude-user.txt ${ipsetExcludeFile}
''}
rm -f "$out/opt/zapret/hostlists/.game_filter.enabled"
${lib.optionalString (z.gameFilter != "null") ''
echo "${z.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"
''
) z.hostlistRules}
${patchConfigScript} --config "$out/opt/zapret/config" --spec ${hostlistRuleSpec}
'';
exemptStart = lib.concatMapStrings (cidr: ''
${iptables} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN
exemptStart = ''
set -euo pipefail
''
+ lib.concatMapStrings (cidr: ''
while ${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN 2>/dev/null; do :; done
while ${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN 2>/dev/null; do :; done
${iptables} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN
${iptables} -t mangle -I POSTROUTING 1 -s ${cidr} -j RETURN
'') z.cidrExemption.cidrs;
'') zapretCfg.cidrExemption.cidrs;
exemptStop = lib.concatMapStrings (cidr: ''
${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN || true
${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN || true
'') z.cidrExemption.cidrs;
exemptStop = ''
set +e
''
+ lib.concatMapStrings (cidr: ''
while ${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN 2>/dev/null; do :; done
while ${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN 2>/dev/null; do :; done
'') 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 != [ ]) z.hostlistRules;
message = "proxy-suite: each zapret.hostlistRules entry must define at least one domain";
}
{
assertion = builtins.all (rule: rule.preset != null || rule.nfqwsArgs != [ ]) z.hostlistRules;
message = "proxy-suite: each zapret.hostlistRules entry must set preset, nfqwsArgs, or both";
}
];
assertions = zapretPackages.assertions;
services.zapret-discord-youtube = {
enable = true;
configName = z.configName;
gameFilter = z.gameFilter;
listGeneral = z.listGeneral;
listExclude = z.listExclude;
ipsetAll = z.ipsetAll;
ipsetExclude = z.ipsetExclude;
};
environment.systemPackages = lib.mkBefore (
lib.optionals zapretCfg.enable [ globalZapretPackage ]
++ lib.optionals perAppZapretCfg.enable [ perAppZapretPackage ]
);
environment.systemPackages = lib.mkBefore [ customZapretPackage ];
systemd.services.zapret-discord-youtube = {
preStart = lib.mkForce ''
${customZapretPackage}/opt/zapret/init.d/sysv/zapret stop || true
${lib.getExe' pkgs.kmod "modprobe"} xt_NFQUEUE 2>/dev/null || true
${lib.getExe' pkgs.kmod "modprobe"} xt_connbytes 2>/dev/null || true
${lib.getExe' pkgs.kmod "modprobe"} xt_multiport 2>/dev/null || true
if ! ${pkgs.ipset}/bin/ipset list nozapret >/dev/null 2>&1; then
${pkgs.ipset}/bin/ipset create nozapret hash:net
fi
'';
serviceConfig = {
ExecStart = lib.mkForce "${customZapretPackage}/opt/zapret/init.d/sysv/zapret start";
ExecStop = lib.mkForce "${customZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
ExecReload = lib.mkForce "${customZapretPackage}/opt/zapret/init.d/sysv/zapret restart";
Environment = lib.mkForce [
"ZAPRET_BASE=${customZapretPackage}/opt/zapret"
"PATH=${lib.makeBinPath runtimeDeps}"
];
};
};
systemd.services.proxy-suite-zapret-vm-exempt = lib.mkIf z.cidrExemption.enable {
description = "Exempt CIDRs from zapret NFQUEUE";
after = [ "zapret-discord-youtube.service" ];
wants = [ "zapret-discord-youtube.service" ];
systemd.services.zapret-discord-youtube = lib.mkIf zapretCfg.enable (mkOneshotService {
description = "zapret DPI bypass";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = awgServiceNames;
wantedBy = [ "multi-user.target" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-start" exemptStart;
ExecStop = pkgs.writeShellScript "proxy-suite-zapret-vm-exempt-stop" exemptStop;
preStart = zapretCommonPreStart globalZapretPackage;
runtimeDirectory = "proxy-suite-zapret";
execStart = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret start";
execStop = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
extraServiceConfig = {
ExecReload = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret restart";
Environment = globalZapretEnv;
};
};
});
systemd.services.proxy-suite-per-app-zapret = lib.mkIf perAppZapretCfg.enable (mkOneshotService {
description = "proxy-suite per-app-routing zapret backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
conflicts = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
]
++ awgServiceNames;
preStart = zapretCommonPreStart perAppZapretPackage;
runtimeDirectory = "proxy-suite-per-app-zapret";
execStart = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret start";
execStop = "${perAppZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
execStartPre = "${perAppZapretMarkUpScript}";
execStopPost = "${perAppZapretMarkDownScript}";
extraServiceConfig.Environment = perAppZapretEnv;
});
systemd.services.proxy-suite-zapret-vm-exempt =
lib.mkIf (zapretCfg.enable && zapretCfg.cidrExemption.enable)
(mkOneshotService {
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";
}
+40 -998
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
)
];
}
@@ -0,0 +1,58 @@
{
pkgs,
minimal,
customSingBoxPackageBin,
customSingBoxPackageStartScript,
proxyDirectConfig,
ruDefaultConfig,
urlTestCustomStartScript,
noProxyBackendDefaultFixture,
invalidCoreProxyAssertions,
}:
{
assertions = [
# -- sing-box package override propagates into generated service scripts --
(
assert pkgs.lib.hasInfix customSingBoxPackageBin customSingBoxPackageStartScript;
true
)
# -- proxy defaults and urltest settings are applied --
(
assert proxyDirectConfig.dns.final == "local";
true
)
(
assert ruDefaultConfig.dns.final == "remote";
true
)
(
assert ruDefaultConfig.route.default_domain_resolver == "local";
true
)
(
assert builtins.match ".*telegram\\.org.*" urlTestCustomStartScript != null;
assert builtins.match ".*1m.*" urlTestCustomStartScript != null;
assert builtins.match ".*100.*" urlTestCustomStartScript != null;
true
)
(
let
cfg = minimal.config.services.proxy-suite.proxy.urlTest;
in
assert cfg.url == "https://www.gstatic.com/generate_204";
assert cfg.interval == "3m";
assert minimal.config.services.proxy-suite.proxy.urlTest.tolerance == 50;
true
)
# -- proxy backend defaults and required inputs are enforced --
(
assert noProxyBackendDefaultFixture.config.services.proxy-suite.proxy.enable == false;
assert !(noProxyBackendDefaultFixture.config.systemd.services ? "proxy-suite-socks");
true
)
]
++ invalidCoreProxyAssertions;
}
+120
View File
@@ -0,0 +1,120 @@
{
pkgs,
evalProxySuite,
baseModule,
mkBadFixture,
mkFailingAssertions,
mkTunConfig,
dnsServerByTag,
checkConstants,
}:
let
fixtures = import ./global-proxy-modes/fixtures.nix {
inherit
evalProxySuite
baseModule
mkBadFixture
mkFailingAssertions
mkTunConfig
;
};
inherit (fixtures)
invalidGlobalProxyModeAssertions
tproxyAutostartFixture
tproxyManualFixture
tproxyManualStartScript
tproxyManualStopScript
tproxyWithFirewall
tunAutostartFixture
tunCleanupScript
tunDefaultConfig
tunManualFixture
tunServiceConfig
;
in
{
assertions = [
(
assert tproxyWithFirewall.config.networking.firewall.enable;
true
)
(
assert tproxyManualFixture.config.services.proxy-suite.proxy.autostart == null;
assert tproxyManualFixture.config.systemd.services."proxy-suite-tproxy".wantedBy == [ ];
true
)
(
assert
tproxyAutostartFixture.config.systemd.services."proxy-suite-tproxy".wantedBy
== [ "multi-user.target" ];
true
)
(
assert pkgs.lib.hasInfix "set -euo pipefail" tproxyManualStartScript;
assert pkgs.lib.hasInfix "rule del fwmark 1 table 100" tproxyManualStartScript;
assert pkgs.lib.hasInfix "route replace local default dev lo table 100" tproxyManualStartScript;
assert pkgs.lib.hasInfix "set +e" tproxyManualStopScript;
assert pkgs.lib.hasInfix "rule del fwmark 1 table 100" tproxyManualStopScript;
true
)
(
assert tunManualFixture.config.services.proxy-suite.proxy.autostart == null;
assert tunManualFixture.config.systemd.services."proxy-suite-tun".wantedBy == [ ];
true
)
(
let
inbound = builtins.head (builtins.filter (item: item.tag == "tun-in") tunDefaultConfig.inbounds);
in
assert inbound.iproute2_table_index == checkConstants.tunAutoRouteTableIndex;
assert inbound.iproute2_rule_index == checkConstants.tunAutoRouteRulePriority;
assert tunDefaultConfig.route.auto_detect_interface == true;
true
)
(
assert tunManualFixture.config.networking.nftables.enable;
true
)
(
assert tunServiceConfig.ExecStartPre == tunServiceConfig.ExecStopPost;
assert pkgs.lib.hasInfix "delete table inet sing-box" tunCleanupScript;
assert pkgs.lib.hasInfix "rule del table ${toString checkConstants.tunAutoRouteTableIndex}"
tunCleanupScript;
assert pkgs.lib.hasInfix "rule del pref ${toString checkConstants.xrayTunPerAppTproxyRulePriority}"
tunCleanupScript;
assert pkgs.lib.hasInfix "rule del pref ${toString checkConstants.xrayTunPerAppTunRulePriority}"
tunCleanupScript;
assert pkgs.lib.hasInfix "route flush table ${toString checkConstants.tunAutoRouteTableIndex}"
tunCleanupScript;
assert pkgs.lib.hasInfix "link del dev" tunCleanupScript;
assert pkgs.lib.hasInfix "singtun0" tunCleanupScript;
true
)
(
assert
tunAutostartFixture.config.systemd.services."proxy-suite-tun".wantedBy == [ "multi-user.target" ];
true
)
(
let
localDns = dnsServerByTag tunDefaultConfig "local";
in
assert !(localDns ? detour);
true
)
(
assert tunDefaultConfig.route.default_domain_resolver == "local";
true
)
(
assert builtins.elem "network-online.target"
tunManualFixture.config.systemd.services."proxy-suite-tun".after;
assert builtins.elem "network-online.target"
tunManualFixture.config.systemd.services."proxy-suite-tun".wants;
true
)
]
++ invalidGlobalProxyModeAssertions;
}
+111
View File
@@ -0,0 +1,111 @@
{
evalProxySuite,
baseModule,
mkBadFixture,
mkFailingAssertions,
mkTunConfig,
}:
let
generated = import ../read-generated.nix;
tproxyWithFirewall = evalProxySuite [
{
system.stateVersion = "26.05";
networking.firewall.enable = true;
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
backend = "sing-box";
tproxy.enable = true;
outbounds = [
{
tag = "primary";
url = "http://proxy.example.com:8080";
}
];
};
};
}
];
tproxyManualFixture = evalProxySuite [
baseModule
{
services.proxy-suite.proxy.tproxy.enable = true;
}
];
tproxyManualServiceConfig =
tproxyManualFixture.config.systemd.services."proxy-suite-tproxy".serviceConfig;
tproxyManualStartScript = generated.readDerivation tproxyManualServiceConfig.ExecStart;
tproxyManualStopScript = generated.readDerivation tproxyManualServiceConfig.ExecStop;
tproxyAutostartFixture = evalProxySuite [
baseModule
{
services.proxy-suite.proxy = {
tproxy.enable = true;
autostart = "tproxy";
};
}
];
tunManualFixture = evalProxySuite [
baseModule
{
services.proxy-suite.proxy.tun.enable = true;
}
];
tunAutostartFixture = evalProxySuite [
baseModule
{
services.proxy-suite.proxy = {
tun.enable = true;
autostart = "tun";
};
}
];
invalidGlobalProxyModeAssertions = mkFailingAssertions mkBadFixture [
# TUN and TProxy can no longer both autostart: proxy.autostart holds one mode.
# Transparent proxy backends require proxy.enable.
[
{
services.proxy-suite.proxy = {
enable = false;
tun.enable = true;
};
}
]
[
{
services.proxy-suite.proxy = {
enable = false;
tproxy.enable = true;
};
}
]
];
tunDefaultConfig = mkTunConfig tunManualFixture;
tunServiceConfig = tunManualFixture.config.systemd.services."proxy-suite-tun".serviceConfig;
tunCleanupScript = generated.readDerivation tunServiceConfig.ExecStopPost;
in
{
inherit
invalidGlobalProxyModeAssertions
tproxyAutostartFixture
tproxyManualFixture
tproxyManualStartScript
tproxyManualStopScript
tproxyWithFirewall
tunAutostartFixture
tunCleanupScript
tunDefaultConfig
tunManualFixture
tunServiceConfig
;
}
+111
View File
@@ -0,0 +1,111 @@
{
pkgs,
evalProxySuite,
mkTProxyConfig,
mkTunConfig,
shellValueByPrefix,
checkConstants,
}:
let
fixtures = import ./hybrid-backend/fixtures.nix {
inherit
pkgs
evalProxySuite
mkTProxyConfig
mkTunConfig
shellValueByPrefix
;
};
inherit (fixtures)
hybridBackendJqFilter
hybridFixture
hybridPerAppTunStartScript
hybridStartScript
hybridSubscriptionStartScript
hybridSubscriptionUpdateScript
hybridTproxyConfig
hybridTunConfig
hybridTunStartScript
hybridXrayRawStartScript
;
in
{
assertions = [
# -- hybrid backend: sing-box frontend with XRay loopback sidecar --
(
let
dnsBridgeInbound = builtins.head (
builtins.filter (inbound: inbound.tag == "xray-dns-in") hybridTproxyConfig.inbounds
);
mixedInbound = builtins.head (
builtins.filter (inbound: inbound.tag == "mixed-in") hybridTproxyConfig.inbounds
);
tproxyInbound = builtins.head (
builtins.filter (inbound: inbound.tag == "tproxy-in") hybridTproxyConfig.inbounds
);
tunDnsBridgeInbound = builtins.head (
builtins.filter (inbound: inbound.tag == "xray-dns-in") hybridTunConfig.inbounds
);
dnsBridgeRouteRule = builtins.head (
builtins.filter (
rule:
(rule.action or "") == "hijack-dns" && (rule ? inbound) && builtins.elem "xray-dns-in" rule.inbound
) hybridTproxyConfig.route.rules
);
in
assert hybridFixture.config.services.proxy-suite.proxy.backend == "hybrid";
assert hybridTproxyConfig ? route;
assert !(hybridTproxyConfig ? routing);
assert dnsBridgeInbound.type == "direct";
assert dnsBridgeInbound.listen == "127.0.0.1";
assert dnsBridgeInbound.listen_port == checkConstants.xrayDnsBridgePorts.socks;
assert mixedInbound.type == "mixed";
assert tproxyInbound.type == "tproxy";
assert tunDnsBridgeInbound.listen_port == checkConstants.xrayDnsBridgePorts.tun;
assert
dnsBridgeRouteRule.network == [
"tcp"
"udp"
];
assert pkgs.lib.hasInfix "/bin/sing-box run -c" hybridStartScript;
assert pkgs.lib.hasInfix "/bin/xray run -c" hybridStartScript;
assert pkgs.lib.hasInfix "xray-sidecar.json" hybridStartScript;
assert pkgs.lib.hasInfix
"XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.socks}"
hybridStartScript;
assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.socks}"
hybridStartScript;
assert pkgs.lib.hasInfix
"XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.tun}"
hybridTunStartScript;
assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.tun}"
hybridTunStartScript;
assert pkgs.lib.hasInfix
"XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.perAppTun}"
hybridPerAppTunStartScript;
assert pkgs.lib.hasInfix
"XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.perAppTun}"
hybridPerAppTunStartScript;
assert pkgs.lib.hasInfix "--backend sing-box" hybridStartScript;
assert pkgs.lib.hasInfix "--backend xray" hybridStartScript;
assert pkgs.lib.hasInfix "_proxy_suite_add_xray_sidecar_ob" hybridStartScript;
assert pkgs.lib.hasInfix "hybrid XRay json sidecar" hybridXrayRawStartScript;
assert pkgs.lib.hasInfix ''{type:"socks",tag:$tag,server:"127.0.0.1"'' hybridXrayRawStartScript;
assert pkgs.lib.hasInfix "udp:true" hybridXrayRawStartScript;
assert pkgs.lib.hasInfix "routing_mark:2" hybridXrayRawStartScript;
assert pkgs.lib.hasInfix "sing_box_preserved_rules" hybridBackendJqFilter;
assert pkgs.lib.hasInfix "xray-dns-in" hybridBackendJqFilter;
assert pkgs.lib.hasInfix "--backend hybrid" hybridSubscriptionStartScript;
assert pkgs.lib.hasInfix "--backend hybrid" hybridSubscriptionUpdateScript;
assert pkgs.lib.hasInfix
''type == "object" and (.singBox | type == "array") and (.xray | type == "array")''
hybridSubscriptionStartScript;
assert pkgs.lib.hasInfix ".singBox" hybridSubscriptionStartScript;
assert pkgs.lib.hasInfix ".xray[]" hybridSubscriptionStartScript;
assert pkgs.lib.hasInfix "_proxy_suite_add_xray_sidecar_ob" hybridSubscriptionStartScript;
true
)
];
}
+121
View File
@@ -0,0 +1,121 @@
{
pkgs,
evalProxySuite,
mkTProxyConfig,
mkTunConfig,
shellValueByPrefix,
}:
let
generated = import ../read-generated.nix;
hybridModule = {
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
backend = "hybrid";
selection = "selector";
outbounds = [
{
tag = "primary";
url = "vless://uuid@example.com:443?type=tcp&security=reality&pbk=pubkey&fp=qq&sni=last.fm&sid=8a54&spx=%2F-%2Fen%2Fgp%2Fbestsellers&flow=xtls-rprx-vision&encryption=none";
}
{
tag = "xray-only";
url = "vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fx";
}
];
tproxy.enable = true;
tun.enable = true;
};
perAppRouting.tun.enable = true;
};
};
hybridFixture = evalProxySuite [ hybridModule ];
hybridTproxyConfig = mkTProxyConfig hybridFixture;
hybridTunConfig = mkTunConfig hybridFixture;
hybridStartScript = generated.readDerivation (
hybridFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart
);
hybridTunStartScript = generated.readDerivation (
hybridFixture.config.systemd.services."proxy-suite-tun".serviceConfig.ExecStart
);
hybridPerAppTunStartScript = generated.readDerivation (
hybridFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStart
);
hybridBackendJqFilter =
import ../../../modules/proxy-suite/service/script-blocks/backend-jq-filter.nix
{
lib = pkgs.lib;
proxyInboundsGuardPrivate = false;
pureXrayEnabled = false;
selectionMode = hybridFixture.config.services.proxy-suite.proxy.selection;
};
hybridXrayRawFixture = evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
backend = "hybrid";
outbounds = [
{
tag = "raw-xray";
xrayJson = {
protocol = "freedom";
settings = { };
};
}
];
};
};
}
];
hybridXrayRawStartScript = generated.readDerivation (
hybridXrayRawFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart
);
hybridSubscriptionFixture = evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
backend = "hybrid";
subscriptions = [
{
tag = "community";
url = "https://example.com/hybrid-sub";
}
];
selection = "selector";
};
};
}
];
hybridSubscriptionStartScript = generated.readDerivation (
hybridSubscriptionFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart
);
hybridSubscriptionUpdateScript = generated.readDerivation (
hybridSubscriptionFixture.config.systemd.services."proxy-suite-subscription-update".serviceConfig.ExecStart
);
in
{
inherit
hybridBackendJqFilter
hybridFixture
hybridPerAppTunStartScript
hybridStartScript
hybridSubscriptionStartScript
hybridSubscriptionUpdateScript
hybridTproxyConfig
hybridTunConfig
hybridTunStartScript
hybridXrayRawStartScript
;
}
+257
View File
@@ -0,0 +1,257 @@
{
pkgs,
system,
nixpkgs,
proxySuiteModule,
zapret,
}:
let
generated = import ./read-generated.nix;
evalProxySuite =
modules:
import "${nixpkgs}/nixos/lib/eval-config.nix" {
inherit system;
modules = [ proxySuiteModule ] ++ modules;
};
forceEval = value: builtins.tryEval (builtins.deepSeq value true);
rg = "${pkgs.ripgrep}/bin/rg";
mkRouting =
fixture:
let
cfg = fixture.config.services.proxy-suite;
in
import ../../modules/proxy-suite/rules.nix {
lib = pkgs.lib;
inherit pkgs cfg zapret;
};
mkRoutingRules = fixture: (mkRouting fixture).routingRules;
mkRouteModeRules = fixture: (mkRouting fixture).routeModeRules;
mkProxyConfig =
fixture: configAttr:
let
cfg = fixture.config.services.proxy-suite;
rules = mkRouting fixture;
configs = import ../../modules/proxy-suite/config.nix {
lib = pkgs.lib;
inherit pkgs cfg rules;
};
in
builtins.fromJSON (
builtins.unsafeDiscardStringContext (generated.readDerivation configs.${configAttr})
);
mkTProxyConfig = fixture: mkProxyConfig fixture "tproxyFile";
mkTunConfig = fixture: mkProxyConfig fixture "tunFile";
mkPerAppTunConfig = fixture: mkProxyConfig fixture "perAppTunFile";
mkInboundsConfig = fixture: mkProxyConfig fixture "proxyInboundsFile";
mkInboundsSpec = fixture: mkProxyConfig fixture "proxyInboundsSpecFile";
mkTProxyNftRules =
fixture:
let
cfg = fixture.config.services.proxy-suite;
nftr = import ../../modules/proxy-suite/nftables.nix {
lib = pkgs.lib;
inherit pkgs cfg;
};
in
generated.readDerivation nftr.nftablesRulesFile;
mkPerAppZapretNftRules =
fixture:
let
cfg = fixture.config.services.proxy-suite;
nftr = import ../../modules/proxy-suite/nftables.nix {
lib = pkgs.lib;
inherit pkgs cfg;
};
in
generated.readDerivation nftr.perAppZapretRulesFile;
mkPerAppUserRules =
fixture:
let
cfg = fixture.config.services.proxy-suite;
derived = import ../../modules/proxy-suite/derived.nix {
lib = pkgs.lib;
inherit cfg;
};
nftr = import ../../modules/proxy-suite/nftables.nix {
lib = pkgs.lib;
inherit pkgs cfg;
};
in
import ../../modules/proxy-suite/service/per-app-routing/user-rules.nix {
lib = pkgs.lib;
inherit pkgs;
inherit (derived)
perAppRoutingTun
perAppRoutingTproxy
perAppZapretCfg
;
perAppTunSliceName = "proxy-suite-per-app-tun.slice";
perAppTproxySliceName = "proxy-suite-per-app-tproxy.slice";
perAppZapretSliceName = "proxy-suite-per-app-zapret.slice";
inherit (nftr) nft;
awk = "${pkgs.gawk}/bin/awk";
grepBin = "${pkgs.gnugrep}/bin/grep";
findBin = "${pkgs.findutils}/bin/find";
headBin = "${pkgs.coreutils}/bin/head";
};
hasDirectDomain =
rules: domain:
builtins.any (
rule: (rule ? domain_suffix) && rule.outbound == "direct" && builtins.elem domain rule.domain_suffix
) rules;
hasDirectIP =
rules: cidr:
builtins.any (
rule: (rule ? ip_cidr) && rule.outbound == "direct" && builtins.elem cidr rule.ip_cidr
) rules;
hasRuleSet =
rules: outbound: ruleSet:
builtins.any (
rule: (rule ? rule_set) && rule.outbound == outbound && builtins.elem ruleSet rule.rule_set
) rules;
dnsHasRuleSet =
dnsRules: ruleSet:
builtins.any (rule: (rule ? rule_set) && builtins.elem ruleSet rule.rule_set) dnsRules;
dnsServerByTag =
dnsConfig: tag: builtins.head (builtins.filter (server: server.tag == tag) dnsConfig.dns.servers);
mkZapretBaseFor =
fixture: serviceName:
let
env = fixture.config.systemd.services.${serviceName}.serviceConfig.Environment;
zapretBaseEnv = builtins.head (
builtins.filter (value: pkgs.lib.hasPrefix "ZAPRET_BASE=" value) env
);
in
pkgs.lib.removePrefix "ZAPRET_BASE=" zapretBaseEnv;
mkZapretBase = fixture: mkZapretBaseFor fixture "zapret-discord-youtube";
packagePathMatches =
packages: pattern:
builtins.any (
pkg: builtins.match pattern (builtins.unsafeDiscardStringContext (toString pkg)) != null
) packages;
packageByPattern =
packages: pattern:
builtins.head (
builtins.filter (
pkg: builtins.match pattern (builtins.unsafeDiscardStringContext (toString pkg)) != null
) packages
);
lineByPrefix =
text: prefix:
builtins.head (
builtins.filter (line: pkgs.lib.hasPrefix prefix line) (pkgs.lib.splitString "\n" text)
);
lineContaining =
text: infix:
builtins.head (
builtins.filter (line: pkgs.lib.hasInfix infix line) (pkgs.lib.splitString "\n" text)
);
shellValueByPrefix =
text: prefix:
let
value = pkgs.lib.removePrefix prefix (lineByPrefix text prefix);
in
if pkgs.lib.hasPrefix "'" value && pkgs.lib.hasSuffix "'" value then
pkgs.lib.removeSuffix "'" (pkgs.lib.removePrefix "'" value)
else if pkgs.lib.hasPrefix "\"" value && pkgs.lib.hasSuffix "\"" value then
pkgs.lib.removeSuffix "\"" (pkgs.lib.removePrefix "\"" value)
else
value;
baseModule = {
system.stateVersion = "26.05";
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
backend = "sing-box";
outbounds = [
{
tag = "primary";
url = "http://proxy.example.com:8080";
}
];
};
};
};
mkFixture =
proxySuiteConfig:
evalProxySuite [
{
system.stateVersion = "26.05";
services.proxy-suite = proxySuiteConfig;
}
];
mkBadFixture =
modules:
forceEval ((evalProxySuite ([ baseModule ] ++ modules)).config.system.build.toplevel.drvPath);
mkBadFixtureRaw =
modules: forceEval ((evalProxySuite modules).config.system.build.toplevel.drvPath);
mkBadProxySuiteFixture =
proxySuiteConfig: forceEval ((mkFixture proxySuiteConfig).config.system.build.toplevel.drvPath);
mkFailingAssertions =
evaluate: cases:
map (
case:
assert (evaluate case).success == false;
true
) cases;
mkProxyCtlDerived =
fixture:
let
proxyCtl = packageByPattern fixture.config.environment.systemPackages ".*/[^/]*proxy-ctl(-[0-9.]+)?$";
metadata = proxyCtl.proxySuiteCheck;
wrapper = pkgs.lib.concatStringsSep "\n" (
pkgs.lib.mapAttrsToList (
name: value: "export ${name}=${pkgs.lib.escapeShellArg value}"
) metadata.wrapperEnv
);
in
{
inherit proxyCtl wrapper;
script = wrapper + "\n" + metadata.script;
profiles = builtins.fromJSON (generated.readDerivation metadata.perAppRoutingProfilesFile);
subscriptionTags = builtins.fromJSON (generated.readDerivation metadata.subscriptionTagsFile);
inherit (metadata) proxychainsConfigFile wrapperEnv;
awgProfiles = builtins.fromJSON (generated.readDerivation metadata.amneziaWgProfileNamesFile);
};
in
{
inherit
rg
evalProxySuite
forceEval
mkRouting
mkRoutingRules
mkRouteModeRules
mkTProxyConfig
mkTunConfig
mkPerAppTunConfig
mkInboundsConfig
mkInboundsSpec
mkTProxyNftRules
mkPerAppZapretNftRules
mkPerAppUserRules
hasDirectDomain
hasDirectIP
hasRuleSet
dnsHasRuleSet
dnsServerByTag
mkZapretBaseFor
mkZapretBase
packagePathMatches
packageByPattern
lineByPrefix
lineContaining
shellValueByPrefix
baseModule
mkFixture
mkBadFixture
mkBadFixtureRaw
mkBadProxySuiteFixture
mkFailingAssertions
mkProxyCtlDerived
;
}
Loaded 100 of 186 files, more files were not shown because too many files have changed in this diff. Show more