14 Commits
Author SHA1 Message Date
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
12 changed files with 7722 additions and 667 deletions

No files matched your search

+13 -485
View File
@@ -1,25 +1,26 @@
# proxy-suite-flake
Declarative proxy stack for NixOS. One flake, one module, done.
Declarative proxy stack for NixOS.
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.
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.
The goal is to replace GUI clients like v2rayN and throne – you configure your proxies in Nix, rebuild, and they just work as systemd services.
---
## 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
- **Transparent proxy (TProxy)** – redirect all system traffic through sing-box without configuring each app; start/stop on demand or autostart at boot
- **TUN mode** – full tunnel via a virtual network interface; useful when TProxy doesn't cover something, with optional boot-time autostart
- **Per-app wrapping** – run selected apps through the local proxy with `proxy-ctl wrap <profile> -- <command>`, without enabling global TProxy or TUN
- **Subscription URLs** – point at a v2rayN/Clash-format subscription endpoint; the module fetches, decodes, and imports all proxies automatically, with a periodic refresh timer
- **Multiple outbounds** with automatic latency-based switching or manual selection
- **Per-outbound routing** – route specific domains, IPs, or geo sets to specific servers
- **Protocol support**: vless (Reality, TLS), vmess, trojan, shadowsocks, hysteria2, 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
- **DPI bypass** via zapret – handles YouTube, Discord, and other sites defined by the project
- **Telegram proxy** – running local MTProto WebSocket proxy using tg-ws-proxy
---
@@ -36,496 +37,23 @@ 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
Enable the service with all defaults:
```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 = {
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;
};
};
```
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.
By default, `zapret` and `tgWsProxy` stay disabled until you enable them explicitly.
---
## Outbound formats
## Options
Each outbound needs exactly one of `urlFile`, `url`, or `json`.
To see options and documentation, check out the [options reference](./docs/options.md).
### 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 = {
enable = true;
autostart = true; # Install XDG autostart for all graphical users (default)
pollInterval = 5; # Status refresh interval in seconds
};
};
```
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
When enabled, the tray app is installed system-wide and autostarts for all graphical users via XDG autostart unless you set `tray.autostart = false;`.
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.
To enable TProxy/TUN toggles in the tray, you need to enable the services in your config:
```nix
services.proxy-suite.singBox = {
tproxy.enable = true; # Show TProxy toggle
tun.enable = true; # Show TUN toggle
};
```
Options are autogenerated from [options.nix](./modules/proxy-suite/options.nix) using `nix run .#update-options-doc`.
+4695
View File
File diff suppressed because it is too large. Load diff
+45 -3
View File
@@ -23,6 +23,9 @@
forAll = nixpkgs.lib.genAttrs systems;
pkgsFor = system: import nixpkgs { inherit system; };
proxySuiteModule = import ./modules/proxy-suite { inherit zapret; };
mkOptionsDoc = import ./nix/options-doc.nix {
inherit nixpkgs pkgsFor proxySuiteModule;
};
in
{
# Main module – bakes in the zapret flake so consumers don't need it as a separate input.
@@ -36,9 +39,47 @@
proxy-suite-tray = import ./pkgs/proxy-suite-tray.nix { pkgs = final; };
};
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;
in
{
tg-ws-proxy = import ./pkgs/tg-ws-proxy.nix { inherit pkgs; };
proxy-suite-tray = import ./pkgs/proxy-suite-tray.nix { inherit pkgs; };
optionsDoc = mkOptionsDoc system;
update-options-doc = pkgs.writeShellApplication {
name = "update-options-doc";
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
output_path="$(nix build --no-link --print-out-paths "''${repo_root}#optionsDoc")"
target_path="''${repo_root}/docs/options.md"
install -Dm644 "''${output_path}" "''${target_path}"
echo "updated ''${target_path}"
'';
};
}
);
apps = forAll (system: {
update-options-doc = {
type = "app";
program = "${self.packages.${system}.update-options-doc}/bin/update-options-doc";
};
});
checks = forAll (
@@ -50,6 +91,7 @@
proxySuiteModule
zapret
;
generatedOptionsDoc = mkOptionsDoc system;
}
);
};
+78 -43
View File
@@ -9,8 +9,38 @@
let
sb = cfg.singBox;
art = cfg.appRouting.backends.tun;
direct = rules.direct;
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" sb.dns.remote "proxy")
(mkDnsServer "local" sb.dns.local localDetour)
];
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";
};
clashApiBlock = lib.optionalAttrs (sb.selection != "first") {
experimental = {
clash_api = {
@@ -19,50 +49,30 @@ let
};
};
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";
};
dnsConfigTun = dnsConfig // {
servers = map (s: if s.tag == "local" then s // { detour = "proxy"; } else s) dnsConfig.servers;
};
mkConfig =
{
enableMixed ? false,
enableTProxy ? false,
enableTun ? false,
tunInterface ? sb.tun.interface,
tunAddress ? sb.tun.address,
tunMtu ? sb.tun.mtu,
tunAutoRoute ? true,
tunAutoRedirect ? true,
tunStrictRoute ? true,
forceLocalDnsViaProxy ? false,
useOutboundRoutingMark ? false,
enableClashApi ? true,
}:
{
log.level = "warn";
dns = if enableTun then dnsConfigTun else dnsConfig;
# Keep "local" DNS on the direct path by default, but avoid explicit
# detour="direct" because sing-box rejects detouring to an empty
# direct outbound. Global TUN can force local DNS through proxy.
dns = mkDnsConfig {
localDetour = if forceLocalDnsViaProxy then "proxy" else null;
};
inbounds =
lib.optional enableMixed {
@@ -80,12 +90,12 @@ let
++ 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;
interface_name = tunInterface;
address = [ tunAddress ];
mtu = tunMtu;
auto_route = tunAutoRoute;
auto_redirect = tunAutoRedirect;
strict_route = tunStrictRoute;
stack = "mixed";
};
@@ -110,24 +120,49 @@ let
rules = rules.routingRules;
final = if sb.proxyByDefault then "proxy" else "direct";
}
// lib.optionalAttrs enableTun { auto_detect_interface = true; };
// lib.optionalAttrs (enableTun && tunAutoRoute) { auto_detect_interface = true; };
}
// clashApiBlock;
// lib.optionalAttrs enableClashApi clashApiBlock;
tproxyTemplate = mkConfig {
enableMixed = true;
enableTProxy = true;
useOutboundRoutingMark = true;
enableClashApi = true;
};
tunTemplate = mkConfig {
enableTun = true;
tunInterface = sb.tun.interface;
tunAddress = sb.tun.address;
tunMtu = sb.tun.mtu;
tunAutoRoute = true;
tunAutoRedirect = true;
tunStrictRoute = true;
forceLocalDnsViaProxy = true;
enableClashApi = false;
};
appTunTemplate = mkConfig {
enableTun = true;
tunInterface = art.interface;
tunAddress = art.address;
tunMtu = art.mtu;
tunAutoRoute = false;
tunAutoRedirect = false;
tunStrictRoute = false;
forceLocalDnsViaProxy = false;
# App TUN can be used alongside TProxy; mark direct egress so TProxy output
# rules do not re-intercept sing-box's own packets.
useOutboundRoutingMark = sb.tproxy.enable;
enableClashApi = false;
};
tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (builtins.toJSON tproxyTemplate);
tunFile = pkgs.writeText "proxy-suite-tun-template.json" (builtins.toJSON tunTemplate);
appTunFile = pkgs.writeText "proxy-suite-app-tun-template.json" (builtins.toJSON appTunTemplate);
in
{
inherit tproxyFile tunFile;
inherit tproxyFile tunFile appTunFile;
}
+4 -6
View File
@@ -11,13 +11,11 @@
let
cfg = config.services.proxy-suite;
nftr = import ./nftables.nix { inherit lib pkgs 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
];
config = lib.mkIf cfg.enable (
@@ -40,7 +38,6 @@ in
rules
;
};
nftr = import ./nftables.nix { inherit lib pkgs cfg; };
in
import ./service.nix {
inherit
@@ -49,8 +46,8 @@ in
pkgs
cfg
;
inherit (configs) tproxyFile tunFile;
inherit (nftr) nftablesRulesFile ip nft;
inherit (configs) tproxyFile tunFile appTunFile;
inherit (nftr) nftablesRulesFile appTproxyRulesFile appZapretRulesFile ip nft;
}
))
@@ -62,6 +59,7 @@ in
cfg
zapret
;
inherit (nftr) appZapretRulesFile nft;
}
))
+62 -6
View File
@@ -7,11 +7,17 @@
let
sb = cfg.singBox;
art = cfg.appRouting.backends.tun;
artp = cfg.appRouting.backends.tproxy;
arz = cfg.appRouting.backends.zapret;
localSubnetLines = lib.concatMapStrings (cidr: ''
mkLocalSubnetLines = subnets: lib.concatMapStrings (cidr: ''
ip daddr ${cidr} tcp dport != 53 return
ip daddr ${cidr} udp dport != 53 return
'') sb.tproxy.localSubnets;
'') subnets;
tproxyLocalSubnetLines = mkLocalSubnetLines sb.tproxy.localSubnets;
appTproxyLocalSubnetLines = mkLocalSubnetLines artp.localSubnets;
nftablesRulesFile = pkgs.writeText "proxy-suite-tproxy.nft" ''
define RESERVED_IP = {
@@ -33,25 +39,75 @@ let
# 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}
${tproxyLocalSubnetLines}
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}
}
chain output {
type route hook output priority mangle; policy accept;
ip daddr $RESERVED_IP return
${localSubnetLines}
${tproxyLocalSubnetLines}
meta mark ${toString sb.proxyMark} return
ip protocol tcp meta mark set ${toString sb.fwmark}
${lib.optionalString art.enable " meta mark ${toString art.fwmark} return\n"}${lib.optionalString artp.enable " meta mark ${toString artp.fwmark} return\n"} ip protocol tcp meta mark set ${toString sb.fwmark}
ip protocol udp meta mark set ${toString sb.fwmark}
}
}
'';
appTproxyRulesFile = pkgs.writeText "proxy-suite-app-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
}
table ip proxy_suite_app_tproxy {
chain prerouting {
type filter hook prerouting priority mangle; policy accept;
ip daddr $RESERVED_IP return
iifname != "lo" ip saddr $RESERVED_IP return
${appTproxyLocalSubnetLines}
ct mark ${toString artp.fwmark} meta mark set ${toString artp.fwmark}
meta mark ${toString artp.fwmark} ip protocol tcp tproxy to 127.0.0.1:${toString sb.tproxyPort}
meta mark ${toString artp.fwmark} ip protocol udp tproxy to 127.0.0.1:${toString sb.tproxyPort}
}
chain output {
type route hook output priority mangle; policy accept;
ip daddr $RESERVED_IP return
${appTproxyLocalSubnetLines}
meta mark ${toString sb.proxyMark} return
${lib.optionalString art.enable " meta mark ${toString art.fwmark} return\n"} ct mark ${toString artp.fwmark} meta mark set ${toString artp.fwmark}
meta mark ${toString artp.fwmark} return
}
}
'';
appZapretRulesFile = pkgs.writeText "proxy-suite-app-zapret.nft" ''
table inet proxy_suite_app_zapret_mark {
chain prerouting {
type filter hook prerouting priority -103; policy accept;
ct mark and ${toString arz.filterMark} == ${toString arz.filterMark} meta mark set meta mark or ${toString arz.filterMark}
}
chain output {
type route hook output priority -103; policy accept;
ct mark and ${toString arz.filterMark} == ${toString arz.filterMark} meta mark set meta mark or ${toString arz.filterMark}
meta mark and ${toString arz.filterMark} == ${toString arz.filterMark} return
}
}
'';
ip = "${pkgs.iproute2}/bin/ip";
nft = "${pkgs.nftables}/bin/nft";
in
{
inherit nftablesRulesFile ip nft;
inherit nftablesRulesFile appTproxyRulesFile appZapretRulesFile ip nft;
}
File diff suppressed because it is too large. Load diff
+771 -2
View File
@@ -6,7 +6,10 @@
cfg,
tproxyFile,
tunFile,
appTunFile,
nftablesRulesFile,
appTproxyRulesFile,
appZapretRulesFile,
ip,
nft,
}:
@@ -14,6 +17,10 @@
let
sb = cfg.singBox;
t = cfg.tgWsProxy;
ar = cfg.appRouting;
art = ar.backends.tun;
artp = ar.backends.tproxy;
arz = ar.backends.zapret;
builtinTags = [
"proxy"
"direct"
@@ -29,6 +36,17 @@ let
jq = "${pkgs.jq}/bin/jq";
python3 = "${pkgs.python3}/bin/python3";
singBox = "${pkgs.sing-box}/bin/sing-box";
proxychains4 = "${pkgs.proxychains-ng}/bin/proxychains4";
systemdRun = "${pkgs.systemd}/bin/systemd-run";
systemctl = "${pkgs.systemd}/bin/systemctl";
journalctl = "${pkgs.systemd}/bin/journalctl";
idBin = "${pkgs.coreutils}/bin/id";
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";
fetchSubscriptionPy = ../../scripts/fetch-subscription.py;
@@ -190,6 +208,15 @@ let
routingMark = null;
};
startAppTun = mkStartScript {
name = "proxy-suite-start-app-tun";
runtimeDir = "/run/proxy-suite-app-tun";
configFile = appTunFile;
# Only needed when TProxy mode is enabled; otherwise avoid tagging app TUN
# proxy outbounds with a host-global mark.
routingMark = if sb.tproxy.enable then sb.proxyMark else null;
};
clashApi = "http://127.0.0.1:${toString sb.clashApiPort}";
selection = sb.selection;
@@ -236,18 +263,293 @@ let
# Subscription tags embedded at build time for proxy-ctl.
subscriptionTagsList = lib.concatStringsSep " " (map (sub: lib.escapeShellArg sub.tag) sb.subscriptions);
hasSubscriptions = sb.subscriptions != [ ];
appRoutingProfileNames = map (profile: profile.name) ar.profiles;
defaultAppRoutingProfiles = lib.optionals ar.createDefaultProfiles [
{
name = "proxychains";
route = "proxychains";
}
] ++ lib.optionals art.enable [
{
name = "tun";
route = "tun";
}
] ++ lib.optionals artp.enable [
{
name = "tproxy";
route = "tproxy";
}
] ++ lib.optionals (arz.enable && cfg.zapret.enable) [
{
name = "zapret";
route = "zapret";
}
];
effectiveAppRoutingProfiles =
ar.profiles
++ builtins.filter (profile: !(builtins.elem profile.name appRoutingProfileNames)) defaultAppRoutingProfiles;
effectiveAppRoutingProfileNames = map (profile: profile.name) effectiveAppRoutingProfiles;
appRoutingProfilesFile = pkgs.writeText "proxy-suite-app-routing-profiles.json" (
builtins.toJSON effectiveAppRoutingProfiles
);
proxychainsConfigFile = pkgs.writeText "proxy-suite-proxychains.conf" ''
strict_chain
${lib.optionalString ar.proxychains.quiet "quiet_mode"}
${lib.optionalString ar.proxychains.proxyDns "proxy_dns"}
tcp_read_time_out 15000
tcp_connect_time_out 8000
[ProxyList]
socks5 ${sb.listenAddress} ${toString sb.port}
'';
proxychainsQuietArg = lib.optionalString ar.proxychains.quiet "-q ";
hasProxychainsProfiles = builtins.any (profile: profile.route == "proxychains") effectiveAppRoutingProfiles;
hasTunProfiles = builtins.any (profile: profile.route == "tun") effectiveAppRoutingProfiles;
hasTproxyProfiles = builtins.any (profile: profile.route == "tproxy") effectiveAppRoutingProfiles;
hasZapretProfiles = builtins.any (profile: profile.route == "zapret") effectiveAppRoutingProfiles;
appTunSliceName = "proxy-suite-app-tun.slice";
appTproxySliceName = "proxy-suite-app-tproxy.slice";
appZapretSliceName = "proxy-suite-app-zapret.slice";
appTunChainFile = pkgs.writeText "proxy-suite-app-tun-chain.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
}
table inet proxy_suite_app_tun {
chain output {
type route hook output priority mangle; policy accept;
ip daddr $RESERVED_IP return
${lib.concatMapStrings (cidr: ''
ip daddr ${cidr} return
'') art.localSubnets}
ct mark ${toString art.fwmark} meta mark set ${toString art.fwmark}
meta mark ${toString art.fwmark} return
}
}
'';
appTunWaitForInterface = pkgs.writeShellScript "proxy-suite-app-tun-wait-for-interface" ''
set -euo pipefail
for _ in $(${seqBin} 1 50); do
if ${ip} link show dev ${lib.escapeShellArg art.interface} >/dev/null 2>&1; then
exit 0
fi
${sleepBin} 0.1
done
echo "proxy-suite: app TUN interface ${art.interface} did not appear in time" >&2
exit 1
'';
appTunUpScript = pkgs.writeShellScript "proxy-suite-app-tun-up" ''
set -euo pipefail
${nft} delete table inet proxy_suite_app_tun 2>/dev/null || true
${nft} -f ${appTunChainFile}
${appTunWaitForInterface}
${ip} route replace default dev ${lib.escapeShellArg art.interface} table ${toString art.routeTable}
${ip} rule add fwmark ${toString art.fwmark} table ${toString art.routeTable} 2>/dev/null || true
'';
appTunDownScript = pkgs.writeShellScript "proxy-suite-app-tun-down" ''
set -euo pipefail
${nft} delete table inet proxy_suite_app_tun 2>/dev/null || true
${ip} route del default dev ${lib.escapeShellArg art.interface} table ${toString art.routeTable} 2>/dev/null || true
${ip} rule del fwmark ${toString art.fwmark} table ${toString art.routeTable} 2>/dev/null || true
'';
appTunUserRuleStart =
pkgs.writeShellScript "proxy-suite-app-tun-user-start" ''
set -euo pipefail
uid="$1"
rule_comment_prefix="proxy-suite-app-tun-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 appTunSliceName} | ${headBin} -n1 || true)
if [ -z "$cgroup_dir" ]; then
echo "proxy-suite: app TUN 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 inet proxy_suite_app_tun output 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 inet proxy_suite_app_tun output handle "$handle" || true
done <<< "$handles"
fi
printf '%s\n' \
"add rule inet proxy_suite_app_tun output socket cgroupv2 level $cgroup_level \"$cgroup_path\" meta mark set ${toString art.fwmark} ct mark set ${toString art.fwmark} comment \"$mark_comment\"" \
| ${nft} -f -
'';
appTunUserRuleStop =
pkgs.writeShellScript "proxy-suite-app-tun-user-stop" ''
set -euo pipefail
uid="$1"
rule_comment_prefix="proxy-suite-app-tun-user-$uid"
handles=$(${nft} -a list chain inet proxy_suite_app_tun output 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 inet proxy_suite_app_tun output handle "$handle" || true
done <<< "$handles"
fi
'';
appTproxyUpScript = pkgs.writeShellScript "proxy-suite-app-tproxy-up" ''
set -euo pipefail
${nft} delete table ip proxy_suite_app_tproxy 2>/dev/null || true
${nft} -f ${appTproxyRulesFile}
${ip} route replace local default dev lo table ${toString artp.routeTable}
${ip} rule add fwmark ${toString artp.fwmark} table ${toString artp.routeTable} 2>/dev/null || true
'';
appTproxyDownScript = pkgs.writeShellScript "proxy-suite-app-tproxy-down" ''
set -euo pipefail
${nft} delete table ip proxy_suite_app_tproxy 2>/dev/null || true
${ip} route del local default dev lo table ${toString artp.routeTable} 2>/dev/null || true
${ip} rule del fwmark ${toString artp.fwmark} table ${toString artp.routeTable} 2>/dev/null || true
'';
appTproxyUserRuleStart =
pkgs.writeShellScript "proxy-suite-app-tproxy-user-start" ''
set -euo pipefail
uid="$1"
rule_comment_prefix="proxy-suite-app-tproxy-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 appTproxySliceName} | ${headBin} -n1 || true)
if [ -z "$cgroup_dir" ]; then
echo "proxy-suite: app TProxy 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 ip proxy_suite_app_tproxy output 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 ip proxy_suite_app_tproxy output handle "$handle" || true
done <<< "$handles"
fi
printf '%s\n' \
"add rule ip proxy_suite_app_tproxy output socket cgroupv2 level $cgroup_level \"$cgroup_path\" meta mark set ${toString artp.fwmark} ct mark set ${toString artp.fwmark} comment \"$mark_comment\"" \
| ${nft} -f -
'';
appTproxyUserRuleStop =
pkgs.writeShellScript "proxy-suite-app-tproxy-user-stop" ''
set -euo pipefail
uid="$1"
rule_comment_prefix="proxy-suite-app-tproxy-user-$uid"
handles=$(${nft} -a list chain ip proxy_suite_app_tproxy output 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 ip proxy_suite_app_tproxy output handle "$handle" || true
done <<< "$handles"
fi
'';
appZapretUserRuleStart =
pkgs.writeShellScript "proxy-suite-app-zapret-user-start" ''
set -euo pipefail
uid="$1"
rule_comment_prefix="proxy-suite-app-zapret-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 appZapretSliceName} | ${headBin} -n1 || true)
if [ -z "$cgroup_dir" ]; then
echo "proxy-suite: app zapret 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 inet proxy_suite_app_zapret_mark output 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 inet proxy_suite_app_zapret_mark output handle "$handle" || true
done <<< "$handles"
fi
printf '%s\n' \
"add rule inet proxy_suite_app_zapret_mark output socket cgroupv2 level $cgroup_level \"$cgroup_path\" meta mark set meta mark or ${toString arz.filterMark} ct mark set ct mark or ${toString arz.filterMark} comment \"$mark_comment\"" \
| ${nft} -f -
'';
appZapretUserRuleStop =
pkgs.writeShellScript "proxy-suite-app-zapret-user-stop" ''
set -euo pipefail
uid="$1"
rule_comment_prefix="proxy-suite-app-zapret-user-$uid"
handles=$(${nft} -a list chain inet proxy_suite_app_zapret_mark output 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 inet proxy_suite_app_zapret_mark output handle "$handle" || true
done <<< "$handles"
fi
'';
proxyCtl = pkgs.writeShellApplication {
name = "proxy-ctl";
runtimeInputs = with pkgs; [
coreutils
curl
gawk
gnugrep
jq
proxychains-ng
systemd
];
text = ''
# Embedded at build time from module config
CLASH_API="${clashApi}"
SELECTION="${selection}"
SUB_TAGS=(${subscriptionTagsList})
APP_ROUTING_ENABLED="${if ar.enable then "1" else "0"}"
APP_ROUTING_PROXYCHAINS_ENABLED="${if ar.proxychains.enable then "1" else "0"}"
APP_ROUTING_TUN_ENABLED="${if art.enable then "1" else "0"}"
APP_ROUTING_TPROXY_ENABLED="${if artp.enable then "1" else "0"}"
APP_ROUTING_ZAPRET_ENABLED="${if (arz.enable && cfg.zapret.enable) then "1" else "0"}"
APP_ROUTING_PROFILES_FILE="${appRoutingProfilesFile}"
PROXYCHAINS_CONFIG="${proxychainsConfigFile}"
APP_TUN_SLICE_BASE="proxy-suite-app-tun"
APP_TUN_ANCHOR_UNIT="proxy-suite-app-tun-anchor.service"
APP_TPROXY_SLICE_BASE="proxy-suite-app-tproxy"
APP_TPROXY_ANCHOR_UNIT="proxy-suite-app-tproxy-anchor.service"
APP_ZAPRET_SLICE_BASE="proxy-suite-app-zapret"
APP_ZAPRET_ANCHOR_UNIT="proxy-suite-app-zapret-anchor.service"
ALL_SERVICES=(
proxy-suite-socks
@@ -269,6 +571,8 @@ let
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 " apps list configured per-app routing profiles"
echo " wrap <profile> -- <cmd> run a command via an appRouting profile"
echo " subscription list show subscriptions, cache age, and proxy count"
echo " subscription update force-refresh all subscription caches and restart"
exit 1
@@ -284,6 +588,48 @@ let
printf " %-44s %s\n" "$svc" "$state"
}
_ensure_app_routing() {
if [ "$APP_ROUTING_ENABLED" != "1" ]; then
echo "appRouting is not enabled in services.proxy-suite.appRouting."
exit 1
fi
}
_profile_route() {
local profile="$1"
${jq} -r --arg name "$profile" '.[] | select(.name == $name) | .route' "$APP_ROUTING_PROFILES_FILE"
}
_tun_scope_running() {
${systemctl} --user list-units --type=scope --state=running --plain --no-legend 'proxy-suite-app-tun-*' \
| ${grepBin} -q .
}
_any_app_tun_user_active() {
${systemctl} list-units --type=service --state=active --plain --no-legend 'proxy-suite-app-tun-user@*.service' \
| ${grepBin} -q .
}
_tproxy_scope_running() {
${systemctl} --user list-units --type=scope --state=running --plain --no-legend 'proxy-suite-app-tproxy-*' \
| ${grepBin} -q .
}
_any_app_tproxy_user_active() {
${systemctl} list-units --type=service --state=active --plain --no-legend 'proxy-suite-app-tproxy-user@*.service' \
| ${grepBin} -q .
}
_zapret_scope_running() {
${systemctl} --user list-units --type=scope --state=running --plain --no-legend 'proxy-suite-app-zapret-*' \
| ${grepBin} -q .
}
_any_app_zapret_user_active() {
${systemctl} list-units --type=service --state=active --plain --no-legend 'proxy-suite-app-zapret-user@*.service' \
| ${grepBin} -q .
}
cmd="''${1:-status}"
shift || true
@@ -357,6 +703,168 @@ let
fi
;;
apps)
_ensure_app_routing
if [ "$(${jq} 'length' "$APP_ROUTING_PROFILES_FILE")" -eq 0 ]; then
echo "No appRouting profiles configured."
else
printf " %-24s %s\n" "PROFILE" "ROUTE"
${jq} -r '.[] | " " + (.name | tostring) + "\t" + (.route | tostring)' \
"$APP_ROUTING_PROFILES_FILE" \
| while IFS=$'\t' read -r profile route; do
printf "%-26s %s\n" "$profile" "$route"
done
fi
;;
wrap)
profile="''${1:?Usage: proxy-ctl wrap <profile> -- <command> [args...]}"
shift || true
if [ "''${1:-}" = "--" ]; then
shift
fi
if [ "$#" -eq 0 ]; then
echo "Usage: proxy-ctl wrap <profile> -- <command> [args...]"
exit 1
fi
_ensure_app_routing
route="$(_profile_route "$profile")"
if [ -z "$route" ] || [ "$route" = "null" ]; then
echo "Unknown appRouting profile: $profile"
exit 1
fi
case "$route" in
direct)
exec "$@"
;;
proxychains)
if [ "$APP_ROUTING_PROXYCHAINS_ENABLED" != "1" ]; then
echo "Profile '$profile' uses route=proxychains, but appRouting.proxychains.enable is false."
exit 1
fi
exec ${proxychains4} ${proxychainsQuietArg}-f "$PROXYCHAINS_CONFIG" "$@"
;;
tun)
if [ "$APP_ROUTING_TUN_ENABLED" != "1" ]; then
echo "Profile '$profile' uses route=tun, but appRouting.backends.tun.enable is false."
exit 1
fi
uid="$(${idBin} -u)"
scope_unit="proxy-suite-app-tun-$profile-$$"
${systemctl} --user start "$APP_TUN_ANCHOR_UNIT"
${systemctl} start proxy-suite-app-tun.service
${systemctl} start "proxy-suite-app-tun-user@$uid.service"
if ${systemdRun} --user --scope --quiet --collect --same-dir \
--slice="$APP_TUN_SLICE_BASE" \
--unit="$scope_unit" \
"$@"; then
status=0
else
status=$?
fi
if ! _tun_scope_running; then
${systemctl} stop "proxy-suite-app-tun-user@$uid.service" || true
${systemctl} --user stop "$APP_TUN_ANCHOR_UNIT" || true
if ! _any_app_tun_user_active; then
${systemctl} stop proxy-suite-app-tun.service || true
fi
fi
exit "$status"
;;
tproxy)
if [ "$APP_ROUTING_TPROXY_ENABLED" != "1" ]; then
echo "Profile '$profile' uses route=tproxy, but appRouting.backends.tproxy.enable is false."
exit 1
fi
if ${systemctl} is-active --quiet proxy-suite-tun.service; then
echo "Global proxy-suite-tun.service is active. Stop it before using route=tproxy profiles."
exit 1
fi
if ${systemctl} is-active --quiet proxy-suite-tproxy.service; then
echo "Global proxy-suite-tproxy.service is active. Stop it before using route=tproxy profiles."
exit 1
fi
uid="$(${idBin} -u)"
scope_unit="proxy-suite-app-tproxy-$profile-$$"
${systemctl} --user start "$APP_TPROXY_ANCHOR_UNIT"
${systemctl} start proxy-suite-app-tproxy.service
${systemctl} start "proxy-suite-app-tproxy-user@$uid.service"
if ${systemdRun} --user --scope --quiet --collect --same-dir \
--slice="$APP_TPROXY_SLICE_BASE" \
--unit="$scope_unit" \
"$@"; then
status=0
else
status=$?
fi
if ! _tproxy_scope_running; then
${systemctl} stop "proxy-suite-app-tproxy-user@$uid.service" || true
${systemctl} --user stop "$APP_TPROXY_ANCHOR_UNIT" || true
if ! _any_app_tproxy_user_active; then
${systemctl} stop proxy-suite-app-tproxy.service || true
fi
fi
exit "$status"
;;
zapret)
if [ "$APP_ROUTING_ZAPRET_ENABLED" != "1" ]; then
echo "Profile '$profile' uses route=zapret, but the app-zapret backend or zapret service is not enabled."
exit 1
fi
if ${systemctl} is-active --quiet proxy-suite-tun.service; then
echo "Global proxy-suite-tun.service is active. Stop it before using route=zapret profiles."
exit 1
fi
if ${systemctl} is-active --quiet proxy-suite-tproxy.service; then
echo "Global proxy-suite-tproxy.service is active. Stop it before using route=zapret profiles."
exit 1
fi
uid="$(${idBin} -u)"
scope_unit="proxy-suite-app-zapret-$profile-$$"
${systemctl} --user start "$APP_ZAPRET_ANCHOR_UNIT"
${systemctl} start proxy-suite-app-zapret.service
${systemctl} start "proxy-suite-app-zapret-user@$uid.service"
if ${systemdRun} --user --scope --quiet --collect --same-dir \
--slice="$APP_ZAPRET_SLICE_BASE" \
--unit="$scope_unit" \
"$@"; then
status=0
else
status=$?
fi
if ! _zapret_scope_running; then
${systemctl} stop "proxy-suite-app-zapret-user@$uid.service" || true
${systemctl} --user stop "$APP_ZAPRET_ANCHOR_UNIT" || true
if ! _any_app_zapret_user_active; then
${systemctl} stop proxy-suite-app-zapret.service || true
fi
fi
exit "$status"
;;
*)
echo "Route backend '$route' is not implemented in this build."
exit 1
;;
esac
;;
subscription)
subcmd="''${1:-list}"
shift || true
@@ -401,7 +909,70 @@ in
environment.systemPackages = [ proxyCtl ];
# nftables must be on for TProxy to work.
networking.nftables.enable = lib.mkIf sb.tproxy.enable (lib.mkDefault true);
networking.nftables.enable = lib.mkIf (sb.tproxy.enable || art.enable || artp.enable || arz.enable) (lib.mkDefault true);
users.groups = lib.mkIf cfg.enable {
"${ar.userControl.group}" = { };
};
security.polkit.enable = lib.mkIf cfg.enable true;
security.polkit.extraConfig = lib.mkIf cfg.enable (lib.mkAfter ''
polkit.addRule(function(action, subject) {
if (!subject.isInGroup("${ar.userControl.group}")) {
return null;
}
if (action.id !== "org.freedesktop.systemd1.manage-units") {
return null;
}
var unit = action.lookup("unit");
if (unit.indexOf("proxy-suite-") === 0 ||
unit === "zapret-discord-youtube.service") {
return polkit.Result.YES;
}
return null;
});
'');
systemd.user.services =
lib.optionalAttrs art.enable {
proxy-suite-app-tun-anchor = {
description = "Anchor service for proxy-suite app TUN slice";
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
Slice = appTunSliceName;
ExecStart = "${pkgs.coreutils}/bin/true";
ExecStop = "${pkgs.coreutils}/bin/true";
};
};
}
// lib.optionalAttrs artp.enable {
proxy-suite-app-tproxy-anchor = {
description = "Anchor service for proxy-suite app TProxy slice";
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
Slice = appTproxySliceName;
ExecStart = "${pkgs.coreutils}/bin/true";
ExecStop = "${pkgs.coreutils}/bin/true";
};
};
}
// lib.optionalAttrs (arz.enable && cfg.zapret.enable) {
proxy-suite-app-zapret-anchor = {
description = "Anchor service for proxy-suite app zapret slice";
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
Slice = appZapretSliceName;
ExecStart = "${pkgs.coreutils}/bin/true";
ExecStop = "${pkgs.coreutils}/bin/true";
};
};
};
assertions = [
{
@@ -420,6 +991,126 @@ in
assertion = invalidRoutingTargets == [ ];
message = "proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}";
}
{
assertion = !(sb.tproxy.enable && sb.tproxy.autostart && sb.tun.enable && sb.tun.autostart);
message = "proxy-suite: singBox.tproxy.autostart and singBox.tun.autostart cannot both be enabled at the same time";
}
{
assertion = ar.enable || ar.profiles == [ ];
message = "proxy-suite: appRouting.profiles requires appRouting.enable = true";
}
{
assertion = !ar.proxychains.enable || ar.enable;
message = "proxy-suite: appRouting.proxychains.enable requires appRouting.enable = true";
}
{
assertion = builtins.length effectiveAppRoutingProfileNames == builtins.length (lib.unique effectiveAppRoutingProfileNames);
message = "proxy-suite: appRouting profile names must be unique";
}
{
assertion = !hasProxychainsProfiles || ar.proxychains.enable;
message = "proxy-suite: route=proxychains in appRouting.profiles requires appRouting.proxychains.enable = true";
}
{
assertion = !art.enable || ar.enable;
message = "proxy-suite: appRouting.backends.tun.enable requires appRouting.enable = true";
}
{
assertion = !(hasTunProfiles && !art.enable);
message = "proxy-suite: route=tun in appRouting profiles requires appRouting.backends.tun.enable = true";
}
{
assertion = !artp.enable || ar.enable;
message = "proxy-suite: appRouting.backends.tproxy.enable requires appRouting.enable = true";
}
{
assertion = !(hasTproxyProfiles && !artp.enable);
message = "proxy-suite: route=tproxy in appRouting profiles requires appRouting.backends.tproxy.enable = true";
}
{
assertion = !arz.enable || ar.enable;
message = "proxy-suite: appRouting.backends.zapret.enable requires appRouting.enable = true";
}
{
assertion = !arz.enable || cfg.zapret.enable;
message = "proxy-suite: appRouting.backends.zapret.enable requires zapret.enable = true";
}
{
assertion = !(hasZapretProfiles && (!arz.enable || !cfg.zapret.enable));
message = "proxy-suite: route=zapret in appRouting profiles requires appRouting.backends.zapret.enable = true and zapret.enable = true";
}
{
assertion = !(art.enable && sb.tproxy.enable && art.fwmark == sb.fwmark);
message = "proxy-suite: appRouting.backends.tun.fwmark must differ from singBox.fwmark when singBox.tproxy.enable = true";
}
{
assertion = !(art.enable && sb.tproxy.enable && art.fwmark == sb.proxyMark);
message = "proxy-suite: appRouting.backends.tun.fwmark must differ from singBox.proxyMark when singBox.tproxy.enable = true";
}
{
assertion = !(art.enable && sb.tproxy.enable && art.routeTable == sb.routeTable);
message = "proxy-suite: appRouting.backends.tun.routeTable must differ from singBox.routeTable when singBox.tproxy.enable = true";
}
{
assertion = !(artp.enable && artp.fwmark == sb.fwmark);
message = "proxy-suite: appRouting.backends.tproxy.fwmark must differ from singBox.fwmark";
}
{
assertion = !(artp.enable && artp.fwmark == sb.proxyMark);
message = "proxy-suite: appRouting.backends.tproxy.fwmark must differ from singBox.proxyMark";
}
{
assertion = !(artp.enable && artp.routeTable == sb.routeTable);
message = "proxy-suite: appRouting.backends.tproxy.routeTable must differ from singBox.routeTable";
}
{
assertion = !(art.enable && artp.enable && art.fwmark == artp.fwmark);
message = "proxy-suite: appRouting.backends.tun.fwmark and appRouting.backends.tproxy.fwmark must differ";
}
{
assertion = !(art.enable && artp.enable && art.routeTable == artp.routeTable);
message = "proxy-suite: appRouting.backends.tun.routeTable and appRouting.backends.tproxy.routeTable must differ";
}
{
assertion = !(arz.enable && arz.filterMark == sb.fwmark);
message = "proxy-suite: appRouting.backends.zapret.filterMark must differ from singBox.fwmark";
}
{
assertion = !(arz.enable && arz.filterMark == sb.proxyMark);
message = "proxy-suite: appRouting.backends.zapret.filterMark must differ from singBox.proxyMark";
}
{
assertion = !(art.enable && arz.enable && art.fwmark == arz.filterMark);
message = "proxy-suite: appRouting.backends.tun.fwmark and appRouting.backends.zapret.filterMark must differ";
}
{
assertion = !(artp.enable && arz.enable && artp.fwmark == arz.filterMark);
message = "proxy-suite: appRouting.backends.tproxy.fwmark and appRouting.backends.zapret.filterMark must differ";
}
{
assertion = !(arz.enable && builtins.elem arz.filterMark [ 536870912 1073741824 ]);
message = "proxy-suite: appRouting.backends.zapret.filterMark must not use zapret internal desync mark bits";
}
{
assertion = !(arz.enable && builtins.elem sb.fwmark [ 67108864 134217728 ]);
message = "proxy-suite: singBox.fwmark must not use app-zapret internal desync mark bits";
}
{
assertion = !(arz.enable && builtins.elem sb.proxyMark [ 67108864 134217728 ]);
message = "proxy-suite: singBox.proxyMark must not use app-zapret internal desync mark bits";
}
{
assertion = !(art.enable && arz.enable && builtins.elem art.fwmark [ 67108864 134217728 ]);
message = "proxy-suite: appRouting.backends.tun.fwmark must not use app-zapret internal desync mark bits";
}
{
assertion = !(artp.enable && arz.enable && builtins.elem artp.fwmark [ 67108864 134217728 ]);
message = "proxy-suite: appRouting.backends.tproxy.fwmark must not use app-zapret internal desync mark bits";
}
{
assertion = !(arz.enable && builtins.elem arz.filterMark [ 67108864 134217728 ]);
message = "proxy-suite: appRouting.backends.zapret.filterMark must not use app-zapret internal desync mark bits";
}
{
assertion =
!t.enable
@@ -484,8 +1175,12 @@ in
"network.target"
"proxy-suite-socks.service"
];
wantedBy = lib.optionals sb.tproxy.autostart [ "multi-user.target" ];
requires = [ "proxy-suite-socks.service" ];
conflicts = [ "proxy-suite-tun.service" ];
conflicts = [
"proxy-suite-tun.service"
"proxy-suite-app-tproxy.service"
];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
@@ -510,6 +1205,7 @@ in
proxy-suite-tun = {
description = "sing-box TUN proxy client";
after = [ "network-online.target" ];
wantedBy = lib.optionals sb.tun.autostart [ "multi-user.target" ];
wants = [ "network-online.target" ];
conflicts = [ "proxy-suite-tproxy.service" ];
serviceConfig = {
@@ -521,6 +1217,79 @@ in
};
};
}
// lib.optionalAttrs art.enable {
proxy-suite-app-tun = {
description = "sing-box app-routing TUN backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
serviceConfig = {
ExecStart = "${startAppTun}";
ExecStartPost = "${appTunUpScript}";
ExecStopPost = "${appTunDownScript}";
Restart = "on-failure";
RestartSec = 5;
RuntimeDirectory = "proxy-suite-app-tun";
StateDirectory = "proxy-suite";
};
};
"proxy-suite-app-tun-user@" = {
description = "Enable proxy-suite app TUN marking for user %i";
requires = [ "proxy-suite-app-tun.service" ];
after = [ "proxy-suite-app-tun.service" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = "${appTunUserRuleStart} %i";
ExecStop = "${appTunUserRuleStop} %i";
};
};
}
// lib.optionalAttrs artp.enable {
proxy-suite-app-tproxy = {
description = "proxy-suite app-routing TProxy backend";
after = [
"network.target"
"proxy-suite-socks.service"
];
requires = [ "proxy-suite-socks.service" ];
conflicts = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = "${appTproxyUpScript}";
ExecStop = "${appTproxyDownScript}";
};
};
"proxy-suite-app-tproxy-user@" = {
description = "Enable proxy-suite app TProxy marking for user %i";
requires = [ "proxy-suite-app-tproxy.service" ];
after = [ "proxy-suite-app-tproxy.service" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = "${appTproxyUserRuleStart} %i";
ExecStop = "${appTproxyUserRuleStop} %i";
};
};
}
// lib.optionalAttrs (arz.enable && cfg.zapret.enable) {
"proxy-suite-app-zapret-user@" = {
description = "Enable proxy-suite app zapret marking for user %i";
requires = [ "proxy-suite-app-zapret.service" ];
after = [ "proxy-suite-app-zapret.service" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = "${appZapretUserRuleStart} %i";
ExecStop = "${appZapretUserRuleStop} %i";
};
};
}
// lib.optionalAttrs hasSubscriptions {
proxy-suite-subscription-update = {
description = "Refresh proxy-suite subscription caches";
+176 -41
View File
@@ -4,10 +4,13 @@
pkgs,
cfg,
zapret,
appZapretRulesFile,
nft,
}:
let
z = cfg.zapret;
arz = cfg.appRouting.backends.zapret;
iptables = "${pkgs.iptables}/bin/iptables";
@@ -15,6 +18,7 @@ let
inherit (pkgs)
iptables
ipset
nftables
coreutils
gawk
curl
@@ -31,7 +35,7 @@ let
hostlistRuleNames = map (rule: rule.name) z.hostlistRules;
upstreamZapretPackage =
baseZapretPackage =
let
upstreamPackages = zapret.packages.${pkgs.stdenv.hostPlatform.system};
in
@@ -87,8 +91,33 @@ let
};
patchConfigScript = "${pkgs.python3}/bin/python3 ${patchConfigScriptSrc}";
customZapretPackage =
pkgs.runCommand "proxy-suite-zapret-${selectedConfigName}"
mkGlobalBypassScript =
filterMark:
pkgs.writeText "proxy-suite-zapret-global-bypass.sh" ''
zapret_custom_firewall_nft() {
nft insert rule inet $ZAPRET_NFT_TABLE postrouting mark and ${filterMark} != 0 return comment "proxy-suite app-zapret bypass"
nft insert rule inet $ZAPRET_NFT_TABLE postnat mark and ${filterMark} != 0 return comment "proxy-suite app-zapret bypass"
nft insert rule inet $ZAPRET_NFT_TABLE prerouting mark and ${filterMark} != 0 return comment "proxy-suite app-zapret bypass"
nft insert rule inet $ZAPRET_NFT_TABLE prenat mark and ${filterMark} != 0 return comment "proxy-suite app-zapret bypass"
}
'';
mkDerivedZapretPackage =
{
packageName,
pidDir,
configName ? z.configName,
gameFilter ? z.gameFilter,
forceDisableFilterMark ? false,
filterMark ? null,
qnum ? null,
modeFilter ? null,
desyncMark ? null,
desyncMarkPostnat ? null,
nftTable ? null,
customScript ? null,
}:
pkgs.runCommand packageName
{
nativeBuildInputs = with pkgs; [
coreutils
@@ -100,25 +129,32 @@ let
set -euo pipefail
mkdir -p "$out"
cp -a ${upstreamZapretPackage}/. "$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|${upstreamZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
{} \;
find "$out/opt/zapret/hostlists" -type f -exec ${pkgs.gnused}/bin/sed -i \
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
{} \;
if [ -f "$out/opt/zapret/configs/${z.configName}" ]; then
cp "$out/opt/zapret/configs/${z.configName}" "$out/opt/zapret/config"
if [ -f "$out/opt/zapret/configs/${configName}" ]; then
cp "$out/opt/zapret/configs/${configName}" "$out/opt/zapret/config"
else
echo "proxy-suite: zapret config '${z.configName}' not found in upstream package" >&2
echo "proxy-suite: zapret config '${configName}' not found in curated package" >&2
ls -la "$out/opt/zapret/configs" >&2 || true
exit 1
fi
${pkgs.gnused}/bin/sed -i \
-e 's|${upstreamZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
-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"
@@ -129,6 +165,16 @@ let
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.optionalString (listGeneralFile != null) ''
append_list_file list-general-user.txt ${listGeneralFile}
''}
@@ -146,8 +192,8 @@ let
''}
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.optionalString (gameFilter != "null") ''
echo "${gameFilter}" > "$out/opt/zapret/hostlists/.game_filter.enabled"
''}
${lib.concatMapStrings (
@@ -163,8 +209,92 @@ let
) z.hostlistRules}
${patchConfigScript} --config "$out/opt/zapret/config" --spec ${hostlistRuleSpec}
${lib.optionalString forceDisableFilterMark ''
set_config_var FILTER_MARK ""
''}
${lib.optionalString (filterMark != null) ''
filter_mark_hex=$(printf '0x%x' ${toString filterMark})
set_config_var FILTER_MARK "$filter_mark_hex"
''}
${lib.optionalString (qnum != null) ''
set_config_var QNUM ${toString qnum}
''}
${lib.optionalString (modeFilter != null) ''
set_config_var MODE_FILTER ${modeFilter}
''}
${lib.optionalString (desyncMark != null) ''
desync_mark_hex=$(printf '0x%x' ${toString desyncMark})
set_config_var DESYNC_MARK "$desync_mark_hex"
''}
${lib.optionalString (desyncMarkPostnat != null) ''
desync_mark_postnat_hex=$(printf '0x%x' ${toString desyncMarkPostnat})
set_config_var DESYNC_MARK_POSTNAT "$desync_mark_postnat_hex"
''}
${lib.optionalString (nftTable != null) ''
set_config_var ZAPRET_NFT_TABLE ${nftTable}
''}
${lib.optionalString (customScript != null) ''
mkdir -p "$out/opt/zapret/init.d/sysv/custom.d"
cp ${customScript} "$out/opt/zapret/init.d/sysv/custom.d/50-proxy-suite-custom.sh"
chmod +x "$out/opt/zapret/init.d/sysv/custom.d/50-proxy-suite-custom.sh"
''}
'';
globalZapretPackage = mkDerivedZapretPackage {
packageName = "proxy-suite-zapret-${selectedConfigName}";
pidDir = "/run/proxy-suite-zapret";
gameFilter = z.gameFilter;
forceDisableFilterMark = true;
customScript = if arz.enable then mkGlobalBypassScript (toString arz.filterMark) else null;
};
appZapretPackage = mkDerivedZapretPackage {
packageName = "proxy-suite-app-zapret-${selectedConfigName}";
pidDir = "/run/proxy-suite-app-zapret";
gameFilter = "all";
filterMark = arz.filterMark;
qnum = arz.qnum;
modeFilter = "none";
desyncMark = 134217728;
desyncMarkPostnat = 67108864;
nftTable = "proxy_suite_app_zapret";
};
zapretCommonPreStart = package: ''
${package}/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
'';
globalZapretEnv = [
"ZAPRET_BASE=${globalZapretPackage}/opt/zapret"
"PATH=${lib.makeBinPath runtimeDeps}"
];
appZapretEnv = [
"ZAPRET_BASE=${appZapretPackage}/opt/zapret"
"PATH=${lib.makeBinPath runtimeDeps}"
];
appZapretMarkUpScript = pkgs.writeShellScript "proxy-suite-app-zapret-mark-up" ''
set -euo pipefail
${nft} delete table inet proxy_suite_app_zapret_mark 2>/dev/null || true
${nft} -f ${appZapretRulesFile}
'';
appZapretMarkDownScript = pkgs.writeShellScript "proxy-suite-app-zapret-mark-down" ''
set -euo pipefail
${nft} delete table inet proxy_suite_app_zapret_mark 2>/dev/null || true
'';
exemptStart = lib.concatMapStrings (cidr: ''
${iptables} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN
${iptables} -t mangle -I POSTROUTING 1 -s ${cidr} -j RETURN
@@ -191,39 +321,44 @@ in
}
];
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 [ customZapretPackage ];
environment.systemPackages =
lib.mkBefore (
[ globalZapretPackage ] ++ lib.optionals arz.enable [ appZapretPackage ]
);
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
'';
description = "zapret DPI bypass";
after = [ "network.target" ];
wantedBy = [ "multi-user.target" ];
preStart = zapretCommonPreStart globalZapretPackage;
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}"
];
Type = "oneshot";
RemainAfterExit = true;
RuntimeDirectory = "proxy-suite-zapret";
ExecStart = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret start";
ExecStop = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
ExecReload = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret restart";
Environment = globalZapretEnv;
};
};
systemd.services.proxy-suite-app-zapret = lib.mkIf arz.enable {
description = "proxy-suite app-routing zapret backend";
after = [ "network.target" ];
conflicts = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
];
preStart = zapretCommonPreStart appZapretPackage;
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
RuntimeDirectory = "proxy-suite-app-zapret";
ExecStartPre = "${appZapretMarkUpScript}";
ExecStart = "${appZapretPackage}/opt/zapret/init.d/sysv/zapret start";
ExecStop = "${appZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
ExecStopPost = "${appZapretMarkDownScript}";
Environment = appZapretEnv;
};
};
+942 -3
View File
File diff suppressed because it is too large. Load diff
+234
View File
@@ -0,0 +1,234 @@
{
nixpkgs,
pkgsFor,
proxySuiteModule,
}:
system:
let
pkgs = pkgsFor system;
lib = pkgs.lib;
eval = import "${nixpkgs}/nixos/lib/eval-config.nix" {
inherit system;
modules = [
proxySuiteModule
{
system.stateVersion = lib.trivial.release;
}
];
};
filterGeneratedOptions = lib.filterAttrs (name: _: name != "_module");
mkGeneratedExampleValue =
option:
if (option ? _type) && option._type == "option" then
if option ? example then
option.example
else if (option ? type) && ((option.type.name or null) == "submodule") then
lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions (option.type.getSubOptions [ ]))
else if option ? default then
option.default
else
throw "Cannot generate example value for option ${lib.showOption option.loc}"
else
lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions option);
defaultConfigText = lib.generators.toPretty { } eval.config.services.proxy-suite;
exampleConfigText = lib.generators.toPretty { } (
lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions eval.options.services.proxy-suite)
);
repoRoot = toString ../.;
repoUrl = "https://github.com/FUFSoB/proxy-suite-flake/blob/main";
transformDeclaration =
decl:
let
declStr = toString decl;
subpath = lib.removePrefix "/" (lib.removePrefix repoRoot declStr);
in
if lib.hasPrefix repoRoot declStr then
{
url = "${repoUrl}/${subpath}";
name = subpath;
}
else
decl;
optionDocs = pkgs.nixosOptionsDoc {
options = {
services = {
"proxy-suite" = eval.options.services.proxy-suite;
};
};
documentType = "none";
variablelistId = "proxy-suite-options";
optionIdPrefix = "proxy-suite-opt-";
transformOptions = opt: opt // { declarations = map transformDeclaration opt.declarations; };
};
in
pkgs.runCommand "proxy-suite-options.md" { } ''
preamble="$TMPDIR/preamble.md"
sections="$TMPDIR/sections.md"
sections_with_anchors="$TMPDIR/sections-with-anchors.md"
section_index="$TMPDIR/sections-index.tsv"
toc="$TMPDIR/toc.md"
cat >"$preamble" <<'EOF'
# proxy-suite options
This file is generated from the `services.proxy-suite` option descriptions in [`modules/proxy-suite/options.nix`](modules/proxy-suite/options.nix).
Update module option docs there instead of editing this file by hand.
## Table of contents
EOF
cat >"$sections" <<'EOF'
## Complete default config
```nix
services.proxy-suite = ${defaultConfigText};
```
## Complete example config
This is generated by filling in all the options with example values (or defaults if no example is provided). This is not meant to be a recommended config, just a comprehensive example of how to set all the options.
```nix
services.proxy-suite = ${exampleConfigText};
```
EOF
cat ${optionDocs.optionsCommonMark} >>"$sections"
: >"$section_index"
: >"$sections_with_anchors"
awk -v section_index="$section_index" -v out="$sections_with_anchors" '
function slugify(text, slug) {
slug = text
gsub(/\\/, "", slug)
slug = tolower(slug)
gsub(/[^a-z0-9]+/, "-", slug)
sub(/^-+/, "", slug)
sub(/-+$/, "", slug)
return slug
}
/^## / {
title = substr($0, 4)
base = slugify(title)
count = seen[base]
seen[base]++
slug = count == 0 ? base : base "-" count
print title "\t" slug >> section_index
print "<a id=\"" slug "\"></a>" >> out
}
{
print >> out
}
' "$sections"
: >"$toc"
awk -F '\t' -v toc="$toc" '
function addChild(parent, child, key) {
key = parent SUBSEP child
if (!(key in seenChild)) {
seenChild[key] = 1
childCount[parent]++
childOrder[parent, childCount[parent]] = child
}
}
function indent(depth, i, prefix) {
prefix = ""
for (i = 0; i < depth; i++) {
prefix = prefix " "
}
return prefix
}
function displayLabel(label) {
if (label == "*") {
return "item"
}
return label
}
function printNode(path, label, depth, i, child, childPath, text) {
text = displayLabel(label)
if (path in slugByPath) {
text = "[" text "](#" slugByPath[path] ")"
}
print indent(depth) "- " text >> toc
for (i = 1; i <= childCount[path]; i++) {
child = childOrder[path, i]
childPath = path "." child
printNode(childPath, child, depth + 1)
}
}
{
title = $1
slug = $2
normalized = title
gsub(/\\/, "", normalized)
if (normalized ~ /^Complete /) {
sampleCount++
sampleTitle[sampleCount] = title
sampleSlug[sampleCount] = slug
next
}
if (index(normalized, "services.proxy-suite") == 1) {
optionRootSeen = 1
slugByPath[normalized] = slug
count = split(normalized, parts, /\./)
if (count < 3) {
next
}
parent = "services.proxy-suite"
for (i = 3; i <= count; i++) {
child = parts[i]
addChild(parent, child)
parent = parent "." child
}
next
}
otherCount++
otherTitle[otherCount] = title
otherSlug[otherCount] = slug
}
END {
if (sampleCount > 0) {
print "- Config samples" >> toc
for (i = 1; i <= sampleCount; i++) {
print " - [" sampleTitle[i] "](#" sampleSlug[i] ")" >> toc
}
}
if (optionRootSeen) {
print "- services.proxy-suite" >> toc
for (i = 1; i <= childCount["services.proxy-suite"]; i++) {
child = childOrder["services.proxy-suite", i]
printNode("services.proxy-suite." child, child, 1)
}
}
for (i = 1; i <= otherCount; i++) {
print "- [" otherTitle[i] "](#" otherSlug[i] ")" >> toc
}
}
' "$section_index"
cat "$preamble" >"$out"
cat "$toc" >>"$out"
printf '\n' >>"$out"
cat "$sections_with_anchors" >>"$out"
''
+2 -2
View File
@@ -4,8 +4,8 @@ let
src = pkgs.fetchFromGitHub {
owner = "Flowseal";
repo = "tg-ws-proxy";
rev = "fe4e0e82344d8e8ca5e54b7752cafa934fb763ab";
hash = "sha256-tXDfYE1qFYTAWTu7pse/jcovDmX/F42SCGOzsUBmljs=";
rev = "v1.6.1";
hash = "sha256-7dFHrD8lrxzQsjGanCWao5zEIIx+swcKRKo+mI/fMlQ=";
};
pythonEnv = pkgs.python3.withPackages (