fix: hardening

This commit is contained in:
FUFSoB committed 2026-10-05 22:44:09 +05:00
1 parent 017a947a18
commit a435942b4f
168 files changed
+9166 -1644

No files matched your search

@@ -11,9 +11,11 @@ for f in asn.txt sni.txt asn.new sni.new proxy.json proxy.json.tmp egress ts for
done
touch asn.txt sni.txt
force=0
if [ -e requests/force ]; then
if [ -e requests/force ] || [ -L requests/force ]; then
force=1
rm -f requests/force
# Whatever the group left under the name, a directory too: rm -f alone failed on one, and
# under set -e every run stopped here.
rm -rf -- requests/force
fi
now=$(date +%s)
# Digits only: $(( )) would run what a[$(...)] in it names.
+13 -1
View File
@@ -104,7 +104,19 @@ in
# `proxy-ctl zapret cutoff probe` drops its `force` file in requests/ instead.
StateDirectoryMode = "0755";
}
// constants.rootInSharedDirConfig;
// constants.rootInSharedDirConfig
# z2k-detect's raw sockets, marks and nft table (NET_*); requests/, which the group writes
# (DAC_*, FOWNER).
// lib.optionalAttrs cfg.host.privileged {
CapabilityBoundingSet = [
"CAP_NET_RAW"
"CAP_NET_ADMIN"
"CAP_DAC_OVERRIDE"
"CAP_DAC_READ_SEARCH"
"CAP_FOWNER"
];
NoNewPrivileges = true;
};
};
tmpfiles = [
+103 -5
View File
@@ -30,33 +30,71 @@ local NOREPLY_MS = 4000
local STALL_MS = 6000
local SYN_MS = 3500
-- Names in it come off the wire (a SNI): a newline would forge journal lines of its own.
local function say(text)
io.stderr:write("zapret2: ", text, "\n")
io.stderr:write("zapret2: ", (tostring(text):gsub("%c", "?")), "\n")
end
-- --- verdicts --------------------------------------------------------------------------
local VERDICTS = os.getenv("PROXY_SUITE_ZAPRET2_VERDICTS")
local status = {} -- "name proto" -> its last kind, so each change is written once
local status_count = 0
-- Names past which no new one gets a verdict: every unanswered address a page dials would
-- add one for good (and a /32 to the proxy's rules), each read back whole on the next.
local MAX_VERDICT_KEYS = 20000
local verdicts_full = false
-- Of them, addresses (ps_syn's), which a page can make by the thousand: never all of them.
local MAX_IP_VERDICT_KEYS = 2000
local ip_count = 0
local ip_full = false
-- The last verdicts, as the file has them now: proxy-ctl's retries land there too.
local function reload()
local f = VERDICTS and io.open(VERDICTS, "r")
if not f then return end
status = {}
status, status_count, ip_count = {}, 0, 0
for line in f:lines() do
local kind, name, proto = line:match("^(%w+)\t([^\t]+)\t([^\t]*)")
if kind then status[name .. " " .. proto] = kind end
if kind then
local key = name .. " " .. proto
if status[key] == nil then
status_count = status_count + 1
if proto == "ip" then ip_count = ip_count + 1 end
end
status[key] = kind
end
end
f:close()
end
reload()
-- A name as a rule can take it: the SNI comes from the wire, raw, and a tab or newline in it
-- would forge lines of its own in the verdicts and lists.
local function plain(name)
return type(name) == "string" and name:match("^[%w%.%-_:]+$") ~= nil
end
local function verdict(kind, name, proto, note)
if not plain(name) then return end
local key = name .. " " .. proto
if not VERDICTS or status[key] == kind then return end
reload()
if status[key] == kind then return end
if status[key] == nil and status_count >= MAX_VERDICT_KEYS then
if not verdicts_full then say("no verdict for " .. name .. ": " .. VERDICTS .. " holds " .. MAX_VERDICT_KEYS .. " names already") end
verdicts_full = true
return
end
if status[key] == nil and proto == "ip" and ip_count >= MAX_IP_VERDICT_KEYS then
if not ip_full then say("no verdict for " .. name .. ": " .. VERDICTS .. " holds " .. MAX_IP_VERDICT_KEYS .. " addresses already") end
ip_full = true
return
end
if status[key] == nil then
status_count = status_count + 1
if proto == "ip" then ip_count = ip_count + 1 end
end
status[key] = kind
local f = io.open(VERDICTS, "a")
if not f then return end
@@ -193,10 +231,67 @@ end
local stalled = {} -- host -> a transfer of it was cut short, within the window
-- A name a site can have: two labels at least, none empty, and not a public suffix (com,
-- co.uk), which would take every site under it.
local function learnable(host)
if not plain(host) or host:find("^%.") or host:find("%.$") or host:find("%.%.") or not host:find("%.") then
return false
end
return not proxy_suite_is_public_suffix(host)
end
-- Learned names, and verdicts' names, past which no new one is taken: a wildcard domain's
-- fresh names would grow the lists without end. Real use stays far below.
local MAX_AUTO_LINES = 20000
local function bounded(t, count)
if count > 4096 then return {}, 1 end
return t, count
end
local learned_count, stalled_count = 0, 0
local auto_full = false
-- The site a name belongs to: the public suffix and one label more (example.co.uk).
local function registrable(host)
local labels = {}
for label in host:gmatch("[^.]+") do labels[#labels + 1] = label end
for i = #labels - 1, 1, -1 do
local candidate = table.concat(labels, ".", i)
if not proxy_suite_is_public_suffix(candidate) then return candidate end
end
return host
end
-- Names of one site past which the site itself is learned instead, so one wildcard domain
-- cannot fill the list.
local MAX_NAMES_PER_SITE = 64
local function learn(host, arg, n)
if not learnable(host) then return end
local site = registrable(host)
if site ~= host and learnable(site) then
local same, tail = 0, "." .. site
for _, line in ipairs(lines(arg.auto)) do
if line:sub(-#tail) == tail then same = same + 1 end
end
if same >= MAX_NAMES_PER_SITE then
say(site .. " has " .. same .. " names learned: learning the site instead of " .. host)
host = site
end
end
if not learned[host] then
learned, learned_count = bounded(learned, learned_count + 1)
end
learned[host] = true
if stalled[host] then verdict("stalls", host, "cutoff", "learned from transfers cut short") end
if covered(host, lines(arg.auto)) then return end
local auto = lines(arg.auto)
if covered(host, auto) then return end
if #auto >= MAX_AUTO_LINES then
if not auto_full then say("not learning " .. host .. ": " .. arg.auto .. " holds " .. MAX_AUTO_LINES .. " names already") end
auto_full = true
return
end
auto_full = false
local f = io.open(arg.auto, "a")
if not f then
say("cannot learn " .. host .. ": " .. arg.auto .. " is not writable")
@@ -227,7 +322,10 @@ local function failure(st, arg, why, stall)
st.counted = true
local host = st.host
if learned[host] or excluded(host, arg) then return end
if stall then stalled[host] = true end
if stall and not stalled[host] then
stalled, stalled_count = bounded(stalled, stalled_count + 1)
stalled[host] = true
end
local n, need = tally(host, tonumber(arg.time) or 300), tonumber(arg.fails) or 3
if arg.log then say(host .. ": " .. why .. " (" .. n .. "/" .. need .. " to learn)") end
if n >= need then learn(host, arg, n) end
@@ -13,10 +13,12 @@ export PATH=@path@
dir=$1
out=$2
# The zapret scope's group writes these: never through a symlink it left (to a file only
# root may read, which would land in the world-readable rule-sets), nor into a FIFO.
lists() {
local f
for f in "$@"; do
[ -r "$f" ] && cat "$f"
[ -r "$f" ] && dd if="$f" iflag=nofollow,nonblock status=none 2>/dev/null
done
true
}
@@ -31,15 +33,28 @@ write() {
}
# nfqws hostlists: one host per line, "#" comments, "^" for the name alone.
hosts='def hosts: split("\n") | map(gsub("^\\s+|\\s+$"; "") | ascii_downcase | ltrimstr("^"))
| map(select(. != "" and (startswith("#") | not)));
# The zapret scope can write them, and an entry sing-box cannot take (999.1.1.1, ::/0,
# fe80::1%eth0) would fail the rule-set and the proxy with it: only an address or a name.
hosts='def octet: "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])";
def ipv4: test("^(" + octet + "\\.){3}" + octet + "$");
def ipv6: test("^[0-9a-f:]+$") and test(":::") == false
and (split("::") | length) <= 2
and (split(":") | map(select(. != "")) | length <= 8 and all(length <= 4))
and (test("::") or (split(":") | length) == 8)
and test("^:[^:]|[^:]:$") == false;
# Two labels at least: a bare "com" would send the whole TLD past the proxy.
def hostname: test("^[a-z0-9_]([a-z0-9_-]*[a-z0-9_])?(\\.[a-z0-9_]([a-z0-9_-]*[a-z0-9_])?)+$")
and test("^[0-9.]+$") == false and length <= 253;
def valid: ipv4 or ipv6 or hostname;
def hosts: split("\n") | map(gsub("^\\s+|\\s+$"; "") | ascii_downcase | ltrimstr("^"))
| map(select(. != "" and (startswith("#") | not) and valid));
def ip: test("^[0-9.]+$|:");
def cidr: map(. + (if test(":") then "/128" else "/32" end));
# A name and a site key cover each other either way round: www.notion.so and notion.so.
def covers($b): . as $a | $a == $b or ($a | endswith("." + $b)) or ($b | endswith("." + $a));
# "kind<TAB>name<TAB>proto<TAB>...", the last per name and proto.
# The zapret scope'"'"'s group can write the file: only names a rule can take.
def verdicts: split("\n") | map(split("\t") | select(length >= 3 and (.[1] | test("^[a-z0-9.-]+$|^[0-9a-f:.]+$"))))
def verdicts: split("\n") | map(split("\t") | select(length >= 3 and (.[1] | test("^[a-z0-9.-]+$|^[0-9a-f:.]+$") and valid)))
| reduce .[] as $v ({}; .[$v[1] + "\t" + $v[2]] = $v[0])
| to_entries | map({name: (.key | split("\t")[0]), proto: (.key | split("\t")[1]), kind: .value});
def named($kind; $proto): map(select(.kind == $kind and .proto == $proto) | .name);'
@@ -44,6 +44,14 @@ local function public_suffix_nld(host, nld)
return key
end
-- For detect.lua (a chunk of its own): whether host is itself a public suffix, or a single
-- label, which no site is.
function proxy_suite_is_public_suffix(host)
local labels = {}
for label in host:lower():gsub("%.$", ""):gmatch("[^.]+") do labels[#labels + 1] = label end
return #labels <= suffix_labels(labels)
end
local standard = standard_hostkey
if type(standard) ~= "function" then
error("proxy-suite: zapret-auto.lua no longer defines standard_hostkey")
+10 -4
View File
@@ -1,7 +1,11 @@
# The ICANN section of the public suffix list, one rule per line, every label in the
# xn-- form a TLS SNI carries ("рф" is "xn--p1ai" on the wire).
# xn-- form a TLS SNI carries ("рф" is "xn--p1ai" on the wire). With --private, the
# PRIVATE section too (workers.dev, github.io): names there belong to unrelated parties.
import sys
with_private = "--private" in sys.argv[1:]
source = next(arg for arg in sys.argv[1:] if arg != "--private")
def ascii_label(label):
return label if label == "*" or label.isascii() else "xn--" + label.encode("punycode").decode()
@@ -14,12 +18,14 @@ def ascii_rule(rule):
inside = False
rules = []
with open(sys.argv[1], encoding="utf-8") as f:
with open(source, encoding="utf-8") as f:
for line in f:
line = line.strip()
if line == "// ===BEGIN ICANN DOMAINS===":
if line == "// ===BEGIN ICANN DOMAINS===" or (with_private and line == "// ===BEGIN PRIVATE DOMAINS==="):
inside = True
elif line == "// ===END ICANN DOMAINS===":
elif line == "// ===END ICANN DOMAINS===" and with_private:
inside = False
elif line in ("// ===END ICANN DOMAINS===", "// ===END PRIVATE DOMAINS==="):
break
elif inside and line and not line.startswith("//"):
rules.append(ascii_rule(line.split()[0]))
+3
View File
@@ -238,6 +238,9 @@ let
[
"# Generated by proxy-suite. Do not edit."
"WS_USER=root"
# /proc/sys is read-only in the units' sandbox: the unit sets autohostlist's
# nf_conntrack_tcp_be_liberal itself, outside it.
"SKIP_CONNTRACK_LIBERAL_MODE=1"
"FWTYPE=nftables"
"INIT_APPLY_FW=1"
"QNUM=${toString qnum}"
+2 -1
View File
@@ -18,7 +18,8 @@ local function name(hrec)
end
local function log(hrec, text)
io.stderr:write("zapret2: ", name(hrec), ": ", text, "\n")
-- The host comes off the wire (a SNI): no control character, so no forged journal line.
io.stderr:write("zapret2: ", (tostring(name(hrec)):gsub("%c", "?")), ": ", (tostring(text):gsub("%c", "?")), "\n")
end
local function of(hrec)