per-app zapret

This commit is contained in:
FUFSoB committed 2026-04-14 22:50:27 +05:00
1 parent c3f4088458
commit 435c908663
6 files changed
+638 -59

No files matched your search

+3 -5
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
@@ -50,7 +47,7 @@ in
cfg
;
inherit (configs) tproxyFile tunFile appTunFile;
inherit (nftr) nftablesRulesFile appTproxyRulesFile ip nft;
inherit (nftr) nftablesRulesFile appTproxyRulesFile appZapretRulesFile ip nft;
}
))
@@ -62,6 +59,7 @@ in
cfg
zapret
;
inherit (nftr) appZapretRulesFile nft;
}
))
+17 -1
View File
@@ -9,6 +9,7 @@ let
sb = cfg.singBox;
art = cfg.appRouting.backends.tun;
artp = cfg.appRouting.backends.tproxy;
arz = cfg.appRouting.backends.zapret;
mkLocalSubnetLines = subnets: lib.concatMapStrings (cidr: ''
ip daddr ${cidr} tcp dport != 53 return
@@ -88,10 +89,25 @@ ${lib.optionalString art.enable " meta mark ${toString art.fwmark}
}
'';
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 appTproxyRulesFile ip nft;
inherit nftablesRulesFile appTproxyRulesFile appZapretRulesFile ip nft;
}
+39 -4
View File
@@ -301,6 +301,7 @@ let
"proxychains"
"tun"
"tproxy"
"zapret"
];
default = "proxychains";
description = ''
@@ -314,6 +315,9 @@ let
- "tproxy": launch the command in the dedicated app-routing TProxy
slice so only that app's traffic is transparently intercepted by
the local sing-box TProxy inbound.
- "zapret": launch the command in the dedicated app-routing zapret
slice so only that app's traffic is handled by the separate
app-scoped zapret instance.
Additional route backends may be added in the future.
'';
@@ -825,11 +829,14 @@ in
- `proxychains`: route = "proxychains"
- `tun`: route = "tun" when appRouting.backends.tun.enable = true
- `tproxy`: route = "tproxy" when appRouting.backends.tproxy.enable = true
- `zapret`: route = "zapret" when appRouting.backends.zapret.enable = true
and zapret.enable = true
This makes `proxy-ctl wrap proxychains -- <command>` available
without defining the profile manually, and similarly exposes
`proxy-ctl wrap tun -- <command>` or
`proxy-ctl wrap tproxy -- <command>` when the corresponding backend
`proxy-ctl wrap tproxy -- <command>` or
`proxy-ctl wrap zapret -- <command>` when the corresponding backend
is enabled.
'';
example = true;
@@ -849,11 +856,14 @@ in
backend
- "tproxy" for app-scoped transparent interception through the
dedicated app TProxy backend
- "zapret" for app-scoped zapret handling through a separate
zapret instance without changing the app's network path or exit IP
proxychains-based wrapping depends on the local proxy-suite mixed
proxy listener provided by sing-box. The "tun" route depends on
appRouting.backends.tun.enable = true. The "tproxy" route depends on
appRouting.backends.tproxy.enable = true.
appRouting.backends.tproxy.enable = true. The "zapret" route depends
on appRouting.backends.zapret.enable = true and zapret.enable = true.
When createDefaultProfiles = true, curated defaults are added on top
of this list unless a user-defined profile already uses the same
@@ -997,6 +1007,31 @@ in
];
};
};
zapret = {
enable = mkEnableOption "app-scoped zapret backend for appRouting profiles";
filterMark = mkOption {
type = types.int;
default = 268435456;
description = ''
Packet mark bit used to mark wrapped app traffic for the
dedicated app-scoped zapret instance.
'';
example = 268435456;
};
qnum = mkOption {
type = types.int;
default = 201;
description = ''
NFQUEUE number used by the dedicated app-scoped zapret instance.
This backend runs as a second zapret daemon and should use a
queue distinct from the global zapret instance.
'';
example = 201;
};
};
};
userControl = {
@@ -1006,8 +1041,8 @@ in
description = ''
Local group allowed to start and stop app-routing backend units via
polkit. Add desktop users who should be able to run
`proxy-ctl wrap ...` for route = "tun" or route = "tproxy"
profiles to this group.
`proxy-ctl wrap ...` for route = "tun", route = "tproxy", or
route = "zapret" profiles to this group.
'';
example = "proxy-suite";
};
+195 -5
View File
@@ -9,6 +9,7 @@
appTunFile,
nftablesRulesFile,
appTproxyRulesFile,
appZapretRulesFile,
ip,
nft,
}:
@@ -19,6 +20,7 @@ let
ar = cfg.appRouting;
art = ar.backends.tun;
artp = ar.backends.tproxy;
arz = ar.backends.zapret;
builtinTags = [
"proxy"
"direct"
@@ -277,6 +279,11 @@ let
name = "tproxy";
route = "tproxy";
}
] ++ lib.optionals (arz.enable && cfg.zapret.enable) [
{
name = "zapret";
route = "zapret";
}
];
effectiveAppRoutingProfiles =
ar.profiles
@@ -299,8 +306,10 @@ let
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,
@@ -462,6 +471,55 @@ ${lib.concatMapStrings (cidr: ''
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";
@@ -483,12 +541,15 @@ ${lib.concatMapStrings (cidr: ''
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
@@ -559,6 +620,16 @@ ${lib.concatMapStrings (cidr: ''
| ${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
@@ -745,6 +816,46 @@ ${lib.concatMapStrings (cidr: ''
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"
;;
*)
@@ -798,14 +909,14 @@ in
environment.systemPackages = [ proxyCtl ];
# nftables must be on for TProxy to work.
networking.nftables.enable = lib.mkIf (sb.tproxy.enable || art.enable || artp.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 (art.enable || artp.enable) {
users.groups = lib.mkIf (art.enable || artp.enable || arz.enable) {
"${ar.userControl.group}" = { };
};
security.polkit.enable = lib.mkIf (art.enable || artp.enable) true;
security.polkit.extraConfig = lib.mkIf (art.enable || artp.enable) (lib.mkAfter ''
security.polkit.enable = lib.mkIf (art.enable || artp.enable || arz.enable) true;
security.polkit.extraConfig = lib.mkIf (art.enable || artp.enable || arz.enable) (lib.mkAfter ''
polkit.addRule(function(action, subject) {
if (!subject.isInGroup("${ar.userControl.group}")) {
return null;
@@ -819,7 +930,9 @@ in
if (unit === "proxy-suite-app-tun.service" ||
unit.indexOf("proxy-suite-app-tun-user@") === 0 ||
unit === "proxy-suite-app-tproxy.service" ||
unit.indexOf("proxy-suite-app-tproxy-user@") === 0) {
unit.indexOf("proxy-suite-app-tproxy-user@") === 0 ||
unit === "proxy-suite-app-zapret.service" ||
unit.indexOf("proxy-suite-app-zapret-user@") === 0) {
return polkit.Result.YES;
}
@@ -851,6 +964,18 @@ in
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 = [
@@ -906,6 +1031,18 @@ in
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";
@@ -938,6 +1075,46 @@ in
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
@@ -1104,6 +1281,19 @@ in
};
};
}
// 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;
};
};
+208 -3
View File
@@ -80,15 +80,16 @@ let
dnsServerByTag =
dnsConfig: tag:
builtins.head (builtins.filter (server: server.tag == tag) dnsConfig.dns.servers);
mkZapretBase =
fixture:
mkZapretBaseFor =
fixture: serviceName:
let
env = fixture.config.systemd.services.zapret-discord-youtube.serviceConfig.Environment;
env = fixture.config.systemd.services.${serviceName}.serviceConfig.Environment;
zapretBaseEnv = builtins.head (
builtins.filter (value: pkgs.lib.hasPrefix "ZAPRET_BASE=" value) env
);
in
pkgs.lib.removePrefix "ZAPRET_BASE=" zapretBaseEnv;
mkZapretBase = fixture: mkZapretBaseFor fixture "zapret-discord-youtube";
packagePathMatches =
packages: pattern:
builtins.any (
@@ -106,6 +107,13 @@ let
builtins.head (
builtins.filter (line: pkgs.lib.hasPrefix prefix line) (pkgs.lib.splitString "\n" text)
);
normalizeExec = value: if builtins.isList value then builtins.head value else value;
readExecScripts =
value:
let
execs = if builtins.isList value then value else [ value ];
in
pkgs.lib.concatStringsSep "\n" (map builtins.readFile execs);
quotedValueByPrefix =
text: prefix:
pkgs.lib.removeSuffix "\"" (pkgs.lib.removePrefix prefix (lineByPrefix text prefix));
@@ -867,6 +875,76 @@ let
]).config.system.build.toplevel.drvPath
);
appRoutingZapretFixture = evalProxySuite [
baseModule
{
services.proxy-suite = {
zapret.enable = true;
appRouting = {
enable = true;
createDefaultProfiles = true;
proxychains.enable = true;
backends.zapret.enable = true;
};
};
}
];
appRoutingZapretScript =
builtins.readFile (
"${packageByPattern appRoutingZapretFixture.config.environment.systemPackages
".*/[^/]*proxy-ctl(-[0-9.]+)?$"}/bin/proxy-ctl"
);
appRoutingZapretProfiles =
builtins.fromJSON (
builtins.readFile (
quotedValueByPrefix appRoutingZapretScript "APP_ROUTING_PROFILES_FILE=\""
)
);
appRoutingZapretStartScript =
readExecScripts appRoutingZapretFixture.config.systemd.services."proxy-suite-app-zapret".serviceConfig.ExecStartPre;
appRoutingZapretUserStartExec =
appRoutingZapretFixture.config.systemd.services."proxy-suite-app-zapret-user@".serviceConfig.ExecStart;
appRoutingZapretUserStartScript =
builtins.readFile (builtins.head (pkgs.lib.splitString " " appRoutingZapretUserStartExec));
appRoutingZapretBase = mkZapretBase appRoutingZapretFixture;
appRoutingZapretConfig = builtins.readFile "${appRoutingZapretBase}/config";
appRoutingAppZapretBase = mkZapretBaseFor appRoutingZapretFixture "proxy-suite-app-zapret";
appRoutingAppZapretConfig = builtins.readFile "${appRoutingAppZapretBase}/config";
appRoutingZapretGlobalCustomScript =
builtins.readFile "${appRoutingZapretBase}/init.d/sysv/custom.d/50-proxy-suite-custom.sh";
appRoutingZapretWithoutEnable = forceEval (
(evalProxySuite [
baseModule
{
services.proxy-suite = {
zapret.enable = true;
appRouting = {
enable = true;
profiles = [
{
name = "yt";
route = "zapret";
}
];
};
};
}
]).config.system.build.toplevel.drvPath
);
appRoutingZapretWithoutZapretService = forceEval (
(evalProxySuite [
baseModule
{
services.proxy-suite.appRouting = {
enable = true;
backends.zapret.enable = true;
};
}
]).config.system.build.toplevel.drvPath
);
duplicateAppRoutingProfiles = forceEval (
(evalProxySuite [
baseModule
@@ -989,6 +1067,49 @@ let
]).config.system.build.toplevel.drvPath
);
appRoutingZapretFilterMarkCollision = forceEval (
(evalProxySuite [
baseModule
{
services.proxy-suite = {
zapret.enable = true;
singBox.proxyMark = 268435456;
appRouting = {
enable = true;
backends.zapret = {
enable = true;
filterMark = 268435456;
};
};
};
}
]).config.system.build.toplevel.drvPath
);
appRoutingTproxyZapretMarkCollision = forceEval (
(evalProxySuite [
baseModule
{
services.proxy-suite = {
zapret.enable = true;
appRouting = {
enable = true;
backends = {
tproxy = {
enable = true;
fwmark = 23;
};
zapret = {
enable = true;
filterMark = 23;
};
};
};
};
}
]).config.system.build.toplevel.drvPath
);
# Validation failures
subscriptionBothSources = forceEval (
(evalProxySuite [
@@ -1459,6 +1580,13 @@ let
true
)
# -- appRouting: createDefaultProfiles injects curated zapret profile when backend and zapret are enabled --
(
assert builtins.length appRoutingZapretProfiles == 2;
assert builtins.any (profile: profile.name == "zapret" && profile.route == "zapret") appRoutingZapretProfiles;
true
)
# -- appRouting: proxy-ctl script embeds wrap/apps commands --
(
assert pkgs.lib.hasInfix "wrap <profile> -- <cmd>" appRoutingProxychainsScript;
@@ -1496,6 +1624,14 @@ let
true
)
# -- appRouting: generated proxy-ctl script dispatches zapret profiles through systemd slices --
(
assert pkgs.lib.hasInfix "APP_ROUTING_ZAPRET_ENABLED" appRoutingZapretScript;
assert pkgs.lib.hasInfix "proxy-suite-app-zapret-user@$uid.service" appRoutingZapretScript;
assert pkgs.lib.hasInfix "proxy-suite-app-zapret-$profile-$$" appRoutingZapretScript;
true
)
# -- appRouting: user mark script installs fwmark + conntrack mark rules --
(
assert pkgs.lib.hasInfix "meta mark set" appRoutingTunUserStartScript;
@@ -1558,6 +1694,14 @@ let
true
)
# -- appRouting: app zapret service and helper units are created --
(
assert appRoutingZapretFixture.config.systemd.services ? "proxy-suite-app-zapret";
assert appRoutingZapretFixture.config.systemd.services ? "proxy-suite-app-zapret-user@";
assert appRoutingZapretFixture.config.systemd.user.services ? "proxy-suite-app-zapret-anchor";
true
)
# -- appRouting: app TUN enables nftables and user control group --
(
assert appRoutingTunFixture.config.networking.nftables.enable;
@@ -1581,6 +1725,45 @@ let
true
)
# -- appRouting: app zapret helper installs socket cgroup bitwise mark rules --
(
assert pkgs.lib.hasInfix "socket cgroupv2" appRoutingZapretUserStartScript;
assert pkgs.lib.hasInfix "meta mark set meta mark or 268435456" appRoutingZapretUserStartScript;
assert pkgs.lib.hasInfix "ct mark set ct mark or 268435456" appRoutingZapretUserStartScript;
true
)
# -- appRouting: app zapret startup installs nftables backend --
(
assert pkgs.lib.hasInfix "proxy_suite_app_zapret_mark" appRoutingZapretStartScript;
true
)
# -- appRouting: global zapret config keeps FILTER_MARK disabled --
(
assert pkgs.lib.hasInfix "FILTER_MARK=" appRoutingZapretConfig;
assert builtins.match ".*FILTER_MARK=0x10000000.*" appRoutingZapretConfig == null;
true
)
# -- appRouting: app zapret config is a separate instance with its own filter/qnum/marks --
(
assert pkgs.lib.hasInfix "FILTER_MARK=0x10000000" appRoutingAppZapretConfig;
assert pkgs.lib.hasInfix "MODE_FILTER=none" appRoutingAppZapretConfig;
assert pkgs.lib.hasInfix "QNUM=201" appRoutingAppZapretConfig;
assert pkgs.lib.hasInfix "DESYNC_MARK=0x8000000" appRoutingAppZapretConfig;
assert pkgs.lib.hasInfix "DESYNC_MARK_POSTNAT=0x4000000" appRoutingAppZapretConfig;
assert pkgs.lib.hasInfix "ZAPRET_NFT_TABLE=proxy_suite_app_zapret" appRoutingAppZapretConfig;
true
)
# -- appRouting: global zapret installs a bypass hook for app-marked traffic --
(
assert pkgs.lib.hasInfix "proxy-suite app-zapret bypass" appRoutingZapretGlobalCustomScript;
assert pkgs.lib.hasInfix "mark and 268435456 != 0 return" appRoutingZapretGlobalCustomScript;
true
)
# -- appRouting: route=proxychains requires proxychains.enable --
(
assert appRoutingProxychainsWithoutEnable.success == false;
@@ -1611,6 +1794,16 @@ let
true
)
# -- appRouting: route=zapret requires appRouting.backends.zapret.enable and zapret.enable --
(
assert appRoutingZapretWithoutEnable.success == false;
true
)
(
assert appRoutingZapretWithoutZapretService.success == false;
true
)
# -- appRouting: profile names must be unique --
(
assert duplicateAppRoutingProfiles.success == false;
@@ -1641,6 +1834,18 @@ let
true
)
# -- appRouting: app zapret filter mark must differ from sing-box proxyMark --
(
assert appRoutingZapretFilterMarkCollision.success == false;
true
)
# -- appRouting: app TProxy and app zapret marks must differ --
(
assert appRoutingTproxyZapretMarkCollision.success == false;
true
)
# -- subscription: no outbounds + no subscriptions fails --
(
assert noOutboundsNoSubscriptions.success == false;