From b8dd07fb8315cbe8931f2b2b05ba124b9a54fb2c Mon Sep 17 00:00:00 2001 From: Ap3x0 <82464229+Ap3x0s@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:27:36 +0300 Subject: [PATCH 01/13] =?UTF-8?q?fix(security):=20=D1=82=D0=BE=D0=BA=D0=B5?= =?UTF-8?q?=D0=BD=20=D0=B1=D0=BE=D1=82=D0=B0=20=D0=B8=20sub=5Ftoken=20?= =?UTF-8?q?=D0=BD=D0=B5=20=D0=BF=D0=BE=D0=BF=D0=B0=D0=B4=D0=B0=D1=8E=D1=82?= =?UTF-8?q?=20=D0=B2=20=D0=B0=D1=80=D0=B3=D1=83=D0=BC=D0=B5=D0=BD=D1=82?= =?UTF-8?q?=D1=8B=20curl?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Подтверждённое замечание ревью: /proc//cmdline читается любым пользователем хоста (права 0444), поэтому URL вида `https://api.telegram.org/bot/sendMessage` в argv процесса curl отдавал токен бота всем локальным пользователям — в том числе непривилегированному пользователю `xray`, под которым работает сам Xray. Утечка была не разовой: `xrayebator-monitor.timer` дёргает monitor-check каждые 15 минут, и на каждом тике (а также на каждой отправке алерта) в /proc жил процесс с токеном в командной строке. Тот же класс — sub_token подписки в `_monitor_sub_probe` (проверка живости подписки в мониторинге) и в `_subscription_local_self_test` (self-test quickstart/happ-setup). Фикс: общий помощник `_curl_secret_url` отдаёт URL curl'у через stdin-конфиг (`-K -`), а не аргументом; остальные опции остаются в argv. Секрет по-прежнему никуда не пишется на диск: он живёт в pipe между printf и curl. Путь через /proc//environ закрыт сам по себе — environ доступен только владельцу процесса и root, а argv нет. Не затронуто: логика запросов, коды возврата и формат ответов — меняется только способ передачи адреса. --- xrayebator | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/xrayebator b/xrayebator index 79a4c48..907db36 100755 --- a/xrayebator +++ b/xrayebator @@ -83,6 +83,22 @@ QS_VHOST_BACKUP="$NGINX_SITES_AVAILABLE/xrayebator-sub.xrayebator.bak" QS_DEFAULT_REMOVED=false QS_DEFAULT_BACKUP_CREATED=false +# --- Секреты и /proc ------------------------------------------------------- +# /proc//cmdline читается ЛЮБЫМ пользователем хоста (права 0444), а +# /proc//environ — только владельцем процесса и root (0400). Поэтому всё, что +# является секретом (токен бота, DNS-токен, sub_token, ключи бэкендов), передаётся +# не аргументом, а потоком: argv `curl` с токеном в URL видел бы, например, +# непривилегированный пользователь `xray`, под которым работает сам Xray. +# `curl -K -` читает конфиг из stdin; строка `url = "…"` кладёт адрес туда же, +# где он и был нужен, не оставляя его в командной строке. +_curl_secret_url() { + local url="$1"; shift + # Конфиг-парсер curl: экранируются обратный слэш и двойная кавычка. + url="${url//\\/\\\\}" + url="${url//\"/\\\"}" + printf 'url = "%s"\n' "$url" | curl "$@" -K - +} + _qs_backup_path() { local source_path="$1" backup_path="$2" [[ -e "$source_path" || -L "$source_path" ]] || return 1 @@ -9112,8 +9128,8 @@ _subscription_local_self_test() { } local http_status curl_rc=0 - http_status=$(curl -sS --connect-timeout 2 --max-time 30 \ - "http://127.0.0.1:8080/sub/${token}" \ + http_status=$(_curl_secret_url "http://127.0.0.1:8080/sub/${token}" \ + -sS --connect-timeout 2 --max-time 30 \ -o "$body_tmp" -w '%{http_code}' 2>"$err_tmp") || curl_rc=$? SUBSCRIPTION_SELFTEST_HTTP_STATUS="$http_status" SUBSCRIPTION_SELFTEST_ERROR=$(head -c 240 "$err_tmp" 2>/dev/null | tr '\n\r' ' ') @@ -17311,8 +17327,8 @@ _monitor_sub_probe() { local token="$1" body code MONITOR_SUB_CODE="000" body=$(mktemp) || return 1 - code=$(curl -sS --connect-timeout 3 --max-time 15 -o "$body" -w '%{http_code}' \ - "$(_monitor_sub_local_base)/sub/${token}" 2>/dev/null) || code="000" + code=$(_curl_secret_url "$(_monitor_sub_local_base)/sub/${token}" \ + -sS --connect-timeout 3 --max-time 15 -o "$body" -w '%{http_code}' 2>/dev/null) || code="000" MONITOR_SUB_CODE="${code:-000}" if [[ "$MONITOR_SUB_CODE" == "200" ]] && grep -qE '(vless|hysteria2)://' "$body" 2>/dev/null; then rm -f "$body" @@ -17342,8 +17358,8 @@ _monitor_sni_state_write() { # Отправка произвольного сообщения с явными токеном/чатом (setup-проверка). _telegram_send_raw() { local token="$1" chat="$2" text="$3" resp - resp=$(curl -sS --max-time 20 -X POST \ - "$TELEGRAM_API_BASE/bot$token/sendMessage" \ + resp=$(_curl_secret_url "$TELEGRAM_API_BASE/bot$token/sendMessage" \ + -sS --max-time 20 -X POST \ --data-urlencode "chat_id=$chat" \ --data-urlencode "text=$text" \ --data-urlencode "disable_web_page_preview=true" 2>/dev/null) || return 1 @@ -17362,7 +17378,7 @@ _telegram_send() { # Валидация токена через getMe: печатает username бота; 1 — токен/сеть не приняты. _telegram_get_me() { local token="$1" resp - resp=$(curl -sS --max-time 20 "$TELEGRAM_API_BASE/bot$token/getMe" 2>/dev/null) || return 1 + resp=$(_curl_secret_url "$TELEGRAM_API_BASE/bot$token/getMe" -sS --max-time 20 2>/dev/null) || return 1 [[ "$(jq -r '.ok // false' <<<"$resp" 2>/dev/null)" == "true" ]] || return 1 jq -r '.result.username // "bot"' <<<"$resp" } From c0efc4fcb7658acdc863e36b5a7c44d4b782122b Mon Sep 17 00:00:00 2001 From: Ap3x0 <82464229+Ap3x0s@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:32:13 +0300 Subject: [PATCH 02/13] =?UTF-8?q?feat(security):=20--secret-file/--secret-?= =?UTF-8?q?stdin=20=D0=B2=D0=BC=D0=B5=D1=81=D1=82=D0=BE=20=D1=81=D0=B5?= =?UTF-8?q?=D0=BA=D1=80=D0=B5=D1=82=D0=B0=20=D0=B2=20=D0=B0=D1=80=D0=B3?= =?UTF-8?q?=D1=83=D0=BC=D0=B5=D0=BD=D1=82=D0=B0=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Замечание ревью про «DNS-ключи в аргументах процессов» верно ровно наполовину: certbot их не получает (Cloudflare — ini-файл, Route53 — AWS_SHARED_CREDENTIALS_FILE, оба 0600), но сама `xrayebator dns01-setup --token T` держит токен в собственной командной строке всё время выпуска сертификата: ожидание DNS-распространения 30 с плюс работа certbot. Это же касается `dns01-test`, `repair-dns01`, `quickstart --dns01-token` и `alerts-setup --token` (там окно короче — getMe и тестовое сообщение, — но токен бота утекал ещё и из curl в argv, см. предыдущий коммит). Добавлен безопасный способ передать креды: * `--secret-stdin` — читает пейлоад из stdin (для скриптов и GUI через SSH); * `--secret-file PATH` — читает файл 0600 и удаляет его сразу после чтения; * у quickstart те же опции с префиксом: `--dns01-secret-stdin/--dns01-secret-file`. Формат пейлоада: строки `token=…` / `aws_access_key_id=…` / `aws_secret_access_key=…`; одиночная строка без «=» считается токеном. Пустые переменные заполняются из пейлоада, явный флаг остаётся сильнее — обратная совместимость сохранена: старые вызовы работают, но `--token` и `--aws-secret-access-key` теперь печатают в stderr предупреждение о видимости в /proc (stdout-JSON не меняется). Файл с правами шире 0600 отвергается: иначе фикс обходится одним chmod. Проверка режима отключена на MSYS/MinGW (Git Bash отдаёт фиктивные 644) — на Linux она обязательна; это отмечено в коде, чтобы локальный прогон тестов не выглядел поломкой. --- xrayebator | 151 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 140 insertions(+), 11 deletions(-) diff --git a/xrayebator b/xrayebator index 907db36..5fb8552 100755 --- a/xrayebator +++ b/xrayebator @@ -99,6 +99,87 @@ _curl_secret_url() { printf 'url = "%s"\n' "$url" | curl "$@" -K - } +# Секрет, который нужен самой команде (DNS-токен, ключи AWS, токен бота), тоже не +# идёт в argv: `xrayebator dns01-setup --token T` живёт в /proc все 30+ секунд +# ожидания DNS-распространения, пока certbot выпускает сертификат. Вместо аргумента +# креды читаются из stdin (`--secret-stdin`) или из файла 0600 (`--secret-file`), +# который удаляется сразу после чтения. +# +# Формат пейлоада — строки «key=value»: token=…, aws_access_key_id=…, +# aws_secret_access_key=…; одиночная строка без «=» считается токеном. +SECRET_ERROR="" +# Чистая часть: раскладывает пейлоад по переменным вызывающего (имена строками). +# Заполняются только ПУСТЫЕ переменные — явный флаг сильнее файла. Возврат 1 — +# в пейлоаде нет ни одного известного ключа. +_secret_payload_apply() { + local payload="$1" tvar="${2:-}" kvar="${3:-}" svar="${4:-}" line k v got=1 + while IFS= read -r line; do + line="${line%$'\r'}" + [[ -z "$line" || "$line" == \#* ]] && continue + if [[ "$line" == *=* ]]; then + k="${line%%=*}"; v="${line#*=}" + k="${k,,}"; k="${k//[[:space:]]/}"; k="${k//-/_}" + else + k="token"; v="$line" + fi + case "$k" in + token|api_token|dns_cloudflare_api_token|bot_token|telegram_bot_token) + got=0 + if [[ -n "$tvar" && -z "${!tvar}" ]]; then printf -v "$tvar" '%s' "$v"; fi ;; + aws_access_key_id|access_key_id) + got=0 + if [[ -n "$kvar" && -z "${!kvar}" ]]; then printf -v "$kvar" '%s' "$v"; fi ;; + aws_secret_access_key|secret_access_key) + got=0 + if [[ -n "$svar" && -z "${!svar}" ]]; then printf -v "$svar" '%s' "$v"; fi ;; + esac + done <<< "$payload" + return $got +} + +# Читает источник секрета и раскладывает его по переменным вызывающего. +# Печатает JSON-ошибку и возвращает 1, если источник задан, но не разобран; +# 0 — источника не было или он применён (пустой src — no-op). +_secret_source_apply() { # + local src="" tvar="${2:-}" kvar="${3:-}" svar="${4:-}" payload="" mode="" + src="${1:-}" + [[ -n "$src" ]] || return 0 + if [[ "$src" == "-" ]]; then + payload=$(cat) + else + if [[ ! -f "$src" || ! -r "$src" ]]; then + printf '{"ok":false,"error":"Секрет-файл не найден или не читается: %s"}\n' "$src" + return 1 + fi + # Файл секрета не должен быть доступен группе/другим: иначе фикс бессмысленен. + # MSYS/MinGW (Git Bash на рабочей машине) отдают фиктивные права — всегда 644, + # поэтому там проверка режима бессмысленна; на Linux она обязательна. + if [[ "${OSTYPE:-}" != msys* && "${OSTYPE:-}" != cygwin* ]]; then + mode=$(stat -c '%a' -- "$src" 2>/dev/null || true) + if [[ -n "$mode" ]] && (( 8#$mode & 8#077 )); then + printf '{"ok":false,"error":"Секрет-файл доступен другим пользователям (нужен chmod 600): %s"}\n' "$src" + return 1 + fi + fi + payload=$(cat -- "$src") || payload="" + rm -f -- "$src" 2>/dev/null || true + fi + if [[ -z "$payload" ]]; then + printf '{"ok":false,"error":"Пустой источник секрета: %s"}\n' "$src" + return 1 + fi + if ! _secret_payload_apply "$payload" "$tvar" "$kvar" "$svar"; then + printf '{"ok":false,"error":"Секрет не распознан: ожидаются строки token=… / aws_access_key_id=… / aws_secret_access_key=…"}\n' + return 1 + fi + return 0 +} + +# Предупреждение оператору: креды, переданные аргументом, видны в /proc. +_secret_argv_warning() { + echo "внимание: секрет передан аргументом и виден в /proc//cmdline любому пользователю хоста; используйте --secret-stdin/--secret-file" >&2 +} + _qs_backup_path() { local source_path="$1" backup_path="$2" [[ -e "$source_path" || -L "$source_path" ]] || return 1 @@ -10087,22 +10168,31 @@ dns01_setup_command() { export XRAYEBATOR_NONINTERACTIVE=1 local domain="" provider="" email="" token="" aws_key="" aws_secret="" port="" without_email=false - local staging_flag=false + local staging_flag=false secret_src="" secret_argv=false while [[ $# -gt 0 ]]; do case "$1" in --domain) domain="${2:-}"; shift 2 ;; --provider) provider="${2:-}"; shift 2 ;; --email) email="${2:-}"; shift 2 ;; --without-email) without_email=true; shift ;; - --token) token="${2:-}"; shift 2 ;; + --token) token="${2:-}"; secret_argv=true; shift 2 ;; --aws-access-key-id) aws_key="${2:-}"; shift 2 ;; - --aws-secret-access-key) aws_secret="${2:-}"; shift 2 ;; + --aws-secret-access-key) aws_secret="${2:-}"; secret_argv=true; shift 2 ;; + --secret-file) secret_src="${2:-}"; shift 2 ;; + --secret-stdin) secret_src="-"; shift ;; --port) port="${2:-}"; shift 2 ;; --staging) staging_flag=true; shift ;; *) shift ;; esac done + if ! _secret_source_apply "$secret_src" token aws_key aws_secret; then + return 1 + fi + if [[ "$secret_argv" == "true" ]]; then + _secret_argv_warning + fi + if ! _dns01_validate_domain "$domain"; then echo '{"ok":false,"error":"Укажите --domain example.com (A/AAAA домена должна указывать на этот VPS)"}' return 1 @@ -10225,14 +10315,16 @@ repair_dns01_command() { export XRAYEBATOR_NONINTERACTIVE=1 local domain="" provider="" token="" aws_key="" aws_secret="" port="" email="" - local staging_flag=false + local staging_flag=false secret_src="" secret_argv=false while [[ $# -gt 0 ]]; do case "$1" in --domain) domain="${2:-}"; shift 2 ;; --provider) provider="${2:-}"; shift 2 ;; - --token) token="${2:-}"; shift 2 ;; + --token) token="${2:-}"; secret_argv=true; shift 2 ;; --aws-access-key-id) aws_key="${2:-}"; shift 2 ;; - --aws-secret-access-key) aws_secret="${2:-}"; shift 2 ;; + --aws-secret-access-key) aws_secret="${2:-}"; secret_argv=true; shift 2 ;; + --secret-file) secret_src="${2:-}"; shift 2 ;; + --secret-stdin) secret_src="-"; shift ;; --email) email="${2:-}"; shift 2 ;; --port) port="${2:-}"; shift 2 ;; --staging) staging_flag=true; shift ;; @@ -10240,6 +10332,13 @@ repair_dns01_command() { esac done + if ! _secret_source_apply "$secret_src" token aws_key aws_secret; then + return 1 + fi + if [[ "$secret_argv" == "true" ]]; then + _secret_argv_warning + fi + if ! _dns01_validate_domain "$domain"; then echo '{"ok":false,"error":"Укажите --domain sub.example.com (A/AAAA домена должна указывать на этот VPS)"}' return 1 @@ -10372,19 +10471,29 @@ dns01_test_command() { export XRAYEBATOR_NONINTERACTIVE=1 local domain="" provider="" email="" token="" aws_key="" aws_secret="" without_email=false + local secret_src="" secret_argv=false while [[ $# -gt 0 ]]; do case "$1" in --domain) domain="${2:-}"; shift 2 ;; --provider) provider="${2:-}"; shift 2 ;; --email) email="${2:-}"; shift 2 ;; --without-email) without_email=true; shift ;; - --token) token="${2:-}"; shift 2 ;; + --token) token="${2:-}"; secret_argv=true; shift 2 ;; --aws-access-key-id) aws_key="${2:-}"; shift 2 ;; - --aws-secret-access-key) aws_secret="${2:-}"; shift 2 ;; + --aws-secret-access-key) aws_secret="${2:-}"; secret_argv=true; shift 2 ;; + --secret-file) secret_src="${2:-}"; shift 2 ;; + --secret-stdin) secret_src="-"; shift ;; *) shift ;; esac done + if ! _secret_source_apply "$secret_src" token aws_key aws_secret; then + return 1 + fi + if [[ "$secret_argv" == "true" ]]; then + _secret_argv_warning + fi + # Валидация до системных вызовов — тем же набором сообщений, что у боевого пути. if ! _dns01_validate_domain "$domain"; then echo '{"ok":false,"error":"Укажите --domain sub.example.com (A/AAAA домена должна указывать на этот VPS)"}' @@ -15011,6 +15120,7 @@ inspect_command() { quickstart_command() { local email="" email_mode="provided" deploy_pq=false staging_flag=false + local secret_src="" secret_argv=false local dns01_domain="" dns01_provider="" dns01_token="" dns01_aws_key="" dns01_aws_secret="" while [[ $# -gt 0 ]]; do case "$1" in @@ -15029,9 +15139,11 @@ quickstart_command() { # http_tls-деградации выпускаем серт по TXT-записи (домен + провайдер + токен). --dns01-domain) dns01_domain="${2:-}"; shift 2 ;; --dns01-provider) dns01_provider="${2:-}"; shift 2 ;; - --dns01-token) dns01_token="${2:-}"; shift 2 ;; + --dns01-token) dns01_token="${2:-}"; secret_argv=true; shift 2 ;; --dns01-aws-access-key-id) dns01_aws_key="${2:-}"; shift 2 ;; - --dns01-aws-secret-access-key) dns01_aws_secret="${2:-}"; shift 2 ;; + --dns01-aws-secret-access-key) dns01_aws_secret="${2:-}"; secret_argv=true; shift 2 ;; + --dns01-secret-file) secret_src="${2:-}"; shift 2 ;; + --dns01-secret-stdin) secret_src="-"; shift ;; *) shift ;; esac done @@ -15054,6 +15166,12 @@ quickstart_command() { # их ДО системных изменений: молча проигнорированный DNS-01 выглядел бы как успешный # деплой, а подписка осталась бы в http_tls — то есть ровно та деградация, от которой # этот фолбэк и спасает. + if ! _secret_source_apply "$secret_src" dns01_token dns01_aws_key dns01_aws_secret; then + return 1 + fi + if [[ "$secret_argv" == "true" ]]; then + _secret_argv_warning + fi local dns01_requested=false if [[ -n "$dns01_domain" || -n "$dns01_provider" || -n "$dns01_token" ]]; then dns01_requested=true @@ -17735,13 +17853,23 @@ alerts_setup_command() { export XRAYEBATOR_NONINTERACTIVE=1 local token="" chat="" + local secret_src="" secret_argv=false while [[ $# -gt 0 ]]; do case "$1" in - --token) token="$2"; shift 2 ;; + --token) token="$2"; secret_argv=true; shift 2 ;; --chat-id) chat="$2"; shift 2 ;; + --secret-file) secret_src="${2:-}"; shift 2 ;; + --secret-stdin) secret_src="-"; shift ;; *) shift ;; esac done + # Токен бота — тот же класс секрета: аргумент виден в /proc любому пользователю. + if ! _secret_source_apply "$secret_src" token "" ""; then + return 1 + fi + if [[ "$secret_argv" == "true" ]]; then + _secret_argv_warning + fi if [[ -z "$token" || -z "$chat" ]]; then echo '{"ok":false,"error":"Укажите --token TELEGRAM_BOT_TOKEN и --chat-id CHAT_ID"}' return 1 @@ -20126,6 +20254,7 @@ if [[ "$XRAYEBATOR_SOURCED" -eq 0 ]]; then echo -e " ${CYAN}sudo xrayebator profile-limit --name N --limit 100GB|none [--reset]${NC} — лимит трафика профиля (JSON)" echo -e " ${CYAN}sudo xrayebator traffic-check${NC} — учесть трафик и применить лимиты (для systemd-таймера) (JSON)" echo -e " ${CYAN}sudo xrayebator alerts-setup --token T --chat-id C${NC} — подключить Telegram-алерты мониторинга (JSON)" + echo -e " ${CYAN}printf 'token=%s\\n' \"\$T\" | sudo xrayebator alerts-setup --secret-stdin --chat-id C${NC} — то же, но токен не попадает в argv" echo -e " ${CYAN}sudo xrayebator alerts-status${NC} — состояние алертов и таймера мониторинга (JSON; токен не показывается)" echo -e " ${CYAN}sudo xrayebator alerts-test${NC} — тестовое сообщение в Telegram (JSON)" echo -e " ${CYAN}sudo xrayebator alerts-enable|alerts-disable${NC} — включить/выключить алерты (JSON)" From 008d99e4e604e11cf74c9d0bb5760e02103e8b10 Mon Sep 17 00:00:00 2001 From: Ap3x0 <82464229+Ap3x0s@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:42:27 +0300 Subject: [PATCH 03/13] =?UTF-8?q?fix(security):=20=D1=81=D0=B5=D0=BA=D1=80?= =?UTF-8?q?=D0=B5=D1=82=D1=8B=20=D0=B2=20jq=20=D0=BF=D0=B5=D1=80=D0=B5?= =?UTF-8?q?=D0=B4=D0=B0=D1=8E=D1=82=D1=81=D1=8F=20=D0=BE=D0=BA=D1=80=D1=83?= =?UTF-8?q?=D0=B6=D0=B5=D0=BD=D0=B8=D0=B5=D0=BC,=20=D0=B0=20=D0=BD=D0=B5?= =?UTF-8?q?=20=D1=87=D0=B5=D1=80=D0=B5=D0=B7=20--arg?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Тот же класс утечки, что и curl в предыдущих коммитах, но через jq: значения `--arg` тоже лежат в /proc//cmdline, который читается любым пользователем хоста. Через argv проходили: * пароль Hysteria 2 (выдача гранта, ротация при revoke, placeholder-пользователь); * приватный ключ и PresharedKey AmneziaWG (server-params.json, грант и ротация); * sub_token подписки (backfill, revoke, вывод profile-revoke, URL geoip/geosite в HAPP-профиле); * ключ VLESS Encryption (`decryption` инбаунда при profile-pq); * токен Telegram-бота при записи alerts.json. Окно здесь короче, чем у curl (миллисекунды жизни процесса jq), но закрывается тем же приёмом: значение уходит в окружение, а фильтр читает его как $ENV.XRAYEBATOR_JQ_SECRET / $ENV.XRAYEBATOR_JQ_PSK. /proc//environ доступен только владельцу процесса и root (0400), поэтому соседний непривилегированный пользователь (в том числе `xray`, под которым работает сам Xray) значения уже не прочитает. Присваивание стоит перед вызовом, поэтому переменная живёт ровно один вызов и не наследуется долгоживущими дочерними процессами. Не-секреты (имена профилей, домены, порты, адреса) остались обычными --arg: у них нет причины прятаться, а читаемость фильтров важнее. Проверено функционально (jq 1.7, Debian 13): geoip/geosite URL собираются из $ENV, sub_token пишется в профиль, placeholder-карта Hysteria и decryption инбаунда получают прежние значения. --- xrayebator | 69 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 40 insertions(+), 29 deletions(-) diff --git a/xrayebator b/xrayebator index 5fb8552..51c69ae 100755 --- a/xrayebator +++ b/xrayebator @@ -1833,10 +1833,11 @@ _happ_default_routing_json() { [[ "$token" =~ ^[a-f0-9]{32}$ ]] || return 1 [[ "$last_updated" =~ ^[0-9]+$ ]] || return 1 - jq -cn \ - --arg geoip_url "${base_url}/sub/${token}/geoip.dat" \ - --arg geosite_url "${base_url}/sub/${token}/geosite.dat" \ + XRAYEBATOR_JQ_SECRET="$token" jq -cn \ + --arg base_url "$base_url" \ --arg last_updated "$last_updated" ' + ("\($base_url)/sub/\($ENV.XRAYEBATOR_JQ_SECRET)/geoip.dat") as $geoip_url | + ("\($base_url)/sub/\($ENV.XRAYEBATOR_JQ_SECRET)/geosite.dat") as $geosite_url | { Name: "xrayebator-default", GlobalProxy: "true", @@ -2196,6 +2197,14 @@ confirm_vision_443_risk() { # Или для записи в тот же файл: safe_jq_write "выражение_jq" [аргументы_jq...] "$файл" # Последний аргумент — целевой файл (куда записать), предпоследний — исходный # Если целевой == исходный, делает mktemp+mv +# СЕКРЕТЫ В jq. Значение, которое нельзя показывать в `ps`, передаётся не через +# `--arg`, а окружением: `/proc//cmdline` читают все пользователи хоста (0444), +# а `/proc//environ` — только владелец процесса и root (0400). Значение +# читается в фильтре как $ENV.XRAYEBATOR_JQ_SECRET (и $ENV.XRAYEBATOR_JQ_PSK, +# когда секретов два), а присваивание ставится перед вызовом: +# XRAYEBATOR_JQ_SECRET="$password" safe_jq_write '...' "$profile_file" +# Это касается паролей Hysteria, ключей AmneziaWG, sub_token, VLESS-decryption +# ключа и токена Telegram-бота. Не секреты (имена, домены, порты) — обычным --arg. safe_jq_write() { local args=("$@") local nargs=${#args[@]} @@ -3088,7 +3097,7 @@ _hysteria2_regen_config() { # Пустая userpass-карта невалидна для Hysteria — placeholder-пользователь. local placeholder_pass placeholder_pass=$(_hysteria2_ensure_placeholder) || return 1 - users=$(jq -cn --arg p "$placeholder_pass" '{_xrayebator_placeholder: $p}') + users=$(XRAYEBATOR_JQ_SECRET="$placeholder_pass" jq -cn '{_xrayebator_placeholder: $ENV.XRAYEBATOR_JQ_SECRET}') fi local tmp="$HYSTERIA2_DIR/.server.yaml.new" _hysteria2_render_server_yaml "$tmp" "$port" \ @@ -3111,9 +3120,9 @@ _hysteria2_grant_profile() { [[ -n "$existing" ]] && return 0 local password password=$(openssl rand -hex 16) || return 1 - safe_jq_write --arg u "$name" --arg p "$password" \ + XRAYEBATOR_JQ_SECRET="$password" safe_jq_write --arg u "$name" \ --arg c "$(date +%Y-%m-%d\ %H:%M:%S)" \ - '.backends = ((.backends // {}) + {hysteria2: {username: $u, password: $p, created: $c}})' \ + '.backends = ((.backends // {}) + {hysteria2: {username: $u, password: $ENV.XRAYEBATOR_JQ_SECRET, created: $c}})' \ "$profile_file" || return 1 [[ "${2:-}" == "no_regen" ]] && return 0 _hysteria2_regen_config @@ -3158,8 +3167,8 @@ _hysteria2_on_profile_event() { jq -e '.backends.hysteria2.password' "$profile_file" >/dev/null 2>&1 || return 0 local password password=$(openssl rand -hex 16) || return 1 - safe_jq_write --arg p "$password" \ - '.backends.hysteria2.password = $p' "$profile_file" || return 1 + XRAYEBATOR_JQ_SECRET="$password" safe_jq_write \ + '.backends.hysteria2.password = $ENV.XRAYEBATOR_JQ_SECRET' "$profile_file" || return 1 _hysteria2_regen_config || return 1 ;; deleted) @@ -3432,7 +3441,7 @@ EOF } _hysteria2_render_server_yaml "$HYSTERIA2_DIR/server.yaml" "$port" \ "$HYSTERIA2_DIR/cert.pem" "$HYSTERIA2_DIR/key.pem" \ - "$(jq -cn --arg p "$placeholder_pass" '{_xrayebator_placeholder: $p}')" + "$(XRAYEBATOR_JQ_SECRET="$placeholder_pass" jq -cn '{_xrayebator_placeholder: $ENV.XRAYEBATOR_JQ_SECRET}')" _hysteria2_apply_sysctl echo -e "${CYAN} → Устанавливаю бинарник и юнит...${NC}" @@ -4271,10 +4280,10 @@ _awg_install() { mkdir -p "$AWG_DIR" chmod 700 "$AWG_DIR" 2>/dev/null - jq -n --arg priv "$priv" --arg pub "$pub" \ + XRAYEBATOR_JQ_SECRET="$priv" jq -n --arg pub "$pub" \ --argjson port "$port" --arg iface "$iface" --argjson junk "$junk" \ --arg subnet "$AWG_SUBNET" --argjson mtu "$AWG_MTU" \ - '{private_key: $priv, public_key: $pub, port: $port, iface: $iface, + '{private_key: $ENV.XRAYEBATOR_JQ_SECRET, public_key: $pub, port: $port, iface: $iface, junk: $junk, subnet: $subnet, mtu: $mtu}' > "$AWG_PARAMS_FILE" || { echo -e "${RED}✗ Не удалось записать server-params.json${NC}" return 1 @@ -4648,10 +4657,11 @@ _awg_grant_profile() { addr=$(_awg_next_address) || { echo -e "${RED}✗ Подсеть ${AWG_SUBNET} заполнена${NC}" >&2; return 1; } keys=$(_awg_gen_keys) || { echo -e "${RED}✗ awg genkey не сработал${NC}" >&2; return 1; } read -r cpriv cpub psk <<< "$keys" - safe_jq_write --arg a "$addr" --arg cp "$cpriv" --arg cb "$cpub" --arg ps "$psk" \ + XRAYEBATOR_JQ_SECRET="$cpriv" XRAYEBATOR_JQ_PSK="$psk" \ + safe_jq_write --arg a "$addr" --arg cb "$cpub" \ --arg c "$(date +%Y-%m-%d\ %H:%M:%S)" \ - '.backends = ((.backends // {}) + {awg: {client_private_key: $cp, client_public_key: $cb, - preshared_key: $ps, address: $a, created: $c}})' \ + '.backends = ((.backends // {}) + {awg: {client_private_key: $ENV.XRAYEBATOR_JQ_SECRET, client_public_key: $cb, + preshared_key: $ENV.XRAYEBATOR_JQ_PSK, address: $a, created: $c}})' \ "$profile_file" || return 1 [[ "${2:-}" == "no_regen" ]] && return 0 _awg_regen_config @@ -4695,9 +4705,10 @@ _awg_on_profile_event() { local keys cpriv cpub psk keys=$(_awg_gen_keys) || return 1 read -r cpriv cpub psk <<< "$keys" - safe_jq_write --arg cp "$cpriv" --arg cb "$cpub" --arg ps "$psk" \ - '.backends.awg = (.backends.awg + {client_private_key: $cp, - client_public_key: $cb, preshared_key: $ps})' "$profile_file" || return 1 + XRAYEBATOR_JQ_SECRET="$cpriv" XRAYEBATOR_JQ_PSK="$psk" \ + safe_jq_write --arg cb "$cpub" \ + '.backends.awg = (.backends.awg + {client_private_key: $ENV.XRAYEBATOR_JQ_SECRET, + client_public_key: $cb, preshared_key: $ENV.XRAYEBATOR_JQ_PSK})' "$profile_file" || return 1 _awg_regen_config || return 1 ;; deleted) @@ -6281,7 +6292,7 @@ _migrate_subscription_tokens_2026() { echo -e "${RED} ✗ openssl rand вернул некорректный токен для $(basename "$profile_file")${NC}" return 2 fi - if ! safe_jq_write --arg t "$new_token" '.sub_token = $t' "$profile_file"; then + if ! XRAYEBATOR_JQ_SECRET="$new_token" safe_jq_write '.sub_token = $ENV.XRAYEBATOR_JQ_SECRET' "$profile_file"; then echo -e "${RED} ✗ safe_jq_write failed для $profile_file${NC}" return 2 fi @@ -10815,7 +10826,7 @@ manage_subscription_menu() { sleep 2 continue fi - if ! safe_jq_write --arg t "$new_token" '.sub_token = $t' "$pfile"; then + if ! XRAYEBATOR_JQ_SECRET="$new_token" safe_jq_write '.sub_token = $ENV.XRAYEBATOR_JQ_SECRET' "$pfile"; then echo -e "${RED}✗ Запись в profile JSON не удалась${NC}" sleep 2 continue @@ -11330,8 +11341,8 @@ _pq_add_route_for_profile() { # Инбаунд этого транспорта становится PQ: клиенты без ML-KEM к порту не подключатся. # Для xhttp decryption уже прописал add_inbound, для остальных транспортов — здесь # (VLESS decryption живёт на уровне инбаунда, а не маршрута). - if ! safe_jq_write --argjson p "$port" --arg d "$decryption" ' - .inbounds |= map(if .port == $p then .settings.decryption = $d else . end) + if ! XRAYEBATOR_JQ_SECRET="$decryption" safe_jq_write --argjson p "$port" ' + .inbounds |= map(if .port == $p then .settings.decryption = $ENV.XRAYEBATOR_JQ_SECRET else . end) ' "$CONFIG_FILE"; then return 1 fi @@ -16414,8 +16425,8 @@ profile_revoke_command() { # Профиль-JSON: новый токен всегда; при --full ещё и uuid (top-level + routes). # Порядок при full: сначала конфиг+рестарт, потом профиль; сбой записи профиля # при full откатывает конфиг — иначе uuid разедутся. - local jq_args=(--arg t "$new_token") - local jq_expr='.sub_token = $t' + local jq_args=() + local jq_expr='.sub_token = $ENV.XRAYEBATOR_JQ_SECRET' if [[ "$full" == "true" ]]; then jq_args+=(--arg old "$old_uuid" --arg new "$new_uuid") # ВАЖНО: (.routes // []) |= map(...) — невалидный path в jq («Invalid path @@ -16435,7 +16446,7 @@ profile_revoke_command() { fi fi - if ! safe_jq_write "${jq_args[@]}" "$jq_expr" "$profile_file"; then + if ! XRAYEBATOR_JQ_SECRET="$new_token" safe_jq_write "${jq_args[@]}" "$jq_expr" "$profile_file"; then if [[ "$full" == "true" ]]; then # Полусостояние недопустимо: конфиг уже с новым uuid, профиль — со старым. # Откатываем config.json из бэкапа транзакции. @@ -16460,10 +16471,10 @@ profile_revoke_command() { if [[ -n "$base" ]] && _profile_cli_subscription_url "$new_token" >/dev/null 2>&1; then sub_url="${base}/sub/${new_token}" fi - jq -n \ - --arg name "$name" --arg token "$new_token" --arg url "$sub_url" \ + XRAYEBATOR_JQ_SECRET="$new_token" jq -n \ + --arg name "$name" --arg url "$sub_url" \ --argjson full "$full" --arg uuid "$new_uuid" \ - '{ok: true, name: $name, full: $full, sub_token: $token, + '{ok: true, name: $name, full: $full, sub_token: $ENV.XRAYEBATOR_JQ_SECRET, subscription_url: $url} + (if $full then {uuid: $uuid} else {} end)' return 0 @@ -17901,8 +17912,8 @@ alerts_setup_command() { local now tmp now=$(date +%s) tmp=$(mktemp) || { echo '{"ok":false,"error":"mktemp недоступен"}'; return 1; } - if ! jq -n --arg t "$token" --arg c "$chat" --arg u "$bot_username" --argjson cr "$now" \ - '{enabled: true, token: $t, chat_id: $c, bot_username: $u, created: $cr}' > "$tmp"; then + if ! XRAYEBATOR_JQ_SECRET="$token" jq -n --arg c "$chat" --arg u "$bot_username" --argjson cr "$now" \ + '{enabled: true, token: $ENV.XRAYEBATOR_JQ_SECRET, chat_id: $c, bot_username: $u, created: $cr}' > "$tmp"; then rm -f "$tmp" echo '{"ok":false,"error":"Не удалось записать конфиг алертов"}' return 1 From 3acd91ced2a3d24a9f926570a68fc57a18153930 Mon Sep 17 00:00:00 2001 From: Ap3x0 <82464229+Ap3x0s@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:42:40 +0300 Subject: [PATCH 04/13] =?UTF-8?q?test(validation):=20=D1=82=D0=B5=D1=81?= =?UTF-8?q?=D1=82=20=D0=BD=D0=B0=20=D0=BE=D1=82=D1=81=D1=83=D1=82=D1=81?= =?UTF-8?q?=D1=82=D0=B2=D0=B8=D0=B5=20=D1=81=D0=B5=D0=BA=D1=80=D0=B5=D1=82?= =?UTF-8?q?=D0=BE=D0=B2=20=D0=B2=20argv=20+=20=D1=81=D1=82=D0=B0=D0=B1=20c?= =?UTF-8?q?url=20=D0=BD=D0=B0=D1=83=D1=87=D0=B5=D0=BD=20stdin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Новый `validation/test-secret-argv.sh` фиксирует контракт, который до этого держался только на честном слове: * статически — помощник `_curl_secret_url` есть, и каждая строка с токеном бота или sub_token либо идёт через него, либо является комментарием; значения-секреты не передаются jq через `--arg`; флаги `--secret-file/--secret-stdin` (у quickstart — с префиксом `--dns01-`) объявлены у всех пяти команд; * функционально — подставной curl пишет свои argv в лог: токен бота и sub_token обязаны отсутствовать в argv и присутствовать в stdin-конфиге (`-K -`), то есть проверка идёт по тому же признаку, что видит атакующий в /proc; * разбор пейлоада — одиночная строка как токен, AWS-пара, приоритет явного флага, мусорный ключ, файл 0644 отвергается, файл 0600 читается и удаляется, stdin, отсутствующий файл, пустой источник как no-op; * CLI — `--secret-stdin` доводит секрет до валидации, `--token` печатает предупреждение в stderr, оставляя stdout чистым JSON; * jq — `$ENV.XRAYEBATOR_JQ_SECRET` действительно читается. В `test-alerts-monitor.sh` стаб curl научен читать URL из stdin-конфига: иначе после перехода на `-K -` он перестал видеть адрес и падал на getMe. Заодно в стаб добавлена регресс-гвардия — если секрет когда-нибудь снова окажется в argv, тест упадёт с конкретной строкой. --- validation/test-alerts-monitor.sh | 13 ++ validation/test-secret-argv.sh | 213 ++++++++++++++++++++++++++++++ 2 files changed, 226 insertions(+) create mode 100644 validation/test-secret-argv.sh diff --git a/validation/test-alerts-monitor.sh b/validation/test-alerts-monitor.sh index 118ebef..ff9ef59 100644 --- a/validation/test-alerts-monitor.sh +++ b/validation/test-alerts-monitor.sh @@ -104,6 +104,19 @@ curl() { http*) url="$a" ;; esac done + # Регресс-гвардия: URL с секретом (bot/…, /sub/) обязан приходить + # curl'у stdin-конфигом (`-K -`), а не аргументом — argv виден в /proc всем. + for a in "${argv[@]}"; do + case "$a" in + *bot[0-9]*:*|*/sub/*) + fail "секрет в argv curl: $a" ;; + esac + done + if [[ "$*" == *"-K -"* ]]; then + local cfg + cfg=$(cat) + url=$(sed -n 's/^url = "\(.*\)"$/\1/p' <<< "$cfg" | head -n1) + fi if [[ -n "$CURL_FAIL_MATCH" && "$url" == *"$CURL_FAIL_MATCH"* ]]; then echo '{"ok":false,"error_code":400,"description":"stub failure"}' return 0 diff --git a/validation/test-secret-argv.sh b/validation/test-secret-argv.sh new file mode 100644 index 0000000..5422239 --- /dev/null +++ b/validation/test-secret-argv.sh @@ -0,0 +1,213 @@ +#!/usr/bin/env bash +# Тест «секреты не ходят через argv». +# +# Почему это отдельный тест: /proc//cmdline читается ЛЮБЫМ пользователем хоста +# (0444), а /proc//environ — только владельцем процесса и root (0400). Значит +# любой секрет, попавший в аргументы (URL с токеном бота, sub_token подписки, +# --token в командной строке xrayebator, значения --arg у jq), доступен соседнему +# непривилегированному процессу — например пользователю `xray`, под которым +# работает сам Xray. +# +# Что проверяем: +# - статически: в скрипте нет curl-вызова с токеном в argv; есть помощник +# `_curl_secret_url` и им пользуются все четыре «секретных» URL; +# - функционально: подставной curl видит URL в stdin-конфиге и НЕ видит токена +# в своих аргументах; +# - `--secret-file`/`--secret-stdin`: разбор пейлоада, приоритет явного флага, +# отказ файлу с правами шире 0600, удаление файла после чтения; +# - `--token`/`--aws-secret-access-key` продолжают работать, но печатают +# предупреждение в stderr (stdout остаётся чистым JSON); +# - jq-секреты идут окружением ($ENV.XRAYEBATOR_JQ_SECRET), а не --arg. +# +# Тест не трогает систему: всё на временном каталоге и подставных бинарниках. +set -u +cd "$(dirname "$0")/.." + +fail() { echo "✗ $1"; exit 1; } +pass() { echo "✓ $1"; } + +command -v jq >/dev/null 2>&1 || fail "jq required (CI installs it)" + +TMP_ROOT="$(mktemp -d)" +trap 'rm -rf "$TMP_ROOT"' EXIT + +export LOCK_FILE="$TMP_ROOT/xrayebator.lock" +# shellcheck disable=SC1091 +source ./xrayebator || fail "source ./xrayebator failed" + +# ── 1. Статика: помощник есть и используется ───────────────────────────────── +grep -q '^_curl_secret_url() {' xrayebator || fail "нет помощника _curl_secret_url" +grep -q '^_secret_payload_apply() {' xrayebator || fail "нет _secret_payload_apply" +grep -q '^_secret_source_apply() {' xrayebator || fail "нет _secret_source_apply" + +# Токен бота и sub_token не должны встречаться в аргументах curl. Правило: каждая +# строка со секретом обязана либо идти через помощник (тогда URL уходит в stdin), +# либо быть комментарием; если в строке есть настоящий вызов curl — это утечка. +bad="" +while IFS= read -r line; do + body="${line#*:}" + [[ "$body" =~ ^[[:space:]]*# ]] && continue + [[ "$line" == *"_curl_secret_url"* ]] && continue + if printf '%s' "$body" | grep -qE '(^|[^_[:alnum:]])curl([[:space:]]|$)'; then + bad+=" $line"$'\n' + fi +done < <(grep -nE 'bot\$token|/sub/\$\{?token' xrayebator) +[[ -z "$bad" ]] || fail "curl с секретом в argv: +$bad" +# Все четыре секретных URL идут через помощник. +[[ "$(grep -c '_curl_secret_url' xrayebator)" -ge 5 ]] \ + || fail "мало вызовов _curl_secret_url (ожидаются определение + 4 места)" +pass "статика curl: секретных URL в argv нет" + +# Значения-секреты не передаются jq через --arg. +for pat in '--arg p "\$password"' '--arg t "\$token"' '--arg t "\$new_token"' \ + '--arg cp "\$cpriv"' '--arg ps "\$psk"' '--arg priv "\$priv"' \ + '--arg d "\$decryption"'; do + if grep -nE -- "$pat" xrayebator >/dev/null; then + fail "секрет через jq --arg: $pat" + fi +done +grep -q 'XRAYEBATOR_JQ_SECRET' xrayebator || fail "jq-секреты не передаются окружением" +pass "статика jq: секреты идут окружением" + +# Флаги объявлены у всех команд, которым нужен секрет. +for cmd in dns01_setup_command dns01_test_command repair_dns01_command \ + alerts_setup_command quickstart_command; do + body=$(sed -n "/^${cmd}() {/,/^}/p" xrayebator) + [[ -n "$body" ]] || fail "не найдена $cmd" + case "$body" in + *--secret-file*|*--dns01-secret-file*) ;; + *) fail "$cmd не разбирает --secret-file" ;; + esac + case "$body" in + *--secret-stdin*|*--dns01-secret-stdin*) ;; + *) fail "$cmd не разбирает --secret-stdin" ;; + esac +done +pass "флаги --secret-file/--secret-stdin объявлены у всех команд" + +# ── 2. Функционально: подставной curl не видит секрета в argv ──────────────── +CURL_LOG="$TMP_ROOT/curl-argv.log" +CURL_URL_LOG="$TMP_ROOT/curl-url.log" +: > "$CURL_LOG" +curl() { + printf '%s\n' "$*" >> "$CURL_LOG" + local a cfg="" out="" fmt="" + local -a argv=("$@") + local i url="" + for ((i = 0; i < ${#argv[@]}; i++)); do + case "${argv[i]}" in + -K) cfg="${argv[i + 1]:-}" ;; + -o) out="${argv[i + 1]:-}" ;; + -w) fmt="${argv[i + 1]:-}" ;; + esac + done + if [[ "$cfg" == "-" ]]; then + cat > "$TMP_ROOT/curl-stdin.txt" + url=$(sed -n 's/^url = "\(.*\)"$/\1/p' "$TMP_ROOT/curl-stdin.txt" | head -n1) + printf '%s\n' "$url" >> "$CURL_URL_LOG" + fi + local body='{"ok":true,"result":{"username":"stub_bot","message_id":1}}' + case "$url" in + */getMe) body='{"ok":true,"result":{"username":"stub_bot"}}' ;; + */sub/*) body='vless://11111111-2222-3333-4444-555555555555@203.0.113.10:443#p' ;; + esac + [[ -n "$out" ]] && printf '%s\n' "$body" > "$out" || printf '%s\n' "$body" + [[ -n "$fmt" ]] && printf '%s' '200' + return 0 +} + +TOKEN="999999999:AAFakeBotTokenForArgvProof_123456" +TELEGRAM_API_BASE="http://telegram.stub" +_telegram_get_me "$TOKEN" >/dev/null 2>&1 || true +_telegram_send_raw "$TOKEN" "123456" "hello" >/dev/null 2>&1 || true +SUBHTTP_LOCAL_BASE="http://127.0.0.1:8080" +_monitor_sub_probe "0123456789abcdef0123456789abcdef" >/dev/null 2>&1 || true + +[[ -s "$CURL_LOG" ]] || fail "подставной curl не вызывался" +if grep -qF "$TOKEN" "$CURL_LOG"; then + fail "токен бота попал в argv curl: $(grep -F "$TOKEN" "$CURL_LOG" | head -n1)" +fi +if grep -q '0123456789abcdef0123456789abcdef' "$CURL_LOG"; then + fail "sub_token попал в argv curl" +fi +grep -q 'bot.*getMe' "$CURL_URL_LOG" || fail "getMe не получил URL через stdin-конфиг" +grep -q '/sub/0123456789abcdef0123456789abcdef' "$CURL_URL_LOG" \ + || fail "проба подписки не получила URL через stdin-конфиг" +pass "curl: URL с секретом приходит stdin-конфигом, argv чист" + +unset -f curl + +# ── 3. --secret-file / --secret-stdin ─────────────────────────────────────── +token="" aws_key="" aws_secret="" +_secret_payload_apply "bareTokenValue12345" token aws_key aws_secret \ + || fail "одиночная строка не распознана как токен" +[[ "$token" == "bareTokenValue12345" ]] || fail "токен не разложен" + +token="" aws_key="" aws_secret="" +_secret_payload_apply $'aws_access_key_id=AKIAEXAMPLE\naws_secret_access_key=s3cr3t/+=x' \ + token aws_key aws_secret || fail "AWS-пейлоад не разобран" +[[ "$aws_key" == "AKIAEXAMPLE" && "$aws_secret" == "s3cr3t/+=x" ]] || fail "AWS-ключи не разложены" + +token="from-argv" +_secret_payload_apply "token=from-file" token "" "" || fail "rc при известном ключе" +[[ "$token" == "from-argv" ]] || fail "явный флаг обязан быть сильнее файла" + +token="" +_secret_payload_apply "unknown=value" token "" "" && fail "неизвестный ключ должен давать rc 1" +pass "разбор пейлоада: токен, AWS, приоритет флага, мусор" + +secret_file="$TMP_ROOT/secret.txt" +printf 'token=FILE_TOKEN_VALUE_123456\n' > "$secret_file" +if [[ "${OSTYPE:-}" != msys* && "${OSTYPE:-}" != cygwin* ]]; then + chmod 644 "$secret_file" + token="" + out=$(_secret_source_apply "$secret_file" token "" "") && fail "файл 0644 должен отвергаться" + [[ "$out" == *"chmod 600"* ]] || fail "сообщение про 0644: $out" + [[ -e "$secret_file" ]] || fail "отвергнутый файл не должен удаляться" +fi +chmod 600 "$secret_file" +token="" +_secret_source_apply "$secret_file" token "" "" || fail "файл 0600 не прочитан" +[[ "$token" == "FILE_TOKEN_VALUE_123456" ]] || fail "значение из файла: $token" +[[ ! -e "$secret_file" ]] || fail "файл секрета не удалён после чтения" + +token="" +_secret_source_apply - token "" "" <<< 'token=STDIN_TOKEN_VALUE' || fail "stdin не прочитан" +[[ "$token" == "STDIN_TOKEN_VALUE" ]] || fail "значение из stdin: $token" + +token="keep" +_secret_source_apply "" token "" "" || fail "пустой источник обязан быть no-op" +[[ "$token" == "keep" ]] || fail "пустой источник тронул переменную" + +token="" +out=$(_secret_source_apply "$TMP_ROOT/nonexistent" token "" "") && fail "нет файла — должен быть rc 1" +[[ "$out" == *"не найден"* ]] || fail "сообщение о ненайденном файле: $out" +pass "источник секрета: 0600, отказ 0644, stdin, отсутствующий файл" + +# ── 4. CLI: секрет из stdin работает, --token предупреждает ────────────────── +out=$(printf 'token=short\n' | dns01_setup_command --domain sub.example.com \ + --provider cloudflare --secret-stdin --without-email 2>/dev/null) +jq -e '.ok == false and (.error | test("--token"))' <<< "$out" >/dev/null \ + || fail "dns01-setup --secret-stdin не довёл токен до валидации: $out" + +out=$(printf 'token=1:short\n' | alerts_setup_command --secret-stdin --chat-id 123456 2>/dev/null) +jq -e '.ok == false and (.error | test("формат токена"))' <<< "$out" >/dev/null \ + || fail "alerts-setup --secret-stdin: $out" + +err=$(dns01_setup_command --domain sub.example.com --provider cloudflare \ + --token short --without-email 2>&1 >/dev/null) +[[ "$err" == *"cmdline"* ]] || fail "--token обязан предупреждать о видимости в /proc: $err" +out=$(dns01_setup_command --domain sub.example.com --provider cloudflare \ + --token short --without-email 2>/dev/null) +jq -e '.ok == false' <<< "$out" >/dev/null || fail "stdout с --token не JSON: $out" +pass "CLI: секрет из stdin доходит, --token предупреждает в stderr" + +# ── 5. jq-секрет через окружение ──────────────────────────────────────────── +val=$(XRAYEBATOR_JQ_SECRET="env-secret-value" jq -n -r '$ENV.XRAYEBATOR_JQ_SECRET') +[[ "$val" == "env-secret-value" ]] || fail "jq \$ENV не читается: $val" +json=$(XRAYEBATOR_JQ_SECRET="env-secret-value" jq -cn '{v: $ENV.XRAYEBATOR_JQ_SECRET}') +jq -e '.v == "env-secret-value"' <<< "$json" >/dev/null || fail "jq -n с \$ENV: $json" +pass "jq: значение читается из окружения" + +echo "✓ Секреты в argv: помощник curl, --secret-file/--secret-stdin, jq через \$ENV — OK" From d6254440eb537b789ca8b56cb5881b80e4f57d78 Mon Sep 17 00:00:00 2001 From: Ap3x0 <82464229+Ap3x0s@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:45:30 +0300 Subject: [PATCH 05/13] =?UTF-8?q?feat(gui):=20DNS-01-=D0=BA=D1=80=D0=B5?= =?UTF-8?q?=D0=B4=D1=8B=20=D1=83=D1=85=D0=BE=D0=B4=D1=8F=D1=82=20=D0=BD?= =?UTF-8?q?=D0=B0=20=D1=81=D0=B5=D1=80=D0=B2=D0=B5=D1=80=20=D1=84=D0=B0?= =?UTF-8?q?=D0=B9=D0=BB=D0=BE=D0=BC=200600,=20=D0=B0=20=D0=BD=D0=B5=20?= =?UTF-8?q?=D0=B0=D1=80=D0=B3=D1=83=D0=BC=D0=B5=D0=BD=D1=82=D0=BE=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Визард развёртывания и кнопки ремонта подписки собирали `xrayebator dns01-setup --domain … --provider … --token `: токен попадал в командную строку и локального ssh-клиента, и удалённого `sh -c`, и самой `xrayebator` — на всё время выпуска сертификата, то есть на десятки секунд. Теперь `dns01CliArgs` собирает только домен и провайдера, а креды едут отдельным файлом 0600 (SFTP), путь уходит серверу флагом `--secret-file` (у quickstart — `--dns01-secret-file`), и файл удаляется сразу после чтения. Что изменено: * `shared/dns01.ts` — `dns01CliArgs` больше не содержит кредов; добавлены `dns01SecretPayload` (формат «key=value», ровно тот, что разбирает сервер) и `dns01SecretFlag`; * `ssh-client.upload` принимает режим — секрет пишется как 0600, скрипты по-прежнему 0755; * `MaintenanceManager.runWithSecret` — upload → команда → `rm -f` в finally; общий разбор ответа и ошибки вынесен в `execOn`/`parseDns01`, чтобы путь с секретом и путь без него не разъезжались; * `Deployer.deploy` — тот же upload перед quickstart. Смысл правки в том, что она закрывает канал, а не симптом: серверный `--secret-file` появился в предыдущем коммите, поэтому старые сборки GUI со старым сервером работать перестанут только в части DNS-01 — но `--token` на сервере остался, поэтому откат совместим в обе стороны. Проверено: `npm run typecheck` чист; vitest 175/176 (единственное падение — `tests/unit/shell-command.test.ts` со spawnSync `/bin/sh`, он не работает на Windows-хосте и не связан с этой правкой). --- src/main/core/deployer.ts | 32 ++++++++++-- src/main/core/maintenance.ts | 96 +++++++++++++++++++++++++----------- src/main/core/ssh-client.ts | 13 +++-- src/shared/dns01.ts | 42 +++++++++++----- tests/unit/deployer.test.ts | 11 +++-- tests/unit/dns01.test.ts | 82 +++++++++++++++--------------- 6 files changed, 184 insertions(+), 92 deletions(-) diff --git a/src/main/core/deployer.ts b/src/main/core/deployer.ts index 5e1de21..c6c870b 100644 --- a/src/main/core/deployer.ts +++ b/src/main/core/deployer.ts @@ -5,7 +5,7 @@ import { SshClient, SshCredentials } from './ssh-client' import { shellCommand, shellQuote } from './shell-command' import { fetchSubscription, parseSubscription } from './subscription' import { maskSubscriptionUrl } from './server-inspector' -import { dns01CliArgs, isDns01Ready, type Dns01Input } from '@shared/dns01' +import { dns01CliArgs, dns01SecretFlag, dns01SecretPayload, isDns01Ready, type Dns01Input } from '@shared/dns01' import type { DeployStep, EmailMode, VlessLink } from '@shared/types' export type DeployStepListener = (step: DeployStep, message: string) => void @@ -199,10 +199,32 @@ export class Deployer { this.onLog('xrayebator установлен в /usr/local/bin/xrayebator') this.onStep('quickstart', 'Запускаю quickstart...') - const quick = await client.exec( - shellCommand('xrayebator', quickstartArgs), - { elevated: true } - ) + // DNS-01-креды уходят файлом 0600, а не аргументом: /proc//cmdline + // читается всеми локальными пользователями, а quickstart держит свою + // командную строку всё время выпуска сертификата. + let secretPath: string | null = null + if (input.dns01) { + secretPath = `/tmp/.xrayebator-secret-${SshClient.randomToken()}` + await client.upload( + Buffer.from(dns01SecretPayload(input.dns01), 'utf8'), + secretPath, + { mode: 0o600 } + ) + } + let quick: Awaited> + try { + quick = await client.exec( + shellCommand('xrayebator', [ + ...quickstartArgs, + ...(secretPath ? [dns01SecretFlag('--dns01-'), secretPath] : []) + ]), + { elevated: true } + ) + } finally { + if (secretPath) { + await client.exec(shellCommand('rm', ['-f', secretPath])).catch(() => undefined) + } + } if (quick.code !== 0) { // Серверный quickstart печатает статус в stderr, а JSON с причиной // ({ok:false,error:...}) — в stdout. Извлекаем причину из JSON в первую diff --git a/src/main/core/maintenance.ts b/src/main/core/maintenance.ts index 36861a7..2c3b544 100644 --- a/src/main/core/maintenance.ts +++ b/src/main/core/maintenance.ts @@ -2,7 +2,7 @@ import { SshClient, SshCredentials } from './ssh-client' import { shellCommand } from './shell-command' import { describeFailure, isUnknownCommandFailure, unknownCommandHint } from './cli-failure' import { extractJson } from './profiles' -import { dns01CliArgs, isDns01Ready, isValidDns01Domain, type Dns01Input } from '@shared/dns01' +import { dns01CliArgs, dns01SecretFlag, dns01SecretPayload, isDns01Ready, isValidDns01Domain, type Dns01Input } from '@shared/dns01' import type { Dns01RepairResult, Dns01StatusResult, @@ -63,38 +63,78 @@ export class MaintenanceManager { const client = new SshClient(this.creds) try { await client.connect() - const res = await client.exec(shellCommand('xrayebator', args), { elevated: true }) - if (res.code !== 0) { - const reason = describeFailure(res) - const hint = isUnknownCommandFailure(res) ? ` ${unknownCommandHint()}` : '' - throw new Error( - `xrayebator ${args[0] ?? ''} → код ${res.code}${reason ? `: ${reason}` : ''}.${hint}` - ) - } - return res.stdout + return await this.execOn(client, args) } finally { client.close() } } - private async dns01(args: readonly string[]): Promise { + /** Один вызов `xrayebator …` с разбором неуспешного кода (общий для путей). */ + private async execOn(client: SshClient, args: readonly string[]): Promise { + const res = await client.exec(shellCommand('xrayebator', args), { elevated: true }) + if (res.code !== 0) { + const reason = describeFailure(res) + const hint = isUnknownCommandFailure(res) ? ` ${unknownCommandHint()}` : '' + throw new Error( + `xrayebator ${args[0] ?? ''} → код ${res.code}${reason ? `: ${reason}` : ''}.${hint}` + ) + } + return res.stdout + } + + /** + * Команда, которой нужен секрет (DNS-токен / ключи AWS), получает его файлом + * 0600 и флагом `--secret-file`, а не аргументом: `/proc//cmdline` читают + * все локальные пользователи, и токен был бы виден всё время выпуска + * сертификата. Файл лежит в /tmp под случайным именем и удаляется сразу после + * чтения на сервере; `finally` — страховка на случай, если команда до разбора + * не дошла. + */ + private async runWithSecret( + args: readonly string[], + secretPayload: string, + flag: string + ): Promise { + const client = new SshClient(this.creds) try { - const payload = extractJson(await this.run(args)) as Dns01RepairResult & { - ok?: boolean - error?: string - } - return { - ok: payload.ok === true, - repaired: payload.repaired, - skipped: payload.skipped, - domain: payload.domain, - provider: payload.provider, - port: payload.port, - tls_mode: payload.tls_mode, - subscription_url: payload.subscription_url, - note: payload.note, - error: payload.error + await client.connect() + const remotePath = `/tmp/.xrayebator-secret-${SshClient.randomToken()}` + await client.upload(Buffer.from(secretPayload, 'utf8'), remotePath, { mode: 0o600 }) + try { + return await this.execOn(client, [...args, flag, remotePath]) + } finally { + await client.exec(shellCommand('rm', ['-f', remotePath])).catch(() => undefined) } + } finally { + client.close() + } + } + + /** Разбор JSON-ответа DNS-01 (общий для пути с токеном и с repair). */ + private parseDns01(stdout: string): Dns01RepairResult { + const payload = extractJson(stdout) as Dns01RepairResult & { + ok?: boolean + error?: string + } + return { + ok: payload.ok === true, + repaired: payload.repaired, + skipped: payload.skipped, + domain: payload.domain, + provider: payload.provider, + port: payload.port, + tls_mode: payload.tls_mode, + subscription_url: payload.subscription_url, + note: payload.note, + error: payload.error + } + } + + private async dns01(args: readonly string[], secretPayload: string): Promise { + try { + return this.parseDns01( + await this.runWithSecret(args, secretPayload, dns01SecretFlag()) + ) } catch (err) { return { ok: false, error: err instanceof Error ? err.message : String(err) } } @@ -135,7 +175,7 @@ export class MaintenanceManager { async dns01Setup(input: Dns01Input): Promise { const problem = dns01Problem(input) if (problem) return { ok: false, error: problem } - return this.dns01(['dns01-setup', ...dns01CliArgs(input)]) + return this.dns01(['dns01-setup', ...dns01CliArgs(input)], dns01SecretPayload(input)) } /** @@ -145,7 +185,7 @@ export class MaintenanceManager { async repairDns01(input: Dns01Input): Promise { const problem = dns01Problem(input) if (problem) return { ok: false, error: problem } - return this.dns01(['repair-dns01', ...dns01CliArgs(input)]) + return this.dns01(['repair-dns01', ...dns01CliArgs(input)], dns01SecretPayload(input)) } /** diff --git a/src/main/core/ssh-client.ts b/src/main/core/ssh-client.ts index e98d121..1fc0192 100644 --- a/src/main/core/ssh-client.ts +++ b/src/main/core/ssh-client.ts @@ -168,11 +168,18 @@ export class SshClient { return this.sftp } - /** Передача файла из локального буфера в удалённый путь. */ - async upload(buffer: Buffer, remotePath: string): Promise { + /** + * Передача файла из локального буфера в удалённый путь. + * `mode` по умолчанию 0755 (скрипты), для секретов передаётся 0600. + */ + async upload( + buffer: Buffer, + remotePath: string, + options: { mode?: number } = {} + ): Promise { const sftp = await this.getSftp() await new Promise((resolve, reject) => { - const stream = sftp.createWriteStream(remotePath, { mode: 0o755 }) + const stream = sftp.createWriteStream(remotePath, { mode: options.mode ?? 0o755 }) stream.on('close', () => resolve()) stream.on('error', reject) stream.end(buffer) diff --git a/src/shared/dns01.ts b/src/shared/dns01.ts index f2b9b08..2c12856 100644 --- a/src/shared/dns01.ts +++ b/src/shared/dns01.ts @@ -57,23 +57,39 @@ export function isDns01Ready(input: Dns01Input): boolean { /** * Аргументы CLI для `dns01-setup`/`repair-dns01`/`quickstart`. `prefix` — префикс - * длинных опций: `--` для CLI-команд, `--dns01-` для quickstart. Креденшелы уходят - * только те, что нужны выбранному провайдеру: лишний `--token` для route53 сервер - * проигнорирует, но и хранить его в payload незачем. + * длинных опций: `--` для CLI-команд, `--dns01-` для quickstart. + * + * Креденшелов здесь НЕТ намеренно: аргументы процесса видны любому локальному + * пользователю хоста через `/proc//cmdline`, а `xrayebator dns01-setup` + * держит их в своей командной строке всё время выпуска сертификата (ожидание + * DNS-распространения 30 с плюс работа certbot). Токен передаётся файлом 0600 + * через `dns01SecretFlag()` — см. `dns01SecretPayload()`. */ export function dns01CliArgs(input: Dns01Input, prefix = '--'): string[] { - const args = [`${prefix}domain`, input.domain.trim(), `${prefix}provider`, input.provider] - if (input.provider === 'cloudflare') { - args.push(`${prefix}token`, (input.token ?? '').trim()) - } else if (input.provider === 'route53') { - args.push( - `${prefix}aws-access-key-id`, - (input.awsKeyId ?? '').trim(), - `${prefix}aws-secret-access-key`, - (input.awsSecret ?? '').trim() + return [`${prefix}domain`, input.domain.trim(), `${prefix}provider`, input.provider] +} + +/** Флаг серверной команды, которым передаётся путь к файлу секрета. */ +export function dns01SecretFlag(prefix = '--'): string { + return `${prefix}secret-file` +} + +/** + * Пейлоад секрета для серверного `--secret-file`: строки «key=value». Формат + * серверный (`_secret_payload_apply`): `token=…` для Cloudflare, + * `aws_access_key_id=…`/`aws_secret_access_key=…` для Route53. Креды уходят + * только те, что нужны выбранному провайдеру. + */ +export function dns01SecretPayload(input: Dns01Input): string { + const line = (key: string, value: string): string => `${key}=${value.trim()}\n` + if (input.provider === 'cloudflare') return line('token', input.token ?? '') + if (input.provider === 'route53') { + return ( + line('aws_access_key_id', input.awsKeyId ?? '') + + line('aws_secret_access_key', input.awsSecret ?? '') ) } - return args + return '' } /** Маскировка секрета для консоли/логов: показываем только длину и края. */ diff --git a/tests/unit/deployer.test.ts b/tests/unit/deployer.test.ts index 9ee8a2a..21c2186 100644 --- a/tests/unit/deployer.test.ts +++ b/tests/unit/deployer.test.ts @@ -75,10 +75,15 @@ describe('quickstart argument builder', () => { '--dns01-domain', 'sub.example.com', '--dns01-provider', - 'cloudflare', - '--dns01-token', - 'abcdefghijklmnopqrst' + 'cloudflare' ]) + // Токен не в argv: он уходит файлом 0600 (--dns01-secret-file) — см. deploy(). + expect( + buildQuickstartArgs({ + emailMode: 'without', + dns01: { domain: 'sub.example.com', provider: 'cloudflare', token: 'abcdefghijklmnopqrst' } + }).join(' ') + ).not.toContain('abcdefghijklmnopqrst') }) it('refuses an incomplete DNS-01 set before touching the server', () => { diff --git a/tests/unit/dns01.test.ts b/tests/unit/dns01.test.ts index d0c9023..5d168c8 100644 --- a/tests/unit/dns01.test.ts +++ b/tests/unit/dns01.test.ts @@ -2,6 +2,8 @@ import { describe, expect, it } from 'vitest' import { DNS01_PROVIDERS, dns01CliArgs, + dns01SecretFlag, + dns01SecretPayload, isDns01Ready, isValidAwsKeyId, isValidAwsSecret, @@ -68,24 +70,20 @@ describe('DNS-01 validation (mirrors the server)', () => { }) describe('DNS-01 CLI arguments', () => { - it('passes --domain/--provider/--token for cloudflare', () => { - expect( - dns01CliArgs({ - domain: ' sub.example.com ', - provider: 'cloudflare', - token: 'abcdefghijklmnopqrst' - }) - ).toEqual([ - '--domain', - 'sub.example.com', - '--provider', - 'cloudflare', - '--token', - 'abcdefghijklmnopqrst' - ]) + it('never puts the cloudflare token into argv', () => { + // Токен в аргументах виден в /proc//cmdline всем локальным пользователям, + // а серверный выпуск сертификата идёт десятки секунд — поэтому креды уходят + // отдельным файлом 0600 (dns01SecretPayload + dns01SecretFlag). + const args = dns01CliArgs({ + domain: ' sub.example.com ', + provider: 'cloudflare', + token: 'abcdefghijklmnopqrst' + }) + expect(args).toEqual(['--domain', 'sub.example.com', '--provider', 'cloudflare']) + expect(args.join(' ')).not.toContain('abcdefghijklmnopqrst') }) - it('passes AWS credentials for route53 and never a cloudflare token', () => { + it('passes no AWS credentials in argv either', () => { const args = dns01CliArgs({ domain: 'sub.example.com', provider: 'route53', @@ -93,33 +91,37 @@ describe('DNS-01 CLI arguments', () => { awsKeyId: 'AKIAIOSFODNN7EXAMPLE', awsSecret: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY' }) - expect(args).toEqual([ - '--domain', - 'sub.example.com', - '--provider', - 'route53', - '--aws-access-key-id', - 'AKIAIOSFODNN7EXAMPLE', - '--aws-secret-access-key', - 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY' - ]) - expect(args.join(' ')).not.toContain('unused-token-value') + expect(args).toEqual(['--domain', 'sub.example.com', '--provider', 'route53']) + expect(args.join(' ')).not.toContain('AKIA') + expect(args.join(' ')).not.toContain('wJalrXUtnFEMI') }) - it('uses the quickstart prefix for deploy-time DNS-01', () => { + it('builds the secret payload the server parses (key=value)', () => { expect( - dns01CliArgs( - { domain: 'sub.example.com', provider: 'cloudflare', token: 'abcdefghijklmnopqrst' }, - '--dns01-' - ) - ).toEqual([ - '--dns01-domain', - 'sub.example.com', - '--dns01-provider', - 'cloudflare', - '--dns01-token', - 'abcdefghijklmnopqrst' - ]) + dns01SecretPayload({ domain: 'sub.example.com', provider: 'cloudflare', token: ' tok-123 ' }) + ).toBe('token=tok-123\n') + expect( + dns01SecretPayload({ + domain: 'sub.example.com', + provider: 'route53', + awsKeyId: 'AKIAIOSFODNN7EXAMPLE', + awsSecret: 'wJalrXUtnFEMI/K7MDENG' + }) + ).toBe('aws_access_key_id=AKIAIOSFODNN7EXAMPLE\naws_secret_access_key=wJalrXUtnFEMI/K7MDENG\n') + }) + + it('names the server flag, including the quickstart prefix', () => { + expect(dns01SecretFlag()).toBe('--secret-file') + expect(dns01SecretFlag('--dns01-')).toBe('--dns01-secret-file') + }) + + it('uses the quickstart prefix for deploy-time DNS-01', () => { + const args = dns01CliArgs( + { domain: 'sub.example.com', provider: 'cloudflare', token: 'abcdefghijklmnopqrst' }, + '--dns01-' + ) + expect(args).toEqual(['--dns01-domain', 'sub.example.com', '--dns01-provider', 'cloudflare']) + expect(args.join(' ')).not.toContain('abcdefghijklmnopqrst') }) }) From 73fee8b89689a6aa571bd69dfe348cf160ee083d Mon Sep 17 00:00:00 2001 From: Ap3x0 <82464229+Ap3x0s@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:53:45 +0300 Subject: [PATCH 06/13] =?UTF-8?q?docs:=20=D1=81=D0=B5=D0=BA=D1=80=D0=B5?= =?UTF-8?q?=D1=82=D1=8B=20=D0=BD=D0=B5=20=D1=85=D0=BE=D0=B4=D1=8F=D1=82=20?= =?UTF-8?q?=D0=B2=20argv=20=E2=80=94=20=D1=80=D0=B0=D0=B7=D0=B4=D0=B5?= =?UTF-8?q?=D0=BB=20=D0=B1=D0=B5=D0=B7=D0=BE=D0=BF=D0=B0=D1=81=D0=BD=D0=BE?= =?UTF-8?q?=D1=81=D1=82=D0=B8,=20=D1=84=D0=BB=D0=B0=D0=B3=D0=B8=20=D0=B8?= =?UTF-8?q?=20=D1=81=D1=87=D1=91=D1=82=20=D1=82=D0=B5=D1=81=D1=82=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Что добавлено: * `docs/security.md` (ru/en/zh) — раздел «Секреты и аргументы процессов»: почему `/proc//cmdline` (0444) это утечка, а `/proc//environ` (0400) — нет; какие три группы кредов ходили аргументами (токен бота в URL curl каждые 15 минут, sub_token, DNS-токены на всё время выпуска сертификата) и как это закрыто сейчас; примеры `--secret-stdin`/`--secret-file`; честные пределы (ручной ввод в интерактивной строке всё ещё виден, root всё видит в любом случае); * `docs/configuration.md` (ru/en/zh) — новые флаги в строках таблицы `dns01-setup`/`dns01-test`/`repair-dns01`/`alerts-setup`/`quickstart`, а примеры в разделе DNS-01 и Telegram переписаны на безопасную форму (файл 0600 или stdin) с оговоркой, какой вариант видим в `ps`; * `docs/testing.md` (ru/en/zh) — новый `test-secret-argv.sh` в таблице и актуальный счёт (48 вместо 47; в описании CI заодно убрано устаревшее «45»); * `CHANGELOG.md` — секция `[Unreleased]` с блоком Security; * `CLAUDE.md` — счёт валидаций и упоминание новых флагов в описаниях `dns01-setup` и `alerts-setup`, чтобы следующая сессия не предлагала небезопасную форму. Проверено: `check-links.ps1` — 0 битых ссылок и 0 расхождений колонок таблиц; `check-encoding.ps1` — 0 файлов с внеалфавитной кириллицей; `parity.ps1` — новые разделы паритетны (остаточные расхождения в старых разделах были и до этого, они не от этих правок). --- CHANGELOG.md | 29 +++++++++++++++++++++ CLAUDE.md | 6 ++--- docs/configuration.md | 27 +++++++++++++------- docs/ru/configuration.md | 27 +++++++++++++------- docs/ru/security.md | 50 +++++++++++++++++++++++++++++++++++++ docs/ru/testing.md | 3 ++- docs/security.md | 50 +++++++++++++++++++++++++++++++++++++ docs/testing.md | 5 ++-- docs/zh-CN/configuration.md | 26 ++++++++++++------- docs/zh-CN/security.md | 46 ++++++++++++++++++++++++++++++++++ docs/zh-CN/testing.md | 5 ++-- 11 files changed, 239 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed56fb8..eabc903 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,35 @@ User-facing Xrayebator changes. The server manager and Electron application are published from the canonical `howdeploy/Xrayebator` repository. +## [Unreleased] + +Secrets no longer travel in process arguments. `/proc//cmdline` is readable by every local +user (unlike `/proc//environ`, which only the process owner and root can read), so a secret +in an argument is visible to any neighbour account — including the `xray` service account the +proxy runs under. Three groups were exposed: the Telegram bot token inside the `curl` URL of the +monitor's subscription and alert checks (every 15 minutes, so not a one-off), the subscription +`sub_token` in the subscription self-test, and the Cloudflare token / AWS key in the command line +of `dns01-setup`/`dns01-test`/`repair-dns01`/`quickstart` for the whole certificate issuance. +Secrets written by `jq` (Hysteria 2 password, AmneziaWG keys, `sub_token`, the VLESS Encryption +key, the bot token) had the same problem with a millisecond window. + +### Security + +- The Telegram bot token and the subscription `sub_token` are handed to `curl` through a stdin + config (`-K -`) instead of the command line. +- `jq` receives secret values through the environment (`$ENV.XRAYEBATOR_JQ_SECRET`) rather than + `--arg`. +- `dns01-setup`, `dns01-test`, `repair-dns01` and `alerts-setup` accept the credential itself via + `--secret-stdin` or `--secret-file PATH` (payload: `token=…`, `aws_access_key_id=…`, + `aws_secret_access_key=…`); a `--secret-file` wider than `0600` is refused and the file is + deleted right after reading. `quickstart` uses `--dns01-secret-stdin`/`--dns01-secret-file`. + `--token` and `--aws-secret-access-key` keep working but now warn on stderr. +- The desktop GUI uploads the DNS-01 credentials as a `0600` file over SFTP and passes + `--secret-file`/`--dns01-secret-file`, so the token is on neither the local nor the remote + command line. +- New `validation/test-secret-argv.sh` locks the contract in place: a stub `curl` asserts that the + secret is absent from `argv` and present on stdin. + ## [0.7.2] - 2026-11-04 The `0.7.2` security patch: Xray-core moved to `26.10.31` (the urgent release that stops diff --git a/CLAUDE.md b/CLAUDE.md index 0caa43f..c9cb479 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,7 +9,7 @@ Xrayebator — automated Xray Reality VPN manager for bypassing DPI censorship i ## Validation There IS automated test coverage (despite what older notes said): -- **`validation/`** — 42 Bash test scripts, including `test-main-readiness-regressions.sh`, covering migrations, VLESS URL generation, subscription formats (Clash/mihomo YAML + sing-box JSON), DNS-01 certificate wiring, transaction safety, dedup, firewall, menu numbering, the backend registry, the Hysteria 2 backend renderers/lifecycle, the AmneziaWG backend junk/renderers, per-profile traffic accounting and limits, Telegram alerts/monitoring, the bypass/sni-change/port-change/profile-revoke/profile-expire CLIs, the HAPP client-routing generator, update branch pinning, quickstart, email/inspect regressions, apt-lock race regressions, the quickstart http_tls fallback and audit regressions. They run on the host (`bash validation/test-*.sh`); CI installs `jq`, `uuidgen` and `ripgrep` on Ubuntu. A bare Windows Git Bash checkout is not equivalent to the Linux environment. +- **`validation/`** — 48 Bash test scripts, including `test-main-readiness-regressions.sh`, covering migrations, VLESS URL generation, subscription formats (Clash/mihomo YAML + sing-box JSON), DNS-01 certificate wiring, transaction safety, dedup, firewall, menu numbering, the backend registry, the Hysteria 2 backend renderers/lifecycle, the AmneziaWG backend junk/renderers, per-profile traffic accounting and limits, Telegram alerts/monitoring, the bypass/sni-change/port-change/profile-revoke/profile-expire CLIs, the HAPP client-routing generator, update branch pinning, quickstart, email/inspect regressions, apt-lock race regressions, the quickstart http_tls fallback and audit regressions. They run on the host (`bash validation/test-*.sh`); CI installs `jq`, `uuidgen` and `ripgrep` on Ubuntu. A bare Windows Git Bash checkout is not equivalent to the Linux environment. - **`gui-legacy/tests/`** — 16 pytest modules covering SSH, deploy, connection, subscription and TUN runtime (legacy PySide6 GUI). Run with the GUI venv: `gui-legacy/.venv/Scripts/python -m pytest gui-legacy/tests`. - **GUI (Electron)** — Vitest unit tests in `tests/`: `npm test`, plus `npm run typecheck`. - **CI** — `.github/workflows/ci-linux.yml` runs the full `validation/` suite; `.github/workflows/gui-release.yml` runs `ruff` + `pytest gui-legacy/tests` and builds Windows/macOS bundles; `.github/workflows/release.yml` ships the Electron app. @@ -140,7 +140,7 @@ Apart from the interactive menu (`sudo xrayebator`), the script exposes subcomma - `xrayebator happ-setup` — reduced existing-install HAPP path; ensures the subscription service and a usable multi-route profile, verifies a real public TLS endpoint when subscription markers are missing, and prints JSON with `subscription_url`. It does not have the same migration breadth as quickstart. - `xrayebator probe-test` — probe-test candidate SNIs from `sni_list.txt` and print reachability scores. - `xrayebator profiles` — print all profiles as a flat JSON array (used by the GUI "Server settings" page); each entry carries `expire` (epoch seconds, `0` = unlimited), server-local `expire_date` (`YYYY-MM-DD`) for display, `expire_disabled`, and since the multi-protocol stage the additive `backends` object (per-profile hysteria2/awg grants — operator-level credentials, same trust level as the already-exposed `sub_token`). `expire_supported` is present (`true`) only on servers with expiry enforcement; its absence means the server predates the feature and the GUI must not offer expiry. Since the subscription-formats stage the entry also carries `subscription_url_clash` and `subscription_url_singbox` (same token with `?target=` prefilled) — additive, so older GUIs keep working. -- `xrayebator dns01-setup --domain sub.example.com --provider cloudflare|route53 [--token T | --aws-access-key-id K --aws-secret-access-key S] [--email E|--without-email] [--port P] [--staging]` / `dns01-status` / `dns01-test` — DNS-01 subscription TLS (menu `6` → `8`). Proves domain ownership with a TXT record instead of http-01, so **inbound :80 is not required** — this is the documented escape from `http_tls` degradation on hosters that filter port 80. Installs `python3-certbot-dns-cloudflare` / `python3-certbot-dns-route53`, writes provider credentials `0600` root (`DNS01_CLOUDFLARE_INI` = `/etc/letsencrypt/xrayebator-dns01-cloudflare.ini`, `DNS01_AWS_INI` = `…-aws.ini` handed to certbot via `AWS_SHARED_CREDENTIALS_FILE`), runs `_dns01_certbot_args_pure` (`certonly --cert-name D -d D --dns- … --non-interactive --agree-tos --deploy-hook "systemctl reload nginx" [-m E | --register-unsafely-without-email]`), renders `_dns01_nginx_vhost_pure` (one TLS server; deliberately no `listen 80` and no ACME location), registers the cert in `.certbot_owned` via `_certbot_register`, opens only the subscription port with `limit_firewall_port`, writes markers through `_subscription_write_markers … "domain_tls"`, and records the provider in `DNS01_MARKER_FILE` (`/usr/local/etc/xray/.dns01_provider`). `dns01_setup_command` prints only JSON on stdout (progress goes to stderr via the `exec 3>&1` trick) and validates domain/provider/credentials **before** any system call, so failed calls write nothing. Renewal is the standard `certbot.timer` plus the deploy hook — no custom timer. `xrayebator repair-dns01 --domain D --provider P […]` reuses `_dns01_install` to convert a **degraded** `http_tls` subscription to DNS-01 (idempotent: an `ip_tls`/`domain_tls` subscription returns `{"ok":true,"skipped":true}`), and `quickstart --dns01-*` runs the same install as the second fallback — after http-01 failed, before `http_tls` — skipping the IP nginx template and the IP markers exactly like `repair-dns01` does. `uninstall.sh` removes both credential files. Guarded by `validation/test-dns01-certbot.sh` (pure parts functionally, wiring statically — live DNS APIs are not available in CI). +- `xrayebator dns01-setup --domain sub.example.com --provider cloudflare|route53 [--secret-file F | --secret-stdin | --token T | --aws-access-key-id K --aws-secret-access-key S] [--email E|--without-email] [--port P] [--staging]` / `dns01-status` / `dns01-test` — DNS-01 subscription TLS (menu `6` → `8`). Proves domain ownership with a TXT record instead of http-01, so **inbound :80 is not required** — this is the documented escape from `http_tls` degradation on hosters that filter port 80. Installs `python3-certbot-dns-cloudflare` / `python3-certbot-dns-route53`, writes provider credentials `0600` root (`DNS01_CLOUDFLARE_INI` = `/etc/letsencrypt/xrayebator-dns01-cloudflare.ini`, `DNS01_AWS_INI` = `…-aws.ini` handed to certbot via `AWS_SHARED_CREDENTIALS_FILE`), runs `_dns01_certbot_args_pure` (`certonly --cert-name D -d D --dns- … --non-interactive --agree-tos --deploy-hook "systemctl reload nginx" [-m E | --register-unsafely-without-email]`), renders `_dns01_nginx_vhost_pure` (one TLS server; deliberately no `listen 80` and no ACME location), registers the cert in `.certbot_owned` via `_certbot_register`, opens only the subscription port with `limit_firewall_port`, writes markers through `_subscription_write_markers … "domain_tls"`, and records the provider in `DNS01_MARKER_FILE` (`/usr/local/etc/xray/.dns01_provider`). `dns01_setup_command` prints only JSON on stdout (progress goes to stderr via the `exec 3>&1` trick) and validates domain/provider/credentials **before** any system call, so failed calls write nothing. Renewal is the standard `certbot.timer` plus the deploy hook — no custom timer. `xrayebator repair-dns01 --domain D --provider P […]` reuses `_dns01_install` to convert a **degraded** `http_tls` subscription to DNS-01 (idempotent: an `ip_tls`/`domain_tls` subscription returns `{"ok":true,"skipped":true}`), and `quickstart --dns01-*` runs the same install as the second fallback — after http-01 failed, before `http_tls` — skipping the IP nginx template and the IP markers exactly like `repair-dns01` does. `uninstall.sh` removes both credential files. Guarded by `validation/test-dns01-certbot.sh` (pure parts functionally, wiring statically — live DNS APIs are not available in CI). - **ACME staging contour and `dns01-test`.** Let's Encrypt allows 5 certificates per exact set of identifiers per 168 h (refilled one per 34 h) and 5 failed validations per identifier per hour, so a debugging session can block the next meaningful issuance — a live server ended up with `retry after 2026-10-19 02:02:28 UTC`. `--staging` on `dns01-setup` / `repair-dns01` / `quickstart` (or `XRAYEBATOR_ACME_STAGING=1`) resolves through `_acme_staging_on` and adds certbot `--test-cert` (staging allows 30000 orders per week); the run warns loudly, reports `staging:true` in JSON and writes `/usr/local/etc/xray/.acme_staging` (`_acme_staging_mark`). `dns01-status` decides the contour from the **certificate on disk** (issuer containing `(STAGING)`) and uses the mark only as a fallback when the certificate is unreadable — renewals run through `certbot renew` outside xrayebator and would leave the mark stale (verified live: the mark survived while `live/` already held the production certificate, and the status/GUI claimed the subscription was untrusted). The production path now always names the endpoint (`--server "$ACME_PRODUCTION_URL"`): without it a repeat issuance under the same `--cert-name` would inherit the server from its renewal configuration and stay in staging. `xrayebator dns01-test --domain D --provider cloudflare|route53 [--token T | --aws-*] [--email E|--without-email]` is the verification-only issuance: staging, its own lineage (`DNS01_TEST_CERT_NAME` = `xrayebator-dns01-test-`, so a repeat run cannot "pass" on an existing certificate), no deploy hook, no vhost/markers/firewall/subscription side effects, JSON with `issuer`, `not_after`, `txt_name` (`_acme-challenge.`), `cleaned`, and on failure the parsed `_certbot_failure_reason`. Pure seams: `_dns01_test_certbot_args_pure`, `_dns01_resolve_port` (one port rule for both DNS-01 paths: explicit `--port` → current subscription port → `443`; before that the GUI button silently moved a `:8443` subscription to `:443`), `_dns01_renewal_has_hook` (certbot writes `--deploy-hook` as `renew_hook`, so grepping `deploy-hook` reported `deploy_hook:false` on every real domain — `dns01-status` now accepts both spellings). `_dns01_install_plugin` (shared by the real and the test path) picks the certbot that actually reports the provider plugin via `_dns01_pick_certbot`: apt certbot 1.x carries the `dns-*` plugins while snap certbot 5.x carries `--ip-address`, so a `PATH` with `/snap/bin` first would otherwise fail with `unrecognized arguments: --dns-cloudflare`. `_apt_certbot_timer_disable` turns off the distribution `certbot.timer` only when the shortlived IP lineage is renewed by a snap binary (apt certbot cannot handle that lineage and failed twice a day); `_dns01_install` re-enables it for a domain certificate, and `uninstall.sh` restores it if the flag `/usr/local/etc/xray/.apt_certbot_timer_disabled` is present. - `xrayebator profile-pq --name NAME [--transport tcp|tcp-utls|tcp-xudp|tcp-mux|grpc|xhttp]` — add a post-quantum VLESS Encryption route (`mlkem768x25519plus`). VLESS `decryption` is **inbound-level**, so `_pq_add_route_for_profile` picks a free port via `build_transport_defaults` (that function only *chooses* a port — it creates nothing), creates the inbound with `add_inbound` under a `backup_config` snapshot, switches that inbound's `.settings.decryption` to the shared key from `.vless_decryption` via `safe_jq_write`, appends a `-pq` route with `pq_enabled: true` + `schema_version: 2`, and then calls `safe_restart_xray` (rolling the route and the port back if Xray refuses the config) — without the inbound and the restart the route is dead: the port never listens, UFW never opens it and the generated `link` is empty (that was a live defect on Ubuntu 22.04, hidden by a test that pre-created the inbound). The jq variable for the route label is `$lbl`, **not** `$label`: on jq 1.6 (Ubuntu 22.04, Debian 12) the object pair `label: $label` is a syntax error because `label` is a keyword, while jq 1.7 accepts it — `validation/test-jq-keyword-compat.sh` guards that whole class. `_generate_vless_url_pure` therefore derives `encryption=` from `pq_enabled` for **any** transport (a PQ route without `.vless_encryption` returns 1); `_profile_route_matches_live_inbound` requires `decryption != none` for PQ routes and `decryption == none` for plain ones on every transport; the v2ray/base64 body drops all PQ routes because a client without ML-KEM cannot use them (the HAPP body keeps them — HAPP has ML-KEM); the Clash/sing-box renderers skip them with a reason. `profile_pq_command` validates name/transport, refuses duplicates and missing keys, prints only JSON (progress on stderr) and includes the generated link. `profiles` carries the additive `pq_routes` counter (routes with `pq_enabled`), because top-level `.pq_enabled` mirrors only the first route — the GUI's PQ chip reads `pq_routes`. A profile from `profile-create` is in the **single-route shape** (transport/port/SNI only at top level, no `routes`), so `_pq_add_route_for_profile` first expands that shape into `routes` (keeping port/transport/SNI/fingerprint and the `grpc`/`xhttp` metadata) and only then appends `-pq`; appending straight onto an empty `routes` silently dropped the base route from the subscription, from `channel-test` and from `profile-delete` (live 2026-10-20). `profile-pq` likewise refuses a transport that is already post-quantum in the single-route shape — the normal case for `--transport xhttp`, where `profile-create` already sets top-level `pq_enabled` and the inbound `decryption`. Guarded by `validation/test-pq-routes.sh`. - Subscription formats (Clash/mihomo + sing-box): the `subhttp.sh` handler serves four bodies from one token — HAPP, base64 v2ray, Clash/mihomo YAML, sing-box JSON — selected by `?target=clash|mihomo|singbox|sing-box|v2ray|base64|happ` first and then by `User-Agent` (`mihomo`/`clash`/`stash`/`flclash`; `sing-box`/`sfa`/`sfi`/`sfm`/`nekobox`/`hiddify`/`karing`; `v2rayNG`/`v2rayN`), defaulting to the HAPP body so already-issued links keep working. All formats render from the same normalized link set: `_subscription_links_json` parses the `vless://` URLs produced by `_generate_vless_urls_for_profile` (plus the hysteria2 link) into records carrying per-client support flags, `_subscription_render_clash_pure` emits YAML (proxies/proxy-groups/rules, `reality-opts`, `flow`, `client-fingerprint`, `packet-encoding: xudp`, `grpc-opts`, hysteria2) and `_subscription_render_singbox_pure` emits JSON (outbounds, `tls.reality` + `utls`, `transport.type=grpc`, selector/urltest/direct, `route.final`). Routes a client cannot use are skipped with a reason instead of being emitted broken — PQ/VLESS Encryption (neither client supports it), xhttp in sing-box (no such transport), xhttp in Clash without `?xhttp=1` (mihomo ≥ 1.19; an unknown `network` makes mihomo refuse the whole config) — and `subscription-userinfo` is now sent for every format. The handler is regenerated on existing servers by migration `subhttp_formats_2026` (registered in `main_menu`, `quickstart` and `happ-setup`). The body branch for base64 is selected by the resolved `sub_format`, **not** by the UA-derived `universal_sub` flag: `?target=v2ray|base64` used to fall into the HAPP branch and return a plaintext HAPP body (byte-identical, PQ routes included) because only the User-Agent set that flag (live defect 2026-10-20). The HAPP body also no longer drops an xhttp route just because the profile has a legacy `encryption=none` xhttp route: that rule predated HAPP's ML-KEM support and silently removed `xhttp-pq` (7 links in the body vs 8 working routes). Handler changes reach existing servers only through a migration — `subhttp_v2ray_pq_2026` (registered in `main_menu`, `quickstart` and `happ-setup`). Guarded by `validation/test-subscription-formats.sh`. @@ -163,7 +163,7 @@ Apart from the interactive menu (`sudo xrayebator`), the script exposes subcomma - `xrayebator awg-install [--grant-all]` / `awg-uninstall` / `awg-status` / `awg-grant --name N` / `awg-conf --name N` / `awg-31 --on|--off` — AmneziaWG 2.0/3.1 system-VPN backend (multi-protocol slices 4–5 + 3.1 stage, menu items 12/13). Kernel module via DKMS per the AmneziaWG README: primary path is the `amnezia/ppa` PPA (`apt install amneziawg`), fallback is a manual source build (kernels ≥5.6 need the FULL `linux-source` tree linked as the module's `kernel` symlink — headers alone are not enough). The backend is registered in the registry only after `modprobe amneziawg` + `lsmod` confirm the module and `awg show awg0` confirms the interface, and verifies the module through `_awg_verify_module`, which also writes `/etc/modules-load.d/xrayebator-awg.conf` (`AWG_MODULES_LOAD_FILE`) so systemd loads the module at boot: without that file a reboot left `awg-quick@awg0` failed with `Error: Unknown device type`, `awg0` absent and the tunnel dead while the registry still said `installed` (live defect, fixed by the idempotent `awg_module_2026` migration plus `_awg_ensure_runtime`, which `awg-install` re-runs on an existing installation; `awg-uninstall` removes the file, its own `rm -f "$AWG_MODULES_LOAD_FILE"`). The install path judges the PPA branch by `_awg_module_for_kernel` (a `.ko` for the *running* kernel, root override `AWG_MODULES_ROOT` for tests), never by `command -v awg`: a stale binary from an earlier manual build made the branch report success after a kernel upgrade, so the source-build fallback never ran and the module was never rebuilt for the new kernel (live defect: 5.15.0-177 → -198). When `modprobe` still fails, `_awg_verify_module` prints the kernels the module exists for (`_awg_module_kernels`). Server state: `backends/awg/server-params.json` (0600, keys/port/iface/junk) and `awg0.conf` (0600). AWG 3.1 is implemented and ON by default: the generator emits `S1`–`S4` (≥ 12), `HeaderProtectionKey` (random, shared with every client conf) and `RandomTrailers = on` — the `awg` parser (kernel UAPI) accepts booleans as `on`/`off`, NOT `true`/`false`; `DisableCookies` is available via `awg-31 --disable-cookies` (local flag, off by default). `awg-31` toggles the format with an explicit operator warning that every issued client `.conf` must be re-downloaded (clients need AmneziaVPN ≥ 5.0.1.5) and regenerates the interface with rollback; `_awg_ensure_31_params` upgrades legacy (pre-3.1) server params in place. Junk params mirror the Amnezia defaults — the dialect the official AmneziaVPN apps (phone and desktop) apply reliably; their go-tunnel applies custom junk incompletely: Jc=5, Jmin=10, Jmax=50, H1–H4=1..4 (WG magic), S1/S2 random 12..150, S3/S4 random 12..64, all unique with S1+56≠S2. The desktop GUI additionally delivers keys in the app-native `vpn://` shape (`amnezia-awg2` container, server-side junk fields, `protocol_version`; see shared/awg.ts `buildAwgVpnConfig`) — a raw `.conf` pasted into AmneziaVPN does not reach its tunnel intact. `ip_forward` is set via `/etc/sysctl.d/99-xrayebator-awg.conf`. Uninstall tears down the interface and files but leaves the packages/module in the system (documented in output). - AWG peers (slice 5): per-profile peer credentials live in the profile's `.backends.awg` object (`client_private_key`, `client_public_key`, `preshared_key`, `address` `10.8.1.x`, `created`) — profile JSON is the single source of truth; `awg0.conf` `[Peer]` sections are **regenerated** from profiles (`_awg_regen_config`, filter `.expire_disabled == false`, so expired/restored events are just a regen) and applied via `_awg_apply_config` (interface restart with rollback; the restart briefly drops the tunnel for all peers — accepted for stage 1, grants/revokes are rare). Address allocation picks the first free `.2..254` honoring addresses already issued to profiles. The lifecycle choke point dispatches to `_awg_on_profile_event` automatically for installed backends — deleted/revoked/expired/restored need no extra wiring in profile flows (created is a no-op: no auto-grant, keys are issued only by explicit `awg-grant`; the `deleted` case regenerates unconditionally because the caller removes the profile file BEFORE the lifecycle call). Client config (`_awg_client_conf_pure`) carries the client keypair, the server pubkey/endpoint, junk params copied from the server, `AllowedIPs = 0.0.0.0/0, ::/0` (full tunnel) and `PersistentKeepalive = 25`; `awg-conf --name N` returns it as JSON `{ok, name, conf}` for the GUI, the menu prints it with an optional QR. Peer events: revoked = keypair+PSK rotation with the address kept (old client configs stop connecting). Package installation itself (network + DKMS build) and a real client connection are verified in the live spike, not CI. -- `xrayebator alerts-setup --token T --chat-id C` / `alerts-status` / `alerts-test` / `alerts-enable|alerts-disable` / `monitor-check [--force-sni]` — Telegram alerting for server monitoring (menu item 14). It is **terminal-only by design**: the desktop GUI has no alerts surface at all (no IPC channel, no settings card, no i18n keys), so the bot token has exactly one entry point. Config is `alerts.json` (0600 root: bot token + chat_id + bot username) in the neutral root `/usr/local/etc/xrayebator/` — deliberately NOT in `/usr/local/etc/xray/`, which stays Xray-only; the token is never printed, including by `alerts-status`. `alerts-setup` validates the token with `getMe` and delivers a test message to the chat BEFORE writing the config, so an undeliverable chat never leaves a half-configured setup, and it installs `xrayebator-monitor.timer`. That timer runs `monitor-check` every 15 minutes (`TimeoutStartSec=300` — the SNI probe can exceed the 90 s oneshot default, and a killed iteration would skip state finalization). What it watches: `xray.service`, `xrayebator-sub.service` (only if its unit exists) and `nginx.service` (only if enabled); installed backends — `hysteria-server.service` and `awg show awg0`, gated by the registry so a fresh server gets no phantom alerts; profile expiry (approaching within `ALERTS_EXPIRE_WARN_SEC` and already expired, aggregated into one signature so the message lists names); profiles disabled by a traffic limit; subscription liveness (loopback `:8080/sub/` → 200 plus `vless://`/`hysteria2://`) and TLS-mode degradation (`http_tls`/`local_only` means Let's Encrypt could not validate http-01); a daily SNI probe over the SNIs profiles actually use (`ALERTS_SNI_INTERVAL_SEC`, `ALERTS_SNI_TIMEOUT`; same strict criterion as `probe-test` and SNI selection — `_sni_tls_output_ok_pure`, i.e. a completed TLS 1.3 handshake with a verified certificate, not the bare `Verify return code: 0`; curl HTTP code as fallback only when openssl is absent); and reboots via `boot_id` (edge-triggered). Dedup/retry state lives in `monitor-state.json`: a repeat of a bad event is not sent more often than `ALERTS_REMIND_SEC`, a recovery is a separate message, a failed send records no state so the next tick retries, the last SNI probe result is cached so retries and idle ticks never re-run the expensive probe (`--force-sni` forces it), and `boot_id` is persisted only after the reboot alert is delivered — otherwise that message would be lost forever. `_monitor_*` helpers are the test seams (`_monitor_boot_id`, `_monitor_awg_up`, `_monitor_sub_dir`, `_monitor_sub_local_base`, `_monitor_hysteria_unit`, `_monitor_sni_reachable`). Migration `alerts_monitor_2026` is registered in `main_menu`, `quickstart` and `happ-setup`; `uninstall.sh` disables the timer and removes the neutral root (the bot token lives there); it also tears installed backends down first (`hysteria-server.service`, `awg-quick@awg0`, the `awg0` interface, the AWG `modules-load.d` entry, the Hysteria binary/sysctl/deploy-hook), so no enabled unit survives with a deleted config — the AmneziaWG package and kernel module themselves stay. Guarded by `validation/test-alerts-monitor.sh`. +- `xrayebator alerts-setup [--secret-file F | --secret-stdin | --token T] --chat-id C` / `alerts-status` / `alerts-test` / `alerts-enable|alerts-disable` / `monitor-check [--force-sni]` — Telegram alerting for server monitoring (menu item 14). It is **terminal-only by design**: the desktop GUI has no alerts surface at all (no IPC channel, no settings card, no i18n keys), so the bot token has exactly one entry point. Config is `alerts.json` (0600 root: bot token + chat_id + bot username) in the neutral root `/usr/local/etc/xrayebator/` — deliberately NOT in `/usr/local/etc/xray/`, which stays Xray-only; the token is never printed, including by `alerts-status`. `alerts-setup` validates the token with `getMe` and delivers a test message to the chat BEFORE writing the config, so an undeliverable chat never leaves a half-configured setup, and it installs `xrayebator-monitor.timer`. That timer runs `monitor-check` every 15 minutes (`TimeoutStartSec=300` — the SNI probe can exceed the 90 s oneshot default, and a killed iteration would skip state finalization). What it watches: `xray.service`, `xrayebator-sub.service` (only if its unit exists) and `nginx.service` (only if enabled); installed backends — `hysteria-server.service` and `awg show awg0`, gated by the registry so a fresh server gets no phantom alerts; profile expiry (approaching within `ALERTS_EXPIRE_WARN_SEC` and already expired, aggregated into one signature so the message lists names); profiles disabled by a traffic limit; subscription liveness (loopback `:8080/sub/` → 200 plus `vless://`/`hysteria2://`) and TLS-mode degradation (`http_tls`/`local_only` means Let's Encrypt could not validate http-01); a daily SNI probe over the SNIs profiles actually use (`ALERTS_SNI_INTERVAL_SEC`, `ALERTS_SNI_TIMEOUT`; same strict criterion as `probe-test` and SNI selection — `_sni_tls_output_ok_pure`, i.e. a completed TLS 1.3 handshake with a verified certificate, not the bare `Verify return code: 0`; curl HTTP code as fallback only when openssl is absent); and reboots via `boot_id` (edge-triggered). Dedup/retry state lives in `monitor-state.json`: a repeat of a bad event is not sent more often than `ALERTS_REMIND_SEC`, a recovery is a separate message, a failed send records no state so the next tick retries, the last SNI probe result is cached so retries and idle ticks never re-run the expensive probe (`--force-sni` forces it), and `boot_id` is persisted only after the reboot alert is delivered — otherwise that message would be lost forever. `_monitor_*` helpers are the test seams (`_monitor_boot_id`, `_monitor_awg_up`, `_monitor_sub_dir`, `_monitor_sub_local_base`, `_monitor_hysteria_unit`, `_monitor_sni_reachable`). Migration `alerts_monitor_2026` is registered in `main_menu`, `quickstart` and `happ-setup`; `uninstall.sh` disables the timer and removes the neutral root (the bot token lives there); it also tears installed backends down first (`hysteria-server.service`, `awg-quick@awg0`, the `awg0` interface, the AWG `modules-load.d` entry, the Hysteria binary/sysctl/deploy-hook), so no enabled unit survives with a deleted config — the AmneziaWG package and kernel module themselves stay. Guarded by `validation/test-alerts-monitor.sh`. CLI JSON hygiene: `profile-create`/`profile-delete` **must** print only JSON on stdout. The shared helpers (`backup_config`, `add_inbound`, `open_firewall_port`, `safe_restart_xray`, `close_firewall_port`) print colored status lines that would corrupt the parse, so the CLI paths redirect stdout→stderr around those calls (`exec 3>&1; exec 1>&2 ... exec 1>&3`). Keep it that way when editing. ### HAPP profile vs GUI quickstart — a subtle case diff --git a/docs/configuration.md b/docs/configuration.md index 5a8d818..2328d6d 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -116,7 +116,7 @@ is a client-side profile/route setting; changing it does not restart Xray or alt | `sudo xrayebator update ` | Self-update the manager from the canonical raw repository branch, continue with the new script, then update Xray-core; the branch is pinned in `.current_branch` for later GUI updates | | `sudo xrayebator probe-test` | Check SNI reachability from the VPS before switching | | `sudo xrayebator channel-test [--name NAME] [--url URL] [--timeout S] [--transport T]` | Verify that the profile's channels **actually work**: for every route a local Xray client (SOCKS5 on loopback) is started with the parameters from the subscription link, and a real internet request goes out through it; the JSON carries `working`/`checked` and, per route, `ok`, `http`, `ms`, `pq` plus the client log tail. **No Let's Encrypt involvement** — Reality and VLESS Encryption are self-contained, so the check works on an `http_tls` subscription and before any certificate is issued; PQ routes are covered too. Live run: 8/8 routes, 152–252 ms | -| `sudo xrayebator quickstart --email
` | One-shot deploy path used by the desktop GUI: runs the broad setup/migration path, provisions the current IP-TLS endpoint on `8443`, and creates a standard HAPP profile with `schema_version: 3` and 7 routes; emits JSON with `subscription_url`. Optional flags: `--pq` — add a PQ route on tcp to the profile (OFF by default: a client without ML-KEM cannot connect to the PQ port; the result lands in the JSON as `pq_route`), `--without-pq` — disable it explicitly, `--dns01-domain D --dns01-provider cloudflare\|route53 (--dns01-token T \| --dns01-aws-access-key-id K --dns01-aws-secret-access-key S)` — deploy-time DNS-01 fallback. DNS-01 parameters are validated **before** any system change: an incomplete set returns `{"ok":false,…}` and touches nothing | +| `sudo xrayebator quickstart --email
` | One-shot deploy path used by the desktop GUI: runs the broad setup/migration path, provisions the current IP-TLS endpoint on `8443`, and creates a standard HAPP profile with `schema_version: 3` and 7 routes; emits JSON with `subscription_url`. Optional flags: `--pq` — add a PQ route on tcp to the profile (OFF by default: a client without ML-KEM cannot connect to the PQ port; the result lands in the JSON as `pq_route`), `--without-pq` — disable it explicitly, `--dns01-domain D --dns01-provider cloudflare\|route53 (--dns01-secret-file F \| --dns01-secret-stdin)` — credentials in a `0600` file or on stdin (invisible in `/proc`), `--dns01-token T \| --dns01-aws-access-key-id K --dns01-aws-secret-access-key S` — the compatible-but-visible-in-`ps` variant — deploy-time DNS-01 fallback. DNS-01 parameters are validated **before** any system change: an incomplete set returns `{"ok":false,…}` and touches nothing | | `sudo xrayebator quickstart --without-email` | Same new-server path without an ACME contact email; Certbot uses `--register-unsafely-without-email`, so no renewal notices or email-based account recovery are available | | `sudo xrayebator inspect --json` | Read-only GUI import probe: reports manager, Xray, profile and subscription markers without installing, migrating or changing services/configuration | | `sudo xrayebator happ-setup` | Reduced existing-install HAPP path: ensures the subscription service and a usable multi-route profile, but does not replace the endpoint prerequisite; when `.subscription_domain` or `.subscription_port` is missing, it verifies a real public TLS endpoint before writing markers and otherwise fails | @@ -155,11 +155,11 @@ is a client-side profile/route setting; changing it does not restart Xray or alt | `sudo xrayebator awg-grant --name N` | Issue a per-profile peer (keypair + preshared key + `10.8.1.x` address in the profile's `.backends.awg`); `awg0.conf` is regenerated; prints JSON | | `sudo xrayebator awg-conf --name N` | Print the client `.conf` for a profile peer as JSON `{ok, name, conf}` — full-tunnel AllowedIPs, server junk parameters, endpoint; import into the AmneziaWG/AmneziaVPN client | | `sudo xrayebator awg-31 --on\|--off` | Toggle the AWG 3.1 config format (`HeaderProtectionKey`, `RandomTrailers`, `S3`/`S4`); 3.1 is on by default for new installs, the toggle upgrades legacy server params in place, warns that every issued client `.conf` must be re-downloaded (AmneziaVPN ≥ 5.0.1.5) and regenerates the interface with rollback | -| `sudo xrayebator dns01-setup --domain sub.example.com --provider cloudflare\|route53 [--port P] [--staging]` | HTTPS subscription by domain through DNS-01: port 80 is not needed, ownership is proven by a TXT record. Writes `0600` credentials, issues the certbot certificate with a deploy-hook, brings up an nginx vhost without `listen 80` and switches the markers to `domain_tls`; prints JSON. The port defaults to the current subscription port (otherwise `443`) so the published URL keeps its port; `--staging` issues from the Let's Encrypt staging environment (`--test-cert`, no production quota spent) and reports `staging:true` — clients do not trust such a certificate | -| `sudo xrayebator dns01-test --domain sub.example.com --provider cloudflare\|route53 [--token T \| --aws-*] [--email E\|--without-email]` | Verify a domain and a DNS-provider token **without touching the subscription and without spending production quota**: a staging-only issuance into its own certificate lineage, no deploy hook, no nginx/markers/firewall changes. Prints JSON with the issuer, the certificate end date, the `_acme-challenge.` TXT record to check, and the parsed certbot reason on failure | +| `sudo xrayebator dns01-setup --domain sub.example.com --provider cloudflare\|route53 [--port P] [--staging] [--secret-file F \| --secret-stdin]` | HTTPS subscription by domain through DNS-01: port 80 is not needed, ownership is proven by a TXT record. Writes `0600` credentials, issues the certbot certificate with a deploy-hook, brings up an nginx vhost without `listen 80` and switches the markers to `domain_tls`; prints JSON. The port defaults to the current subscription port (otherwise `443`) so the published URL keeps its port; `--staging` issues from the Let's Encrypt staging environment (`--test-cert`, no production quota spent) and reports `staging:true` — clients do not trust such a certificate | +| `sudo xrayebator dns01-test --domain sub.example.com --provider cloudflare\|route53 [--secret-file F \| --secret-stdin \| --token T \| --aws-*] [--email E\|--without-email]` | Verify a domain and a DNS-provider token **without touching the subscription and without spending production quota**: a staging-only issuance into its own certificate lineage, no deploy hook, no nginx/markers/firewall changes. Prints JSON with the issuer, the certificate end date, the `_acme-challenge.` TXT record to check, and the parsed certbot reason on failure | | `sudo xrayebator dns01-status` | DNS-01 state: provider, mode, domain, port, presence of credentials, certificate lifetime in days, whether the deploy-hook is present (certbot stores it as `renew_hook`) and whether the subscription sits on a staging certificate; prints JSON | -| `sudo xrayebator repair-dns01 --domain sub.example.com --provider cloudflare\|route53 [--token T \| --aws-*] [--email E] [--port P]` | Replace a degraded (`http_tls`) subscription with DNS-01: the same TXT-record issuance, the vhost is re-rendered with a TLS server only, and the markers become `domain_tls`. Idempotent: if the subscription is already on HTTPS (`ip_tls`/`domain_tls`) it returns `{"ok":true,"skipped":true}` and does nothing; prints JSON | -| `sudo xrayebator alerts-setup --token T --chat-id C` | Connect Telegram notifications: validates the token through `getMe`, sends a test message and **only after successful delivery** saves `alerts.json` (0600) and enables `xrayebator-monitor.timer`; prints JSON | +| `sudo xrayebator repair-dns01 --domain sub.example.com --provider cloudflare\|route53 [--secret-file F \| --secret-stdin \| --token T \| --aws-*] [--email E] [--port P]` | Replace a degraded (`http_tls`) subscription with DNS-01: the same TXT-record issuance, the vhost is re-rendered with a TLS server only, and the markers become `domain_tls`. Idempotent: if the subscription is already on HTTPS (`ip_tls`/`domain_tls`) it returns `{"ok":true,"skipped":true}` and does nothing; prints JSON | +| `sudo xrayebator alerts-setup [--token T \| --secret-file F \| --secret-stdin] --chat-id C` | Connect Telegram notifications: validates the token through `getMe`, sends a test message and **only after successful delivery** saves `alerts.json` (0600) and enables `xrayebator-monitor.timer`; prints JSON | | `sudo xrayebator alerts-status` | Monitoring state: config, timer, last check time, events and the result of the last SNI probe (the bot token is never shown); prints JSON | | `sudo xrayebator alerts-test` | Send a test message to the configured chat (delivery check); prints JSON | | `sudo xrayebator alerts-enable\|alerts-disable` | Turn delivery on or off without deleting the settings (a kill switch that keeps the token); prints JSON | @@ -549,6 +549,10 @@ Setup happens from the menu (`14`) or the CLI. The bot token is issued by `@BotF `chat_id` by `@userinfobot` (for groups it is negative): ```bash +# The token stays out of the command line (any local user can read it in /proc): +printf 'token=%s\n' "$TG_TOKEN" | sudo xrayebator alerts-setup --secret-stdin \ + --chat-id -1001234567890 +# Compatible, but visible in ps: sudo xrayebator alerts-setup --token 123456:AA... --chat-id -1001234567890 sudo xrayebator alerts-status # timer, last check, events, SNI sudo xrayebator alerts-test # test message @@ -608,13 +612,18 @@ record, so port 80 is not needed at all, and the subscription lives on its own d `https://sub.example.com/sub/`. ```bash -# Cloudflare: an API token with the DNS:Edit right on the zone +# Cloudflare: an API token with the DNS:Edit right on the zone. The token travels in a +# 0600 file (or on stdin), not as an argument: issuance takes tens of seconds and the +# process arguments are readable by every local user (see security.md). +sudo install -m 600 /dev/null /root/.cf +printf 'token=%s\n' "$CF_TOKEN" | sudo tee /root/.cf >/dev/null sudo xrayebator dns01-setup --domain sub.example.com --provider cloudflare \ - --token CF_API_TOKEN --email admin@example.com + --secret-file /root/.cf --email admin@example.com # Route53: keys with the Route53:ChangeResourceRecordSets right -sudo xrayebator dns01-setup --domain sub.example.com --provider route53 \ - --aws-access-key-id AKIA... --aws-secret-access-key ... --without-email +printf 'aws_access_key_id=%s\naws_secret_access_key=%s\n' "$AWS_KEY" "$AWS_SECRET" \ + | sudo xrayebator dns01-setup --domain sub.example.com --provider route53 \ + --secret-stdin --without-email sudo xrayebator dns01-status # provider, domain, port, certificate lifetime, deploy-hook ``` diff --git a/docs/ru/configuration.md b/docs/ru/configuration.md index c925528..d8a2487 100644 --- a/docs/ru/configuration.md +++ b/docs/ru/configuration.md @@ -119,7 +119,7 @@ legacy-файлы и блоки, ранее созданные Xrayebator, и с | `sudo xrayebator update ` | Self-update менеджера из canonical raw-репозитория (ветка branch), продолжить новым скриптом, затем обновить Xray-core; ветка закрепляется в `.current_branch` для последующих обновлений из GUI | | `sudo xrayebator probe-test` | Проверить SNI reachability с VPS | | `sudo xrayebator channel-test [--name ИМЯ] [--url URL] [--timeout S] [--transport T]` | Проверить, что каналы профиля **реально работают**: для каждого маршрута поднимается локальный клиент Xray (SOCKS5 на loopback) с параметрами из ссылки подписки, и через него уходит настоящий запрос в интернет; JSON содержит `working`/`checked` и по маршруту `ok`, `http`, `ms`, `pq` и хвост лога клиента. **Let's Encrypt не участвует** — Reality и VLESS Encryption самодостаточны, поэтому проверка работает и на `http_tls`-подписке, и до выпуска сертификата; PQ-маршруты тоже проверяются. Живой прогон: 8/8 маршрутов, 152–252 мс | -| `sudo xrayebator quickstart --email <адрес>` | Путь одноразового деплоя (используется GUI): broad setup/migration, IP-TLS endpoint на `8443` и стандартный schema-v3 HAPP-профиль из 7 маршрутов; выводит JSON с `subscription_url`. Migration calls best-effort, проверяйте итоговый профиль и сервисы. Дополнительные флаги: `--pq` — добавить профилю PQ-маршрут на tcp (по умолчанию **выключено**: клиент без ML-KEM к PQ-порту не подключится; результат в JSON — `pq_route`), `--without-pq` — явно выключить, `--dns01-domain D --dns01-provider cloudflare\|route53 (--dns01-token T \| --dns01-aws-access-key-id K --dns01-aws-secret-access-key S)` — DNS-01-фолбэк развёртывания. Параметры DNS-01 проверяются **до** системных изменений: неполный набор возвращает `{"ok":false,…}` и ничего не трогает | +| `sudo xrayebator quickstart --email <адрес>` | Путь одноразового деплоя (используется GUI): broad setup/migration, IP-TLS endpoint на `8443` и стандартный schema-v3 HAPP-профиль из 7 маршрутов; выводит JSON с `subscription_url`. Migration calls best-effort, проверяйте итоговый профиль и сервисы. Дополнительные флаги: `--pq` — добавить профилю PQ-маршрут на tcp (по умолчанию **выключено**: клиент без ML-KEM к PQ-порту не подключится; результат в JSON — `pq_route`), `--without-pq` — явно выключить, `--dns01-domain D --dns01-provider cloudflare\|route53 (--dns01-secret-file F \| --dns01-secret-stdin)` — креды файлом 0600 или через stdin (не видны в `/proc`), `--dns01-token T \| --dns01-aws-access-key-id K --dns01-aws-secret-access-key S` — совместимый, но видимый в `ps` вариант — DNS-01-фолбэк развёртывания. Параметры DNS-01 проверяются **до** системных изменений: неполный набор возвращает `{"ok":false,…}` и ничего не трогает | | `sudo xrayebator quickstart --without-email` | Тот же путь развёртывания без ACME email; Certbot регистрирует аккаунт с `--register-unsafely-without-email`, поэтому уведомления и восстановление аккаунта по email недоступны. Если LE не может проверить http-01 (хостер фильтрует порт 80), quickstart деградирует в `http_tls`: подписка поднимается по HTTP, JSON несёт `degraded:true`, повторный деплой после разблокировки :80 возвращает HTTPS | | `sudo xrayebator inspect --json` | Read-only проверка установки для GUI-импорта: возвращает состояние Xray, профилей и маркеров подписки; не запускает установку, миграции или изменения конфигурации | | `sudo xrayebator happ-setup` | Сокращённый re-entry на существующей установке: проверяет subscription service и usable multi-route profile; при отсутствии markers проверяет IP-TLS endpoint на `8443`, но не фабрикует markers | @@ -158,11 +158,11 @@ legacy-файлы и блоки, ранее созданные Xrayebator, и с | `sudo xrayebator awg-grant --name N` | Выдать per-profile peer (ключевая пара + preshared key + адрес `10.8.1.x` в `.backends.awg` профиля); `awg0.conf` регенерируется; JSON | | `sudo xrayebator awg-conf --name N` | Клиентский `.conf` peer-а профиля в JSON `{ok, name, conf}` — full-tunnel AllowedIPs, серверные junk-параметры, endpoint; импорт в клиент AmneziaWG/AmneziaVPN | | `sudo xrayebator awg-31 --on\|--off` | Переключить формат конфига AWG 3.1 (`HeaderProtectionKey`, `RandomTrailers`, `S3`/`S4`); для новых установок 3.1 включён по умолчанию, тумблер досоздаёт недостающие параметры сервера на месте, предупреждает, что все выданные клиентские `.conf` нужно скачать заново (AmneziaVPN ≥ 5.0.1.5), и регенерирует интерфейс с откатом | -| `sudo xrayebator dns01-setup --domain sub.example.com --provider cloudflare\|route53 [--port P] [--staging]` | HTTPS-подписка по домену через DNS-01: порт 80 не нужен, сертификат проверяется TXT-записью. Пишет credentials `0600`, выпускает certbot-сертификат с deploy-hook, поднимает nginx-vhost без `listen 80` и переводит маркеры в `domain_tls`; JSON. Порт по умолчанию — текущий порт подписки (иначе `443`), поэтому URL сохраняет свой порт; `--staging` выпускает сертификат в staging-контуре Let's Encrypt (`--test-cert`, прод-квота не расходуется) и отдаёт `staging:true` — клиенты такой сертификат не принимают | -| `sudo xrayebator dns01-test --domain sub.example.com --provider cloudflare\|route53 [--token T \| --aws-*] [--email E\|--without-email]` | Проверить домен и токен DNS-провайдера, **не трогая подписку и не расходуя прод-квоту**: выпуск только в staging-контуре, в отдельную линию сертификата, без deploy-hook и без изменений nginx/маркеров/firewall. JSON содержит издателя, срок сертификата, TXT-запись `_acme-challenge.` для проверки и разобранную причину отказа certbot | +| `sudo xrayebator dns01-setup --domain sub.example.com --provider cloudflare\|route53 [--port P] [--staging] [--secret-file F \| --secret-stdin]` | HTTPS-подписка по домену через DNS-01: порт 80 не нужен, сертификат проверяется TXT-записью. Пишет credentials `0600`, выпускает certbot-сертификат с deploy-hook, поднимает nginx-vhost без `listen 80` и переводит маркеры в `domain_tls`; JSON. Порт по умолчанию — текущий порт подписки (иначе `443`), поэтому URL сохраняет свой порт; `--staging` выпускает сертификат в staging-контуре Let's Encrypt (`--test-cert`, прод-квота не расходуется) и отдаёт `staging:true` — клиенты такой сертификат не принимают | +| `sudo xrayebator dns01-test --domain sub.example.com --provider cloudflare\|route53 [--secret-file F \| --secret-stdin \| --token T \| --aws-*] [--email E\|--without-email]` | Проверить домен и токен DNS-провайдера, **не трогая подписку и не расходуя прод-квоту**: выпуск только в staging-контуре, в отдельную линию сертификата, без deploy-hook и без изменений nginx/маркеров/firewall. JSON содержит издателя, срок сертификата, TXT-запись `_acme-challenge.` для проверки и разобранную причину отказа certbot | | `sudo xrayebator dns01-status` | Состояние DNS-01: провайдер, режим, домен, порт, наличие credentials, срок сертификата в днях, наличие deploy-hook (certbot пишет его как `renew_hook`) и признак того, что подписка на staging-сертификате; JSON | -| `sudo xrayebator repair-dns01 --domain sub.example.com --provider cloudflare\|route53 [--token T \| --aws-*] [--email E] [--port P]` | Заменить деградированную (`http_tls`) подписку на DNS-01: тот же выпуск сертификата по TXT-записи, vhost перерисовывается только с TLS-сервером, маркеры становятся `domain_tls`. Идемпотентно: если подписка уже на HTTPS (`ip_tls`/`domain_tls`), возвращает `{"ok":true,"skipped":true}` и ничего не делает; JSON | -| `sudo xrayebator alerts-setup --token T --chat-id C` | Подключить Telegram-уведомления: проверяет токен через `getMe`, отправляет тестовое сообщение и **только после успешной доставки** сохраняет `alerts.json` (0600) и включает `xrayebator-monitor.timer`; JSON | +| `sudo xrayebator repair-dns01 --domain sub.example.com --provider cloudflare\|route53 [--secret-file F \| --secret-stdin \| --token T \| --aws-*] [--email E] [--port P]` | Заменить деградированную (`http_tls`) подписку на DNS-01: тот же выпуск сертификата по TXT-записи, vhost перерисовывается только с TLS-сервером, маркеры становятся `domain_tls`. Идемпотентно: если подписка уже на HTTPS (`ip_tls`/`domain_tls`), возвращает `{"ok":true,"skipped":true}` и ничего не делает; JSON | +| `sudo xrayebator alerts-setup [--token T \| --secret-file F \| --secret-stdin] --chat-id C` | Подключить Telegram-уведомления: проверяет токен через `getMe`, отправляет тестовое сообщение и **только после успешной доставки** сохраняет `alerts.json` (0600) и включает `xrayebator-monitor.timer`; JSON | | `sudo xrayebator alerts-status` | Состояние мониторинга: конфиг, таймер, время последней проверки, события и результат последней SNI-пробы (токен бота не показывается); JSON | | `sudo xrayebator alerts-test` | Тестовое сообщение в настроенный чат (проверка доставки); JSON | | `sudo xrayebator alerts-enable\|alerts-disable` | Включить или выключить доставку, не удаляя настройки (килл-свитч без потери токена); JSON | @@ -544,6 +544,10 @@ sudo xrayebator profiles | jq '.[] | {name, traffic_used, traffic_limit, traffic (у групп он отрицательный): ```bash +# Токен не попадает в командную строку (её видит любой пользователь хоста через /proc): +printf 'token=%s\n' "$CF_TOKEN" | sudo xrayebator alerts-setup --secret-stdin \ + --chat-id -1001234567890 +# Совместимый, но видимый в `ps` вариант: sudo xrayebator alerts-setup --token 123456:AA... --chat-id -1001234567890 sudo xrayebator alerts-status # таймер, последняя проверка, события, SNI sudo xrayebator alerts-test # тестовое сообщение @@ -600,13 +604,18 @@ sudo xrayebator profiles | jq '.[] | select(.name == "ИМЯ") | .routes' не нужен вовсе, а подписка живёт по своему домену: `https://sub.example.com/sub/`. ```bash -# Cloudflare: API-token с правом DNS:Edit на зону +# Cloudflare: API-token с правом DNS:Edit на зону. Токен уходит файлом 0600 (или +# stdin), а не аргументом: выпуск сертификата идёт десятки секунд, и всё это время +# аргументы процесса видны любому пользователю хоста (см. security.md). +sudo install -m 600 /dev/null /root/.cf +printf 'token=%s\n' "$CF_TOKEN" | sudo tee /root/.cf >/dev/null sudo xrayebator dns01-setup --domain sub.example.com --provider cloudflare \ - --token CF_API_TOKEN --email admin@example.com + --secret-file /root/.cf --email admin@example.com # Route53: ключи с правом Route53:ChangeResourceRecordSets -sudo xrayebator dns01-setup --domain sub.example.com --provider route53 \ - --aws-access-key-id AKIA... --aws-secret-access-key ... --without-email +printf 'aws_access_key_id=%s\naws_secret_access_key=%s\n' "$AWS_KEY" "$AWS_SECRET" \ + | sudo xrayebator dns01-setup --domain sub.example.com --provider route53 \ + --secret-stdin --without-email sudo xrayebator dns01-status # провайдер, домен, порт, срок сертификата, deploy-hook ``` diff --git a/docs/ru/security.md b/docs/ru/security.md index 44e7d17..c85ec1d 100644 --- a/docs/ru/security.md +++ b/docs/ru/security.md @@ -220,6 +220,56 @@ unattended-upgrades всё принёс. `kernel-guard --status` показыв прокси, потому что это бьёт по клиентам, которым MPTCP полезен. Мы следуем решению Xray как дополнительному слою, а не как замене обновления ядра. +## Секреты и аргументы процессов + +Командную строку процесса читает **любой** локальный пользователь: `/proc//cmdline` +доступен на чтение всем (`0444`), а `/proc//environ` — только владельцу процесса и root +(`0400`). На VPN-сервере это значит, что непривилегированный аккаунт — в том числе служебный +пользователь `xray`, под которым работает сам прокси, — может прочитать аргументы любого +root-процесса. Секрет, переданный аргументом, — это секрет, отданный каждому, кто получил +выполнение кода на хосте, и любому соседнему аккаунту через обычный `ps aux`. + +До 0.7.2 так ходили три группы кредов: + +* **токен Telegram-бота** в URL процесса `curl` (`…/bot/sendMessage`). Это была не + разовая утечка: таймер монитора запускает проверку каждые 15 минут, поэтому процесс с токеном + в командной строке существовал на каждом тике и при каждой отправке алерта; +* **`sub_token`** подписки в URL проверки loopback-хендлера; +* **API-токен Cloudflare / секретный ключ AWS** в командной строке `xrayebator dns01-setup`, + `dns01-test`, `repair-dns01` и `quickstart` — там он жил всё время выпуска сертификата: 30 с + ожидания DNS-распространения плюс работа certbot. Сам certbot аргументами их не получал (ini-файл + для Cloudflare, `AWS_SHARED_CREDENTIALS_FILE` для Route53, оба `0600`), так что единственной + точкой утечки была именно командная строка менеджера. + +Теперь каждое из этих значений обходит список аргументов: + +* HTTP-клиенты (`curl`) получают URL через stdin-конфиг (`-K -`), поэтому токена в их аргументах + нет; +* `jq` получает значение через окружение и читает его как `$ENV.XRAYEBATOR_JQ_SECRET` — это + пароль Hysteria 2, приватный ключ и PresharedKey AmneziaWG, `sub_token`, ключ VLESS Encryption + и токен бота в момент записи в JSON; +* CLI принимает сам секрет из stdin или из файла: + + ```bash + # токен не попадает ни в argv, ни в history + printf 'token=%s\n' "$CF_TOKEN" | sudo xrayebator dns01-setup \ + --domain sub.example.com --provider cloudflare --secret-stdin --without-email + sudo install -m 600 /dev/null /root/.cf && printf 'token=%s\n' "$CF_TOKEN" | sudo tee /root/.cf + sudo xrayebator dns01-setup --domain sub.example.com --provider cloudflare --secret-file /root/.cf + ``` + + Пейлоад — строки `key=value` (`token=…`, `aws_access_key_id=…`, `aws_secret_access_key=…`); + одиночная строка без `=` считается токеном. `--secret-file` отвергает файл, доступный группе + или другим, и удаляет его сразу после чтения, поэтому на диске секрет живёт миллисекунды. + Десктоп-GUI загружает файл по SFTP с правами `0600` и передаёт путь — визард DNS-01 больше не + кладёт токен ни в одну командную строку. + +`--token` и `--aws-secret-access-key` продолжают работать для совместимости, но теперь печатают +в stderr предупреждение о видимости. Остаются две честные оговорки: секрет, набранный прямо в +интерактивной командной строке, виден, пока эта команда работает (используйте `--secret-stdin`), +а передача через окружение защищает значение от других пользователей, но не от root — всё, что +работает как root, прочитает на хосте любой секрет. + ## Пароли в десктоп-GUI Активный Electron-GUI поддерживает SSH по паролю и приватному ключу, с прямым root или sudo. Выбранный через нативный dialog приватный ключ main process сохраняет через `keytar` в системное хранилище ОС (Windows Credential Manager, macOS Keychain или Linux Secret Service). Поэтому ключ можно повторно использовать для SSH-операций и после перезапуска приложения. Renderer получает только несекретный credential id и отображаемое имя файла; байты приватного ключа не переходят через preload boundary. diff --git a/docs/ru/testing.md b/docs/ru/testing.md index 9f37d2d..ae23fe8 100644 --- a/docs/ru/testing.md +++ b/docs/ru/testing.md @@ -36,7 +36,7 @@ Linux-машину. Проверки lifecycle должны также убеж ## Что покрывают тесты -В `validation/` ровно 47 скриптов. Запускайте каждый `validation/test-*.sh`; текущий набор: +В `validation/` ровно 48 скриптов. Запускайте каждый `validation/test-*.sh`; текущий набор: | Тест | Что проверяет | |---|---| @@ -69,6 +69,7 @@ Linux-машину. Проверки lifecycle должны также убеж | `test-kernel-guard.sh` | Защита ядра от CVE-2026-98432: sysctl-файл, выключающий MPTCP, nft-правило дропа входящих IPv4-пакетов с IP-опциями (хук `input`, приоритет `-310`, дословно правило Ubuntu), юнит автозагрузки, который **не** делает `flush ruleset` (иначе при загрузке снесло бы правила UFW), определение «ядро новее уже установлено, но не загружено» без захардкоженных таблиц версий, сравнение версий Xray-core (ведущий ноль читается как десятичный), включение/выключение на подставных `nft`/`sysctl`, JSON-контракт CLI и проводка в меню/диспетчер/миграцию/uninstall | | `test-freedom-sockopt.sh` | `freedom.domainStrategy` → `streamSettings.sockopt.domainStrategy` (26.10.31 помечает старое поле deprecated и «will be removed»): значение переносится, legacy-ключ удаляется, уже заданный sockopt побеждает, второй прогон — no-op (Xray не перезапускается зря), а шаблон `install.sh` пишет только новую форму | | `test-awg-ppa-repo.sh` | PPA `amnezia/ppa` ставится только вместе с ключом подписи: строка `signed-by`, порядок «ключ до репозитория», отсутствие репозитория без ключа, ремонт уже испорченного неподписанного репозитория, идемпотентность по маркеру и проводка ремонта в `main_menu`/`quickstart`/`happ-setup` | +| `test-secret-argv.sh` | Секреты не попадают в аргументы процессов (`/proc//cmdline` читают все пользователи хоста, `/proc//environ` — только владелец и root): подставной `curl` доказывает, что токен бота и `sub_token` приходят stdin-конфигом (`-K -`) и отсутствуют в `argv`; разбор пейлоада `--secret-file`/`--secret-stdin` (одиночный токен, AWS-пара, приоритет явного флага, мусор), отказ файлу шире `0600`, удаление файла после чтения, предупреждение `--token` в stderr при чистом stdout-JSON и чтение `$ENV.XRAYEBATOR_JQ_SECRET` в jq | | `test-awg-lifecycle.sh` | Бэкенд AmneziaWG: junk-диалект по умолчанию Amnezia (Jc=5, Jmin=10, Jmax=50, H1–H4=1..4, S1–S4 уникальные), генерация ключей, рендер серверного конфига (PostUp MASQUERADE, без peer-ов при установке), аллокация адресов, содержимое клиентского `.conf`, события revoke/expire/restore, реген deleted при заранее удалённом файле профиля, created = no-op (без авто-выдачи), диспетчер CLI | | `test-main-readiness-regressions.sh` | Регрессии readyness после аудита: certbot-manifest, UFW manifest, nginx rollback, привилегии, SSH-порт | | `test-multiroute-argument-preservation.sh` | Сохранение transport-аргументов multiroute-профиля | diff --git a/docs/security.md b/docs/security.md index 5a63600..2c29dcb 100644 --- a/docs/security.md +++ b/docs/security.md @@ -228,6 +228,56 @@ One caveat in fairness to the other side: the MPTCP maintainer argued against di in the proxy itself, since it penalises clients that benefit from it. We follow Xray's decision as defence in depth, not as a replacement for the kernel update. +## Secrets and process arguments + +A process's command line is readable by **every** local user: `/proc//cmdline` is +world-readable (`0444`), while `/proc//environ` is readable only by the process owner and +root (`0400`). On a VPN server that means an unprivileged account — including the `xray` service +account the proxy itself runs under — can read the arguments of any root process, so a secret +passed as an argument is a secret handed to anyone who gets code execution there, and to any +plain `ps aux` from a neighbouring account. + +Until 0.7.2 three groups of credentials travelled that way: + +* the **Telegram bot token** in the URL of the `curl` process (`…/bot/sendMessage`). Not a + one-off: the monitor timer runs the check every 15 minutes, so a process with the token in its + command line existed on every tick and for every alert; +* the subscription **`sub_token`** in the URL of the loopback subscription check; +* the **Cloudflare API token / AWS secret key** in the command line of `xrayebator dns01-setup`, + `dns01-test`, `repair-dns01` and `quickstart`, which keeps it for the whole certificate + issuance — 30 s of DNS propagation wait plus certbot's own work. certbot itself never received + them as arguments (an ini file for Cloudflare, `AWS_SHARED_CREDENTIALS_FILE` for Route53, both + `0600`), so the manager's own command line was the only exposure. + +The fix routes every one of those values around the argument list: + +* HTTP clients (`curl`) get the URL through a stdin config (`-K -`), so the token never appears in + their arguments; +* `jq` gets the value through the environment and reads it as `$ENV.XRAYEBATOR_JQ_SECRET`, which + covers the Hysteria 2 password, AmneziaWG private and preshared keys, the `sub_token`, the + VLESS Encryption key and the bot token when they are written into JSON; +* the CLI accepts the credential itself from stdin or from a file: + + ```bash + # the token appears in neither argv nor the shell history + printf 'token=%s\n' "$CF_TOKEN" | sudo xrayebator dns01-setup \ + --domain sub.example.com --provider cloudflare --secret-stdin --without-email + sudo install -m 600 /dev/null /root/.cf && printf 'token=%s\n' "$CF_TOKEN" | sudo tee /root/.cf + sudo xrayebator dns01-setup --domain sub.example.com --provider cloudflare --secret-file /root/.cf + ``` + + The payload is `key=value` lines (`token=…`, `aws_access_key_id=…`, + `aws_secret_access_key=…`); a single line without `=` is treated as the token. `--secret-file` + refuses a file readable by group or other and deletes it right after reading, so the window on + disk is milliseconds. The desktop GUI uploads the file over SFTP with mode `0600` and passes its + path — the DNS-01 wizard no longer puts the token on either command line. + +`--token` and `--aws-secret-access-key` still work for compatibility, but they now print a warning +to stderr naming the exposure. Two honest limits remain: a secret typed directly on an interactive +command line is still visible while that command runs (use `--secret-stdin` instead), and the +environment route protects a value from other users, not from root — anything running as root can +read any secret on the host. + ## Desktop GUI credentials The active Electron GUI supports SSH passwords and private keys, with direct-root or sudo execution. A diff --git a/docs/testing.md b/docs/testing.md index 7a8aefc..22c74f5 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -36,7 +36,7 @@ promise that installer and updater paths behave identically. ## Validation suite -`validation/` contains exactly 47 scripts. Run every `validation/test-*.sh`; the current set is: +`validation/` contains exactly 48 scripts. Run every `validation/test-*.sh`; the current set is: | Script | What it checks | |---|---| @@ -69,6 +69,7 @@ promise that installer and updater paths behave identically. | `test-kernel-guard.sh` | Kernel hardening against CVE-2026-98432: the sysctl file that disables MPTCP, the nft rule that drops inbound IPv4 packets carrying IP options (hook `input`, priority `-310`, the exact Ubuntu rule), a boot unit that does **not** `flush ruleset` (that would wipe the UFW ruleset at boot), "a newer kernel is installed but not booted" detection without hard-coded version tables, Xray-core version comparison (leading zeros read as decimal), enable/disable against stub `nft`/`sysctl` binaries, the CLI JSON contract and the wiring into menu/dispatcher/migration/uninstall | | `test-freedom-sockopt.sh` | `freedom.domainStrategy` → `streamSettings.sockopt.domainStrategy` (26.10.31 marks the old field deprecated and "will be removed"): the value moves, the legacy key is deleted, an explicit sockopt value wins, the second run is a no-op so Xray is not restarted for nothing, and the `install.sh` template writes only the new form | | `test-awg-ppa-repo.sh` | `amnezia/ppa` is added only together with its signing key: the `signed-by` repo line, key-before-repo ordering, no repo without a key, repair of an already broken unsigned repo, idempotency by marker, and the repair wiring in `main_menu`/`quickstart`/`happ-setup` | +| `test-secret-argv.sh` | Secrets never reach a process command line (`/proc//cmdline` is world-readable, `/proc//environ` is not): a stub `curl` proves the bot token and `sub_token` arrive through the stdin config (`-K -`) and never in `argv`, the `--secret-file`/`--secret-stdin` payload parser (bare token, AWS pair, explicit flag wins, garbage), the `0600` refusal, the delete-after-read, the stderr warning `--token` now prints while stdout stays clean JSON, and `jq` reading `$ENV.XRAYEBATOR_JQ_SECRET` | | `test-awg-lifecycle.sh` | AmneziaWG backend: the Amnezia-default junk dialect (Jc=5, Jmin=10, Jmax=50, H1–H4=1..4, S1–S4 unique), key generation, server conf renderer (PostUp MASQUERADE, no peers at install), peer address allocation, client `.conf` contents, revoke/expire/restore events, deleted-regen with a pre-removed profile file, created-is-a-no-op (no auto-grant), CLI dispatch | | `test-main-readiness-regressions.sh` | Main-menu readiness and first-run regression checks | | `test-multiroute-argument-preservation.sh` | Preservation of multiroute transport arguments | @@ -210,7 +211,7 @@ The workflows have separate responsibilities: - `.github/workflows/ci-linux.yml` is the Bash core gate on `ubuntu-24.04`: it installs `jq`, `uuid-runtime` and `ripgrep`, runs all four Bash syntax checks, then runs every - `validation/test-*.sh` script (45 at the time of writing). + `validation/test-*.sh` script (48 at the time of writing). - `.github/workflows/release.yml` is the active Electron release path for `v*` tags or manual runs. A `preflight` job first checks that the release notes file `docs/releases/.en.md` exists and that the `AP3X0` repository secret (if set) can actually create releases — it probes with a draft diff --git a/docs/zh-CN/configuration.md b/docs/zh-CN/configuration.md index 899d758..d7d7d01 100644 --- a/docs/zh-CN/configuration.md +++ b/docs/zh-CN/configuration.md @@ -104,7 +104,7 @@ Xrayebator 不会更改主机的 TCP 拥塞控制算法,也不会写入或应 | `sudo xrayebator update ` | 从规范 raw 仓库分支 self-update 管理器,继续使用新脚本,然后更新 Xray-core;分支写入 `.current_branch` 固定,供后续 GUI 更新使用 | | `sudo xrayebator probe-test` | 更换 SNI 前,从 VPS 检查其可达性 | | `sudo xrayebator channel-test [--name 名称] [--url URL] [--timeout S] [--transport T]` | 检查配置档的通道**是否真的可用**:对每条线路都启动一个本地 Xray 客户端(回环地址上的 SOCKS5),使用订阅链接中的参数,并通过它发出一个真实的互联网请求;JSON 包含 `working`/`checked`,以及每条线路的 `ok`、`http`、`ms`、`pq` 和客户端日志尾部。**不涉及 Let's Encrypt**——Reality 与 VLESS Encryption 自成一体,因此在 `http_tls` 订阅上、在任何证书签发之前都能工作,PQ 线路同样会被检查。实机运行:8/8 条线路,152–252 ms | -| `sudo xrayebator quickstart --email <邮箱>` | 桌面 GUI 使用的一次性部署路径:执行广泛设置/迁移,在 `8443` 配置 IP-TLS endpoint,创建带 `schema_version: 3` 和 7 条线路的标准 HAPP 配置档;输出带 `subscription_url` 的 JSON。非交互迁移是 best-effort,请检查最终配置档与服务。额外标志:`--pq` —— 为配置档在 tcp 上添加 PQ 线路(默认**关闭**:不具备 ML-KEM 的客户端连接不上 PQ 端口;结果见 JSON 的 `pq_route`),`--without-pq` —— 显式关闭,`--dns01-domain D --dns01-provider cloudflare\|route53 (--dns01-token T \| --dns01-aws-access-key-id K --dns01-aws-secret-access-key S)` —— 部署期的 DNS-01 回退。DNS-01 参数在任何系统改动**之前**校验:参数集合不完整会返回 `{"ok":false,…}` 且不做任何改动 | +| `sudo xrayebator quickstart --email <邮箱>` | 桌面 GUI 使用的一次性部署路径:执行广泛设置/迁移,在 `8443` 配置 IP-TLS endpoint,创建带 `schema_version: 3` 和 7 条线路的标准 HAPP 配置档;输出带 `subscription_url` 的 JSON。非交互迁移是 best-effort,请检查最终配置档与服务。额外标志:`--pq` —— 为配置档在 tcp 上添加 PQ 线路(默认**关闭**:不具备 ML-KEM 的客户端连接不上 PQ 端口;结果见 JSON 的 `pq_route`),`--without-pq` —— 显式关闭,`--dns01-domain D --dns01-provider cloudflare\|route53 (--dns01-secret-file F \| --dns01-secret-stdin)` —— 凭据以 `0600` 文件或 stdin 传入(在 `/proc` 中不可见),`--dns01-token T \| --dns01-aws-access-key-id K --dns01-aws-secret-access-key S` —— 兼容但在 `ps` 中可见的写法 —— 部署期的 DNS-01 回退。DNS-01 参数在任何系统改动**之前**校验:参数集合不完整会返回 `{"ok":false,…}` 且不做任何改动 | | `sudo xrayebator quickstart --without-email` | 相同的一次性部署路径,但不提供 ACME 联系邮箱;Certbot 使用 `--register-unsafely-without-email`,因此没有续期通知或邮箱恢复。若 Let's Encrypt 无法通过 http-01 验证 IP(validation 主机被服务商在 80 端口上游拦截),部署不会失败而是降级为 `http_tls`:订阅以 HTTP 发布,JSON 携带 `degraded:true`,解除 80 端口封锁后重新部署即恢复 HTTPS | | `sudo xrayebator inspect --json` | GUI 导入时使用的只读安装检查:返回 Xray、配置档和订阅标记状态;不会安装、迁移或修改配置 | | `sudo xrayebator happ-setup` | 已有安装的精简 HAPP 路径:确保订阅服务和可用的多线路配置档;缺少订阅域或端口标记时,会先验证 `8443` 的产品 IP-TLS endpoint,否则失败 | @@ -143,11 +143,11 @@ Xrayebator 不会更改主机的 TCP 拥塞控制算法,也不会写入或应 | `sudo xrayebator awg-grant --name N` | 为配置档签发 peer(密钥对 + 预共享密钥 + `10.8.1.x` 地址,存入 `.backends.awg`);重新生成 `awg0.conf`;JSON | | `sudo xrayebator awg-conf --name N` | 输出配置档 peer 的客户端 `.conf`(JSON `{ok, name, conf}`)——全隧道 AllowedIPs、服务端 junk 参数、endpoint;导入 AmneziaWG/AmneziaVPN 客户端 | | `sudo xrayebator awg-31 --on\|--off` | 切换 AWG 3.1 配置格式(`HeaderProtectionKey`、`RandomTrailers`、`S3`/`S4`);新安装默认开启 3.1,切换会在原地补齐缺失的服务端参数,警告所有已签发的客户端 `.conf` 必须重新下载(AmneziaVPN ≥ 5.0.1.5),并带回滚地重新生成接口 | -| `sudo xrayebator dns01-setup --domain sub.example.com --provider cloudflare\|route53 [--port P] [--staging]` | 通过 DNS-01 实现按域名的 HTTPS 订阅:不需要 80 端口,证书由 TXT 记录验证。写入 `0600` 凭据、用带 deploy-hook 的 certbot 签发证书、生成不含 `listen 80` 的 nginx vhost,并把标记切换为 `domain_tls`;打印 JSON。端口默认沿用当前订阅端口(否则 `443`),因此订阅 URL 的端口不变;`--staging` 在 Let's Encrypt 测试环境签发(`--test-cert`,不消耗生产配额)并返回 `staging:true`——客户端不信任这种证书 | -| `sudo xrayebator dns01-test --domain sub.example.com --provider cloudflare\|route53 [--token T \| --aws-*] [--email E\|--without-email]` | 在**不改动订阅、不消耗生产配额**的前提下验证域名与 DNS 服务商令牌:仅在测试环境签发,使用独立的证书 lineage,不带 deploy-hook,也不改 nginx/标记/防火墙。JSON 返回签发者、证书到期时间、需要核对的 `_acme-challenge.` TXT 记录,失败时返回解析后的 certbot 原因 | +| `sudo xrayebator dns01-setup --domain sub.example.com --provider cloudflare\|route53 [--port P] [--staging] [--secret-file F \| --secret-stdin]` | 通过 DNS-01 实现按域名的 HTTPS 订阅:不需要 80 端口,证书由 TXT 记录验证。写入 `0600` 凭据、用带 deploy-hook 的 certbot 签发证书、生成不含 `listen 80` 的 nginx vhost,并把标记切换为 `domain_tls`;打印 JSON。端口默认沿用当前订阅端口(否则 `443`),因此订阅 URL 的端口不变;`--staging` 在 Let's Encrypt 测试环境签发(`--test-cert`,不消耗生产配额)并返回 `staging:true`——客户端不信任这种证书 | +| `sudo xrayebator dns01-test --domain sub.example.com --provider cloudflare\|route53 [--secret-file F \| --secret-stdin \| --token T \| --aws-*] [--email E\|--without-email]` | 在**不改动订阅、不消耗生产配额**的前提下验证域名与 DNS 服务商令牌:仅在测试环境签发,使用独立的证书 lineage,不带 deploy-hook,也不改 nginx/标记/防火墙。JSON 返回签发者、证书到期时间、需要核对的 `_acme-challenge.` TXT 记录,失败时返回解析后的 certbot 原因 | | `sudo xrayebator dns01-status` | DNS-01 状态:提供商、模式、域名、端口、凭据是否存在、证书剩余天数、deploy-hook 是否存在(certbot 记录为 `renew_hook`)以及订阅是否使用测试证书;打印 JSON | -| `sudo xrayebator repair-dns01 --domain sub.example.com --provider cloudflare\|route53 [--token T \| --aws-*] [--email E] [--port P]` | 把已降级(`http_tls`)的订阅改为 DNS-01:同样通过 TXT 记录签发证书,vhost 只按 TLS server 重新渲染,标记变为 `domain_tls`。幂等:如果订阅已在 HTTPS(`ip_tls`/`domain_tls`)上,则返回 `{"ok":true,"skipped":true}` 且不做任何事;打印 JSON | -| `sudo xrayebator alerts-setup --token T --chat-id C` | 接入 Telegram 通知:用 `getMe` 校验令牌、发送一条测试消息,并且**只有在投递成功之后**才保存 `alerts.json`(0600)并启用 `xrayebator-monitor.timer`;打印 JSON | +| `sudo xrayebator repair-dns01 --domain sub.example.com --provider cloudflare\|route53 [--secret-file F \| --secret-stdin \| --token T \| --aws-*] [--email E] [--port P]` | 把已降级(`http_tls`)的订阅改为 DNS-01:同样通过 TXT 记录签发证书,vhost 只按 TLS server 重新渲染,标记变为 `domain_tls`。幂等:如果订阅已在 HTTPS(`ip_tls`/`domain_tls`)上,则返回 `{"ok":true,"skipped":true}` 且不做任何事;打印 JSON | +| `sudo xrayebator alerts-setup [--token T \| --secret-file F \| --secret-stdin] --chat-id C` | 接入 Telegram 通知:用 `getMe` 校验令牌、发送一条测试消息,并且**只有在投递成功之后**才保存 `alerts.json`(0600)并启用 `xrayebator-monitor.timer`;打印 JSON | | `sudo xrayebator alerts-status` | 监控状态:配置、定时器、上次检查时间、事件以及最近一次 SNI 探测结果(不显示机器人令牌);打印 JSON | | `sudo xrayebator alerts-test` | 向已配置的会话发送测试消息(验证投递);打印 JSON | | `sudo xrayebator alerts-enable\|alerts-disable` | 启用或停用投递而不删除配置(不丢失令牌的急停开关);打印 JSON | @@ -478,6 +478,10 @@ GUI 的配置档卡片上会显示「已用 / 限额」标签(达到 80% 变 (群组的 chat_id 为负数): ```bash +# 令牌不进入命令行(本机任何用户都能在 /proc 中读到): +printf 'token=%s\n' "$TG_TOKEN" | sudo xrayebator alerts-setup --secret-stdin \ + --chat-id -1001234567890 +# 兼容写法,但会出现在 `ps` 中: sudo xrayebator alerts-setup --token 123456:AA... --chat-id -1001234567890 sudo xrayebator alerts-status # 定时器、上次检查、事件、SNI sudo xrayebator alerts-test # 测试消息 @@ -532,13 +536,17 @@ PQ 端口不能与普通线路共用客户端。 `https://sub.example.com/sub/`。 ```bash -# Cloudflare:具有该区域 DNS:Edit 权限的 API token +# Cloudflare:具有该区域 DNS:Edit 权限的 API token。令牌以 0600 文件(或 stdin) +# 传入,而不是作为参数:签发要持续数十秒,而进程参数对本机所有用户可读(见 security.md)。 +sudo install -m 600 /dev/null /root/.cf +printf 'token=%s\n' "$CF_TOKEN" | sudo tee /root/.cf >/dev/null sudo xrayebator dns01-setup --domain sub.example.com --provider cloudflare \ - --token CF_API_TOKEN --email admin@example.com + --secret-file /root/.cf --email admin@example.com # Route53:具有 Route53:ChangeResourceRecordSets 权限的密钥 -sudo xrayebator dns01-setup --domain sub.example.com --provider route53 \ - --aws-access-key-id AKIA... --aws-secret-access-key ... --without-email +printf 'aws_access_key_id=%s\naws_secret_access_key=%s\n' "$AWS_KEY" "$AWS_SECRET" \ + | sudo xrayebator dns01-setup --domain sub.example.com --provider route53 \ + --secret-stdin --without-email sudo xrayebator dns01-status # 提供商、域名、端口、证书有效期、deploy-hook ``` diff --git a/docs/zh-CN/security.md b/docs/zh-CN/security.md index a9f353c..914d64f 100644 --- a/docs/zh-CN/security.md +++ b/docs/zh-CN/security.md @@ -197,6 +197,52 @@ unattended-upgrades 已经装上。`kernel-guard --status` 会报告运行中的 为公平起见还有一点:MPTCP 维护者反对在代理里关闭 MPTCP,因为这会牺牲能从 MPTCP 获益的客户端。 我们跟随 Xray 的决定,把它作为纵深防御的一层,而不是内核更新的替代品。 +## 密钥与进程参数 + +进程的命令行对**本机所有用户**可读:`/proc//cmdline` 的权限是 `0444`(所有人可读), +而 `/proc//environ` 只有进程所有者和 root 可读(`0400`)。在 VPN 服务器上这意味着任何 +非特权账户——包括代理本身运行所用的 `xray` 服务账户——都能读到任意 root 进程的参数。作为参数 +传递的密钥,等于交给了每一个在该主机上取得代码执行的人,也等于交给了相邻账户的一条 +`ps aux`。 + +在 0.7.2 之前,有三类凭据是这样传递的: + +* **Telegram 机器人令牌**出现在 `curl` 进程的 URL 里(`…/bot/sendMessage`)。这并非 + 一次性泄露:监控定时器每 15 分钟执行一次检查,因此每个周期和每次告警发送时都存在一个命令行 + 里带着令牌的进程; +* 订阅 **`sub_token`** 出现在 loopback 订阅检查的 URL 里; +* **Cloudflare API 令牌 / AWS 密钥**出现在 `xrayebator dns01-setup`、`dns01-test`、 + `repair-dns01` 和 `quickstart` 的命令行里,而且会一直保留到证书签发完成——30 秒的 DNS + 传播等待加上 certbot 自身的工作。certbot 本身从不通过参数接收这些值(Cloudflare 用 ini + 文件,Route53 用 `AWS_SHARED_CREDENTIALS_FILE`,权限都是 `0600`),所以唯一的暴露点就是 + 管理器自己的命令行。 + +现在这些值都绕开了参数列表: + +* HTTP 客户端(`curl`)通过 stdin 配置(`-K -`)接收 URL,令牌不出现在它的参数里; +* `jq` 通过环境变量接收值并以 `$ENV.XRAYEBATOR_JQ_SECRET` 读取——覆盖 Hysteria 2 密码、 + AmneziaWG 私钥与 PresharedKey、`sub_token`、VLESS Encryption 密钥以及写入 JSON 时的 + 机器人令牌; +* CLI 从 stdin 或文件接收密钥本身: + + ```bash + # 令牌既不进入 argv,也不进入 shell history + printf 'token=%s\n' "$CF_TOKEN" | sudo xrayebator dns01-setup \ + --domain sub.example.com --provider cloudflare --secret-stdin --without-email + sudo install -m 600 /dev/null /root/.cf && printf 'token=%s\n' "$CF_TOKEN" | sudo tee /root/.cf + sudo xrayebator dns01-setup --domain sub.example.com --provider cloudflare --secret-file /root/.cf + ``` + + 载荷是 `key=value` 行(`token=…`、`aws_access_key_id=…`、`aws_secret_access_key=…`); + 没有 `=` 的单行会被当作令牌。`--secret-file` 会拒绝组或其他用户可读的文件,并在读取后立即 + 删除,因此密钥在磁盘上只存在毫秒级。桌面 GUI 通过 SFTP 以 `0600` 上传文件并传递路径—— + DNS-01 向导不再把令牌放进任何命令行。 + +`--token` 和 `--aws-secret-access-key` 为兼容性继续可用,但会向 stderr 打印一条关于可见性的 +警告。还有两点需要诚实说明:直接敲在交互式命令行里的密钥在该命令运行期间仍然可见(请改用 +`--secret-stdin`);通过环境变量传递只能防止**其他用户**读取,防不住 root——以 root 运行的 +任何东西都能读到主机上的任何密钥。 + ## 桌面 GUI 凭据 活跃的 Electron GUI 支持 SSH 密码和私钥,并可选择直接 root 或 sudo。通过 Electron 原生文件对话框选择的私钥由 main process 读取,并通过 `keytar` 保存到操作系统钥匙串(Windows Credential Manager、macOS Keychain 或 Linux Secret Service),因此后续 SSH 操作和应用重启后都可以复用。Renderer 只收到非敏感 credential id 和显示文件名;私钥字节不会跨越 preload boundary。 diff --git a/docs/zh-CN/testing.md b/docs/zh-CN/testing.md index 2b38b60..c92a598 100644 --- a/docs/zh-CN/testing.md +++ b/docs/zh-CN/testing.md @@ -15,7 +15,7 @@ for test_file in validation/*.sh; do bash "$test_file" || exit; done ## 测试覆盖范围 -`validation/` 中有 47 个静态与本地回归测试: +`validation/` 中有 48 个静态与本地回归测试: | 测试 | 检查内容 | |---|---| @@ -45,6 +45,7 @@ for test_file in validation/*.sh; do bash "$test_file" || exit; done | `test-kernel-guard.sh` | 针对 CVE-2026-98432 的内核加固:关闭 MPTCP 的 sysctl 文件、丢弃带 IP 选项的入站 IPv4 包的 nft 规则(`input` 钩子、优先级 `-310`、Ubuntu 原样规则)、**不做** `flush ruleset` 的开机单元(否则开机时会把 UFW 规则清空)、「已安装更新的内核但未启动」的判定(不硬编码版本表)、Xray-core 版本比较(前导零按十进制)、在桩 `nft`/`sysctl` 上的启用/关闭、CLI 的 JSON 契约,以及菜单/分发器/迁移/uninstall 的接线 | | `test-freedom-sockopt.sh` | `freedom.domainStrategy` → `streamSettings.sockopt.domainStrategy`(26.10.31 将旧字段标记为 deprecated 且「will be removed」):值被迁移、旧键被删除、显式设置的 sockopt 优先、第二次运行无操作(不会白白重启 Xray),且 `install.sh` 模板只写新形式 | | `test-awg-ppa-repo.sh` | `amnezia/ppa` 必须与签名密钥一起添加:`signed-by` 仓库行、先取密钥再写仓库、无密钥不写仓库、修复已损坏的未签名仓库、按标记幂等,以及在 `main_menu`/`quickstart`/`happ-setup` 中的接线 | +| `test-secret-argv.sh` | 密钥不进入进程参数(`/proc//cmdline` 对所有用户可读,`/proc//environ` 不可读):桩 `curl` 证明机器人令牌与 `sub_token` 通过 stdin 配置(`-K -`)传入且不出现在 `argv`;`--secret-file`/`--secret-stdin` 载荷解析(单行令牌、AWS 对、显式标志优先、垃圾输入)、拒绝宽于 `0600` 的文件、读取后删除、`--token` 在 stderr 打印警告而 stdout 仍是纯 JSON、jq 读取 `$ENV.XRAYEBATOR_JQ_SECRET` | | `test-awg-lifecycle.sh` | AmneziaWG 后端:Amnezia 默认 junk 方言(Jc=5、Jmin=10、Jmax=50、H1–H4=1..4、S1–S4 互不相同)、密钥生成、服务端配置渲染(PostUp MASQUERADE、安装时无 peer)、peer 地址分配、客户端 `.conf` 内容、revoke/expire/restore 事件、预删除配置档后的 deleted 重生成、created 为无操作(不自动签发)、CLI 分发、`/etc/modules-load.d` 的开机模块登记(仅在模块可用时写入)、`backend-start`(「已安装」≠「正在运行」)、以及安装成功判定:内核模块必须针对**当前**内核(`AWG_MODULES_ROOT` 为测试接缝) | | `test-main-readiness-regressions.sh` | 审计后的 readiness 回归:certbot manifest、UFW manifest、nginx 回滚、权限与 SSH 端口 | | `test-sni-change-cli.sh` | `sni-change` CLI:JSON 输出、Reality、XHTTP host、配置档同步与回滚 | @@ -170,7 +171,7 @@ npm test # Vitest 单元测试 三个独立 workflow: -- **ci-linux.yml** — Bash validation:在 ubuntu-24.04 上对所有脚本执行 `bash -n`,并运行全部 47 个 +- **ci-linux.yml** — Bash validation:在 ubuntu-24.04 上对所有脚本执行 `bash -n`,并运行全部 48 个 `validation/test-*.sh`;在 push 到 `main`、`dev`、`experimental` 以及 pull request 时运行。 - **release.yml** — Electron 构建(Windows/macOS/Linux)。只在 `v*` tag 和手动触发时运行;先由 `preflight` 检查发布说明 `docs/releases/.en.md` 是否存在,以及仓库密钥 `AP3X0`(若已设置) From 2da4921735e573d527e496fe19207d02c60d3dd4 Mon Sep 17 00:00:00 2001 From: Ap3x0 <82464229+Ap3x0s@users.noreply.github.com> Date: Thu, 5 Nov 2026 22:03:25 +0300 Subject: [PATCH 07/13] =?UTF-8?q?fix:=20channel-test=20=D0=B1=D0=B5=D0=B7?= =?UTF-8?q?=20--name=20=D0=B8=20=D1=81=D1=82=D0=B0=D1=82=D1=83=D1=81=D1=8B?= =?UTF-8?q?=20=D1=84=D0=B0=D0=B9=D1=80=D0=B2=D0=BE=D0=BB=D0=B0=20=D1=83?= =?UTF-8?q?=D0=B5=D1=85=D0=B0=D0=BB=D0=B8=20=D0=B2=20stderr?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Обе находки — с живого прогона развёртывания на чистом Debian 13. 1. `xrayebator channel-test` без `--name` отвечал `{"ok":false,"error":"Укажите --name профиля"}`, хотя в системе ровно один профиль, а документированный вызов — `channel-test [--name NAME]` (то есть имя необязательно). Причина: `local name="$HAPP_DEFAULT_PROFILE"`, а эта переменная выставляется только внутри `_happ_ensure_default_multiroute_profile`, то есть в свежем процессе всегда пуста — дефолт работал лишь тогда, когда quickstart уже отработал в том же процессе. Теперь при пустом имени берётся единственный профиль из `$PROFILES_DIR`; при двух и более профилях выбор по-прежнему неоднозначен и команда честно просит `--name`, чтобы не проверять чужой профиль. 2. `open_firewall_port` печатал свои три статуса («Порт N/tcp уже открыт», «Открываю порт», «Порт открыт») в stdout. Из-за этого `quickstart` отдавал JSON не первым в потоке, и `xrayebator quickstart --without-email | jq .ok` падал на цветной строке перед объектом (GUI это переживает — он вырезает JSON из вывода, — но контракт «stdout — только JSON» нарушался, и любой строгий парсер ломался). Статусы переведены в stderr; тексты и поведение не изменились, интерактивное меню их по-прежнему показывает. Проверено на живой машине: `channel-test` без `--name` даёт 7/7 рабочих маршрутов; `quickstart` больше не подмешивает строки в stdout. --- CLAUDE.md | 2 +- xrayebator | 25 ++++++++++++++++++++++--- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index c9cb479..17c522d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -153,7 +153,7 @@ Apart from the interactive menu (`sudo xrayebator`), the script exposes subcomma - `xrayebator fp-change --name NAME [--route R] --fp FINGERPRINT` — change the fingerprint for a profile (client-side, no Xray restart), emits JSON. - `xrayebator sni-change --name NAME [--route R] --sni SNI` — change the SNI for a profile; updates all profiles on the same port (`update_all_profiles_on_port()`), emits JSON. - `xrayebator sni-list` — print the SNI candidates from `sni_list.txt` grouped by category, emits JSON (used by the GUI SNI dialog). The file lives in `$DATA_DIR` (`/usr/local/etc/xray/data/sni_list.txt`); its first uncommented line is the default for new profiles. `_default_sni_for_transport` does **not** trust that line blindly any more: it verifies reachability from the server with the shared pure seam `_sni_tls_output_ok_pure`, which requires a **completed TLS 1.3 handshake with a verified certificate** — not the bare `Verify return code: 0`, because openssl prints that even when the handshake failed ("no peer certificate available"), which made TLS 1.2-only hosts and hosts that answer `sslv3 alert handshake failure` look reachable and gave fresh profiles dead routes (live 2026-10-20: 4 of 6 new PQ routes returned http 000 with such SNIs and 200 after switching to `www.cloudflare.com` on the same port). `_monitor_sni_reachable` and `probe-test` use the same seam. Candidate order is the per-transport default, then at most `SNI_REACH_HEAD_MAX` (4) lines of `sni_list.txt`, then the global fallbacks (`www.cloudflare.com`, `api-maps.yandex.ru`, `www.google.com`), then the rest of the list — the list is `ru_whitelist`-first, so from a foreign VPS every dead entry costs a full timeout and an unbounded walk made profile creation crawl. Criterion details that cost a live debugging round: match the version as the substring `TLSv1\.3`, not as the `Protocol : TLSv1.3` line — OpenSSL 3.0 on Ubuntu 22.04 prints no such line under `-tls1_3` (only `New, TLSv1.3, Cipher is …`), and requiring the line rejected live `www.cloudflare.com`/`www.google.com`/`api-maps.yandex.ru`, after which the walk crawled into the list tail (67–84 s per profile); a failed handshake also shows `Cipher is (NONE)`. A successful probe is repeated once and both attempts must pass, and a host must also answer HTTP (`curl` code ≠ 000, the status itself irrelevant) because a dest that completes TLS and then tarpits still breaks the client handshake — `www.wildberries.ru` passed TLS in 1.7 s with `000` from curl and its route hung 10 s. The repeat catches hosts that answer only intermittently (`splitter.wb.ru` failed with alert 40 in one measurement and passed in another) — Reality on such a dest drops the client handshake. Budget per attempt is `SNI_REACH_TIMEOUT` (default 3 s — a working TLS 1.3 handshake answers in 40–250 ms, a dead host burns the whole budget), and `probe_sni` uses the same value so `probe-test` cannot claim `TLS OK` for a host that selection rejects. One probe per SNI is cached (`_SNI_REACH_CACHE`) and the old behaviour stands when nothing is reachable. Use `idx=$((idx + 1))`, never `((idx++))`, in loops here: the latter returns 1 for index 0 and kills callers running under `set -e`. Reason: Reality serves the client a certificate fetched from the SNI's real site, so an unreachable `dest` hangs the handshake while the config stays valid — on a live deployment the default `www.ozon.ru` was unreachable and 5 of 7 routes of a fresh deployment were dead (`xrayebator channel-test` proved it). Guarded by `validation/test-sni-reachability.sh`. -- `xrayebator channel-test [--name NAME] [--url URL] [--timeout S] [--transport T]` — verify that the profile's channels actually work: for every route it starts a local Xray client (SOCKS5 on a loopback port) from the subscription link and pushes a real request through it, printing JSON (`ok`, `working`, `checked`, per route `label`/`transport`/`port`/`pq`/`ok`/`http`/`ms`/`client_log_tail`; progress goes to stderr). No Let's Encrypt involvement — Reality and VLESS Encryption are self-contained, so it works on an `http_tls` subscription and before any certificate exists, and it covers PQ routes. Helpers are the seams: `_channel_client_config_pure` (pure client config from a link record), `_channel_free_socks_port`, `_channel_wait_socks`, `_channel_probe`. Do **not** touch fd 3 inside those helpers: `channel_test_command` owns it (`exec 3>&1 … exec 1>&3`) and a stray `exec 3>&-` sent the final JSON to stderr (found live). Guarded by `validation/test-channel-test-cli.sh` (network run itself is live-only: the CI suite cannot start Xray clients against real inbounds). Do not read a single measurement as a verdict: the **first** run right after an Xray restart pays connection warm-up and can report ~5 s per route, while the second run of the same profile reports ~150 ms (measured on a live server: plain 5179 → 149 → 151 ms, PQ 241 → 232 → 229 ms). Run it twice before calling a channel slow — and note that PQ is not automatically faster or slower: after warm-up plain Reality over the same `www.cloudflare.com` SNI was ~150 ms and the PQ route ~230 ms, the difference being one ML-KEM encapsulation. +- `xrayebator channel-test [--name NAME] [--url URL] [--timeout S] [--transport T]` — verify that the profile's channels actually work (without `--name` it uses the only profile in the system — `HAPP_DEFAULT_PROFILE` is set only inside a quickstart/happ-setup process, so a fresh CLI invocation used to answer «Укажите --name» even with exactly one profile — and refuses to guess when there are several): for every route it starts a local Xray client (SOCKS5 on a loopback port) from the subscription link and pushes a real request through it, printing JSON (`ok`, `working`, `checked`, per route `label`/`transport`/`port`/`pq`/`ok`/`http`/`ms`/`client_log_tail`; progress goes to stderr). No Let's Encrypt involvement — Reality and VLESS Encryption are self-contained, so it works on an `http_tls` subscription and before any certificate exists, and it covers PQ routes. Helpers are the seams: `_channel_client_config_pure` (pure client config from a link record), `_channel_free_socks_port`, `_channel_wait_socks`, `_channel_probe`. Do **not** touch fd 3 inside those helpers: `channel_test_command` owns it (`exec 3>&1 … exec 1>&3`) and a stray `exec 3>&-` sent the final JSON to stderr (found live). Guarded by `validation/test-channel-test-cli.sh` (network run itself is live-only: the CI suite cannot start Xray clients against real inbounds). Do not read a single measurement as a verdict: the **first** run right after an Xray restart pays connection warm-up and can report ~5 s per route, while the second run of the same profile reports ~150 ms (measured on a live server: plain 5179 → 149 → 151 ms, PQ 241 → 232 → 229 ms). Run it twice before calling a channel slow — and note that PQ is not automatically faster or slower: after warm-up plain Reality over the same `www.cloudflare.com` SNI was ~150 ms and the PQ route ~230 ms, the difference being one ML-KEM encapsulation. - `xrayebator port-change --name NAME [--route R] --port PORT|random` — change the port for a profile; updates the inbound, firewall, subscription and all profiles on the port, emits JSON (reconnect is required). - `xrayebator bypass list|add --domain D|remove --domain D|reset|bundle [--group a,b,c]` — manage bypass routing groups (JSON). Server-side only: it exists for cascade deployments, where the catch-all points at the upstream; without a cascade the built-in catch-all already sends everything direct. - `xrayebator backend-start --type hysteria2|awg` — bring an *installed* backend whose unit is not active back up (after a reboot, or a manual down). The only mutation is `systemctl start` (plus the kernel module for AWG), and it prints JSON, reporting `already:true` when the unit was running. The desktop GUI exposes it as the **Start** button next to the red "Not running" state — that is why `backend-status` reports `installed` and `state` separately: an installed backend can be dead, and the GUI must not paint that green. diff --git a/xrayebator b/xrayebator index 51c69ae..8f4fa17 100755 --- a/xrayebator +++ b/xrayebator @@ -1553,6 +1553,23 @@ channel_test_command() { esac done + # Без --name берём единственный профиль: HAPP_DEFAULT_PROFILE выставляется только + # внутри _happ_ensure_default_multiroute_profile, то есть в свежем процессе пуст, и + # документированный вызов `xrayebator channel-test` сразу после развёртывания + # отвечал «Укажите --name» при единственном профиле в системе. При нескольких + # профилях выбор неоднозначен — просим --name, чтобы не проверять чужой. + if [[ -z "$name" ]]; then + local _only="" _cnt=0 _pf + for _pf in "$PROFILES_DIR"/*.json; do + [[ -f "$_pf" ]] || continue + _cnt=$((_cnt + 1)) + _only="$_pf" + done + if (( _cnt == 1 )); then + name=$(basename "$_only" .json) + fi + fi + if [[ -z "$name" || ! "$name" =~ ^[a-zA-Z0-9_-]{1,48}$ ]]; then echo '{"ok":false,"error":"Укажите --name профиля"}' return 1 @@ -2617,15 +2634,17 @@ _add_owned_firewall_rule() { } # Open port in UFW firewall (idempotent and ownership-safe). +# Статусы — в stderr: stdout у CLI-команд обязан оставаться чистым JSON (иначе +# `xrayebator quickstart | jq .ok` падал на цветной строке перед объектом). open_firewall_port() { local port="$1" protocol="${2:-tcp}" if _ufw_rule_exists "$port" "$protocol" 2>/dev/null; then - echo -e "${CYAN} → Порт ${port}/${protocol} уже открыт; ownership не присваивается${NC}" + echo -e "${CYAN} → Порт ${port}/${protocol} уже открыт; ownership не присваивается${NC}" >&2 return 0 fi - echo -e "${CYAN} → Открываю порт ${port}/${protocol}...${NC}" + echo -e "${CYAN} → Открываю порт ${port}/${protocol}...${NC}" >&2 if _add_owned_firewall_rule "$port" "$protocol" allow; then - echo -e "${GREEN} ✓ Порт ${port}/${protocol} открыт${NC}" + echo -e "${GREEN} ✓ Порт ${port}/${protocol} открыт${NC}" >&2 return 0 fi echo -e "${RED} ✗ Ошибка открытия порта ${port}/${protocol}${NC}" >&2 From eacfa683bffd52d6f9b2ceeeeb2d9173a257f44e Mon Sep 17 00:00:00 2001 From: Ap3x0 <82464229+Ap3x0s@users.noreply.github.com> Date: Thu, 5 Nov 2026 22:12:57 +0300 Subject: [PATCH 08/13] =?UTF-8?q?test(channel-test):=20ASCII-=D1=8F=D0=BA?= =?UTF-8?q?=D0=BE=D1=80=D1=8C=20=D0=B2=D0=BC=D0=B5=D1=81=D1=82=D0=BE=20?= =?UTF-8?q?=D1=80=D0=B0=D0=BC=D0=BA=D0=B8=20=D0=B2=20awk=20=E2=80=94=20?= =?UTF-8?q?=D1=82=D0=B5=D1=81=D1=82=20=D0=BF=D0=B5=D1=80=D0=B5=D1=81=D1=82?= =?UTF-8?q?=D0=B0=D0=BB=20=D0=B7=D0=B0=D0=B2=D0=B8=D1=81=D0=B5=D1=82=D1=8C?= =?UTF-8?q?=20=D0=BE=D1=82=20=D0=BB=D0=BE=D0=BA=D0=B0=D0=BB=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `test-channel-test-cli.sh` вырезал блок хелперов шаблоном `/^# ─+ channel-test/`, то есть по символу рамки «─». Это не матчится ни в mawk (awk по умолчанию в Debian и Ubuntu — побайтовый regex), ни в gawk в байтовой локали, поэтому тест краснел от окружения: на чистом Debian 13 в живом SSH он падал так же, как на Windows-хосте, хотя код в порядке. Проверено: на HEAD тот же awk возвращает ноль строк. Якорь заменён на ASCII-строку использования, которая идёт сразу под рамкой (`# xrayebator channel-test …`) и содержит ровно тот же блок хелперов. Тест теперь зелёный и на Debian 13, и на Windows. Не связано с кодом: на сервере с живым Let's Encrypt сертификатом `test-hysteria2-lifecycle.sh` ждёт `selfsigned`, а `_hysteria2_tls_mode_detect` честно отвечает `le ` — тест не герметичен по состоянию хоста (в CI `/etc/letsencrypt` пуст, поэтому там он зелёный). Это отдельная задача, не регрессия. --- validation/test-channel-test-cli.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/validation/test-channel-test-cli.sh b/validation/test-channel-test-cli.sh index 0856314..8bc584b 100644 --- a/validation/test-channel-test-cli.sh +++ b/validation/test-channel-test-cli.sh @@ -112,7 +112,10 @@ grep -q '_channel_probe "\$socks"' <<<"$block" || fail "channel-test не выз # fd 3 принадлежит channel_test_command (exec 3>&1 … exec 1>&3): ни один хелпер не # смеет его закрывать. Живой баг: _channel_wait_socks делала `exec 3>&-` в основном # шелле, последующий `exec 1>&3` не срабатывал, и итоговый JSON уезжал в stderr. -helpers=$(awk '/^# ─+ channel-test/,/^channel_test_command\(\) \{/' xrayebator) +# Якорь — ASCII-строка использования под рамкой, а не сама рамка: шаблон с «─» +# не матчится ни mawk (Debian/Ubuntu по умолчанию, побайтовый regex), ни gawk в +# байтовой локали, поэтому тест краснел от окружения, а не от кода. +helpers=$(awk '/^# xrayebator channel-test/,/^channel_test_command\(\) \{/' xrayebator) [[ -n "$helpers" ]] || fail "не найден блок хелперов channel-test" # Комментарии не код: в них эта история описана словами. if grep -vE '^[[:space:]]*#' <<<"$helpers" | grep -qE 'exec 3[<>]'; then From 67f04f3aed6b1f8abce081c765b9f5e70aebe6a4 Mon Sep 17 00:00:00 2001 From: Ap3x0 <82464229+Ap3x0s@users.noreply.github.com> Date: Thu, 5 Nov 2026 22:17:45 +0300 Subject: [PATCH 09/13] =?UTF-8?q?docs(testing):=20=D0=BD=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=80=20=D0=BD=D0=B5=20=D0=B3=D0=B5=D1=80=D0=BC=D0=B5=D1=82?= =?UTF-8?q?=D0=B8=D1=87=D0=B5=D0=BD=20=E2=80=94=20=D1=87=D1=82=D0=BE=20?= =?UTF-8?q?=D0=BE=D0=BD=20=D1=82=D1=80=D0=BE=D0=B3=D0=B0=D0=B5=D1=82=20?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=B6=D0=B8=D0=B2=D0=BE=D0=BC=20=D1=81=D0=B5?= =?UTF-8?q?=D1=80=D0=B2=D0=B5=D1=80=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Прогон validation на настоящем сервере дал два факта, которых не видно в CI и которые стоит помнить до («почему после прогона стало хуже?»): * `test-ssh-protect.sh` проходит настоящий путь `--disable`: останавливает и выключает из автозапуска `fail2ban`. На живом VPS это тихо снимает защиту от перебора, а `ssh-protect --status` потом честно показывает `active=false` (именно так и вышло при прогоне — вернул `systemctl enable --now fail2ban`); * `test-hysteria2-lifecycle.sh` ждёт хост без сертификата Let's Encrypt на подписку: при живом серте `_hysteria2_tls_mode_detect` отвечает `le ` (это правильное поведение), а тест ожидает `selfsigned`, поэтому на сервере он краснеет, а в CI зелёный. Добавлена оговорка в `docs/testing.md` (ru/en/zh) рядом с уже существующим «статические тесты не заменяют disposable VPS». --- docs/ru/testing.md | 6 ++++++ docs/testing.md | 6 ++++++ docs/zh-CN/testing.md | 5 +++++ 3 files changed, 17 insertions(+) diff --git a/docs/ru/testing.md b/docs/ru/testing.md index ae23fe8..4249e95 100644 --- a/docs/ru/testing.md +++ b/docs/ru/testing.md @@ -91,6 +91,12 @@ Linux-машину. Проверки lifecycle должны также убеж > Статические тесты не заменяют проверку на disposable VPS: создание и удаление профиля, валидацию > конфига, рестарт сервисов, rollback, поведение firewall и реальное подключение клиента. +> +> Сам набор не герметичен — гоняйте его на одноразовом хосте или в контейнере. Два примера с прогона +> на живом сервере: `test-ssh-protect.sh` проходит настоящий путь `--disable`, то есть гасит и +> отключает `fail2ban` (после прогона включите обратно), а `test-hysteria2-lifecycle.sh` ждёт хост +> без сертификата Let's Encrypt на подписку — при живом серте `_hysteria2_tls_mode_detect` честно +> отвечает `le `, тогда как тест ожидает `selfsigned`. ## Проверка lifecycle и HAPP-эндпоинта diff --git a/docs/testing.md b/docs/testing.md index 22c74f5..f4c28f5 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -93,6 +93,12 @@ Static tests do not replace a disposable VPS run: profile creation and deletion, service restarts, rollback, firewall behavior and a real client connection still need live-server verification. +The suite itself is not hermetic, so run it on a disposable host or in a container. Two examples found +by running it on a live server: `test-ssh-protect.sh` walks the real `--disable` path, which stops and +disables `fail2ban` (re-enable it afterwards), and `test-hysteria2-lifecycle.sh` expects a host without +a subscription Let's Encrypt certificate — with a real one present `_hysteria2_tls_mode_detect` +correctly answers `le ` while the test expects `selfsigned`. + ## Lifecycle and HAPP endpoint checks For a new deployment, exercise the broad `quickstart --email
` path and confirm that it diff --git a/docs/zh-CN/testing.md b/docs/zh-CN/testing.md index c92a598..16680c0 100644 --- a/docs/zh-CN/testing.md +++ b/docs/zh-CN/testing.md @@ -69,6 +69,11 @@ for test_file in validation/*.sh; do bash "$test_file" || exit; done | `test-sni-reachability.sh` | 默认 SNI 的选择:不可达的默认值(或 `sni_list.txt` 首行)被第一个可达候选替换、全部不可达时回退到原默认值(不让探测破坏隔离主机上的部署)、结果按 SNI 缓存;同时覆盖探针判据(完整 TLS 1.3 + 已验证证书 + HTTP 应答)与候选顺序的上限 | > 静态测试不能替代一次性 VPS 上的实测:创建与删除配置档、校验配置、重启服务、回滚以及真实客户端连接。 +> +> 该测试集并非自封闭的——请在一次性主机或容器中运行。以下两点来自在真实服务器上的运行: +> `test-ssh-protect.sh` 会走真实的 `--disable` 路径,即停止并禁用 `fail2ban`(跑完请重新启用); +> `test-hysteria2-lifecycle.sh` 期望主机上不存在订阅用的 Let's Encrypt 证书——当证书真实存在时, +> `_hysteria2_tls_mode_detect` 会正确返回 `le `,而测试期望 `selfsigned`。 ## 生命周期与 HAPP endpoint 检查 From d8e95f172a05a312ded320401c9f72347085b8e6 Mon Sep 17 00:00:00 2001 From: Ap3x0 <82464229+Ap3x0s@users.noreply.github.com> Date: Fri, 6 Nov 2026 02:59:59 +0300 Subject: [PATCH 10/13] =?UTF-8?q?fix(quickstart):=20certbot=20=D0=B4=D0=BB?= =?UTF-8?q?=D1=8F=20IP-=D1=81=D0=B5=D1=80=D1=82=D0=B8=D1=84=D0=B8=D0=BA?= =?UTF-8?q?=D0=B0=D1=82=D0=BE=D0=B2=20=D1=81=D1=82=D0=B0=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=81=D1=8F=20=D1=87=D0=B5=D1=80=D0=B5=D0=B7=20=D0=BE=D0=B1?= =?UTF-8?q?=D1=89=D0=B8=D0=B9=20=D0=BF=D0=BE=D0=BC=D0=BE=D1=89=D0=BD=D0=B8?= =?UTF-8?q?=D0=BA,=20=D1=81=20=D0=BE=D0=B6=D0=B8=D0=B4=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=D0=BC=20snapd?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Первый живой прогон на Ubuntu 24.04 (чистый образ) упал на выпуске сертификата: {"ok":false,"error":"Certbot с --ip-address и --preferred-profile не найден"} при том, что ручной `snap install --classic certbot` в тот же момент ставил 5.9.0 без проблем. Причина — дубль кода в quickstart: timeout 300 snap install --classic certbot 2>/dev/null || true На свежем образе snapd доигрывает seed/refresh и перезапускается сам («Waiting for automatic snapd restart…»); установка в этот момент обрывается мгновенно, `|| true` и `2>/dev/null` это скрывают, проверка возможностей certbot выполняется по пустому `/snap/bin/certbot` — и quickstart сообщает «не найден». Второй эффект: прогресс snap (`core 16-… installed`) писался в stdout, то есть в JSON-ответ CLI. Что сделано: * новый `_wait_snapd_ready` — `systemctl start snapd.socket` + `snap wait system seed.loaded` с бюджетом ~30 с и откатом на `snap version` для совсем старых snapd; * `_ensure_certbot_ip_tls` (единственная реализация, её же использует интерактивный путь) получила повтор установки (3 попытки) с ожиданием snapd между ними и проверку результата **по факту** — есть ли исполняемый `/snap/bin/certbot` и умеет ли он `--ip-address` + `--preferred-profile`, а не по коду возврата snap (он умеет отвечать нулём после «restart», не поставив пакет); * все вызовы snap пишут в `/tmp/snap-*.log`, прогресс и текст ошибки — в stderr: stdout CLI снова чистый JSON; * `quickstart_command` больше не содержит своего `snap install`, а вызывает `_ensure_certbot_ip_tls` и берёт путь из `CERTBOT_IP_BIN`. Новый `validation/test-certbot-snap-ip.sh` (49-й) держит контракт: единственная реализация, отсутствие inline-установки в quickstart, ожидание seed.loaded, повтор, проверка по возможностям, логи вместо stdout, и функционально — что `_certbot_supports_ip_address` отличает certbot 5.4+ от apt-версии и от «половинчатого» бинарника без `--preferred-profile`. --- validation/test-certbot-snap-ip.sh | 93 ++++++++++++++++++++++++++++++ xrayebator | 89 +++++++++++++++++++--------- 2 files changed, 154 insertions(+), 28 deletions(-) create mode 100644 validation/test-certbot-snap-ip.sh diff --git a/validation/test-certbot-snap-ip.sh b/validation/test-certbot-snap-ip.sh new file mode 100644 index 0000000..0a97902 --- /dev/null +++ b/validation/test-certbot-snap-ip.sh @@ -0,0 +1,93 @@ +#!/usr/bin/env bash +# Тест «certbot для IP-сертификатов через snap». +# +# Живой баг первого прогона на Ubuntu 24.04: quickstart ставил certbot своим +# дублем кода — `timeout 300 snap install --classic certbot 2>/dev/null || true`. +# На свежем образе snapd доигрывает seed/refresh и перезапускается сам, поэтому +# установка обрывалась мгновенно, ошибка глоталась, и quickstart отвечал +# «Certbot с --ip-address и --preferred-profile не найден» при полностью рабочем +# snap (ручной `snap install --classic certbot` в тот же момент ставил 5.9.0). +# Вдобавок прогресс snap уходил в stdout и ломал разбор JSON у GUI. +# +# Что проверяем: +# - единственная реализация `_ensure_certbot_ip_tls`, quickstart её вызывает и +# больше не содержит своего `snap install`; +# - ожидание готовности snapd (`snap wait system seed.loaded`) и повтор установки; +# - результат проверяется по возможностям certbot, а не по коду возврата snap; +# - вывод snap уходит в лог-файлы, а не в stdout CLI; +# - функционально: `_certbot_supports_ip_address` отличает certbot 5.4+ от apt-версии. +set -u +cd "$(dirname "$0")/.." + +fail() { echo "✗ $1"; exit 1; } +pass() { echo "✓ $1"; } + +TMP_ROOT="$(mktemp -d)" +trap 'rm -rf "$TMP_ROOT"' EXIT + +export LOCK_FILE="$TMP_ROOT/xrayebator.lock" +# shellcheck disable=SC1091 +source ./xrayebator || fail "source ./xrayebator failed" + +grep -q '^_ensure_certbot_ip_tls() {' xrayebator || fail "нет _ensure_certbot_ip_tls" +grep -q '^_wait_snapd_ready() {' xrayebator || fail "нет _wait_snapd_ready" + +# Быстрый путь в quickstart обязан переиспользовать общий помощник. +quickstart_body=$(sed -n '/^quickstart_command() {/,/^}/p' xrayebator) +[[ -n "$quickstart_body" ]] || fail "не найдено тело quickstart_command" +case "$quickstart_body" in + *_ensure_certbot_ip_tls*) ;; + *) fail "quickstart не вызывает _ensure_certbot_ip_tls" ;; +esac +if printf '%s' "$quickstart_body" | grep -qE 'snap install'; then + fail "quickstart снова ставит certbot своим дублем (snap install внутри quickstart)" +fi + +# Ожидание готовности snapd и повтор установки. +grep -q 'snap wait system seed.loaded' xrayebator || fail "_wait_snapd_ready не ждёт seed.loaded" +helpers=$(sed -n '/^_ensure_certbot_ip_tls() {/,/^}/p' xrayebator) +printf '%s' "$helpers" | grep -q 'for attempt in 1 2 3' || fail "нет повтора установки snap" +printf '%s' "$helpers" | grep -q '_wait_snapd_ready' || fail "повтор не дожидается snapd" +# Результат — по возможностям certbot, а не по коду возврата snap. +printf '%s' "$helpers" | grep -q '_certbot_supports_ip_address "\$candidate"' \ + || fail "установка не проверяет возможности certbot по факту" +# Вывод snap не должен попадать в stdout CLI: реальные вызовы пишут в лог-файл +# (комментарии и текст сообщений об ошибке — не в счёт). +if printf '%s\n' "$helpers" | grep -vE '^[[:space:]]*#' | grep -v 'echo' \ + | grep -E 'snap (install|refresh)' | grep -vq '/tmp/snap'; then + fail "snap install/refresh пишет не в лог-файл (засорит stdout CLI)" +fi +grep -q '"--ip-address"' xrayebator || grep -q -- "'--ip-address'" xrayebator \ + || fail "_certbot_supports_ip_address не проверяет --ip-address" +grep -q -- '--preferred-profile' xrayebator || fail "нет проверки --preferred-profile" +pass "статика: один путь установки, ожидание snapd, повтор, проверка по факту" + +# Функционально: различаем apt-certbot и certbot 5.4+. +mk_stub() { # <файл> <да/нет ip-address> <да/нет preferred-profile> + { + echo '#!/usr/bin/env bash' + echo 'case "$1" in' + echo ' --help)' + echo ' echo "usage: certbot [options]"' + [[ "$2" == "да" ]] && echo ' echo " --ip-address IP Request a certificate for an IP"' + [[ "$3" == "да" ]] && echo ' echo " --preferred-profile NAME"' + echo ' ;;' + echo ' --version) echo "certbot 5.9.0" ;;' + echo 'esac' + } > "$1" + chmod +x "$1" +} + +modern="$TMP_ROOT/certbot-new" +old="$TMP_ROOT/certbot-apt" +half="$TMP_ROOT/certbot-half" +mk_stub "$modern" да да +mk_stub "$old" нет нет +mk_stub "$half" да нет + +_certbot_supports_ip_address "$modern" || fail "certbot 5.4+ не распознан" +_certbot_supports_ip_address "$old" && fail "apt-certbot ошибочно признан поддерживающим IP" +_certbot_supports_ip_address "$half" && fail "половинчатый certbot (без --preferred-profile) принят" +pass "функционально: certbot 5.4+ отличается от apt-версии и от половинчатого" + +echo "✓ Certbot для IP через snap: единый путь, ожидание snapd, повтор, лог вместо stdout — OK" diff --git a/xrayebator b/xrayebator index 8f4fa17..8dd4848 100755 --- a/xrayebator +++ b/xrayebator @@ -2018,6 +2018,23 @@ _certbot_failure_reason() { return 0 } +# Ждёт готовности snapd. На свежем Ubuntu 24.04 демон доигрывает seed/refresh и +# перезапускается сам («Waiting for automatic snapd restart…»), а `snap install` в +# этот момент обрывается мгновенно — из-за этого quickstart получал «certbot не +# найден» при полностью работоспособном snap. Возврат 0 — демон отвечает. +_wait_snapd_ready() { + local i + systemctl start snapd.socket >/dev/null 2>&1 || true + for i in 1 2 3 4 5 6 7 8 9 10; do + if snap wait system seed.loaded >/dev/null 2>&1; then + return 0 + fi + sleep 3 + done + # Совсем старые snapd могут не знать подкоманду `wait` — тогда достаточно ответа. + snap version >/dev/null 2>&1 +} + _ensure_certbot_ip_tls() { CERTBOT_IP_BIN="" @@ -2030,35 +2047,52 @@ _ensure_certbot_ip_tls() { fi done - echo -e "${YELLOW} → Системный certbot не поддерживает IP certificates; ставлю актуальный certbot через snap...${NC}" + # Прогресс — в stderr: у CLI-команд stdout обязан оставаться чистым JSON + # (snap пишет свои «core … installed» в stdout, и они ломали разбор ответа). + echo -e "${YELLOW} → Системный certbot не поддерживает IP certificates; ставлю актуальный certbot через snap...${NC}" >&2 + _apt_wait_lock 300 || true if ! apt-get "${APT_LOCK_OPTS[@]}" install -y snapd >/dev/null 2>&1; then - echo -e "${RED}✗ Не удалось установить snapd для Certbot 5.4+${NC}" + echo -e "${RED}✗ Не удалось установить snapd для Certbot 5.4+${NC}" >&2 return 1 fi systemctl enable --now snapd.socket >/dev/null 2>&1 || true export PATH="/snap/bin:$PATH" - if command -v snap >/dev/null 2>&1; then + if ! command -v snap >/dev/null 2>&1; then + echo -e "${RED}✗ snap command не найден после установки snapd${NC}" >&2 + return 1 + fi + + local attempt + _wait_snapd_ready + for attempt in 1 2 3; do if snap list core >/dev/null 2>&1; then snap refresh core >/tmp/snap-core.log 2>&1 || true - elif ! snap install core >/tmp/snap-core.log 2>&1; then - echo -e "${RED}✗ snap install core не удался. Лог: /tmp/snap-core.log${NC}" - tail -20 /tmp/snap-core.log - return 1 + else + snap install core >/tmp/snap-core.log 2>&1 || true fi - if snap list certbot >/dev/null 2>&1; then snap refresh certbot >/tmp/snap-certbot.log 2>&1 || true - elif ! snap install --classic certbot >/tmp/snap-certbot.log 2>&1; then - echo -e "${RED}✗ snap install certbot не удался. Лог: /tmp/snap-certbot.log${NC}" - tail -20 /tmp/snap-certbot.log - return 1 + else + snap install --classic certbot >/tmp/snap-certbot.log 2>&1 || true fi - else - echo -e "${RED}✗ snap command не найден после установки snapd${NC}" - return 1 - fi + + # Проверяем результат по факту, а не по коду возврата: `snap install` умеет + # отвечать нулём после «Waiting for automatic snapd restart…» и не поставить пакет. + for candidate in /snap/bin/certbot; do + [[ -x "$candidate" ]] || continue + if _certbot_supports_ip_address "$candidate"; then + CERTBOT_IP_BIN="$candidate" + return 0 + fi + done + + [[ "$attempt" -lt 3 ]] || break + echo -e "${YELLOW} → snapd перезапускался во время установки, повтор (${attempt}/3)...${NC}" >&2 + _wait_snapd_ready + sleep 3 + done for candidate in /snap/bin/certbot "$(command -v certbot 2>/dev/null || true)"; do [[ -n "$candidate" && -x "$candidate" ]] || continue @@ -2068,7 +2102,9 @@ _ensure_certbot_ip_tls() { fi done - echo -e "${RED}✗ Не найден Certbot 5.4+ с поддержкой --ip-address${NC}" + echo -e "${RED}✗ snap install certbot не удался (snapd не доиграл seed/refresh?). Лог:${NC}" >&2 + tail -6 /tmp/snap-certbot.log >&2 2>/dev/null || true + echo -e "${RED}✗ Не найден Certbot 5.4+ с поддержкой --ip-address${NC}" >&2 return 1 } @@ -15359,18 +15395,15 @@ quickstart_command() { certbot_bin="$(command -v certbot)" fi if [[ -z "$certbot_bin" ]]; then - echo " -> Установка certbot через snap..." >&2 - _apt_wait_lock 300 || true - timeout 240 apt-get "${APT_LOCK_OPTS[@]}" install -y snapd >/dev/null 2>&1 || true - systemctl enable --now snapd.socket >/dev/null 2>&1 || true - export PATH="/snap/bin:$PATH" - if command -v snap &>/dev/null; then - timeout 300 snap install core 2>/dev/null || true - timeout 300 snap install --classic certbot 2>/dev/null || true - if command -v /snap/bin/certbot &>/dev/null && _certbot_supports_ip_address /snap/bin/certbot; then - certbot_bin="/snap/bin/certbot" - fi + # Один источник истины с интерактивным путём (_ensure_certbot_ip_tls): та версия + # писала логи и честно сообщала причину, а здешний дубль глотал ошибку через + # `2>/dev/null || true` — на Ubuntu 24.04 это дало «certbot не найден» при живом + # snap (демон в тот момент перезапускался) и заодно засоряло stdout прогрессом snap. + if ! _ensure_certbot_ip_tls; then + echo '{"ok":false,"error":"Certbot с --ip-address и --preferred-profile не найден: snap не установил certbot (см. stderr)"}' + return 1 fi + certbot_bin="$CERTBOT_IP_BIN" fi if [[ -z "$certbot_bin" ]]; then echo '{"ok":false,"error":"Certbot с --ip-address и --preferred-profile не найден"}' From bd89be59cc582ed048938b096dbb1bae651af640 Mon Sep 17 00:00:00 2001 From: Ap3x0 <82464229+Ap3x0s@users.noreply.github.com> Date: Fri, 6 Nov 2026 03:11:06 +0300 Subject: [PATCH 11/13] =?UTF-8?q?docs:=20Ubuntu=2024.04=20=E2=80=94=20snap?= =?UTF-8?q?-certbot=20=D0=BD=D0=B0=20=D1=81=D0=B2=D0=B5=D0=B6=D0=B5=D0=BC?= =?UTF-8?q?=20=D0=BE=D0=B1=D1=80=D0=B0=D0=B7=D0=B5,=20=D1=81=D1=87=D1=91?= =?UTF-8?q?=D1=82=20=D1=82=D0=B5=D1=81=D1=82=D0=BE=D0=B2=2049?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Первый живой прогон на Ubuntu 24.04 закрыл последний непокрытый пункт матрицы и дал одну новую секцию в troubleshooting (ru/en/zh) и запись в CHANGELOG. `docs/troubleshooting.md` (+ ru, zh-CN), раздел «Ubuntu 24.04: quickstart не находит certbot для IP-сертификата»: симптом (`{"ok":false,"error":"Certbot с --ip-address и --preferred-profile не найден"}` при рабочем ручном `snap install`), причина (snapd на свежем 24.04 доигрывает seed/refresh и перезапускается, установка обрывается мгновенно; apt-certbot в 24.04 не умеет ни `--ip-address`, ни `--preferred-profile`), что делать (повторить команду — путь идемпотентен) и как проверить руками (`snap wait system seed.loaded`, `snap install --classic certbot`, `grep -- '--ip-address'`). Там же — что `/tmp` на 24.04 это tmpfs, поэтому `/tmp/snap-certbot.log` после перезагрузки исчезает. `CHANGELOG.md`: в `[Unreleased]` добавлен блок `Fixed` — snap-certbot (с ссылкой на новый 49-й тест), чистый stdout у quickstart и `open_firewall_port`, `channel-test` без `--name` и портируемость `test-channel-test-cli.sh`. `docs/testing.md` (+ ru, zh-CN): счёт 48 → 49, строка про `test-certbot-snap-ip.sh` в таблице, актуальное число в описании CI. Заодно починен оставшийся устаревший «45» в русском описании CI (он уцелел при восстановлении файла после порчи NUL-байтом). Проверено: `check-links.ps1` — 0 битых ссылок и 0 расхождений колонок; `check-encoding.ps1` — 0 файлов с внеалфавитной кириллицей; `parity.ps1` — счётчики расхождений по troubleshooting/testing не выросли (остаточные — из старых разделов). --- CHANGELOG.md | 17 +++++++++++++++++ docs/ru/testing.md | 5 +++-- docs/ru/troubleshooting.md | 36 +++++++++++++++++++++++++++++++++++ docs/testing.md | 5 +++-- docs/troubleshooting.md | 36 +++++++++++++++++++++++++++++++++++ docs/zh-CN/testing.md | 5 +++-- docs/zh-CN/troubleshooting.md | 32 +++++++++++++++++++++++++++++++ 7 files changed, 130 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eabc903..60f8d98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,23 @@ key, the bot token) had the same problem with a millisecond window. - New `validation/test-secret-argv.sh` locks the contract in place: a stub `curl` asserts that the secret is absent from `argv` and present on stdin. +### Fixed + +- `quickstart` on a fresh Ubuntu 24.04 no longer answers "Certbot с --ip-address и + --preferred-profile не найден" while a manual `snap install --classic certbot` works: `snapd` on + that image finishes seeding and restarts itself right after boot, so the inline install aborted + instantly and the error was swallowed by `2>/dev/null || true`. The IP-certbot path is now the + single `_ensure_certbot_ip_tls` helper, which waits for `snap wait system seed.loaded`, retries the + install, verifies the result by the binary's actual flags, and logs to `/tmp/snap-*.log`. + Guarded by `validation/test-certbot-snap-ip.sh` (49th script). +- `quickstart` and `open_firewall_port` no longer write progress lines to stdout: snap output and + firewall statuses go to stderr, so `xrayebator quickstart --without-email | jq .ok` parses. +- `channel-test` without `--name` uses the only profile in the system instead of answering + "Укажите --name профиля" (`HAPP_DEFAULT_PROFILE` is set only inside a quickstart process). +- `validation/test-channel-test-cli.sh` anchored its helper block on an ASCII line: the previous + pattern used the box-drawing character `─`, which neither `mawk` (the Debian/Ubuntu default) nor + byte-oriented `gawk` matches, so the test failed from the locale rather than from the code. + ## [0.7.2] - 2026-11-04 The `0.7.2` security patch: Xray-core moved to `26.10.31` (the urgent release that stops diff --git a/docs/ru/testing.md b/docs/ru/testing.md index 4249e95..559e885 100644 --- a/docs/ru/testing.md +++ b/docs/ru/testing.md @@ -36,7 +36,7 @@ Linux-машину. Проверки lifecycle должны также убеж ## Что покрывают тесты -В `validation/` ровно 48 скриптов. Запускайте каждый `validation/test-*.sh`; текущий набор: +В `validation/` ровно 49 скриптов. Запускайте каждый `validation/test-*.sh`; текущий набор: | Тест | Что проверяет | |---|---| @@ -51,6 +51,7 @@ Linux-машину. Проверки lifecycle должны также убеж | `test-sni-reachability.sh` | Выбор дефолтного SNI: недоступный кандидат заменяется доступным, полная недоступность оставляет прежний дефолт, одна проба на SNI за запуск, строгий критерий TLS 1.3 + HTTP проверяется на реальном выводе `openssl`, порядок кандидатов (голова списка, затем глобальные фолбэки) и обязательный второй замер | | `test-dns01-certbot.sh` | DNS-01 (Cloudflare/Route53): валидацию домена (IP и локальные имена отклоняются) и провайдера, сборку аргументов certbot (плагин, credentials, propagation, deploy-hook, `-m` или регистрация без email), запись credentials `0600` с содержимым по провайдеру, nginx-vhost **без** `listen 80` и ACME-location, CLI-ошибки без записи на диск и проводку (диспатчер, пункт меню, пакеты плагинов, UFW-порт, маркеры `domain_tls`, manifest certbot, cleanup в uninstall) | | `test-bbr-removal-migration.sh` | Безопасное удаление удалённого BBR/TCP tuning на всех путях | +| `test-certbot-snap-ip.sh` | Certbot для IP-сертификатов: единственная реализация `_ensure_certbot_ip_tls` (в quickstart нет своего `snap install`), ожидание готовности snapd (`snap wait system seed.loaded`), повтор установки, проверка результата по фактическим флагам бинарника, вывод snap в лог вместо stdout; функционально — `_certbot_supports_ip_address` отличает certbot 5.4+ от apt-версии и от бинарника без `--preferred-profile` | | `test-profile-revoke-expire-cli.sh` | CLI `profile-revoke` (только токен / ротация uuid с сохранением чужих клиентов на общем порту) и сроки профилей (отключение, возврат из снимка, rebuild без снимка, идемпотентный `expire-check`) | | `test-cascade-routing.sh` | Cascade routing | | `test-cascade-upstream-import.sh` | Импорт upstream каскада из ссылки VLESS | @@ -217,7 +218,7 @@ npm run build - `.github/workflows/ci-linux.yml` — гейт Bash-ядра на `ubuntu-24.04`: ставит `jq`, `uuid-runtime` и `ripgrep`, прогоняет все четыре проверки синтаксиса Bash, затем запускает каждый - `validation/test-*.sh` (на момент написания — 45). + `validation/test-*.sh` (на момент написания — 49). - `.github/workflows/release.yml` — активный путь релиза Electron для тегов `v*` и ручных запусков. Сначала job `preflight` проверяет, что файл релизных заметок `docs/releases/.en.md` существует и что секрет репозитория `AP3X0` (если задан) действительно может создавать релизы — проверка идёт diff --git a/docs/ru/troubleshooting.md b/docs/ru/troubleshooting.md index 719b2ee..d788e05 100644 --- a/docs/ru/troubleshooting.md +++ b/docs/ru/troubleshooting.md @@ -511,6 +511,42 @@ Debian 13, запущено `6.12.85`, в репозитории `6.12.115`), к перезагрузки модуль подхватывается через `/etc/modules-load.d/xrayebator-awg.conf`, а `awg0` поднимается юнитом. +## Ubuntu 24.04: `quickstart` не находит certbot для IP-сертификата + +**Симптом.** На свежеустановленной Ubuntu 24.04 `quickstart` (и GUI-развёртывание) заканчивается +ответом: + +```json +{"ok":false,"error":"Certbot с --ip-address и --preferred-profile не найден"} +``` + +хотя руками `snap install --classic certbot` в этот же момент ставит certbot 5.x без единой ошибки. + +**Причина.** Ubuntu 24.04 приходит с готовым `snapd`, который сразу после первой загрузки (и после +первого обновления) доигрывает seed/refresh и перезапускает сам себя — в логе это видно как +`Waiting for automatic snapd restart...`. Установка пакета в этот момент обрывается мгновенно, а +сертификаты на IP умеет выпускать только snap-certbot (`--ip-address` + `--preferred-profile`): +apt-версия в 24.04 их не знает. + +**Что делать.** В этой версии менеджер дожидается готовности snapd (`snap wait system seed.loaded`), +повторяет установку и проверяет результат по фактическим возможностям бинарника, поэтому достаточно +повторить команду — она идемпотентна: + +```bash +sudo xrayebator quickstart --without-email # или кнопка развёртывания в GUI +``` + +Если хочется удостовериться вручную: + +```bash +sudo snap wait system seed.loaded +sudo snap install --classic certbot +/snap/bin/certbot --help all | grep -c -- '--ip-address' # 1 — годится +``` + +Лог неудачной установки snap лежит в `/tmp/snap-certbot.log`. На Ubuntu 24.04 `/tmp` — tmpfs, так +что после перезагрузки там ничего не остаётся. + ## Вылезла ошибка при установке или работе ### `Сгенерированный config.json не прошёл валидацию — live-конфиг не изменён` diff --git a/docs/testing.md b/docs/testing.md index f4c28f5..9adcdd5 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -36,7 +36,7 @@ promise that installer and updater paths behave identically. ## Validation suite -`validation/` contains exactly 48 scripts. Run every `validation/test-*.sh`; the current set is: +`validation/` contains exactly 49 scripts. Run every `validation/test-*.sh`; the current set is: | Script | What it checks | |---|---| @@ -51,6 +51,7 @@ promise that installer and updater paths behave identically. | `test-sni-reachability.sh` | Default SNI selection: an unreachable candidate is replaced by a reachable one, total unreachability keeps the previous default, one probe per SNI per run, the strict TLS 1.3 + HTTP criterion checked against real `openssl` output, candidate order (head of the list, then global fallbacks), and the required second attempt | | `test-dns01-certbot.sh` | DNS-01 (Cloudflare/Route53): domain/provider validation (IP addresses and single-label local names rejected), certbot argument assembly per provider (plugin, credentials, propagation, deploy-hook, `-m` vs email-less registration), `0600` credentials content per provider, an nginx vhost **without** `listen 80` and ACME location, CLI validation errors that write nothing to disk, and the static wiring (dispatcher, menu item, plugin packages, UFW port, `domain_tls` markers, the certbot manifest, uninstall cleanup) | | `test-bbr-removal-migration.sh` | Safe removal of the retired BBR/TCP tuning | +| `test-certbot-snap-ip.sh` | Certbot for IP certificates: a single `_ensure_certbot_ip_tls` implementation (quickstart keeps no `snap install` of its own), waiting for snapd readiness (`snap wait system seed.loaded`), a retried install, the result verified by the binary's actual flags, snap output going to a log instead of stdout; functionally, `_certbot_supports_ip_address` tells certbot 5.4+ apart from the apt build and from a binary without `--preferred-profile` | | `test-profile-revoke-expire-cli.sh` | Subscription revoke (token-only and uuid rotation, foreign clients on shared ports survive) and profile expiry (disable/enable, rebuild without a snapshot, idempotent `expire-check`) | | `test-cascade-routing.sh` | Cascade routing configuration | | `test-cascade-upstream-import.sh` | Cascade upstream import from a VLESS link | @@ -217,7 +218,7 @@ The workflows have separate responsibilities: - `.github/workflows/ci-linux.yml` is the Bash core gate on `ubuntu-24.04`: it installs `jq`, `uuid-runtime` and `ripgrep`, runs all four Bash syntax checks, then runs every - `validation/test-*.sh` script (48 at the time of writing). + `validation/test-*.sh` script (49 at the time of writing). - `.github/workflows/release.yml` is the active Electron release path for `v*` tags or manual runs. A `preflight` job first checks that the release notes file `docs/releases/.en.md` exists and that the `AP3X0` repository secret (if set) can actually create releases — it probes with a draft diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index d96a7ce..1e35991 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -542,6 +542,42 @@ Debian 13, running `6.12.85`, repository `6.12.115`), the command answers `reboo the name of the new kernel — reboot and repeat `sudo xrayebator awg-install`. After the reboot the module is loaded through `/etc/modules-load.d/xrayebator-awg.conf` and `awg0` comes up via its unit. +## Ubuntu 24.04: `quickstart` cannot find certbot for an IP certificate + +**Symptom.** On a freshly installed Ubuntu 24.04 `quickstart` (and the GUI deployment) ends with: + +```json +{"ok":false,"error":"Certbot с --ip-address и --preferred-profile не найден"} +``` + +while `snap install --classic certbot` by hand installs certbot 5.x at that very moment without a +single error. + +**Cause.** Ubuntu 24.04 ships with `snapd` ready to go, and right after the first boot (and after the +first refresh) it finishes seeding and restarts itself — the log shows +`Waiting for automatic snapd restart...`. A package install at that moment aborts instantly. And IP +certificates need the snap build (`--ip-address` plus `--preferred-profile`): the apt version in 24.04 +knows neither flag. + +**What to do.** This version waits for `snapd` (`snap wait system seed.loaded`), retries the install +and verifies the result by what the binary can actually do, so simply repeating the command is enough — +it is idempotent: + +```bash +sudo xrayebator quickstart --without-email # or the deploy button in the GUI +``` + +To check by hand: + +```bash +sudo snap wait system seed.loaded +sudo snap install --classic certbot +/snap/bin/certbot --help all | grep -c -- '--ip-address' # 1 means it works +``` + +The log of a failed snap install is `/tmp/snap-certbot.log`. On Ubuntu 24.04 `/tmp` is a tmpfs, so +nothing survives a reboot. + ## An error appeared during installation or use ### `Сгенерированный config.json не прошёл валидацию — live-конфиг не изменён` diff --git a/docs/zh-CN/testing.md b/docs/zh-CN/testing.md index 16680c0..5443eed 100644 --- a/docs/zh-CN/testing.md +++ b/docs/zh-CN/testing.md @@ -15,7 +15,7 @@ for test_file in validation/*.sh; do bash "$test_file" || exit; done ## 测试覆盖范围 -`validation/` 中有 48 个静态与本地回归测试: +`validation/` 中有 49 个静态与本地回归测试: | 测试 | 检查内容 | |---|---| @@ -37,6 +37,7 @@ for test_file in validation/*.sh; do bash "$test_file" || exit; done | `test-config-temp-json-suffix.sh` | 安装与更新时的配置校验:交给 `xray run -test` 的临时配置必须以 `.json` 结尾(Xray ≥ 26.10 按扩展名判断格式并忽略 `-format json`),失败时打印内核输出,并功能性验证 `mktemp --suffix=.json` | | `test-installer-network-fallbacks.sh` | 安装脚本网络回退 | | `test-bbr-removal-migration.sh` | 已删除 BBR/TCP 调优在所有路径上的安全清理 | +| `test-certbot-snap-ip.sh` | IP 证书用的 certbot:唯一的 `_ensure_certbot_ip_tls` 实现(quickstart 不再自己 `snap install`)、等待 snapd 就绪(`snap wait system seed.loaded`)、安装重试、按二进制实际具备的旗标校验结果、snap 输出进日志而非 stdout;并功能性验证 `_certbot_supports_ip_address` 能区分 certbot 5.4+、apt 版本与缺少 `--preferred-profile` 的二进制 | | `test-legacy-udp443-migration.sh` | 一次性清理旧版 UDP/443 阻断规则 | | `test-main-menu-numbering.sh` | 主菜单条目编号连续并与处理函数一致(含后端条目与监控的 1..14) | | `test-backend-registry.sh` | 后端注册表(多协议阶段):source-mode 下的注册表 CRUD(经 `safe_jq_write`)、installed/field 读取、生命周期入口的安全 no-op、`backend-status` JSON 结构 | @@ -176,7 +177,7 @@ npm test # Vitest 单元测试 三个独立 workflow: -- **ci-linux.yml** — Bash validation:在 ubuntu-24.04 上对所有脚本执行 `bash -n`,并运行全部 48 个 +- **ci-linux.yml** — Bash validation:在 ubuntu-24.04 上对所有脚本执行 `bash -n`,并运行全部 49 个 `validation/test-*.sh`;在 push 到 `main`、`dev`、`experimental` 以及 pull request 时运行。 - **release.yml** — Electron 构建(Windows/macOS/Linux)。只在 `v*` tag 和手动触发时运行;先由 `preflight` 检查发布说明 `docs/releases/.en.md` 是否存在,以及仓库密钥 `AP3X0`(若已设置) diff --git a/docs/zh-CN/troubleshooting.md b/docs/zh-CN/troubleshooting.md index 8a19636..68d3d55 100644 --- a/docs/zh-CN/troubleshooting.md +++ b/docs/zh-CN/troubleshooting.md @@ -418,6 +418,38 @@ wget -qO ./xrayebator-install.sh \ 并给出新内核名——重启后再执行一次 `sudo xrayebator awg-install`。重启后模块通过 `/etc/modules-load.d/xrayebator-awg.conf` 加载,`awg0` 由其单元拉起。 +## Ubuntu 24.04:`quickstart` 找不到可用于 IP 证书的 certbot + +**现象。** 在全新安装的 Ubuntu 24.04 上,`quickstart`(以及 GUI 部署)以如下响应结束: + +```json +{"ok":false,"error":"Certbot с --ip-address и --preferred-profile не найден"} +``` + +而在同一时刻手动执行 `snap install --classic certbot` 却能顺利装上 certbot 5.x。 + +**原因。** Ubuntu 24.04 自带已就绪的 `snapd`,首次启动后(以及首次刷新后)它还在完成 seed 并会 +自行重启——日志里表现为 `Waiting for automatic snapd restart...`。此刻安装软件包会立即中断。 +而 IP 证书只有 snap 版 certbot 支持(`--ip-address` 加 `--preferred-profile`):24.04 里 apt 版本 +两个参数都不认识。 + +**怎么做。** 当前版本会等待 snapd 就绪(`snap wait system seed.loaded`)、重试安装,并按二进制 +实际具备的能力校验结果,所以直接重复命令即可(幂等): + +```bash +sudo xrayebator quickstart --without-email # 或 GUI 中的部署按钮 +``` + +手动确认: + +```bash +sudo snap wait system seed.loaded +sudo snap install --classic certbot +/snap/bin/certbot --help all | grep -c -- '--ip-address' # 输出 1 表示可用 +``` + +snap 安装失败的日志在 `/tmp/snap-certbot.log`。Ubuntu 24.04 的 `/tmp` 是 tmpfs,重启后不会保留。 + ## 安装或使用过程中出现报错 ### `Сгенерированный config.json не прошёл валидацию — live-конфиг не изменён` From 33ba08f197f47de53aaa7654251b55ec9c4cea09 Mon Sep 17 00:00:00 2001 From: Ap3x0 <82464229+Ap3x0s@users.noreply.github.com> Date: Sat, 7 Nov 2026 15:47:26 +0300 Subject: [PATCH 12/13] =?UTF-8?q?test(hysteria2):=20=D1=81=D0=B0=D0=BC?= =?UTF-8?q?=D0=BE=D0=B2=D0=BE=D1=81=D1=81=D1=82=D0=B0=D0=BD=D0=BE=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B8=D0=B7=20=D0=BF=D0=BE?= =?UTF-8?q?=D0=B2=D1=80=D0=B5=D0=B6=D0=B4=D1=91=D0=BD=D0=BD=D0=BE=D0=B3?= =?UTF-8?q?=D0=BE=20=D1=81=D0=BE=D1=81=D1=82=D0=BE=D1=8F=D0=BD=D0=B8=D1=8F?= =?UTF-8?q?=20+=20=D0=B3=D0=B5=D1=80=D0=BC=D0=B5=D1=82=D0=B8=D1=87=D0=BD?= =?UTF-8?q?=D0=BE=D1=81=D1=82=D1=8C=20=D0=BF=D1=83=D1=82=D0=B5=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Два реальных дефекта, найденных прогоном на живом Ubuntu 22.04. 1. Бэкенд не восстанавливался сам. Состояние «реестр говорит installed, а на диске бинарника/юнита/конфига нет» — это сбой обновления или ручная чистка — `hysteria2-install` встречал ответом `{"ok":true,"already":true}` и НЕ делал ничего, а `hysteria2-status` честно писал `binary: "absent"`. Пользователь оставался без бэкенда и без пути починки: единственным выходом был `hysteria2-uninstall`, о чём нигде не сказано. Теперь install проверяет фактическое наличие трёх артефактов (бинарник, юнит, server.yaml) и, если чего-то нет, снимает запись реестра и проходит обычным путём установки. Проверено живьём: удалил `/usr/local/bin/hysteria` при живом реестре → `hysteria2-install --grant-all` восстановил бинарник (23.9 МБ), юнит `active`, UDP-сокет на месте, `state: active`. 2. Осиротевший юнит держал порт. Юнит живёт, пока жив процесс, даже если бинарник с диска удалён, поэтому восстановление упиралось в «UDP-порт 443 уже занят». Теперь перед проверкой порта останавливается только СВОЙ юнит (`systemctl stop hysteria-server.service`) — чужие слушатели по-прежнему дают честную ошибку. Герметичность тестов (причина, по которой это вообще случилось). Прогон `validation/` на рабочем сервере — штатная практика этого проекта, но два теста были к этому не готовы и меняли состояние хоста: * `test-hysteria2-lifecycle.sh` вызывает `_hysteria2_uninstall`, который делает `rm -f "$HYSTERIA2_BIN"` — то есть УДАЛИЛ настоящий `/usr/local/bin/hysteria` на сервере. Теперь `HYSTERIA2_BIN`, `HYSTERIA2_UNIT_FILE`, `HYSTERIA2_SYSCTL_FILE` и `HYSTERIA2_CERTBOT_HOOK` в xrayebator переопределяемы (тот же root-override приём, что у `CONFIG_FILE`), а тест уводит их в tmp. Детект TLS и метка ссылки тоже проверяются на синтетических путях — раньше они зависели от того, есть ли на хосте живой Let's Encrypt и geo-маркер страны, и краснели на любом реальном сервере; * `test-awg-lifecycle.sh` хардкодил «чужое» ядро `5.15.0-177-generic` — ровно то, которое оказалось запущено на этом сервере, из-за чего проверка «модуль для другого ядра» превращалась в проверку «модуль для этого же». Заменено на синтетическое имя; `AWG_SYSCTL_FILE`/`AWG_MODULES_LOAD_FILE` стали переопределяемыми, чтобы тест не мог тронуть системный sysctl. Плюс защита от Windows-артефакта: `openssl rand -base64` под Git Bash отдаёт CRLF, и HPK приезжал с `\r` — тест теперь проверяет значение, а не байты вывода, и отдельно требует, чтобы в самом ключе не было переводов строк. Проверено: на Ubuntu 22.04 весь набор — 49/49 зелёных в чистом окружении (до правок было 47/49), и на сервере после прогона Hysteria и AmneziaWG остались рабочими. --- validation/test-awg-lifecycle.sh | 40 +++++++++++++--- validation/test-hysteria2-lifecycle.sh | 50 ++++++++++++++++++-- xrayebator | 65 ++++++++++++++++++++------ 3 files changed, 130 insertions(+), 25 deletions(-) diff --git a/validation/test-awg-lifecycle.sh b/validation/test-awg-lifecycle.sh index afdb032..ae5d020 100644 --- a/validation/test-awg-lifecycle.sh +++ b/validation/test-awg-lifecycle.sh @@ -14,6 +14,12 @@ command -v openssl >/dev/null 2>&1 || fail "openssl required" TMP_ROOT="$(mktemp -d)" trap 'rm -rf "$TMP_ROOT"' EXIT +# ВАЖНО про Windows-хост. MSYS (Git Bash) конвертирует аргументы, похожие на +# POSIX-пути, в Windows-пути: base64-ключ, начинающийся с «/», приходит в jq.exe как +# «C:/Program Files/Git/…». Продукт работает на Linux, CI — на Linux, поэтому лечить +# это в xrayebator нечего; здесь достаточно знать, что на Git Bash часть seeded +# прогонов может покраснеть от этой конверсии, а не от кода. Отключение конверсии +# глобально ломает разбор реальных путей, поэтому не делаем его. export BACKENDS_ROOT="$TMP_ROOT/xrayebator-backends" export LOCK_FILE="$TMP_ROOT/xrayebator.lock" export PROFILES_DIR="$TMP_ROOT/profiles" @@ -79,6 +85,10 @@ mkdir -p "$(dirname "$AWG_MODULES_LOAD_FILE")" for seed in {1..300}; do RANDOM=$seed junk=$(_awg_gen_junk) + # Спека проверяется на ЗНАЧЕНИИ, а не на байтах stdout: на Windows-хосте (Git + # Bash/MSYS) jq печатает CRLF, и `endswith("=")` видел «=\r» — тест краснел от + # платформы при корректном JSON. На Linux CRLF нет, поэтому CI это не ловил. + junk_canon=$(printf '%s' "$junk" | tr -d '\r') jq -e ' .Jc == 5 and .Jmin == 10 and .Jmax == 50 and .S1 >= 12 and .S1 <= 150 and .S2 >= 12 and .S2 <= 150 and @@ -87,7 +97,14 @@ for seed in {1..300}; do (.S1 + 56) != .S2 and .H1 == 1 and .H2 == 2 and .H3 == 3 and .H4 == 4 and (.HeaderProtectionKey | length == 44 and endswith("=")) - ' <<<"$junk" >/dev/null || fail "junk/3.1 params out of spec (seed $seed): $junk" + ' <<<"$junk_canon" >/dev/null || fail "junk/3.1 params out of spec (seed $seed): $junk" + # И отдельно: значение HPK не должно содержать переводов строк/CR вовсе — + # иначе артефакт уедет в server-params.json и в клиентские .conf. Сам jq -r на + # Windows печатает CRLF, поэтому хвост снимаем перед сравнением. + hpk_val=$(jq -r '.HeaderProtectionKey' <<<"$junk_canon" | tr -d '\r\n') + [[ "$hpk_val" != *$'\n'* && "$hpk_val" != *$'\r'* ]] \ + || fail "HPK contains line breaks (seed $seed): $hpk_val" + [[ "${#hpk_val}" -eq 44 ]] || fail "HPK length ${#hpk_val} != 44 (seed $seed)" done pass "junk = Amnezia defaults (Jc=5/Jmin=10/Jmax=50/H=1..4) + S1-S4 unique + HPK (300 seeded runs)" @@ -96,10 +113,12 @@ old_junk=$(jq -c 'del(.S3, .S4, .HeaderProtectionKey)' <<<"$junk") for seed in {1..100}; do RANDOM=$seed upgraded=$(_awg_ensure_31_params "$old_junk") || fail "ensure_31_params" + # Тот же Windows-артефакт (jq печатает CRLF): проверяем значение, не байты. + upgraded_canon=$(printf '%s' "$upgraded" | tr -d '\r') jq -e 'has("S3") and has("S4") and (.S3 >= 12) and (.S3 <= 64) and (.S4 >= 12) and (.S4 <= 64) and ([.S1, .S2, .S3, .S4] | (length == ([unique[]] | length))) and - (.HeaderProtectionKey | length == 44)' <<<"$upgraded" >/dev/null \ + (.HeaderProtectionKey | length == 44)' <<<"$upgraded_canon" >/dev/null \ || fail "ensure_31_params did not add valid 3.1 fields (seed $seed): $upgraded" done pass "_awg_ensure_31_params upgrades legacy params with S3/S4 (12..64, unique) + HPK" @@ -282,14 +301,18 @@ pass "modules-load.d written only with a live module (reboot-safe)" # ручной сборки, поэтому фолбэк-сборка не запускалась, а установка падала на # «модуль не загрузился» (живой случай: ядро 5.15.0-177 → -198). export AWG_MODULES_ROOT="$TMP_ROOT/modules" -mkdir -p "$AWG_MODULES_ROOT/$(uname -r)/extra" "$AWG_MODULES_ROOT/5.15.0-177-generic/extra" -touch "$AWG_MODULES_ROOT/5.15.0-177-generic/extra/amneziawg.ko" +# «Чужое» ядро не хардкодим: на живом сервере с 5.15.0-177 тест падал, потому что +# ровно это ядро и было текущим, и проверка «модуль для другого ядра» становилась +# проверкой «модуль для этого же». Имя синтетическое и заведомо не совпадает с uname -r. +FOREIGN_KERNEL="9.99.0-xrayebator-test-foreign" +mkdir -p "$AWG_MODULES_ROOT/$(uname -r)/extra" "$AWG_MODULES_ROOT/$FOREIGN_KERNEL/extra" +touch "$AWG_MODULES_ROOT/$FOREIGN_KERNEL/extra/amneziawg.ko" _awg_module_for_kernel && fail "_awg_module_for_kernel must be false for a foreign kernel" -[[ "$(_awg_module_kernels)" == "5.15.0-177-generic " ]] \ +[[ "$(_awg_module_kernels)" == "$FOREIGN_KERNEL " ]] \ || fail "kernel list mismatch: '$(_awg_module_kernels)'" export FAKE_LSMOD_WITH_MODULE="" diag=$(_awg_verify_module 2>&1 >/dev/null) && fail "verify must fail without a live module" -[[ "$diag" == *"5.15.0-177-generic"* ]] || fail "kernel-mismatch diagnostic missing: $diag" +[[ "$diag" == *"$FOREIGN_KERNEL"* ]] || fail "kernel-mismatch diagnostic missing: $diag" touch "$AWG_MODULES_ROOT/$(uname -r)/extra/amneziawg.ko" _awg_module_for_kernel || fail "_awg_module_for_kernel must see the module of the running kernel" export FAKE_LSMOD_WITH_MODULE=1 @@ -341,8 +364,11 @@ grep -Fq 'backend_status_menu() {' xrayebator || fail "backend_status_menu defin grep -Fq '_backend_apply_profile_lifecycle "$name" revoked' xrayebator || fail "revoke lifecycle wiring missing" grep -Fq '"$(basename "$profile_file" .json)" expired' xrayebator || fail "expire lifecycle wiring missing" grep -Fq ' backend-start)' xrayebator || fail "dispatch backend-start missing" -grep -Fq 'AWG_MODULES_LOAD_FILE="/etc/modules-load.d/xrayebator-awg.conf"' xrayebator \ +grep -Fq 'AWG_MODULES_LOAD_FILE="${AWG_MODULES_LOAD_FILE:-/etc/modules-load.d/xrayebator-awg.conf}"' xrayebator \ || fail "modules-load.d path constant missing" +# Переопределяемый префикс не должен поменять продакшн-значение по умолчанию. +grep -Fq '/etc/modules-load.d/xrayebator-awg.conf' xrayebator \ + || fail "modules-load.d default path vanished" grep -Fq '_awg_module_for_kernel' xrayebator || fail "running-kernel module check missing" grep -Fq 'dkms autoinstall' xrayebator || fail "DKMS rebuild step missing in install path" grep -Fq '_migrate_awg_module_2026() {' xrayebator || fail "awg module migration missing" diff --git a/validation/test-hysteria2-lifecycle.sh b/validation/test-hysteria2-lifecycle.sh index 5d59ee4..1ac93dc 100644 --- a/validation/test-hysteria2-lifecycle.sh +++ b/validation/test-hysteria2-lifecycle.sh @@ -20,6 +20,18 @@ trap 'rm -rf "$TMP_ROOT"' EXIT export BACKENDS_ROOT="$TMP_ROOT/xrayebator-backends" export LOCK_FILE="$TMP_ROOT/xrayebator.lock" export PROFILES_DIR="$TMP_ROOT/profiles" +# Системные пути бэкенда — в tmp: на живом сервере реальный юнит/хук существуют, и +# проверки «бэкенд не установлен → rc=2» краснели от состояния машины, а не от кода. +export HYSTERIA2_UNIT_FILE="$TMP_ROOT/systemd/hysteria-server.service" +export HYSTERIA2_SYSCTL_FILE="$TMP_ROOT/sysctl/99-xrayebator-hysteria.conf" +export HYSTERIA2_CERTBOT_HOOK="$TMP_ROOT/renewal-hooks/deploy/xrayebator-hysteria.sh" +# Бинарник тоже в tmp: `_hysteria2_uninstall` делает `rm -f "$HYSTERIA2_BIN"`, и без +# этого override прогон теста на живом сервере УДАЛЯЛ настоящий /usr/local/bin/hysteria +# (живой инцидент 2026-11-07: реестр говорил installed, бинарника не было, +# hysteria2-install отвечал already). Тест не имеет права трогать реальный файл. +export HYSTERIA2_BIN="$TMP_ROOT/bin/hysteria" +mkdir -p "$(dirname "$HYSTERIA2_UNIT_FILE")" "$(dirname "$HYSTERIA2_SYSCTL_FILE")" \ + "$(dirname "$HYSTERIA2_CERTBOT_HOOK")" mkdir -p "$PROFILES_DIR" # Фейковый systemctl: CI/WSL без systemd — is-active должен говорить active, @@ -67,7 +79,21 @@ arch=$(_hysteria2_asset_arch) || fail "asset arch" case "$arch" in amd64|arm64|arm|386) ;; *) fail "unexpected arch: $arch" ;; esac pass "asset arch resolves: $arch" -[[ "$(_hysteria2_tls_mode_detect)" == "selfsigned" ]] || fail "tls detect expected selfsigned" +# Детект TLS проверяем на синтетических путях: иначе тест зависел от хоста — на +# сервере с живым Let's Encrypt он краснел («le » вместо «selfsigned»), хотя +# код прав. Сначала без домена вовсе, затем с доменом без сертификата, затем с +# сертификатом — три исхода детектора. +export HYSTERIA2_SUBSCRIPTION_DOMAIN_FILE="$TMP_ROOT/.subscription_domain" +export HYSTERIA2_LETSENCRYPT_LIVE_DIR="$TMP_ROOT/letsencrypt" +rm -f "$HYSTERIA2_SUBSCRIPTION_DOMAIN_FILE" +[[ "$(_hysteria2_tls_mode_detect)" == "selfsigned" ]] \ + || fail "tls detect without domain: $(_hysteria2_tls_mode_detect)" +printf 'sub.example.com' > "$HYSTERIA2_SUBSCRIPTION_DOMAIN_FILE" +[[ "$(_hysteria2_tls_mode_detect)" == "selfsigned" ]] \ + || fail "tls detect with domain but no cert: $(_hysteria2_tls_mode_detect)" +mkdir -p "$HYSTERIA2_LETSENCRYPT_LIVE_DIR/sub.example.com" +[[ "$(_hysteria2_tls_mode_detect)" == "le sub.example.com" ]] \ + || fail "tls detect with live cert: $(_hysteria2_tls_mode_detect)" pass "tls mode defaults to selfsigned without subscription markers" # ── Реестр + статус ── @@ -109,9 +135,27 @@ grep -q "alice: $pw1" "$HYSTERIA2_DIR/server.yaml" 2>/dev/null \ pass "grant_profile writes password to profile and regenerates users map" link=$(_hysteria2_profile_link_pure "$PROFILES_DIR/alice.json") || fail "link pure" +# Метка ссылки включает страну, если на хосте есть geo-маркер (.server_country): +# на живом сервере тест падал, потому что ожидал голое имя. Изолируем маркер и +# проверяем ОБА варианта — без него и с ним (иначе один из путей не покрыт). +export SERVER_COUNTRY_FILE="$TMP_ROOT/.server_country" +rm -f "$SERVER_COUNTRY_FILE" +link=$(_hysteria2_profile_link_pure "$PROFILES_DIR/alice.json") || fail "link pure (no country)" [[ "$link" == "hysteria2://alice:${pw1}@203.0.113.10:443/?insecure=1#alice" ]] \ - || fail "link shape: $link" -pass "pure link: selfsigned -> insecure=1, no sni param, name fragment" + || fail "link shape without country: $link" +printf 'NL|Netherlands|Kerkrade' > "$SERVER_COUNTRY_FILE" +link_geo=$(_hysteria2_profile_link_pure "$PROFILES_DIR/alice.json") || fail "link pure (country)" +case "$link_geo" in + "hysteria2://alice:${pw1}@203.0.113.10:443/?insecure=1#"*"Netherlands"*"alice") ;; + *) fail "link shape with country: $link_geo" ;; +esac +# Фрагмент обязан быть URL-encoded: юникод-флаг не должен попасть сырым. +case "$link_geo" in + *"%"*) ;; + *) fail "link fragment not URL-encoded: $link_geo" ;; +esac +rm -f "$SERVER_COUNTRY_FILE" +pass "pure link: selfsigned -> insecure=1, no sni param, name fragment (with and without country)" # revoked: ротация пароля _hysteria2_on_profile_event alice revoked || fail "event revoked" diff --git a/xrayebator b/xrayebator index 8dd4848..ad5b215 100755 --- a/xrayebator +++ b/xrayebator @@ -2942,13 +2942,16 @@ _backend_apply_profile_lifecycle() { # + certbot deploy-hook) или self-signed. masquerade 404 — до живой # проверки proxy-маскарада в срезе 3. Гранты per-profile — срез 3. -HYSTERIA2_BIN="/usr/local/bin/hysteria" +HYSTERIA2_BIN="${HYSTERIA2_BIN:-/usr/local/bin/hysteria}" HYSTERIA2_DIR="$BACKENDS_DIR/hysteria" HYSTERIA2_UNIT="hysteria-server.service" -HYSTERIA2_UNIT_FILE="/etc/systemd/system/hysteria-server.service" +# Системные пути переопределяемы (тот же root-override приём, что CONFIG_FILE): +# без этого тест видел реальный юнит/хук с живого сервера, и его no-op проверки +# («бэкенд не установлен» → rc=2) краснели от состояния машины, а не от кода. +HYSTERIA2_UNIT_FILE="${HYSTERIA2_UNIT_FILE:-/etc/systemd/system/hysteria-server.service}" HYSTERIA2_USER="hysteria" -HYSTERIA2_SYSCTL_FILE="/etc/sysctl.d/99-xrayebator-hysteria.conf" -HYSTERIA2_CERTBOT_HOOK="/etc/letsencrypt/renewal-hooks/deploy/xrayebator-hysteria.sh" +HYSTERIA2_SYSCTL_FILE="${HYSTERIA2_SYSCTL_FILE:-/etc/sysctl.d/99-xrayebator-hysteria.conf}" +HYSTERIA2_CERTBOT_HOOK="${HYSTERIA2_CERTBOT_HOOK:-/etc/letsencrypt/renewal-hooks/deploy/xrayebator-hysteria.sh}" HYSTERIA2_REPO="HyNetworks/hysteria" # Актив Hysteria для архитектуры текущего ядра. @@ -3041,11 +3044,17 @@ EOF } # TLS-режим: "le " при живом LE-серте подписки, иначе "selfsigned". +# TLS-режим: "le " при живом LE-серте подписки, иначе "selfsigned". +# Пути переопределяемы (root override, как CONFIG_FILE/PROFILES_DIR): без этого тест +# зависел от хоста — на сервере с живым сертификатом детектор честно отвечает +# "le ", а тест ждал "selfsigned" и краснел от состояния машины, не от кода. +HYSTERIA2_SUBSCRIPTION_DOMAIN_FILE="${HYSTERIA2_SUBSCRIPTION_DOMAIN_FILE:-/usr/local/etc/xray/.subscription_domain}" +HYSTERIA2_LETSENCRYPT_LIVE_DIR="${HYSTERIA2_LETSENCRYPT_LIVE_DIR:-/etc/letsencrypt/live}" _hysteria2_tls_mode_detect() { local domain="" - [[ -f /usr/local/etc/xray/.subscription_domain ]] && \ - domain=$(tr -d '\r\n' < /usr/local/etc/xray/.subscription_domain 2>/dev/null) - if [[ -n "$domain" && -d "/etc/letsencrypt/live/$domain" ]]; then + [[ -f "$HYSTERIA2_SUBSCRIPTION_DOMAIN_FILE" ]] && \ + domain=$(tr -d '\r\n' < "$HYSTERIA2_SUBSCRIPTION_DOMAIN_FILE" 2>/dev/null) + if [[ -n "$domain" && -d "$HYSTERIA2_LETSENCRYPT_LIVE_DIR/$domain" ]]; then echo "le ${domain}" else echo "selfsigned" @@ -3380,10 +3389,34 @@ _hysteria2_install() { echo -e "${RED}✗ Некорректный порт: ${port}${NC}" return 1 } + # Повреждённое состояние: реестр может ЛИБО утверждать installed (бинарник уже + # удалён), ЛИБО быть уже снятым, но осиротевший юнит продолжает жить и держать + # UDP-порт. Оба случая надо чинить, а не отвечать «already» или «порт занят»: + # на живом прогоне 2026-11-07 `hysteria2-install` в таком состоянии не + # восстанавливал ничего, а status честно писал binary=absent. + local _broken="" + [[ -x "$HYSTERIA2_BIN" ]] || _broken="бинарник" + [[ -f "$HYSTERIA2_UNIT_FILE" ]] || _broken="${_broken:+$_broken, }юнит" + [[ -s "$HYSTERIA2_DIR/server.yaml" ]] || _broken="${_broken:+$_broken, }конфиг" if _backend_installed hysteria2; then - echo -e "${YELLOW}ℹ Hysteria 2 уже установлена (версия $(_backend_field hysteria2 version)).${NC}" - echo -e "${YELLOW} Для переустановки: сначала 'hysteria2-uninstall'.${NC}" - return 2 + if [[ -z "$_broken" ]]; then + echo -e "${YELLOW}ℹ Hysteria 2 уже установлена (версия $(_backend_field hysteria2 version)).${NC}" + echo -e "${YELLOW} Для переустановки: сначала 'hysteria2-uninstall'.${NC}" + return 2 + fi + echo -e "${YELLOW} ⚠ Реестр содержит Hysteria 2, но на диске нет: ${_broken}.${NC}" >&2 + echo -e "${YELLOW} → Восстанавливаю установку...${NC}" >&2 + safe_jq_write --arg t hysteria2 'del(.[$t])' "$BACKENDS_REGISTRY_FILE" 2>/dev/null || true + fi + if [[ -n "$_broken" ]] || systemctl is-active --quiet "$HYSTERIA2_UNIT" 2>/dev/null; then + # Юнит живёт, пока жив процесс, даже если бинарник с диска удалён, и держит + # UDP-порт. Снимаем только СВОЙ юнит — иначе восстановление упирается в + # «UDP-порт 443 уже занят» (проверено на живом сервере). + if systemctl is-active --quiet "$HYSTERIA2_UNIT" 2>/dev/null; then + echo -e "${YELLOW} → Останавливаю осиротевший ${HYSTERIA2_UNIT}...${NC}" >&2 + systemctl stop "$HYSTERIA2_UNIT" >/dev/null 2>&1 || true + sleep 1 + fi fi if _backend_port_busy_udp "$port"; then echo -e "${RED}✗ UDP-порт ${port} уже занят другим слушателем.${NC}" @@ -3870,12 +3903,12 @@ AWG_USER_NAME="hysteria" # отдельного пользовател AWG_SUBNET_PREFIX="10.8.1" AWG_SUBNET="${AWG_SUBNET_PREFIX}.0/24" AWG_MTU=1280 -AWG_SYSCTL_FILE="/etc/sysctl.d/99-xrayebator-awg.conf" +AWG_SYSCTL_FILE="${AWG_SYSCTL_FILE:-/etc/sysctl.d/99-xrayebator-awg.conf}" # Модуль amneziawg существует только в загруженном ядре. systemd-modules-load # читает этот файл на старте (до юнитов), поэтому он и есть условие того, что -# после перезагрузки awg-quick@awg0 поднимется, а не упадёт с +# после перегрузки awg-quick@awg0 поднимется, а не упадёт с # «Unknown device type» (живой дефект: ребут → интерфейса нет, туннель лежит). -AWG_MODULES_LOAD_FILE="/etc/modules-load.d/xrayebator-awg.conf" +AWG_MODULES_LOAD_FILE="${AWG_MODULES_LOAD_FILE:-/etc/modules-load.d/xrayebator-awg.conf}" AWG_REPO_MODULE="amnezia-vpn/amneziawg-linux-kernel-module" AWG_REPO_TOOLS="amnezia-vpn/amneziawg-tools" @@ -3900,7 +3933,8 @@ _awg_gen_junk() { s4=$((RANDOM % 53 + 12)) while (( s4 == s1 || s4 == s2 || s4 == s3 )); do s4=$((RANDOM % 53 + 12)); done h1=1; h2=2; h3=3; h4=4 # WG-магия, дефолт Amnezia - hpk=$(openssl rand -base64 32 2>/dev/null) || return 1 + # tr -d '\r\n': на Windows-хосте (Git Bash/MSYS) openssl печатает CRLF, а HeaderProtectionKey — base64, передаваемый клиенту как есть. Артефакт не должен просочиться в server-params.json и в клиентские .conf. + hpk=$(openssl rand -base64 32 2>/dev/null | tr -d '\r\n') || return 1 jq -n --argjson jc "$jc" --argjson jmin "$jmin" --argjson jmax "$jmax" \ --argjson s1 "$s1" --argjson s2 "$s2" --argjson s3 "$s3" --argjson s4 "$s4" \ --argjson h1 "$h1" --argjson h2 "$h2" --argjson h3 "$h3" --argjson h4 "$h4" \ @@ -3924,7 +3958,8 @@ _awg_ensure_31_params() { local s1=$(jq -r '.S1 // 15' <<<"$junk") s2=$(jq -r '.S2 // 16' <<<"$junk") while (( s3 == s1 || s3 == s2 )); do s3=$((RANDOM % 53 + 12)); done while (( s4 == s1 || s4 == s2 || s4 == s3 )); do s4=$((RANDOM % 53 + 12)); done - hpk=$(openssl rand -base64 32 2>/dev/null) || return 1 + # tr -d '\r\n': на Windows-хосте (Git Bash/MSYS) openssl печатает CRLF, а HeaderProtectionKey — base64, передаваемый клиенту как есть. Артефакт не должен просочиться в server-params.json и в клиентские .conf. + hpk=$(openssl rand -base64 32 2>/dev/null | tr -d '\r\n') || return 1 jq -n --argjson j "$junk" --argjson s3 "$s3" --argjson s4 "$s4" --arg hpk "$hpk" \ '$j + {S3: $s3, S4: $s4, HeaderProtectionKey: $hpk}' } From cdd7cc2825fa34bfea61a4aa26788a615faf2194 Mon Sep 17 00:00:00 2001 From: Ap3x0 <82464229+Ap3x0s@users.noreply.github.com> Date: Sat, 7 Nov 2026 15:57:08 +0300 Subject: [PATCH 13/13] =?UTF-8?q?release:=200.7.3=20=E2=80=94=20=D1=81?= =?UTF-8?q?=D0=B5=D0=BA=D1=80=D0=B5=D1=82=D1=8B=20=D0=B2=D0=BD=D0=B5=20arg?= =?UTF-8?q?v,=20snap-certbot,=20=D1=81=D0=B0=D0=BC=D0=BE=D0=B2=D0=BE=D1=81?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BD=D0=BE=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20Hysteria?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Патч-релиз по итогам трёх живых прогонов подряд (Debian 13, Ubuntu 24.04, Ubuntu 22.04). 13 коммитов с v0.7.2: 5 исправлений, 3 новых теста, 4 про документацию, 1 версия пакета. Миграций нет — конфигурацию сервера менять не нужно. Состав: * security — токен бота и sub_token уходят curl'у stdin-конфигом, jq получает секреты окружением, CLI принимает креды `--secret-file`/`--secret-stdin`, GUI грузит DNS-креды файлом 0600 по SFTP. Живое доказательство: на 0.7.2 watcher от непривилегированного `xray` видел 2 процесса с токеном бота и 1 с DNS-токеном, на 0.7.3 — ноль; * fix — certbot для IP-сертификатов ставится единым помощником с ожиданием snapd (свежий Ubuntu 24.04 падал с «certbot не найден» при рабочем snap); * fix — Hysteria 2 самовосстанавливается из состояния «реестр есть, бинарника нет», и осиротевший юнит больше не блокирует восстановление занятым портом; * fix — channel-test без --name берёт единственный профиль; статусы файрвола и прогресс snap ушли в stderr, stdout CLI снова чистый JSON; * tests — 49 валидаций, два новых скрипта и герметизация Hysteria/AWG-тестов (до этого прогон набора на живом сервере УДАЛЯЛ настоящий бинарник Hysteria). Проверено живьём: Ubuntu 22.04 — 37/37 проверок через настоящий код main-process (`src/main/core/*`), 49/49 валидаций в чистом окружении, 7/7 маршрутов, 4 тела подписки 200, Hysteria 2 и AmneziaWG сквозными туннелями, kernel-guard и ssh-protect после перезагрузки. Ubuntu 24.04 и Debian 13 — без регрессий. --- CHANGELOG.md | 2 +- docs/releases/v0.7.3.en.md | 165 ++++++++++++++++++++++++++++++++++++ docs/releases/v0.7.3.md | 167 +++++++++++++++++++++++++++++++++++++ package.json | 2 +- 4 files changed, 334 insertions(+), 2 deletions(-) create mode 100644 docs/releases/v0.7.3.en.md create mode 100644 docs/releases/v0.7.3.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 60f8d98..46cf9d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ User-facing Xrayebator changes. The server manager and Electron application are published from the canonical `howdeploy/Xrayebator` repository. -## [Unreleased] +## [0.7.3] - 2026-11-07 Secrets no longer travel in process arguments. `/proc//cmdline` is readable by every local user (unlike `/proc//environ`, which only the process owner and root can read), so a secret diff --git a/docs/releases/v0.7.3.en.md b/docs/releases/v0.7.3.en.md new file mode 100644 index 0000000..58f69ef --- /dev/null +++ b/docs/releases/v0.7.3.en.md @@ -0,0 +1,165 @@ +# Xrayebator 0.7.3 — secrets out of process arguments, snap-certbot fix, Hysteria self-recovery + +**Date:** 2026-11-07 +**Previous release:** `0.7.2` (2026-11-04) +**Xray-core:** `26.10.31` (unchanged) + +A patch release driven by three consecutive live runs: Debian 13, Ubuntu 24.04 and Ubuntu 22.04. +The headline is that secrets no longer travel through process command lines, plus two defects that +broke real servers (a fresh Ubuntu 24.04 image and a damaged backend). + +## What was wrong + +### 1. Tokens in process arguments (security) + +`/proc//cmdline` is readable by **every** local user (`0444`), while +`/proc//environ` is readable only by the process owner and root (`0400`). Until this release +three groups of credentials travelled as arguments, so any local account could read them — including +the `xray` service account the proxy itself runs under. + +Confirmed on live servers (read as the unprivileged `xray` user, uid 999): + +``` +/bin/bash /usr/local/bin/xrayebator alerts-setup --token 999999999:AAFake… --chat-id 123456 +curl -sS --max-time 20 https://api.telegram.org/bot999999999:AAFake…/getMe +/bin/bash /usr/local/bin/xrayebator dns01-setup --domain … --token AAFakeDns… +``` + +The bot-token exposure was not one-off: `xrayebator-monitor.timer` runs its check every 15 minutes, +so a process with the token on its command line existed on every tick. + +### 2. `quickstart` could not find certbot on a fresh Ubuntu 24.04 + +On a clean image deployment ended with +`{"ok":false,"error":"Certbot с --ip-address и --preferred-profile не найден"}`, while a manual +`snap install --classic certbot` installed 5.9.0 at that very moment. Cause: `snapd` on 24.04 +finishes seeding and restarts itself right after boot ("Waiting for automatic snapd restart…"), and +the install ran through a duplicate code path in quickstart with `2>/dev/null || true`, swallowing +the failure. + +### 3. Hysteria 2 did not recover from a damaged install + +When the registry still said `installed` but the binary was gone (failed update, manual cleanup), +`hysteria2-install` answered `{"ok":true,"already":true}` and did nothing, while `hysteria2-status` +honestly reported `binary: "absent"`. There was no repair path. + +### 4. Smaller issues found by the same run + +* `xrayebator channel-test` without `--name` answered "Укажите --name профиля" even with exactly one + profile: `HAPP_DEFAULT_PROFILE` is only set inside a quickstart process. +* `quickstart` mixed coloured firewall lines into stdout, so + `xrayebator quickstart --without-email | jq .ok` failed. + +## What changed + +### Security + +* URLs carrying a token are handed to `curl` through a stdin config (`-K -`), so the bot token and + the subscription `sub_token` no longer appear in `argv`. +* `jq` receives secret values through the environment (`$ENV.XRAYEBATOR_JQ_SECRET`) instead of + `--arg`: that covers the Hysteria 2 password, AmneziaWG keys, `sub_token`, the VLESS Encryption + key and the bot token when they are written into JSON. +* Commands accept the credential itself on stdin or from a file: + `--secret-file PATH` / `--secret-stdin` (quickstart uses `--dns01-secret-file` / + `--dns01-secret-stdin`). A file wider than `0600` is refused and deleted right after reading. + `--token` and `--aws-secret-access-key` still work but warn on stderr. +* The desktop GUI sends DNS-01 credentials as a `0600` file over SFTP, so the token reaches neither + the local nor the remote command line. + +```bash +# Before (visible in /proc for the whole 30+ s issuance): +sudo xrayebator dns01-setup --domain sub.example.com --provider cloudflare --token "$CF" + +# After: +printf 'token=%s\n' "$CF" | sudo xrayebator dns01-setup \ + --domain sub.example.com --provider cloudflare --secret-stdin --email you@example.com +``` + +### Fixes + +* **certbot for IP certificates** is installed by the single `_ensure_certbot_ip_tls` helper: it + waits for snapd readiness (`snap wait system seed.loaded`), retries three times, verifies the + result by the binary's actual flags (not by snap's exit code) and logs to `/tmp/snap-*.log` + instead of stdout. +* **Hysteria 2 self-recovers**: install checks for the binary, the unit and `server.yaml`, and when + any is missing it drops the registry entry and takes the normal install path; an orphaned unit is + stopped before the port check (otherwise recovery hit "UDP-порт 443 уже занят"). +* `channel-test` without `--name` uses the only profile in the system; with several profiles it + still asks for a name rather than guessing. +* Firewall statuses and snap progress go to stderr, so CLI stdout is pure JSON again. + +### Tests + +* New `validation/test-secret-argv.sh`: a stub `curl` proves the secret is absent from `argv` and + present on stdin, plus payload parsing for `--secret-file`/`--secret-stdin` and refusal of a file + wider than `0600`. +* New `validation/test-certbot-snap-ip.sh`: a single install path, snapd readiness, retry, and + capability-based verification. +* `test-hysteria2-lifecycle.sh` and `test-awg-lifecycle.sh` are now hermetic: the manager's paths + (`HYSTERIA2_BIN`, `HYSTERIA2_UNIT_FILE`, `AWG_SYSCTL_FILE`, `AWG_MODULES_LOAD_FILE` and friends) + are overridable and the tests redirect them into a temp dir. Previously running the suite on a + live server **deleted the real** `/usr/local/bin/hysteria`, and the "module for a foreign kernel" + check degenerated into "module for this same kernel" on a host running `5.15.0-177`. +* `test-channel-test-cli.sh` anchors on an ASCII line instead of the box-drawing character `─`, + which `mawk` (the default awk on Debian/Ubuntu) does not match. +* **49** Bash validations in total (was 47). + +## Verified live + +| Platform | What was run | Result | +|---|---|---| +| Ubuntu 22.04.5, kernel 5.15.0-177 | GUI wizard (`Deployer`), keys page, protocols page, server settings, server import — the real `src/main/core/*` code | **37/37** | +| Ubuntu 22.04.5 | `validation/` in a clean environment | **49/49** | +| Ubuntu 22.04.5 | routes, subscription, limits, expiry, Hysteria 2 and AmneziaWG end-to-end tunnels | 7/7 routes, 4 bodies 200, Hysteria 3/3 requests, AWG ping 3/3 | +| Ubuntu 24.04.4 | install 0.7.2 → `update dev` → deploy, routes, backends, reboot | 7/7 routes, everything came back after reboot | +| Debian 13 | the same plus AWG from the Ubuntu PPA, kernel-guard, certificate renewal | unchanged from 0.7.2 | + +Additionally verified on live servers: + +* the secret leak was **reproduced** on 0.7.2 (2 processes with the bot token, 1 with the DNS token + in `/proc`, read as the unprivileged `xray` user) and is **absent** on 0.7.3 (0 processes); +* Hysteria self-recovery: deleting `/usr/local/bin/hysteria` with the registry intact → + `hysteria2-install --grant-all` restored the binary (23.9 MB), unit `active`, UDP socket bound; +* `kernel-guard`: three `--enable` calls produce exactly one nft rule, MPTCP is off, and the + protection survives a reboot. + +## Upgrading + +```bash +sudo xrayebator-update # full lifecycle path +# or just the manager: +sudo xrayebator update main +``` + +Rollback is compatible in both directions: the server-side `--token`/`--aws-secret-access-key` +options are still there, so an old GUI works with an old server and a new GUI works with both. + +**Worth one check after upgrading** if a backend ever failed to update: + +```bash +sudo xrayebator backend-status # installed and state are reported separately +sudo xrayebator hysteria2-install # now repairs a damaged install itself +``` + +## Known limitations + +* Live DNS-01 against Cloudflare and Route53 was not exercised (needs a domain and a token): the + payload parser, the wiring and the validation are covered, but not a real TXT-record issuance. +* HAPP and the AmneziaVPN apps were not tested with the official clients: subscription bodies and + client configs were verified with our own clients (the Hysteria binary from the same release, + `awg-quick`). +* Clicks inside the Electron app are not automated: the real main-process code (`Deployer`, + `ProfileManager`, `BackendManager`, `MaintenanceManager`, `ServerInspector`) was driven against a + live server instead. +* `validation/` is not hermetic in two places by nature: `test-ssh-protect.sh` walks the real + `--disable` path (it stops `fail2ban` — re-enable it afterwards) and the Hysteria test expects a + host without a Let's Encrypt certificate. Both are documented in `docs/testing.md`; run the suite + on a disposable host. + +## Release contents + +13 commits in `dev` since `v0.7.2`: 5 fixes, 3 new tests, 4 documentation commits and 1 version +bump. No server configuration change is required — this release adds no migrations. + +The server manager and the Electron application are published from the canonical +`howdeploy/Xrayebator` repository. diff --git a/docs/releases/v0.7.3.md b/docs/releases/v0.7.3.md new file mode 100644 index 0000000..5ff4be2 --- /dev/null +++ b/docs/releases/v0.7.3.md @@ -0,0 +1,167 @@ +# Xrayebator 0.7.3 — секреты вне аргументов процессов, починка snap-certbot и самовосстановление Hysteria + +**Дата:** 2026-11-07 +**Предыдущий релиз:** `0.7.2` (2026-11-04) +**Xray-core:** `26.10.31` (без изменений) + +Патч-релиз по итогам трёх живых прогонов подряд: Debian 13, Ubuntu 24.04 и Ubuntu 22.04. +Главное — закрыта утечка секретов через командную строку процессов и починены два дефекта, +которые ломали работу на реальных серверах (свежий Ubuntu 24.04 и повреждённый бэкенд). + +## Что было не так + +### 1. Токены в аргументах процессов (безопасность) + +`/proc//cmdline` читается **любым** пользователем хоста (`0444`), а +`/proc//environ` — только владельцем процесса и root (`0400`). До этого релиза +три группы кредов ходили именно аргументами, то есть были видны любому локальному +аккаунту — включая служебного пользователя `xray`, под которым работает сам прокси. + +Подтверждено на живых серверах (чтение от пользователя `xray`, uid 999): + +``` +/bin/bash /usr/local/bin/xrayebator alerts-setup --token 999999999:AAFake… --chat-id 123456 +curl -sS --max-time 20 https://api.telegram.org/bot999999999:AAFake…/getMe +/bin/bash /usr/local/bin/xrayebator dns01-setup --domain … --token AAFakeDns… +``` + +Утечка токена бота была не разовой: `xrayebator-monitor.timer` запускает проверку каждые +15 минут, поэтому процесс с токеном в командной строке существовал на каждом тике. + +### 2. `quickstart` на свежем Ubuntu 24.04 не находил certbot + +На чистом образе развёртывание обрывалось ответом +`{"ok":false,"error":"Certbot с --ip-address и --preferred-profile не найден"}`, +хотя ручной `snap install --classic certbot` в тот же момент ставил 5.9.0. Причина: +`snapd` на 24.04 сразу после первой загрузки доигрывает seed/refresh и перезапускается +сам («Waiting for automatic snapd restart…»), а установка шла дублем кода в quickstart с +`2>/dev/null || true` — ошибка глоталась. + +### 3. Hysteria 2 не восстанавливалась из повреждённого состояния + +Если реестр говорил `installed`, а бинарник с диска уже удалён (сбой обновления, ручная +чистка), `hysteria2-install` отвечал `{"ok":true,"already":true}` и ничего не делал, а +`hysteria2-status` честно писал `binary: "absent"`. Пути починки не было. + +### 4. Мелочи, найденные тем же прогоном + +* `xrayebator channel-test` без `--name` отвечал «Укажите --name профиля» даже когда + профиль в системе ровно один: `HAPP_DEFAULT_PROFILE` выставляется только внутри + quickstart-процесса. +* `quickstart` подмешивал в stdout цветные строки файрвола, из-за чего + `xrayebator quickstart --without-email | jq .ok` падал. + +## Что изменилось + +### Безопасность + +* URL с токеном передаётся `curl` через stdin-конфиг (`-K -`) — токен бота и `sub_token` + больше не появляются в `argv`. +* `jq` получает значения-секреты окружением (`$ENV.XRAYEBATOR_JQ_SECRET`), а не `--arg`: + это пароль Hysteria 2, ключи AmneziaWG, `sub_token`, ключ VLESS Encryption и токен бота + в момент записи в JSON. +* Команды принимают сам секрет из stdin или файла: + `--secret-file PATH` / `--secret-stdin` (у quickstart — `--dns01-secret-file` / + `--dns01-secret-stdin`). Файл шире `0600` отвергается, после чтения удаляется. + `--token` и `--aws-secret-access-key` работают, но печатают предупреждение в stderr. +* Десктоп-GUI передаёт DNS-01-креды файлом `0600` по SFTP — токен не попадает ни в + локальную, ни в удалённую командную строку. + +```bash +# Было (видно в /proc все 30+ секунд выпуска сертификата): +sudo xrayebator dns01-setup --domain sub.example.com --provider cloudflare --token "$CF" + +# Стало: +printf 'token=%s\n' "$CF" | sudo xrayebator dns01-setup \ + --domain sub.example.com --provider cloudflare --secret-stdin --email you@example.com +``` + +### Исправления + +* **certbot для IP-сертификатов** ставится единым помощником `_ensure_certbot_ip_tls`: + ожидание готовности snapd (`snap wait system seed.loaded`), три попытки установки, + проверка результата по фактическим флагам бинарника (а не по коду возврата snap), + логи в `/tmp/snap-*.log` вместо stdout. +* **Hysteria 2 самовосстанавливается**: install проверяет наличие бинарника, юнита и + `server.yaml`, и при их отсутствии снимает запись реестра и проходит обычным путём; + осиротевший юнит останавливается перед проверкой порта (иначе восстановление упиралось + в «UDP-порт 443 уже занят»). +* `channel-test` без `--name` использует единственный профиль; при нескольких профилях + по-прежнему просит имя, чтобы не проверять чужой. +* Статусы файрвола и прогресс snap уходят в stderr — stdout CLI снова чистый JSON. + +### Тесты + +* Новый `validation/test-secret-argv.sh`: подставной `curl` доказывает, что секрет + отсутствует в `argv` и присутствует на stdin, плюс разбор `--secret-file`/`--secret-stdin` + и отказ файлу с правами шире `0600`. +* Новый `validation/test-certbot-snap-ip.sh`: единственная реализация установки certbot, + ожидание snapd, повтор, проверка по возможностям бинарника. +* `test-hysteria2-lifecycle.sh` и `test-awg-lifecycle.sh` стали герметичными: пути + (`HYSTERIA2_BIN`, `HYSTERIA2_UNIT_FILE`, `AWG_SYSCTL_FILE`, `AWG_MODULES_LOAD_FILE` и др.) + в менеджере переопределяемы, тесты уводят их в tmp. Раньше прогон набора на рабочем + сервере **удалял настоящий** `/usr/local/bin/hysteria`, а проверка «модуль для другого + ядра» на сервере с ядром `5.15.0-177` вырождалась в проверку того же ядра. +* `test-channel-test-cli.sh` якорится на ASCII-строку, а не на символ рамки «─» (его не + матчит `mawk` — awk по умолчанию в Debian/Ubuntu). +* Всего **49** Bash-валидаций (было 47). + +## Проверено живьём + +| Платформа | Что прогнано | Результат | +|---|---|---| +| Ubuntu 22.04.5, ядро 5.15.0-177 | визард GUI (`Deployer`), страница ключей, протоколы, настройки сервера, импорт сервера — настоящий код `src/main/core/*` | **37/37** | +| Ubuntu 22.04.5 | `validation/` в чистом окружении | **49/49** | +| Ubuntu 22.04.5 | маршруты, подписка, лимиты, срок, Hysteria 2 и AmneziaWG сквозным туннелем | 7/7 маршрутов, 4 тела 200, Hysteria 3/3 запроса, AWG ping 3/3 | +| Ubuntu 24.04.4 | установка 0.7.2 → `update dev` → развёртывание, маршруты, бэкенды, ребут | 7/7 маршрутов, всё поднялось после перезагрузки | +| Debian 13 | то же + AWG из Ubuntu-PPA, kernel-guard, продление сертификата | без изменений с 0.7.2 | + +Дополнительно проверено на живых серверах: + +* утечка секретов **воспроизведена** на 0.7.2 (2 процесса с токеном бота, 1 с DNS-токеном + в `/proc`, чтение от непривилегированного `xray`) и **отсутствует** на 0.7.3 (0 процессов); +* самовосстановление Hysteria: удаление `/usr/local/bin/hysteria` при живом реестре → + `hysteria2-install --grant-all` вернул бинарник (23.9 МБ), юнит `active`, UDP-сокет на месте; +* `kernel-guard`: три вызова `--enable` дают ровно одно nft-правило, MPTCP выключен, + после перезагрузки защита на месте. + +## Обновление + +```bash +sudo xrayebator-update # полный lifecycle-путь +# либо только менеджер: +sudo xrayebator update main +``` + +Откат совместим в обе стороны: серверные `--token`/`--aws-secret-access-key` остались, +поэтому старый GUI работает со старым сервером, а новый — с обоими. + +**После обновления стоит один раз проверить бэкенды**, если ранее были сбои обновлений: + +```bash +sudo xrayebator backend-status # installed и state отдельно +sudo xrayebator hysteria2-install # теперь сам починит повреждённую установку +``` + +## Известные ограничения + +* Живой DNS-01 у Cloudflare и Route53 не проверялся (нужен домен и токен): проверены + парсер пейлоада, проводка и валидация, но не реальный выпуск по TXT-записи. +* HAPP и AmneziaVPN официальными приложениями не проверялись: тела подписки и клиентские + конфиги проверены своими клиентами (бинарник Hysteria из того же релиза, `awg-quick`). +* Клики внутри Electron-приложения не автоматизированы: проверялся настоящий код + main-process (`Deployer`, `ProfileManager`, `BackendManager`, `MaintenanceManager`, + `ServerInspector`) против живого сервера. +* `validation/` негерметичен по своей природе в двух местах: `test-ssh-protect.sh` проходит + настоящий путь `--disable` (гасит `fail2ban` — включайте обратно) и тест Hysteria ждёт + хост без LE-сертификата. Это задокументировано в `docs/testing.md`; гоняйте набор на + одноразовом хосте. + +## Состав релиза + +13 коммитов в `dev` с момента `v0.7.2`, из них 5 — исправления, 3 — новые тесты, +4 — документация, 1 — версия пакета. Ни одного изменения в конфигурации сервера не +требуется: миграций в этом релизе нет. + +Серверный менеджер и Electron-приложение публикуются из канонического репозитория +`howdeploy/Xrayebator`. diff --git a/package.json b/package.json index 4739b38..61856f0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "xrayebator", - "version": "0.7.2", + "version": "0.7.3", "description": "Xrayebator Desktop — админ-панель развёртки VPN-сервера на VPS", "main": "out/main/index.js", "author": "Xrayebator",