feat: select zapret2 strategies source

This commit is contained in:
fufsob committed 2026-09-13 19:33:26 +00:00
1 parent fdb2b08790
commit 441be87b61
14 files changed
+566 -208

No files matched your search

+1 -1
View File
@@ -124,7 +124,7 @@ A group without a verb shows its status or list.
zapret auto [list] hosts zapret2 learned as blocked
zapret auto add|forget|exclude <domain>
pin, forget, or never learn a host (sudo)
zapret auto clear forget every learned host (sudo)
zapret auto clear forget learned hosts and strategies (sudo)
awg [list] AmneziaWG profiles and their state
awg on <profile> | off [profile] | restart [profile]
+5 -35
View File
@@ -287,46 +287,16 @@ services.proxy-suite = {
udpIn = 1;
udpOut = 4;
};
blobs = {
quic_initial = "quic_initial_www_google_com.bin";
tls_clienthello = "tls_clienthello_www_google_com.bin";
};
blobs = { };
domains = [ ];
excludeDomains = [ ];
ipv6 = false;
ports = {
tcp = "80,443,1984,2053,2083,2087,2096,5222,8443";
udp = "443,590-600,1400,3478-3481,5349,19294-19344,49152-65535";
tcp = null;
udp = null;
};
profiles = [
''
--filter-tcp=443,80,1984,5222 --filter-l7=http,tls,mtproto <HOSTLIST>
--payload=tls_client_hello,mtproto_initial
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
--lua-desync=fake:blob=tls_clienthello:tls_mod=rnd,dupsid,sni=fonts.google.com:tcp_seq=10000:strategy=1
--lua-desync=multisplit:pos=1,midsld:seqovl=1:seqovl_pattern=tls_clienthello:tcp_ts_up:strategy=1
--lua-desync=fake:blob=0x00000000:tcp_ack=-66000:tls_mod=rnd,dupsid,sni=www.google.com:repeats=2:strategy=2
--lua-desync=multisplit:pos=1,midsld:strategy=2
--lua-desync=hostfakesplit:host=ozon.ru:midhost=host-2:seqovl=sniext+3:seqovl_pattern=tls_clienthello:badsum:tcp_md5:tcp_ts_up:strategy=3
--lua-desync=hostfakesplit:tcp_md5:tcp_ts_up:strategy=3
--payload=http_req
--lua-desync=http_methodeol:badsum
''
''
--filter-udp=443 --filter-l7=quic <HOSTLIST_NOAUTO>
--payload=quic_initial
--lua-desync=fake:blob=quic_initial:repeats=11
''
''
--filter-udp=590-600,1400,3478-3481,5349,19294-19344,49152-65535
--filter-l7=wireguard,stun,discord,mtproto,unknown
--out-range=<n2
--payload=wireguard_initiation,wireguard_response,wireguard_cookie,stun,discord_ip_discovery,mtproto_initial,unknown
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
--lua-desync=fake:repeats=6:strategy=1
--lua-desync=fake:blob=quic_initial:repeats=6:strategy=2
''
];
profiles = null;
strategySource = "nfqws2-keenetic";
};
};
};
+55 -44
View File
@@ -53,6 +53,7 @@ Part of the [proxy-suite options reference](./index.md).
- [tcp](#services-proxy-suite-zapret-zapret2-ports-tcp)
- [udp](#services-proxy-suite-zapret-zapret2-ports-udp)
- [profiles](#services-proxy-suite-zapret-zapret2-profiles)
- [strategySource](#services-proxy-suite-zapret-zapret2-strategysource)
<a id="services-proxy-suite-zapret-enable"></a>
## services\.proxy-suite\.zapret\.enable
@@ -542,6 +543,8 @@ list of string
Learn blocked hosts: after failThreshold failures (retransmissions, early RST, DPI
redirect, one-sided UDP) a host joins /var/lib/proxy-suite/zapret2/zapret-hosts-auto\.txt\.
Off, only zapret2\.domains and ` proxy-ctl zapret auto add ` are acted on\.
The thresholds below also fill whichever of them a profile’s strategy rotation
(circular) leaves unset; its own fails and time are kept\.
*Type:*
boolean
@@ -687,7 +690,7 @@ positive integer, meaning >0
<a id="services-proxy-suite-zapret-zapret2-blobs"></a>
## services\.proxy-suite\.zapret\.zapret2\.blobs
Fake payloads by name (blob=\<name>): a file in zapret2’s files/fake, or an absolute path\.
Fake payloads by name (blob=\<name>) on top of those of strategySource: a file in zapret2’s files/fake, or an absolute path\.
*Type:*
attribute set of string
@@ -695,10 +698,7 @@ attribute set of string
*Default:*
```nix
{
quic_initial = "quic_initial_www_google_com.bin";
tls_clienthello = "tls_clienthello_www_google_com.bin";
}
{ }
```
*Example:*
@@ -770,73 +770,57 @@ false
<a id="services-proxy-suite-zapret-zapret2-ports-tcp"></a>
## services\.proxy-suite\.zapret\.zapret2\.ports\.tcp
TCP ports sent to NFQUEUE\. Must cover every port a profile filters on\.
TCP ports sent to NFQUEUE\. Must cover every port a profile filters on\. null uses the ports of strategySource\.
*Type:*
string
null or string
*Default:*
```nix
"80,443,1984,2053,2083,2087,2096,5222,8443"
null
```
*Example:*
```nix
"80,443"
```
<a id="services-proxy-suite-zapret-zapret2-ports-udp"></a>
## services\.proxy-suite\.zapret\.zapret2\.ports\.udp
UDP ports sent to NFQUEUE\. Must cover every port a profile filters on\.
UDP ports sent to NFQUEUE\. Must cover every port a profile filters on\. null uses the ports of strategySource\.
*Type:*
string
null or string
*Default:*
```nix
"443,590-600,1400,3478-3481,5349,19294-19344,49152-65535"
null
```
*Example:*
```nix
"443"
```
<a id="services-proxy-suite-zapret-zapret2-profiles"></a>
## services\.proxy-suite\.zapret\.zapret2\.profiles
nfqws2 profiles, joined with --new; first match wins\. \<HOSTLIST> expands to the hostlist
arguments, \<HOSTLIST_NOAUTO> to the same without learning\. --qnum, --fwmark and --lua-init
are added automatically\.
nfqws2 profiles replacing those of strategySource, joined with --new; first match wins\.
\<HOSTLIST> expands to the hostlist arguments, \<HOSTLIST_NOAUTO> to the same without
learning\. --qnum, --fwmark and --lua-init are added automatically\. null uses the profiles of strategySource\.
*Type:*
list of string
null or (list of string)
*Default:*
```nix
[
''
--filter-tcp=443,80,1984,5222 --filter-l7=http,tls,mtproto <HOSTLIST>
--payload=tls_client_hello,mtproto_initial
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
--lua-desync=fake:blob=tls_clienthello:tls_mod=rnd,dupsid,sni=fonts.google.com:tcp_seq=10000:strategy=1
--lua-desync=multisplit:pos=1,midsld:seqovl=1:seqovl_pattern=tls_clienthello:tcp_ts_up:strategy=1
--lua-desync=fake:blob=0x00000000:tcp_ack=-66000:tls_mod=rnd,dupsid,sni=www.google.com:repeats=2:strategy=2
--lua-desync=multisplit:pos=1,midsld:strategy=2
--lua-desync=hostfakesplit:host=ozon.ru:midhost=host-2:seqovl=sniext+3:seqovl_pattern=tls_clienthello:badsum:tcp_md5:tcp_ts_up:strategy=3
--lua-desync=hostfakesplit:tcp_md5:tcp_ts_up:strategy=3
--payload=http_req
--lua-desync=http_methodeol:badsum
''
''
--filter-udp=443 --filter-l7=quic <HOSTLIST_NOAUTO>
--payload=quic_initial
--lua-desync=fake:blob=quic_initial:repeats=11
''
''
--filter-udp=590-600,1400,3478-3481,5349,19294-19344,49152-65535
--filter-l7=wireguard,stun,discord,mtproto,unknown
--out-range=<n2
--payload=wireguard_initiation,wireguard_response,wireguard_cookie,stun,discord_ip_discovery,mtproto_initial,unknown
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
--lua-desync=fake:repeats=6:strategy=1
--lua-desync=fake:blob=quic_initial:repeats=6:strategy=2
''
]
null
```
*Example:*
@@ -846,3 +830,30 @@ list of string
"--filter-tcp=443 --filter-l7=tls <HOSTLIST> --payload=tls_client_hello --lua-desync=multisplit:pos=1,midsld"
]
```
<a id="services-proxy-suite-zapret-zapret2-strategysource"></a>
## services\.proxy-suite\.zapret\.zapret2\.strategySource
Where profiles, blobs and ports come from; both are pinned flake inputs\.
“nfqws2-keenetic”: its nfqws2\.conf strategies with its user and exclude lists\.
“z2k”: z2k’s own config generator, run at build time: per-category rotation pools
(general, YouTube, googlevideo, QUIC, Discord), its failure detectors and fake-TTL
hook, its blobs, whitelist and hostlists, including the ~125k-domain RKN list
(about 15 MB more RSS per nfqws2 process)\.
Either way each host’s working strategy is remembered across restarts in
/var/lib/proxy-suite/zapret2/circular/state\.tsv\.
*Type:*
one of “nfqws2-keenetic”, “z2k”
*Default:*
```nix
"nfqws2-keenetic"
```
*Example:*
```nix
"z2k"
```
Generated
+35
View File
@@ -1,5 +1,21 @@
{
"nodes": {
"nfqws2-keenetic": {
"flake": false,
"locked": {
"lastModified": 1789144514,
"narHash": "sha256-G+LvvXDqzYm8SOXNc3N+HIzvD9DR3J+WT+HHDdmjB0Y=",
"owner": "nfqws",
"repo": "nfqws2-keenetic",
"rev": "fa22c177b340e73d8b8a94b295af20e0228c4c22",
"type": "github"
},
"original": {
"owner": "nfqws",
"repo": "nfqws2-keenetic",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1788614874,
@@ -18,10 +34,29 @@
},
"root": {
"inputs": {
"nfqws2-keenetic": "nfqws2-keenetic",
"nixpkgs": "nixpkgs",
"z2k": "z2k",
"zapret": "zapret"
}
},
"z2k": {
"flake": false,
"locked": {
"lastModified": 1789186266,
"narHash": "sha256-d9gg7s66P3pkN7d4l72ryaGC9Ayoqg4tbHaoDNbDTT4=",
"owner": "necronicle",
"repo": "z2k",
"rev": "7beb9754d65a2cafd9c1d26d382bcb61d453d5b3",
"type": "github"
},
"original": {
"owner": "necronicle",
"ref": "z2k-enhanced",
"repo": "z2k",
"type": "github"
}
},
"zapret": {
"inputs": {
"nixpkgs": [
+18 -1
View File
@@ -7,6 +7,14 @@
url = "github:kartavkun/zapret-discord-youtube";
inputs.nixpkgs.follows = "nixpkgs";
};
nfqws2-keenetic = {
url = "github:nfqws/nfqws2-keenetic";
flake = false;
};
z2k = {
url = "github:necronicle/z2k/z2k-enhanced";
flake = false;
};
};
outputs =
@@ -14,6 +22,8 @@
self,
nixpkgs,
zapret,
nfqws2-keenetic,
z2k,
}:
let
systems = [
@@ -22,7 +32,14 @@
];
forAll = nixpkgs.lib.genAttrs systems;
pkgsFor = system: import nixpkgs { inherit system; };
proxySuiteModule = import ./modules/proxy-suite { inherit zapret nixpkgs; };
proxySuiteModule = import ./modules/proxy-suite {
inherit
zapret
nixpkgs
nfqws2-keenetic
z2k
;
};
mkOptionsDoc = import ./nix/options-doc.nix {
inherit nixpkgs pkgsFor proxySuiteModule;
};
+7 -1
View File
@@ -1,7 +1,12 @@
# Factory function – receives the zapret flake and this flake's own nixpkgs,
# returns a NixOS module. This lets consumers add a single flake input and get
# everything transitively.
{ zapret, nixpkgs }:
{
zapret,
nixpkgs,
nfqws2-keenetic,
z2k,
}:
{
config,
@@ -103,6 +108,7 @@ in
packages
;
inherit (nftr) perAppZapretRulesFile nft;
zapret2Sources = { inherit nfqws2-keenetic z2k; };
}
))
+38 -51
View File
@@ -8,50 +8,36 @@ let
type = types.ints.positive;
inherit default description;
};
# Ported from nfqws2-keenetic. `circular` rotates strategy=1/2/3 per
# second-level domain whenever the failure detector fires.
defaultProfiles = [
''
--filter-tcp=443,80,1984,5222 --filter-l7=http,tls,mtproto <HOSTLIST>
--payload=tls_client_hello,mtproto_initial
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
--lua-desync=fake:blob=tls_clienthello:tls_mod=rnd,dupsid,sni=fonts.google.com:tcp_seq=10000:strategy=1
--lua-desync=multisplit:pos=1,midsld:seqovl=1:seqovl_pattern=tls_clienthello:tcp_ts_up:strategy=1
--lua-desync=fake:blob=0x00000000:tcp_ack=-66000:tls_mod=rnd,dupsid,sni=www.google.com:repeats=2:strategy=2
--lua-desync=multisplit:pos=1,midsld:strategy=2
--lua-desync=hostfakesplit:host=ozon.ru:midhost=host-2:seqovl=sniext+3:seqovl_pattern=tls_clienthello:badsum:tcp_md5:tcp_ts_up:strategy=3
--lua-desync=hostfakesplit:tcp_md5:tcp_ts_up:strategy=3
--payload=http_req
--lua-desync=http_methodeol:badsum
''
# QUIC reads the learned list but never adds to it: browsers retry over TCP.
''
--filter-udp=443 --filter-l7=quic <HOSTLIST_NOAUTO>
--payload=quic_initial
--lua-desync=fake:blob=quic_initial:repeats=11
''
# No hostlist: these protocols carry no SNI.
''
--filter-udp=590-600,1400,3478-3481,5349,19294-19344,49152-65535
--filter-l7=wireguard,stun,discord,mtproto,unknown
--out-range=<n2
--payload=wireguard_initiation,wireguard_response,wireguard_cookie,stun,discord_ip_discovery,mtproto_initial,unknown
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
--lua-desync=fake:repeats=6:strategy=1
--lua-desync=fake:blob=quic_initial:repeats=6:strategy=2
''
];
fromSource = what: "null uses the ${what} of strategySource.";
in
{
options.services.proxy-suite.zapret.zapret2 = {
profiles = mkOption {
type = types.listOf types.str;
default = defaultProfiles;
strategySource = mkOption {
type = types.enum [
"nfqws2-keenetic"
"z2k"
];
default = "nfqws2-keenetic";
description = ''
nfqws2 profiles, joined with --new; first match wins. <HOSTLIST> expands to the hostlist
arguments, <HOSTLIST_NOAUTO> to the same without learning. --qnum, --fwmark and --lua-init
are added automatically.
Where profiles, blobs and ports come from; both are pinned flake inputs.
"nfqws2-keenetic": its nfqws2.conf strategies with its user and exclude lists.
"z2k": z2k's own config generator, run at build time: per-category rotation pools
(general, YouTube, googlevideo, QUIC, Discord), its failure detectors and fake-TTL
hook, its blobs, whitelist and hostlists, including the ~125k-domain RKN list
(about 15 MB more RSS per nfqws2 process).
Either way each host's working strategy is remembered across restarts in
/var/lib/proxy-suite/zapret2/circular/state.tsv.
'';
example = "z2k";
};
profiles = mkOption {
type = types.nullOr (types.listOf types.str);
default = null;
description = ''
nfqws2 profiles replacing those of strategySource, joined with --new; first match wins.
<HOSTLIST> expands to the hostlist arguments, <HOSTLIST_NOAUTO> to the same without
learning. --qnum, --fwmark and --lua-init are added automatically. ${fromSource "profiles"}
'';
example = [
"--filter-tcp=443 --filter-l7=tls <HOSTLIST> --payload=tls_client_hello --lua-desync=multisplit:pos=1,midsld"
@@ -60,11 +46,8 @@ in
blobs = mkOption {
type = types.attrsOf types.str;
default = {
tls_clienthello = "tls_clienthello_www_google_com.bin";
quic_initial = "quic_initial_www_google_com.bin";
};
description = "Fake payloads by name (blob=<name>): a file in zapret2's files/fake, or an absolute path.";
default = { };
description = "Fake payloads by name (blob=<name>) on top of those of strategySource: a file in zapret2's files/fake, or an absolute path.";
example = {
tls_clienthello = "/etc/proxy-suite/my_clienthello.bin";
};
@@ -86,15 +69,17 @@ in
ports = {
tcp = mkOption {
type = types.str;
default = "80,443,1984,2053,2083,2087,2096,5222,8443";
description = "TCP ports sent to NFQUEUE. Must cover every port a profile filters on.";
type = types.nullOr types.str;
default = null;
description = "TCP ports sent to NFQUEUE. Must cover every port a profile filters on. ${fromSource "ports"}";
example = "80,443";
};
udp = mkOption {
type = types.str;
default = "443,590-600,1400,3478-3481,5349,19294-19344,49152-65535";
description = "UDP ports sent to NFQUEUE. Must cover every port a profile filters on.";
type = types.nullOr types.str;
default = null;
description = "UDP ports sent to NFQUEUE. Must cover every port a profile filters on. ${fromSource "ports"}";
example = "443";
};
};
@@ -111,6 +96,8 @@ in
Learn blocked hosts: after failThreshold failures (retransmissions, early RST, DPI
redirect, one-sided UDP) a host joins /var/lib/proxy-suite/zapret2/zapret-hosts-auto.txt.
Off, only zapret2.domains and `proxy-ctl zapret auto add` are acted on.
The thresholds below also fill whichever of them a profile's strategy rotation
(circular) leaves unset; its own fails and time are kept.
'';
};
+3 -1
View File
@@ -4,6 +4,7 @@
pkgs,
cfg,
packages,
zapret2Sources,
perAppZapretRulesFile,
nft,
}:
@@ -25,6 +26,7 @@ let
pkgs
cfg
packages
zapret2Sources
;
};
@@ -69,7 +71,7 @@ let
# nfqws2 and proxy-ctl expect the list files to exist.
mkPreStart = ''
${lib.getExe' pkgs.kmod "modprobe"} nfnetlink_queue 2>/dev/null || true
install -d -m 0755 ${runtime.stateDir}
install -d -m 0755 ${runtime.stateDir} ${runtime.circularStateDir}
touch ${runtime.autoHostlistFile} ${runtime.userHostlistFile} ${runtime.excludeHostlistFile}
'';
+135 -55
View File
@@ -4,6 +4,7 @@
pkgs,
cfg,
packages,
zapret2Sources,
}:
let
@@ -19,6 +20,7 @@ let
autoHostlistFile = "${stateDir}/zapret-hosts-auto.txt";
userHostlistFile = "${stateDir}/zapret-hosts-user.txt";
excludeHostlistFile = "${stateDir}/zapret-hosts-user-exclude.txt";
circularStateDir = "${stateDir}/circular";
runtimeDeps = lib.attrValues {
inherit (pkgs)
@@ -38,9 +40,17 @@ let
};
toHex = value: "0x" + lib.toHexString value;
orSource = value: fallback: if value != null then value else fallback;
withSpaces = lib.concatMapStrings (arg: " " + arg);
sources = import ./sources.nix {
inherit lib pkgs;
sources = zapret2Sources;
};
source = sources.${zapret2Cfg.strategySource};
isZ2k = zapret2Cfg.strategySource == "z2k";
blobPath = file: if lib.hasPrefix "/" file then file else "${zapretBase}/files/fake/${file}";
blobArgs = lib.mapAttrsToList (name: file: "--blob=${name}:@${blobPath file}") zapret2Cfg.blobs;
hostlistMarkers = [
"<HOSTLIST>"
@@ -52,29 +62,65 @@ let
lib.optional (
zapret2Cfg.domains != [ ]
) "--hostlist-domains=${lib.concatStringsSep "," zapret2Cfg.domains}"
++ lib.optional (
zapret2Cfg.excludeDomains != [ ]
) "--hostlist-exclude-domains=${lib.concatStringsSep "," zapret2Cfg.excludeDomains}";
++ excludeDomainArgs;
excludeDomainArgs = lib.optional (
zapret2Cfg.excludeDomains != [ ]
) "--hostlist-exclude-domains=${lib.concatStringsSep "," zapret2Cfg.excludeDomains}";
renderProfile =
profile:
let
suffix = lib.concatMapStrings (arg: " " + arg) staticListArgs;
in
lib.replaceStrings hostlistMarkers (map (marker: marker + suffix) hostlistMarkers) (
lib.trim profile
);
lib.replaceStrings hostlistMarkers (map (
marker: marker + withSpaces staticListArgs
) hostlistMarkers) (lib.trim profile);
nfqwsOpt = lib.concatStringsSep " " (
blobArgs ++ [ (lib.concatStringsSep " --new " (map renderProfile zapret2Cfg.profiles)) ]
z2kGenerated = sources.z2k.mkProfiles {
hostlistSuffix = withSpaces staticListArgs;
# z2k's category profiles filter on their own lists, not on a marker.
excludeSuffix = withSpaces ([ "--hostlist-exclude=${excludeHostlistFile}" ] ++ excludeDomainArgs);
};
profilesFile =
if zapret2Cfg.profiles == null && isZ2k then
"${z2kGenerated}/profiles"
else
pkgs.writeText "proxy-suite-zapret2-profiles" (
lib.concatStringsSep " --new " (map renderProfile (orSource zapret2Cfg.profiles source.profiles))
);
blobsFile =
if isZ2k then
"${z2kGenerated}/blobs"
else
pkgs.writeText "proxy-suite-zapret2-blobs" (lib.concatStringsSep " " source.blobArgs);
# The state layer wraps circular, so it loads after the source's Lua.
optPrefix = lib.concatStringsSep " " (
map (file: "--lua-init=@${file}") (
source.luaInit ++ [ "${zapret2Sources.z2k}/files/lua/z2k-state-persist.lua" ]
)
++ lib.mapAttrsToList (name: file: "--blob=${name}:@${blobPath file}") zapret2Cfg.blobs
);
# The NFQUEUE window must exceed the retransmission threshold it counts.
# Detector args a circular instance leaves unset come from autoHostlist, so
# learning and rotation agree; each source keeps its own fails and time.
circularFill = lib.concatStringsSep " " (
[
"retrans=${toString autoCfg.retransThreshold}"
"maxseq=${toString autoCfg.retransMaxseq}"
"inseq=${toString autoCfg.incomingMaxseq}"
"udp_out=${toString autoCfg.udpOut}"
"udp_in=${toString autoCfg.udpIn}"
]
++ lib.optional autoCfg.retransReset "reset"
);
# The NFQUEUE window must exceed the retransmission threshold it counts, and
# cover what the source's detectors need.
packetWindow = {
tcpOut = 6 + autoCfg.retransThreshold;
tcpOut = lib.max (6 + autoCfg.retransThreshold) (source.window.tcpOut or 0);
tcpIn = 15;
udpOut = 6 + autoCfg.retransThreshold;
udpIn = 3;
udpOut = lib.max (6 + autoCfg.retransThreshold) (source.window.udpOut or 0);
udpIn = source.window.udpIn or 3;
};
mkConfig =
@@ -86,43 +132,74 @@ let
filterMark ? null,
modeFilter,
}:
pkgs.writeText "proxy-suite-zapret2-config" (
lib.concatStringsSep "\n" (
[
"# Generated by proxy-suite. Do not edit."
"WS_USER=root"
"FWTYPE=nftables"
"INIT_APPLY_FW=1"
"QNUM=${toString qnum}"
"DESYNC_MARK=${toHex desyncMark}"
"DESYNC_MARK_POSTNAT=${toHex desyncMarkPostnat}"
"ZAPRET_NFT_TABLE=${nftTable}"
]
++ lib.optional (filterMark != null) "FILTER_MARK=${toHex filterMark}"
++ lib.optional (!zapret2Cfg.ipv6) "DISABLE_IPV6=1"
++ [
"NFQWS2_ENABLE=1"
"NFQWS2_PORTS_TCP=${zapret2Cfg.ports.tcp}"
"NFQWS2_PORTS_UDP=${zapret2Cfg.ports.udp}"
"NFQWS2_TCP_PKT_OUT=${toString packetWindow.tcpOut}"
"NFQWS2_TCP_PKT_IN=${toString packetWindow.tcpIn}"
"NFQWS2_UDP_PKT_OUT=${toString packetWindow.udpOut}"
"NFQWS2_UDP_PKT_IN=${toString packetWindow.udpIn}"
"MODE_FILTER=${modeFilter}"
"AUTOHOSTLIST_FAIL_THRESHOLD=${toString autoCfg.failThreshold}"
"AUTOHOSTLIST_FAIL_TIME=${toString autoCfg.failTime}"
"AUTOHOSTLIST_RETRANS_THRESHOLD=${toString autoCfg.retransThreshold}"
"AUTOHOSTLIST_RETRANS_RESET=${if autoCfg.retransReset then "1" else "0"}"
"AUTOHOSTLIST_RETRANS_MAXSEQ=${toString autoCfg.retransMaxseq}"
"AUTOHOSTLIST_INCOMING_MAXSEQ=${toString autoCfg.incomingMaxseq}"
"AUTOHOSTLIST_UDP_OUT=${toString autoCfg.udpOut}"
"AUTOHOSTLIST_UDP_IN=${toString autoCfg.udpIn}"
"AUTOHOSTLIST_DEBUGLOG=${if autoCfg.debugLog then "1" else "0"}"
"NFQWS2_OPT=${lib.escapeShellArg nfqwsOpt}"
""
]
)
);
let
header = pkgs.writeText "proxy-suite-zapret2-config-header" (
lib.concatStringsSep "\n" (
[
"# Generated by proxy-suite. Do not edit."
"WS_USER=root"
"FWTYPE=nftables"
"INIT_APPLY_FW=1"
"QNUM=${toString qnum}"
"DESYNC_MARK=${toHex desyncMark}"
"DESYNC_MARK_POSTNAT=${toHex desyncMarkPostnat}"
"ZAPRET_NFT_TABLE=${nftTable}"
]
++ lib.optional (filterMark != null) "FILTER_MARK=${toHex filterMark}"
++ lib.optional (!zapret2Cfg.ipv6) "DISABLE_IPV6=1"
++ [
"NFQWS2_ENABLE=1"
"NFQWS2_PORTS_TCP=${orSource zapret2Cfg.ports.tcp source.ports.tcp}"
"NFQWS2_PORTS_UDP=${orSource zapret2Cfg.ports.udp source.ports.udp}"
"NFQWS2_TCP_PKT_OUT=${toString packetWindow.tcpOut}"
"NFQWS2_TCP_PKT_IN=${toString packetWindow.tcpIn}"
"NFQWS2_UDP_PKT_OUT=${toString packetWindow.udpOut}"
"NFQWS2_UDP_PKT_IN=${toString packetWindow.udpIn}"
"MODE_FILTER=${modeFilter}"
"AUTOHOSTLIST_FAIL_THRESHOLD=${toString autoCfg.failThreshold}"
"AUTOHOSTLIST_FAIL_TIME=${toString autoCfg.failTime}"
"AUTOHOSTLIST_RETRANS_THRESHOLD=${toString autoCfg.retransThreshold}"
"AUTOHOSTLIST_RETRANS_RESET=${if autoCfg.retransReset then "1" else "0"}"
"AUTOHOSTLIST_RETRANS_MAXSEQ=${toString autoCfg.retransMaxseq}"
"AUTOHOSTLIST_INCOMING_MAXSEQ=${toString autoCfg.incomingMaxseq}"
"AUTOHOSTLIST_UDP_OUT=${toString autoCfg.udpOut}"
"AUTOHOSTLIST_UDP_IN=${toString autoCfg.udpIn}"
"AUTOHOSTLIST_DEBUGLOG=${if autoCfg.debugLog then "1" else "0"}"
""
]
)
);
in
pkgs.runCommand "proxy-suite-zapret2-config"
{
nativeBuildInputs = [ pkgs.gawk ];
inherit circularFill optPrefix;
}
''
opt="$optPrefix $(cat ${blobsFile}) $(cat ${profilesFile})"
opt=$(printf '%s\n' "$opt" | awk -v fill="$circularFill" '
{
for (i = 1; i <= NF; i++) {
t = $i
if (t ~ /^--lua-desync=circular(:|$)/) {
n = split(fill, f, " ")
for (j = 1; j <= n; j++) {
k = f[j]
sub(/=.*/, "", k)
if (t !~ (":" k "(=|:|$)")) t = t ":" f[j]
}
}
printf "%s%s", (i > 1 ? " " : ""), t
}
}')
case "$opt" in
*"'"*)
echo "nfqws2 options must not contain a single quote" >&2
exit 1
;;
esac
{ cat ${header}; printf "NFQWS2_OPT='%s'\n" "$opt"; } >"$out"
'';
# Keep desync off TUN interfaces (it breaks proxied handshakes), off per-app
# traffic, and off exempted subnets (e.g. NATed VMs whose traffic it would break).
@@ -168,8 +245,7 @@ let
interface: mkRule chain.name "${chain.direction} '\"${interface}\"'" "proxy-suite TUN bypass"
) tunInterfaces
++ map (
cidr:
mkRule chain.name "${nftFamily cidr} ${chain.ipMatch} ${cidr}" "proxy-suite CIDR exemption"
cidr: mkRule chain.name "${nftFamily cidr} ${chain.ipMatch} ${cidr}" "proxy-suite CIDR exemption"
) exemptCidrs
) chains;
in
@@ -214,6 +290,9 @@ let
"HOSTLIST_BASE=${stateDir}"
"PIDDIR=${pidDir}"
"PATH=${lib.makeBinPath runtimeDeps}"
# Read by z2k-state-persist.lua inside nfqws2, which inherits the unit's environment.
"Z2K_STATE_DIR_OVERRIDE=${circularStateDir}"
"Z2K_AUTOCIRCULAR_FALLBACK_OVERRIDE=${pidDir}"
];
in
{
@@ -223,6 +302,7 @@ in
autoHostlistFile
userHostlistFile
excludeHostlistFile
circularStateDir
mkCustomScript
mkRuntime
mkEnv
+180
View File
@@ -0,0 +1,180 @@
# Strategy sources for nfqws2, both pinned flake inputs.
{
lib,
pkgs,
sources,
}:
let
inherit (lib)
concatStringsSep
filter
hasPrefix
replaceStrings
splitString
trim
;
words = s: filter (w: w != "") (splitString " " (replaceStrings [ "\n" "\t" ] [ " " " " ] s));
# The text between start and the next stop. Split, not a regex: std::regex overflows
# its stack on files this size. A pinned file that stopped matching must fail the
# build, not render an empty profile.
between =
what: start: stop: text:
let
parts = splitString start text;
in
if builtins.length parts != 2 then
throw "proxy-suite: expected one `${start}` in ${what}; did a flake input bump change its format?"
else
builtins.head (splitString stop (builtins.elemAt parts 1));
keenetic =
let
src = sources.nfqws2-keenetic;
conf = builtins.readFile "${src}/etc/nfqws2/nfqws2.conf";
quoted = name: between "nfqws2.conf" "\n${name}=\"" "\"" conf;
bare = name: between "nfqws2.conf" "\n${name}=" "\n" conf;
# The strategy blocks carry "# Strategy N" comment lines inside the quotes.
args =
name:
concatStringsSep " " (
words (
concatStringsSep "\n" (filter (l: !(hasPrefix "#" (trim l))) (splitString "\n" (quoted name)))
)
);
lists = "--hostlist=${src}/etc/nfqws2/lists/user.list --hostlist-exclude=${src}/etc/nfqws2/lists/exclude.list";
in
{
# Its init script's order. QUIC reads the learned list but never adds to it:
# browsers retry over TCP. The UDP profile carries no SNI, so no lists.
profiles = [
(args "NFQWS_ARGS_UDP")
"${args "NFQWS_ARGS_QUIC"} <HOSTLIST_NOAUTO> ${lists}"
"${args "NFQWS_ARGS"} <HOSTLIST> ${lists}"
];
blobArgs = map (replaceStrings [ "@/opt/etc/nfqws2/" ] [ "@${src}/etc/nfqws2/" ]) (
filter (hasPrefix "--blob=") (words (quoted "NFQWS_BASE_ARGS"))
);
luaInit = [ ];
ports = {
tcp = bare "TCP_PORTS";
udp = replaceStrings [ ":" ] [ "-" ] (bare "UDP_PORTS");
};
window = { };
};
z2k =
let
src = sources.z2k;
generator = builtins.readFile "${src}/lib/config_official.sh";
ports = name: between "config_official.sh" "\n${name}=\"" "\"" generator;
in
{
luaInit = map (name: "${src}/files/lua/${name}.lua") [
"z2k-alert"
"z2k-quic-silence"
"z2k-fooling-ext"
"z2k-modern-core"
];
ports = {
tcp = ports "NFQWS2_PORTS_TCP";
udp = ports "NFQWS2_PORTS_UDP";
};
# Queue windows from its generated config: the clone of a multi-segment
# ClientHello and the QUIC silence detector need more packets than nfqws2's defaults.
window = {
tcpOut = 20;
udpOut = 8;
udpIn = 8;
};
# z2k's own installer and config generator, run offline against a staged copy
# of its tree, so every pass it applies (pool layout, in-range windows,
# detectors, fake TTL) comes out exactly as on a router. Its tree is staged
# under $out because the generated options point into it.
mkProfiles =
{ hostlistSuffix, excludeSuffix }:
pkgs.runCommand "proxy-suite-zapret2-z2k-profiles"
{
nativeBuildInputs = with pkgs; [
bash
coreutils
findutils
gawk
gnugrep
gnused
];
inherit hostlistSuffix excludeSuffix;
}
''
root=$out/root
mkdir -p "$root/lists" "$root/lua" conf
cp -r ${src}/files/lists/extra_strats "$root/"
chmod -R u+w "$root"
cp "$root/extra_strats/TCP/RKN/Discord.txt" "$root/extra_strats/TCP_Discord.txt"
cp ${src}/files/lists/cf_extra_check_ips.txt "$root/lists/"
: >"$root/lists/discovered-domains.txt"
# The generator wires its detectors only when their Lua files exist.
ln -s ${src}/files/lua/*.lua "$root/lua/"
export ZAPRET2_DIR="$root" CONFIG_DIR="$PWD/conf" LISTS_DIR="$root/lists"
(
cd ${src}
bash -c '
. lib/utils.sh && . lib/config.sh && . lib/strategies.sh && . lib/config_official.sh || exit 1
print_info() { echo "$*" >&2; }
print_success() { echo "$*" >&2; }
print_warning() { echo "$*" >&2; }
print_error() { echo "$*" >&2; }
create_base_config >&2 &&
generate_strategies_conf strats_new2.txt "$STRATEGIES_CONF" >&2 &&
generate_quic_strategies_conf quic_strats.ini "$QUIC_STRATEGIES_CONF" >&2 &&
create_default_strategy_files >&2 &&
generate_nfqws2_opt_from_strategies
'
) >generated
sed -n '/^NFQWS2_OPT="/,/^"$/p' generated | sed '1s/^NFQWS2_OPT="//; $d' | tr '\n' ' ' >raw
grep -q -- '--lua-desync=circular' raw || { echo "z2k generator produced no profiles" >&2; exit 1; }
# Its learned-host list becomes ours (only the first profile learns), its
# whitelist gains our excludes, and the circular args it pins to the zapret2
# docs are dropped so autoHostlist fills them in.
awk -v disc="--hostlist=$root/lists/discovered-domains.txt" \
-v wl="--hostlist-exclude=$root/lists/whitelist.txt" \
-v hsuf="$hostlistSuffix" -v esuf="$excludeSuffix" '
{
for (i = 1; i <= NF; i++) {
t = $i
if (t == disc) {
t = (seen++ ? "<HOSTLIST_NOAUTO>" : "<HOSTLIST>") hsuf
} else if (t == wl) {
t = t esuf
} else if (t ~ /^--lua-desync=circular:/) {
n = split(substr(t, 23), p, ":")
t = "--lua-desync=circular"
for (j = 1; j <= n; j++)
if (p[j] !~ /^(retrans|maxseq|inseq)=/ && p[j] != "reset") t = t ":" p[j]
}
printf "%s%s", (i > 1 ? " " : ""), t
}
}' raw >body
awk -v z=${src} '
match($0, /^([A-Z0-9_]+_BLOB)="\$ZAPRET_BASE\/([^"]+)"/, m) { file[m[1]] = m[2] }
match($0, /--blob=([a-z0-9_]+):@\$([A-Z0-9_]+_BLOB)/, m) { printf "--blob=%s:@%s/%s ", m[1], z, file[m[2]] }
' ${src}/files/S99zapret2.new >blobs
grep -q -- '--blob=' blobs || { echo "z2k blob registrations not found" >&2; exit 1; }
mkdir -p "$out"
cp blobs "$out/blobs"
cp body "$out/profiles"
'';
};
in
{
nfqws2-keenetic = keenetic;
inherit z2k;
}
+10
View File
@@ -215,6 +215,7 @@
nativeBuildInputs = [
pkgs.bash
pkgs.coreutils
pkgs.gawk
pkgs.gnugrep
];
}
@@ -247,8 +248,17 @@
# The lists stay readable by unprivileged proxy-ctl after a rewrite.
test "$(stat -c %a "$state/zapret-hosts-user.txt")" = 644
# Forgetting a host also drops the strategy remembered for its apex.
mkdir -p "$state/circular"
printf '# key\thost\tstrategy\tts\tmode\tsni\nrkn_tcp\tyoutube.com\t3\t1\tauto\t\nrkn_tcp\tother.example\t2\t1\tauto\t\nyt_tcp\tyoutube.com\t5\t1\tauto\t\n' > "$state/circular/state.tsv"
run forget www.youtube.com > /dev/null
! grep -q 'youtube.com' "$state/circular/state.tsv"
grep -q 'other.example' "$state/circular/state.tsv"
grep -q '^# key' "$state/circular/state.tsv"
run clear > /dev/null
run list | grep -q 'No hostnames learned'
test ! -s "$state/circular/state.tsv"
# Without the zapret2 engine there is nothing to inspect.
! env ZAPRET_AUTO_ENABLED=0 ZAPRET_STATE_DIR="$state" bash "$proxy_ctl" zapret auto list
+50 -16
View File
@@ -17,6 +17,7 @@ let
zapret2PerApp
zapret2Tuned
zapret2NoAuto
zapret2Z2k
;
envValue =
@@ -40,6 +41,7 @@ let
perAppRuntime = runtimeDir zapret2PerApp perAppService;
tunedRuntime = runtimeDir zapret2Tuned globalService;
noAutoRuntime = runtimeDir zapret2NoAuto globalService;
z2kRuntime = runtimeDir zapret2Z2k globalService;
proxyCtlEnv = fixture: (mkProxyCtlDerived fixture).wrapperEnv;
in
@@ -61,6 +63,8 @@ in
zapret2Global.config.systemd.services.${globalService}.serviceConfig.StateDirectory
== "proxy-suite";
assert envValue zapret2PerApp perAppService "HOSTLIST_BASE=" == "/var/lib/proxy-suite/zapret2";
assert
envValue zapret2PerApp perAppService "Z2K_STATE_DIR_OVERRIDE=" == "/var/lib/proxy-suite/zapret2/circular";
true
)
@@ -117,6 +121,25 @@ in
grep -qF -- '<HOSTLIST_NOAUTO> --hostlist-domains=pinned.example --hostlist-exclude-domains=excluded.example' "${tunedRuntime}/config"
test "$(grep -oF -- '--hostlist-domains=pinned.example' "${tunedRuntime}/config" | wc -l)" = 2
# --- strategy sources -----------------------------------------------
# nfqws2-keenetic by default; every source remembers strategies across restarts.
grep -qx 'NFQWS2_PORTS_TCP=80,443,1984,2053,2083,2087,2096,5222,8443' "${globalRuntime}/config"
grep -qx 'NFQWS2_PORTS_UDP=443,590-600,1400,3478-3481,5349,19294-19344,49152-65535' "${globalRuntime}/config"
grep -qF -- '/files/lua/z2k-state-persist.lua' "${globalRuntime}/config"
# autoHostlist fills what circular leaves unset; the source keeps its fails and time.
grep -qF -- '--lua-desync=circular:fails=2:time=300:retrans=3:nld=2:maxseq=32768:inseq=4096:udp_out=4:udp_in=1:reset ' "${globalRuntime}/config"
# z2k: its generator's pools, detectors and fake TTL; only the general profile learns.
grep -qx 'NFQWS2_TCP_PKT_OUT=20' "${z2kRuntime}/config"
grep -qx 'NFQWS2_UDP_PKT_IN=8' "${z2kRuntime}/config"
grep -qx 'NFQWS2_PORTS_UDP=443,50000-50099,1400,3478-3481,5349,19294-19344' "${z2kRuntime}/config"
grep -qF -- 'key=rkn_tcp:nld=2:failure_detector=z2k_fail_tls_alert:retrans=3:maxseq=32768:inseq=4096:udp_out=4:udp_in=1:reset' "${z2kRuntime}/config"
grep -qF -- 'failure_detector=z2k_fail_quic_silence' "${z2kRuntime}/config"
grep -qF -- ':fool=z2k_dynamic_ttl' "${z2kRuntime}/config"
grep -qF -- '/extra_strats/TCP_Discord.txt <HOSTLIST> ' "${z2kRuntime}/config"
test "$(grep -oF -- '<HOSTLIST>' "${z2kRuntime}/config" | wc -l)" = 1
grep -qF -- '/lists/whitelist.txt --hostlist-exclude=/var/lib/proxy-suite/zapret2/zapret-hosts-user-exclude.txt' "${z2kRuntime}/config"
# --- per-app instance -------------------------------------------------
# Wrapped apps opted in explicitly, so no hostlist gates them.
grep -qx 'MODE_FILTER=none' "${perAppRuntime}/config"
@@ -132,31 +155,42 @@ in
grep -q 'nft insert rule inet $ZAPRET_NFT_TABLE prenat mark and 0x10000000 != 0 return' "$hook"
# --- the command line nfqws2 receives ---
# Expand <HOSTLIST> with zapret2's list.sh and let nfqws2 validate the result.
# Expand <HOSTLIST> with zapret2's list.sh and let nfqws2 validate the result,
# Lua included; the strategy state layer gets a writable directory.
export HOSTLIST_BASE="$PWD/lists"
export ZAPRET_BASE="$base"
mkdir -p "$HOSTLIST_BASE"
export Z2K_STATE_DIR_OVERRIDE="$PWD/circular"
mkdir -p "$HOSTLIST_BASE" "$Z2K_STATE_DIR_OVERRIDE"
touch "$HOSTLIST_BASE/zapret-hosts-auto.txt" \
"$HOSTLIST_BASE/zapret-hosts-user.txt" \
"$HOSTLIST_BASE/zapret-hosts-user-exclude.txt"
. "${globalRuntime}/config"
. "$base/common/base.sh"
. "$base/common/list.sh"
dry_run() (
. "$1/config"
. "$base/common/base.sh"
. "$base/common/list.sh"
opt="--qnum=$QNUM $NFQWS2_OPT"
filter_apply_hostlist_target opt
opt="--qnum=$QNUM $NFQWS2_OPT"
filter_apply_hostlist_target opt
# The service creates its state files; here they live in the sandbox.
opt=$(printf '%s' "$opt" | sed "s|/var/lib/proxy-suite/zapret2/|$HOSTLIST_BASE/|g")
printf '%s\n' "$opt" | tr ' ' '\n' >"$2"
printf '%s\n' "$opt" | tr ' ' '\n' | grep -qx -- "--hostlist-auto=$HOSTLIST_BASE/zapret-hosts-auto.txt"
printf '%s\n' "$opt" | tr ' ' '\n' | grep -qx -- '--hostlist-auto-fail-threshold=3'
printf '%s\n' "$opt" | tr ' ' '\n' | grep -qx -- '--hostlist-auto-fail-time=300'
# --user is deliberately omitted: the sandbox is not root.
"$base/nfq2/nfqws2" --dry-run --fwmark="$DESYNC_MARK" \
--lua-init=@"$base/lua/zapret-lib.lua" \
--lua-init=@"$base/lua/zapret-antidpi.lua" \
--lua-init=@"$base/lua/zapret-auto.lua" \
$opt
)
# --user is deliberately omitted: the sandbox is not root.
"$base/nfq2/nfqws2" --dry-run --fwmark="$DESYNC_MARK" \
--lua-init=@"$base/lua/zapret-lib.lua" \
--lua-init=@"$base/lua/zapret-antidpi.lua" \
--lua-init=@"$base/lua/zapret-auto.lua" \
$opt
dry_run ${globalRuntime} global.args
grep -qx -- "--hostlist-auto=$HOSTLIST_BASE/zapret-hosts-auto.txt" global.args
grep -qx -- '--hostlist-auto-fail-threshold=3' global.args
grep -qx -- '--hostlist-auto-fail-time=300' global.args
dry_run ${z2kRuntime} z2k.args
test "$(grep -cx -- "--hostlist-auto=$HOSTLIST_BASE/zapret-hosts-auto.txt" z2k.args)" = 1
touch "$out"
'';
+5
View File
@@ -58,4 +58,9 @@ in
enable = true;
zapret2.autoHostlist.enable = false;
};
zapret2Z2k = mkZapret2 {
enable = true;
zapret2.strategySource = "z2k";
};
}
+24 -3
View File
@@ -50,7 +50,7 @@ A group without a verb shows its status or list.
zapret auto [list] hosts zapret2 learned as blocked
zapret auto add|forget|exclude <domain>
pin, forget, or never learn a host (sudo)
zapret auto clear forget every learned host (sudo)
zapret auto clear forget learned hosts and strategies (sudo)
awg [list] AmneziaWG profiles and their state
awg on <profile> | off [profile] | restart [profile]
@@ -1095,8 +1095,23 @@ _zapret_auto_edit() {
fi
}
# Remembered strategies are keyed by the domain circular rotates on (usually the
# apex); z2k-state-persist.lua applies external deletions live.
_zapret_strategy_drop() {
local file domain="$1" tmp
file=$(_zapret_auto_file circular/state.tsv)
[ -s "$file" ] || return 0
tmp=$(mktemp "$file.XXXXXX" 2>/dev/null) || _die "Cannot write $file - re-run with sudo."
awk -F'\t' -v d="$domain" '/^#/ || ($2 != d && substr(d, length(d) - length($2)) != "." $2)' "$file" >"$tmp"
chmod 0644 "$tmp"
if ! mv "$tmp" "$file"; then
rm -f "$tmp"
_die "Cannot replace $file - re-run with sudo."
fi
}
cmd_zapret_auto() {
local verb="${1:-list}" domain="${2:-}" auto user exclude
local verb="${1:-list}" domain="${2:-}" auto user exclude state
[ "${ZAPRET_AUTO_ENABLED:-0}" = 1 ] || _die "Learned hostlists need zapret.engine = \"zapret2\"."
auto=$(_zapret_auto_file zapret-hosts-auto.txt)
user=$(_zapret_auto_file zapret-hosts-user.txt)
@@ -1117,16 +1132,22 @@ cmd_zapret_auto() {
;;
forget)
_zapret_auto_edit "$auto" "$domain" drop
_zapret_strategy_drop "$domain"
echo "Forgot $domain. It is learned again if it keeps failing; 'exclude' prevents that."
;;
exclude)
_zapret_auto_edit "$auto" "$domain" drop
_zapret_strategy_drop "$domain"
_zapret_auto_edit "$exclude" "$domain" add
echo "Excluded $domain. It is no longer touched or learned."
;;
clear)
: >"$auto" 2>/dev/null || _die "Cannot write $auto - re-run with sudo."
echo "Cleared the learned hostlist."
state=$(_zapret_auto_file circular/state.tsv)
if [ -e "$state" ]; then
: >"$state" 2>/dev/null || _die "Cannot write $state - re-run with sudo."
fi
echo "Cleared learned hosts and remembered strategies."
;;
*) _usage "zapret auto [list|add|forget|exclude|clear]" ;;
esac