Files
zapret-autotune/managed-target-entrypoint.sh
T
ZeusinaandGPT-6 Bot f88c8e9c45 fix(managed): guard experimental authorization and startup requests
Reject explicit candidate-ID and inherited-policy CLI bypasses of the guarded native-circular operator path. Validate empty private runtime-owned request inodes without following links before state mutation, atomically claim and sync them before apply, retain failed claims, and never delete replacement requests. Keep internal journal reconciliation and legacy qualification unchanged.

Co-authored-by: GPT-6 <gpt-6@openai.com>
2026-10-12 07:14:20 +03:00

269 lines
11 KiB
Bash

#!/bin/sh
set -eu
umask 077
[ "$#" -eq 0 ] || { echo 'error: target entrypoint accepts no arguments' >&2; exit 64; }
# Credentials never enter argv or logs. Docker supplies SS_PASSWORD via env;
# clear the exported value before starting any child processes.
ss_password=${SS_PASSWORD-}
unset SS_PASSWORD
case "$ss_password" in
''|*[!0123456789abcdefABCDEF]*)
echo 'error: target secret must contain only hexadecimal characters' >&2; exit 64 ;;
esac
[ "${#ss_password}" -ge 32 ] || { echo 'error: target secret must be at least 32 hex characters' >&2; exit 64; }
# Validate before creating configs or launching any service. Errors never echo input.
/usr/local/bin/zapret-autotune target-config-check || exit 64
config_dir=/run/zapret-autotune-ss
awk '$2 == "/run/zapret-autotune-ss" && $3 == "tmpfs" { found=1 } END { exit !found }' /proc/mounts || {
echo 'error: target Shadowsocks config directory must be a dedicated tmpfs' >&2; exit 78;
}
chmod 0700 "$config_dir"
cat > "$config_dir/server.json" <<EOF
{"server":"0.0.0.0","server_port":8388,"password":"$ss_password","method":"chacha20-ietf-poly1305","mode":"tcp_and_udp"}
EOF
cat > "$config_dir/local.json" <<EOF
{"server":"127.0.0.1","server_port":8388,"local_address":"0.0.0.0","local_port":1080,"password":"$ss_password","method":"chacha20-ietf-poly1305","mode":"tcp_and_udp"}
EOF
chmod 0600 "$config_dir/server.json" "$config_dir/local.json"
unset ss_password
server_pid=
local_pid=
monitor_pid=
monitor_sid=
zapret_started=0
cooldown_pid=
# Signal only descendants of an owned child, never the container/host namespace.
# The monitor gets TERM itself first so it can join scans and restore bytes;
# descendant signalling is reserved for SS shutdown and forced watchdog cleanup.
. /opt/managed-target-supervision.sh
pause() {
sleep "$1" </dev/null >/dev/null 2>&1 & cooldown_pid=$!
wait "$cooldown_pid"
cooldown_pid=
}
cleanup_session() {
[ -n "$monitor_sid" ] || return 0
# The verified SID survives leader death and Go's separate worker PGIDs.
# Never sweep all namespace children: Docker exec peers/SS/helpers are not
# in this session. Detached sysv daemons are reconciled/stopped separately.
for session_signal in TERM KILL; do
signal_session "$monitor_sid" "$session_signal" || return 78
session_deadline=$(($(date +%s) + 3))
while :; do
signal_session "$monitor_sid" CHECK || return 78
if [ "$session_live" -eq 0 ]; then
monitor_sid=
return 0
fi
[ "$(date +%s)" -lt "$session_deadline" ] || break
pause 1
done
done
echo 'error: owned monitor session survived cleanup' >&2
return 78
}
capture_monitor_session() {
[ -z "$monitor_sid" ] || return 0
if [ -e "$config_dir/monitor-ready" ]; then
read -r candidate_sid < "$config_dir/monitor-ready" || return 78
case "$candidate_sid" in ''|*[!0-9]*) return 78 ;; esac
[ "$candidate_sid" = "$monitor_pid" ] && [ "$candidate_sid" -gt 1 ] && [ "$candidate_sid" != "$$" ] || return 78
monitor_sid=$candidate_sid
elif proc_identity "$monitor_pid" && [ "$proc_sid" = "$monitor_pid" ] && [ "$proc_sid" -gt 1 ]; then
monitor_sid=$proc_sid
fi
}
# Wait with a watchdog: never let an unresponsive child exceed Docker's grace.
bounded_wait() {
child=$1
seconds=$2
rm -f "$config_dir/join-timeout" "$config_dir/join-ready"
# Fresh interpreter: a forked shell can inherit a deferred EXIT/TERM trap
# context and never run its cancellation handler during PID 1 shutdown.
/bin/sh /opt/managed-target-supervision.sh --watchdog "$child" "$seconds" "$config_dir" </dev/null >/dev/null 2>&1 &
watchdog=$!
# A fast-exiting child must not cancel the watchdog before its trap exists.
# Fail closed if exec/setup fails before acknowledgement; never wait forever.
ack_deadline=$(($(date +%s) + 5))
while [ ! -e "$config_dir/join-ready" ]; do
if ! kill -0 "$watchdog" 2>/dev/null || [ "$(date +%s)" -ge "$ack_deadline" ]; then
: > "$config_dir/join-timeout"
signal_tree "$watchdog" KILL
signal_tree "$child" KILL
break
fi
done
waited_code=0
wait "$child" 2>/dev/null || waited_code=$?
kill -TERM "$watchdog" 2>/dev/null || true
wait "$watchdog" 2>/dev/null || true
join_timed_out=0
[ ! -e "$config_dir/join-timeout" ] || join_timed_out=1
}
cleanup_cycle() {
cleanup_code=0
# Let the monitor cancel/join scans and restore committed bytes BEFORE stop.
if [ -n "$monitor_pid" ]; then
capture_monitor_session || cleanup_code=78
kill -TERM "$monitor_pid" 2>/dev/null || true
bounded_wait "$monitor_pid" 45
# Cancellation must restore safely even when SS failure requested retry.
case "$waited_code" in 0|143) ;; *) echo "error: monitor cleanup status $waited_code" >&2; cleanup_code=78 ;; esac
[ "$join_timed_out" -eq 0 ] || { echo 'error: monitor join timeout' >&2; cleanup_code=78; }
# SIGTERM may have arrived before the launch acknowledgement was read.
capture_monitor_session || cleanup_code=78
monitor_pid=
fi
# Join/sweep scans even if the monitor was already reaped after SIGKILL.
# A failed sweep vetoes reconciliation and all daemon script sourcing.
if ! cleanup_session; then
cleanup_code=78
zapret_started=0
fi
# Dedicated PID/network namespace: no host/other-target stop.
if [ "$zapret_started" -eq 1 ]; then
# Stop also sources config: clear trust before reconciliation, never
# source unknown bytes left by a crashed monitor, even for shutdown.
zapret_started=0
if timeout -k 5 45 /usr/local/bin/zapret-autotune managed reconcile; then
timeout -k 5 30 /opt/zapret2/init.d/sysv/zapret2 stop || cleanup_code=78
else
cleanup_code=78
fi
fi
for pid in "$local_pid" "$server_pid"; do
[ -z "$pid" ] || signal_tree "$pid" TERM
done
for pid in "$local_pid" "$server_pid"; do
if [ -n "$pid" ]; then
bounded_wait "$pid" 5
# Its original failure triggered supervision; only forced shutdown
# is a cleanup failure, not the already-dead Shadowsocks status.
[ "$join_timed_out" -eq 0 ] || { echo 'error: Shadowsocks join timeout' >&2; cleanup_code=78; }
fi
done
server_pid=
local_pid=
return "$cleanup_code"
}
cleanup() {
final_code=$?
trap - EXIT
# A caught (not ignored) signal lets watchdog children install TERM traps.
trap ':' INT TERM
if [ -n "$cooldown_pid" ]; then
kill "$cooldown_pid" 2>/dev/null || true
wait "$cooldown_pid" 2>/dev/null || true
fi
cleanup_cycle || final_code=78
exit "$final_code"
}
trap cleanup EXIT
trap 'exit 0' INT TERM
# Never invoke /opt/entrypoint.sh: zapret must start AFTER reconciliation.
run_cycle() {
set -- ss-server -c "$config_dir/server.json"
# DNS is not a secret. Native -d avoids assuming support for a JSON DNS key.
[ -z "${SS_DNS_SERVER-}" ] || set -- "$@" -d "$SS_DNS_SERVER"
"$@" &
server_pid=$!
ss-local -c "$config_dir/local.json" &
local_pid=$!
# Bounded readiness, no network probe. Managed commands verify socket ownership.
attempt=0
until awk '$2 == "00000000:0438" && $4 == "0A" { found=1 } END { exit !found }' /proc/net/tcp; do
{ kill -0 "$server_pid" && kill -0 "$local_pid"; } || return 75
attempt=$((attempt + 1))
[ "$attempt" -lt 30 ] || { echo 'error: target SOCKS listener timeout' >&2; return 75; }
pause 1
done
# Reject unsafe operator requests before init/reconcile can mutate owned state.
timeout -k 5 45 /usr/local/bin/zapret-autotune managed experimental-request-check || exit 78
if [ ! -e "$ZAPRET_CONFIG" ]; then
timeout -k 5 45 /usr/local/bin/zapret-autotune managed init || exit 78
fi
# Never activate pending or unknown bytes. Any reconciliation failure is fatal,
# not a transient (75) restart request. Reload restores known bytes first.
timeout -k 5 45 /usr/local/bin/zapret-autotune managed reconcile || exit 78
zapret_started=1
timeout -k 5 30 /opt/zapret2/init.d/sysv/zapret2 start || exit 78
# Private operator request, consumed only after a successful guarded transaction.
# Never suppress qualification gates globally or race the owned monitor.
if [ -e "${ZAPRET_CONFIG%/*}/.autotune-experimental-suffix-request" ] || [ -L "${ZAPRET_CONFIG%/*}/.autotune-experimental-suffix-request" ]; then
timeout -k 5 120 /usr/local/bin/zapret-autotune managed apply --googlevideo-experiment native-circular --googlevideo-scope experimental_googlevideo_suffix --googlevideo-request startup || exit 78
fi
# A replacement SS child can fail during reconciliation/activation. Do not
# fork a monitor we already need to cancel: an early TERM can race interpreter
# startup before its cancellation handler exists. Clean this cycle directly.
{ kill -0 "$server_pid" 2>/dev/null && kill -0 "$local_pid" 2>/dev/null; } || return 75
rm -f "$config_dir/monitor-ready"
setsid /bin/sh /opt/managed-target-supervision.sh --monitor "$config_dir" /usr/local/bin/zapret-autotune managed monitor &
monitor_pid=$!
monitor_ack_deadline=$(($(date +%s) + 5))
while [ ! -e "$config_dir/monitor-ready" ]; do
if ! kill -0 "$monitor_pid" 2>/dev/null || [ "$(date +%s)" -ge "$monitor_ack_deadline" ]; then
signal_tree "$monitor_pid" KILL
exit 78
fi
done
capture_monitor_session || exit 78
if proc_identity "$monitor_pid" && [ "$proc_sid" != "$monitor_sid" ]; then
monitor_sid=
exit 78
fi
while kill -0 "$server_pid" && kill -0 "$local_pid" && kill -0 "$monitor_pid"; do
pause 1
done
if ! kill -0 "$monitor_pid" 2>/dev/null; then
code=0
wait "$monitor_pid" || code=$?
monitor_pid=
echo 'error: target managed monitor exited' >&2
case "$code" in
0|2|137|139) code=75 ;;
64|75|78) ;;
*) code=78 ;;
esac
return "$code"
fi
echo 'error: target child process exited' >&2
return 75
}
# Three starts per rolling six hours, including initial startup. PID 1 owns
# the entire runtime cycle; cooldown is cancellable without any external manager.
starts=
backoff=15
while :; do
now=$(date +%s)
recent=
count=0
for started in $starts; do
if [ "$((now - started))" -lt 21600 ]; then
recent="$recent $started"
count=$((count + 1))
fi
done
[ "$count" -lt 3 ] || { echo 'error: target restart budget exhausted' >&2; exit 78; }
starts="$recent $now"
code=0
run_cycle || code=$?
cleanup_cycle || code=78
[ "$code" -eq 75 ] || exit "$code"
# A long-running monitor may outlive the window; recheck at failure time.
now=$(date +%s)
retry_count=0
for started in $starts; do
[ "$((now - started))" -ge 21600 ] || retry_count=$((retry_count + 1))
done
[ "$retry_count" -lt 3 ] || { echo 'error: target restart budget exhausted' >&2; exit 78; }
pause "$backoff"
[ "$backoff" -ge 60 ] || backoff=$((backoff * 2))
done