initial commit

This commit is contained in:
FUFSoB committed 2026-04-11 16:50:50 +05:00
commit 91ac090057
17 files changed
+2533

No files matched your search

+122
View File
@@ -0,0 +1,122 @@
# Build-time sing-box configuration templates.
# The proxy outbound(s) are injected at service start time, not here.
{ lib, pkgs, cfg, rules }:
let
sb = cfg.singBox;
clashApiBlock = lib.optionalAttrs (sb.selection != "first") {
experimental = {
clash_api = {
external_controller = "127.0.0.1:${toString sb.clashApiPort}";
};
};
};
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 (builtins.elem "category-ru" sb.routing.direct.geosites) {
rule_set = [ "geosite-category-ru" ];
server = "local";
};
final = "remote";
};
dnsConfigTun = dnsConfig // {
servers = map (
s: if s.tag == "local" then s // { detour = "proxy"; } else s
) dnsConfig.servers;
};
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;
};
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);
in
{
inherit tproxyFile tunFile;
}
+40
View File
@@ -0,0 +1,40 @@
# Factory function — receives the zapret flake, returns a NixOS module.
# This lets consumers add a single flake input and get everything transitively.
{ zapret }:
{ config, lib, pkgs, ... }:
let
cfg = config.services.proxy-suite;
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 (lib.mkMerge [
(lib.mkIf cfg.singBox.enable (
let
rules = import ./rules.nix { inherit lib pkgs cfg; };
configs = import ./config.nix { inherit lib pkgs cfg rules; };
nftr = import ./nftables.nix { inherit lib pkgs cfg; };
in
import ./service.nix {
inherit config lib pkgs cfg;
inherit (configs) tproxyFile tunFile;
inherit (nftr) nftablesRulesFile ip nft;
}
))
(lib.mkIf cfg.zapret.enable (
import ./zapret.nix { inherit lib pkgs cfg; }
))
(lib.mkIf cfg.tgWsProxy.enable (
import ./tg-ws-proxy.nix { inherit lib pkgs cfg; }
))
]);
}
+53
View File
@@ -0,0 +1,53 @@
# TProxy nftables rules
{ lib, pkgs, cfg }:
let
sb = cfg.singBox;
localSubnetLines = lib.concatMapStrings (cidr: ''
ip daddr ${cidr} tcp dport != 53 return
ip daddr ${cidr} udp dport != 53 return
'') sb.tproxy.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
}
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}
}
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}
}
}
'';
ip = "${pkgs.iproute2}/bin/ip";
nft = "${pkgs.nftables}/bin/nft";
in
{
inherit nftablesRulesFile ip nft;
}
+427
View File
@@ -0,0 +1,427 @@
# 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;
};
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;
};
};
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 is required when singBox.enable = true.
'';
};
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 every 3 minutes and auto-switch to the fastest
'';
};
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 = {
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 = [ "category-ru" ];
description = "sing-geosite names to send direct.";
};
geoips = mkOption {
type = types.listOf types.str;
default = [ "ru" ];
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.";
};
};
# 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";
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.";
};
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.
'';
};
};
};
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";
};
};
};
};
}
+128
View File
@@ -0,0 +1,128 @@
# Routing rules and rule-set definitions for sing-box
{ lib, pkgs, cfg }:
let
r = cfg.singBox.routing;
sb = cfg.singBox;
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;
};
# 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;
# Collect per-outbound routing attached directly to outbound definitions.
perOutboundRules = lib.concatMap (ob:
let
ro = ob.routing;
hasAny = ro.domains != [ ] || ro.ips != [ ] || ro.geosites != [ ] || ro.geoips != [ ];
in
lib.optional hasAny {
outbound = resolveTag ob.tag;
inherit (ro) domains ips geosites geoips;
}
) sb.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))
];
# All geosite names referenced anywhere (for rule-set file definitions).
allGeositeNames = lib.unique (
r.proxy.geosites
++ r.direct.geosites
++ lib.concatMap (rule: rule.geosites) customRules
);
# All geoip names referenced anywhere.
allGeoIPNames = lib.unique (
r.proxy.geoips
++ r.direct.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" r.direct.domains)
(mkIPRule "direct" r.direct.ips)
(mkRulesetRule "direct" (map (s: "geosite-${s}") r.direct.geosites))
(mkRulesetRule "direct" (map (s: "geoip-${s}") r.direct.geoips))
{ ip_is_private = true; outbound = "direct"; }
# Global proxy geo lists
(mkRulesetRule "proxy" (map (s: "geosite-${s}") r.proxy.geosites))
(mkRulesetRule "proxy" (map (s: "geoip-${s}") r.proxy.geoips))
# Block
(mkDomainRule "block" r.block.domains)
(mkIPRule "block" r.block.ips)
];
in
{
inherit
geositeRuleSets
geoIPRuleSets
routingRules
;
}
+375
View File
@@ -0,0 +1,375 @@
# 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";
# 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")
'';
# Shell code that builds all outbounds, then optionally adds a selector/urltest wrapper.
mkOutboundScript =
routingMark:
let
outboundBlocks =
if sb.selection == "first" then
# Only the first 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;
wrapperBlock =
if sb.selection == "first" then
""
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" \
'{type:"urltest",tag:"proxy",outbounds:$tags,url:"https://www.gstatic.com/generate_204",interval:"3m",tolerance:50}')
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
'';
in
outboundBlocks + 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;
proxyCtl = pkgs.writeShellApplication {
name = "proxy-ctl";
runtimeInputs = with pkgs; [ curl jq ];
text = ''
# Embedded at build time from module config
CLASH_API="${clashApi}"
SELECTION="${selection}"
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)"
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
;;
*)
_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 != [ ];
message = "proxy-suite: singBox.outbounds must not be empty 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;
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";
};
};
}
// 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";
};
};
};
}
+29
View File
@@ -0,0 +1,29 @@
# Telegram MTProto WebSocket proxy service
{ lib, pkgs, cfg }:
let
t = cfg.tgWsProxy;
tgPkg = import ../../pkgs/tg-ws-proxy.nix { inherit pkgs; };
dcArgs = lib.concatMapStrings (id: " --dc-ip=${id}:${t.dcIps.${id}}") (
builtins.attrNames t.dcIps
);
secretArg =
if t.secretFile != null then
" --secret-file=%d/tg_ws_proxy_secret"
else
" --secret=${t.secret}";
in
{
systemd.services.proxy-suite-tg-ws-proxy = {
description = "Telegram MTProto WebSocket proxy";
after = [ "network.target" ];
wantedBy = [ "multi-user.target" ];
serviceConfig = {
ExecStart = "${tgPkg}/bin/tg-ws-proxy --port=${toString t.port} --host=${t.host}${secretArg}${dcArgs}";
LoadCredential = lib.optional (t.secretFile != null) "tg_ws_proxy_secret:${t.secretFile}";
Restart = "on-failure";
RestartSec = 5;
};
};
}
+42
View File
@@ -0,0 +1,42 @@
# zapret DPI bypass configuration + optional CIDR exemption from NFQUEUE
{ lib, pkgs, cfg }:
let
z = cfg.zapret;
iptables = "${pkgs.iptables}/bin/iptables";
exemptStart = lib.concatMapStrings (cidr: ''
${iptables} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN
${iptables} -t mangle -I POSTROUTING 1 -s ${cidr} -j RETURN
'') z.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;
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;
};
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" ];
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;
};
};
}