feat: add configurable PID1-owned DoH forwarding

Default managed SOCKS hostname DNS to verified HTTPS with literal-IP bootstrap and no plaintext fallback. Supervise the loopback forwarder with private anchored readiness and preserve foreign markers. Include configuration, deployment, documentation and offline checks.

Co-authored-by: GPT-6 <gpt-6@openai.com>
This commit is contained in:
ZeusinaandGPT-6 Bot committed 2026-10-13 14:32:58 +03:00
1 parent ea886e5bc8
commit 367d956ae3
20 files changed
+2383 -37

No files matched your search

+140 -6
View File
@@ -4,6 +4,7 @@ Only a temporary COPY of the entrypoint is redirected to fake executables;
production has no test switches, real network probes, or accelerated timers.
"""
import ctypes
import atexit
import os
from pathlib import Path
import shutil
@@ -13,6 +14,15 @@ import time
ROOT = Path(__file__).resolve().parents[2]
# Real readiness CLI checks root ownership. Use an isolated user namespace for
# offline fixtures when invoked as an ordinary user; no host-root requirement.
if os.geteuid() != 0:
os.execvp('unshare', ['unshare', '-Ur', 'python3', str(Path(__file__).resolve())])
CLI_TMP = tempfile.TemporaryDirectory(prefix='dns-readiness-cli-')
atexit.register(CLI_TMP.cleanup)
DNS_CLI = Path(CLI_TMP.name) / 'autotune'
subprocess.run(['go', 'build', '-o', str(DNS_CLI), './cmd/zapret-autotune'],
cwd=ROOT, env=dict(os.environ, GOPROXY='off', GOTOOLCHAIN='local'), check=True)
FAKE = r'''#!/usr/bin/env python3
import ctypes, os, pathlib, signal, subprocess, sys, time
root = pathlib.Path(os.environ['FIXTURE'])
@@ -27,7 +37,11 @@ def increment(key):
path.write_text(str(n))
return n
def linger(code=0):
signal.signal(signal.SIGTERM, lambda *_: sys.exit(code))
def stop(*_):
if os.environ.get('ZAPRET_AUTOTUNE_DNS_MODE', 'doh') == 'doh' and scenario not in ('dns-death', 'dns-killed', 'dns-replace', 'dns-replace-symlink', 'dns-prestart'):
os.kill(int((root / 'dns-pid').read_text()), 0)
sys.exit(code)
signal.signal(signal.SIGTERM, stop)
while True:
time.sleep(.01)
def assert_workers_gone():
@@ -74,8 +88,12 @@ if name in ('ss-server', 'ss-local'):
f.write(str(os.getpid()) + '\n')
assert 'SS_PASSWORD' not in os.environ
assert sys.argv[1] == '-c'
dns = os.environ.get('SS_DNS_SERVER', '') if name == 'ss-server' else ''
dns = ('127.0.0.1:5353' if os.environ.get('ZAPRET_AUTOTUNE_DNS_MODE', 'doh') == 'doh'
else os.environ.get('SS_DNS_SERVER', '')) if name == 'ss-server' else ''
assert sys.argv[3:] == (['-d', dns] if dns else [])
if dns == '127.0.0.1:5353':
assert (root / 'private' / 'dns-ready').read_text().strip() == (root / 'dns-pid').read_text()
os.kill(int((root / 'dns-pid').read_text()), 0)
assert (pathlib.Path(sys.argv[2]).stat().st_mode & 0o777) == 0o600
log(name)
if name == 'ss-local' and scenario in ('ss', 'mixed', 'joinfail') and increment('ss_runs') == 1:
@@ -96,6 +114,71 @@ if name == 'zapret2':
assert name == 'autotune'
if sys.argv[1:] == ['target-config-check']:
sys.exit(0)
if sys.argv[1] == 'dns-forwarder':
if sys.argv[2] in ('readiness-check', 'readiness-cleanup'):
# exec preserves PID1's actual inherited anchors; no simulated unlink.
os.execv(os.environ['DNS_CLI'], [os.environ['DNS_CLI'], *sys.argv[1:]])
mode = os.environ.get('ZAPRET_AUTOTUNE_DNS_MODE', 'doh')
if sys.argv[2] == 'mode':
print(mode)
sys.exit(0)
if sys.argv[2] == 'address':
print('127.0.0.1:5353' if mode == 'doh' else os.environ.get('SS_DNS_SERVER', ''))
sys.exit(0)
assert sys.argv[2:] == ['serve'] and mode == 'doh'
assert 'SS_PASSWORD' not in os.environ
with (root / 'children').open('a') as f:
f.write(str(os.getpid()) + '\n')
(root / 'dns-pid').write_text(str(os.getpid()))
log('dns-start')
if scenario == 'dns-early':
sys.exit(1)
ready = root / 'private' / 'dns-ready'
owned = None
if scenario == 'dns-preack-foreign':
ready.write_text('foreign evidence\n')
sys.exit(1)
if scenario not in ('dns-noack', 'dns-term', 'dns-int'):
with ready.open('x') as f:
os.chmod(ready, 0o600)
f.write(str(os.getpid() + (1 if scenario == 'dns-wrongack' else 0)) + '\n')
owned = ready.stat()
if scenario == 'dns-permissions':
ready.chmod(0o644)
if scenario == 'dns-symlink':
payload = ready.with_name('dns-payload')
ready.rename(payload)
ready.symlink_to(payload)
log('dns-ready')
def stop_dns(*_):
assert not (root / 'prepared').exists(), 'DNS stopped before restoration'
# SS children have been joined, not merely signalled.
for pid in (root / 'children').read_text().splitlines():
if int(pid) != os.getpid():
assert not pathlib.Path('/proc/' + pid).exists(), ('DNS stopped before child join', pid)
log('dns-stop')
if ready.exists() and not ready.is_symlink() and owned and os.path.samestat(owned, ready.stat()):
ready.unlink()
sys.exit(0)
signal.signal(signal.SIGTERM, stop_dns)
if scenario in ('dns-term', 'dns-int'):
os.kill(os.getppid(), signal.SIGTERM if scenario == 'dns-term' else signal.SIGINT)
if scenario in ('dns-death', 'dns-killed', 'dns-replace', 'dns-replace-symlink') and increment('dns_runs') == 1:
while not (root / 'monitor_runs').exists():
time.sleep(.01)
if scenario.startswith('dns-replace'):
# Retain old inode so a replacement cannot reuse its number.
ready.rename(ready.with_name('retired-ready'))
payload = ready.with_name('foreign-ready')
payload.write_text('foreign evidence\n')
payload.chmod(0o600)
if scenario == 'dns-replace-symlink':
ready.symlink_to(payload)
else:
payload.rename(ready)
os.kill(os.getpid(), signal.SIGKILL)
while True:
time.sleep(.01)
command = sys.argv[2]
if command == 'init':
log('init')
@@ -107,6 +190,9 @@ elif command == 'reconcile':
assert_workers_gone()
if scenario == 'prestartfail':
sys.exit(78)
if scenario == 'dns-prestart':
os.kill(int((root / 'dns-pid').read_text()), signal.SIGKILL)
time.sleep(.03)
if scenario in ('unknown', 'unknown75') and n == 2:
sys.exit(78)
(root / 'prepared').unlink(missing_ok=True)
@@ -116,6 +202,11 @@ elif command == 'monitor':
n = increment('monitor_runs')
log('monitor ' + str(n))
assert os.getsid(0) == os.getpid(), 'monitor not in its own verified session'
if scenario in ('dns-death', 'dns-killed', 'dns-replace', 'dns-replace-symlink') and n == 1:
linger()
if scenario == 'dns-outage':
# Upstream SERVFAIL is modelled by a live DNS child, not child failure.
assert (root / 'dns-pid').exists()
if n == 1 and scenario == 'orphans':
subprocess.Popen([str(root / 'bin' / 'blockcheck')], preexec_fn=os.setpgrp)
while not (root / 'workers').exists() or len((root / 'workers').read_text().splitlines()) != 2:
@@ -144,7 +235,7 @@ elif command == 'monitor':
'''
def run(scenario, expected, dns=''):
def run(scenario, expected, dns='', mode='native'):
with tempfile.TemporaryDirectory(prefix='supervision-') as tmp:
root = Path(tmp)
binary = root / 'bin'
@@ -156,6 +247,11 @@ def run(scenario, expected, dns=''):
(binary / name).symlink_to(fake)
configs = root / 'private'
configs.mkdir()
if scenario.startswith('dns-stale'):
if scenario == 'dns-stale-symlink':
(configs / 'dns-ready').symlink_to(configs / 'missing')
else:
(configs / 'dns-ready').write_text('foreign evidence\n')
text = (ROOT / 'managed-target-entrypoint.sh').read_text()
helper = ROOT / 'managed-target-supervision.sh'
if scenario == 'ackfail':
@@ -170,7 +266,11 @@ def run(scenario, expected, dns=''):
entry.write_text(text)
env = dict(os.environ, PATH=f'{binary}:{os.environ["PATH"]}', FIXTURE=tmp,
SCENARIO=scenario, SS_PASSWORD='ab' * 32, SS_DNS_SERVER=dns,
ZAPRET_CONFIG=str(root / 'config'))
ZAPRET_CONFIG=str(root / 'config'), DNS_CLI=str(DNS_CLI))
if mode is None:
env.pop('ZAPRET_AUTOTUNE_DNS_MODE', None)
else:
env['ZAPRET_AUTOTUNE_DNS_MODE'] = mode
peer = None
if scenario == 'orphans':
# Local fixture is not PID 1. Adopt orphan workers here so the test
@@ -186,10 +286,10 @@ def run(scenario, expected, dns=''):
if peer:
peer.terminate()
peer.wait(timeout=2)
events = (root / 'events').read_text().splitlines()
events = (root / 'events').read_text().splitlines() if (root / 'events').exists() else []
assert result.returncode == expected, (scenario, result.returncode, result.stderr, events)
assert b'ab' * 32 not in result.stdout + result.stderr
for pid in (root / 'children').read_text().splitlines():
for pid in ((root / 'children').read_text().splitlines() if (root / 'children').exists() else []):
assert not Path(f'/proc/{pid}').exists(), (scenario, 'child not joined', pid)
if scenario == 'orphans':
for pid in (root / 'workers').read_text().splitlines():
@@ -205,6 +305,16 @@ def run(scenario, expected, dns=''):
for i, event in enumerate(events):
if event in ('start', 'stop'):
assert events[i - 1] == 'reconcile', (scenario, events)
foreign = scenario in ('dns-symlink', 'dns-preack-foreign', 'dns-replace', 'dns-replace-symlink', 'dns-stale', 'dns-stale-symlink')
if foreign:
ready = configs / 'dns-ready'
assert ready.exists() or ready.is_symlink(), (scenario, 'foreign readiness deleted')
if scenario != 'dns-stale-symlink' and scenario != 'dns-symlink':
assert ready.read_text() == 'foreign evidence\n', (scenario, 'foreign bytes changed')
else:
assert not (configs / 'dns-ready').exists(), (scenario, 'stale DNS readiness')
if mode == 'native':
assert 'dns-start' not in events
return events
@@ -233,6 +343,30 @@ for dns in ('8.8.8.8', '2001:4860:4860::8888'):
events = run('fatal64', 64, dns)
assert events.count('ss-server') == 1 and events.count('ss-local') == 1
for scenario in ('dns-outage', 'technical', 'ss', 'cancel', 'dns-death', 'dns-killed'):
events = run(scenario, 0, dns='8.8.8.8', mode=None)
assert events.index('dns-ready') < events.index('ss-server')
assert events.index('dns-ready') < events.index('ss-local')
if scenario not in ('dns-death', 'dns-killed'):
assert events.count('dns-start') == events.count('dns-stop')
assert events.index('stop') < events.index('dns-stop')
if scenario == 'dns-outage':
assert events.count('start') == 1 and 'cooldown 15' not in events
for scenario, code in (('dns-early', 78), ('dns-noack', 78), ('dns-wrongack', 78),
('dns-permissions', 78), ('dns-symlink', 78), ('dns-prestart', 78)):
events = run(scenario, code, mode='doh')
assert not any(e.startswith('monitor ') for e in events)
if scenario != 'dns-prestart':
assert 'ss-server' not in events and 'ss-local' not in events
for scenario in ('dns-stale', 'dns-stale-symlink', 'dns-preack-foreign', 'dns-replace', 'dns-replace-symlink'):
events = run(scenario, 78, mode='doh')
assert events.count('dns-start') <= 1 and 'cooldown 15' not in events
if scenario.startswith('dns-stale'):
assert not events
for scenario in ('dns-term', 'dns-int'):
events = run(scenario, 0, mode='doh')
assert events == ['dns-start', 'dns-stop'], events
def check_watchdog_traps(shell):
"""Same bounded_wait from normal flow, plain EXIT, and TERM -> EXIT traps."""