Fix Xray reverse access and compatible router core installation

This commit is contained in:
kzolotarev95 committed 2026-10-29 13:06:54 +04:00
1 parent 5956daa8c2
commit d7d350fd8b
14 files changed
+1134 -31

No files matched your search

+72 -20
View File
@@ -6,9 +6,11 @@ CONFIG="owrtremote"
SECTION="main"
# OpenWrt packages are published by yichya for the architectures reported by
# opkg/apk. Keep the version explicit so a release cannot change underneath a
# running router; it can be overridden for a controlled test or rollback.
# running router. 26.6.27 is the last release compatible with the existing
# unencrypted VLESS reverse transport; 26.7.11+ rejects public destinations.
# Changing the package source alone does not change that protocol requirement.
XRAY_RELEASE_REPO="${XRAY_RELEASE_REPO:-https://github.com/yichya/openwrt-xray}"
XRAY_RELEASE_VERSION="${XRAY_RELEASE_VERSION:-26.10.21}"
XRAY_RELEASE_VERSION="${XRAY_RELEASE_VERSION:-26.6.27}"
XRAY_RELEASE_REVISION="${XRAY_RELEASE_REVISION:-1}"
XRAY_RELEASE_BASE_URL="${XRAY_RELEASE_BASE_URL:-$XRAY_RELEASE_REPO/releases/download/v$XRAY_RELEASE_VERSION}"
@@ -473,14 +475,29 @@ xray_package_format() {
}
xray_release_asset() {
local version arch
local version arch package_arch
version="${XRAY_RELEASE_VERSION#v}"
arch="$(xray_arch)" || return 1
[ -n "$arch" ] || return 1
case "$(xray_package_format)" in
apk) printf 'openwrt-xray-%s-r%s-%s.apk\n' "$version" "$XRAY_RELEASE_REVISION" "$arch" ;;
*)
# These yichya releases include both package and target architecture
# in the IPK filename. APK filenames do not use this extra suffix.
case "$version" in
26.6.1|26.6.22|26.6.27)
package_arch="$arch"
case "$arch" in
i386_pentium) package_arch=i386_pentium-mmx ;;
arm_cortex-a5-vfpv4) package_arch=arm_cortex-a5_vfpv4 ;;
arm_cortex-a5_vfpv4) arch=arm_cortex-a5-vfpv4 ;;
esac
printf 'openwrt-xray_%s-%s_%s-%s.ipk\n' "$version" "$XRAY_RELEASE_REVISION" "$package_arch" "$arch"
;;
*) printf 'openwrt-xray_%s-%s_%s.ipk\n' "$version" "$XRAY_RELEASE_REVISION" "$arch" ;;
esac
;;
esac
}
install_package() {
@@ -580,6 +597,40 @@ validate_xray_config() {
fi
}
xray_requires_legacy_replacement() {
local version
# Keep an existing working core. Replace a known incompatible core only
# for the transport generated here (VLESS encryption=none, security=none).
[ "$(uci_get vless_encryption none)" = none ] || return 1
version="$("$1" version 2>/dev/null | sed -n '1s/^Xray \([0-9][0-9.]*\) .*/\1/p')"
[ -n "$version" ] || return 1
LC_ALL=C awk -v version="$version" 'BEGIN {
n=split(version, v, ".")
exit !(n==3 && (v[1]*10000 + v[2]*100 + v[3]) >= 260711)
}'
}
xray_validate_transport_binary() (
# Validate actual protocol support, not just `xray version`. This probe
# contains no router credentials, does not connect and does not alter UCI.
binary="$1"
probe="$(mktemp -d "$(xray_runtime_dir)/.compat.XXXXXX")" || return 1
trap 'rm -rf "$probe"' EXIT
trap 'exit 1' INT TERM
umask 077
cat >"$probe/config.json" <<'EOF'
{"log":{"loglevel":"none"},"outbounds":[{"tag":"vps-interconn","protocol":"vless","settings":{"address":"example.com","port":8443,"id":"11111111-1111-4111-8111-111111111111","encryption":"none","reverse":{"tag":"compat-reverse"}},"streamSettings":{"network":"tcp","security":"none"}}]}
EOF
if "$binary" -test -config "$probe/config.json" >"$probe/result" 2>&1; then
return 0
else
rc=$?
head -c 8192 "$probe/result" >&2
log "ОШИБКА: пакет Xray несовместим с текущим VLESS reverse без TLS (rc=$rc). Нужна совместимая сборка $XRAY_RELEASE_VERSION; рабочий бинарник и кэш сохранены"
return "$rc"
fi
)
render_client_config() (
local temp_dir rc xray_host out stdout router_id vps_host vps_port uuid ssh_uuid encryption flow reverse_tag ssh_reverse_tag admin_host admin_port ssh_host ssh_port xray_config xray_config_dir
temp_dir=""
@@ -643,6 +694,8 @@ render_client_config() (
# Xray detects JSON by extension; keep the candidate private and on the
# same filesystem as the destination so the final rename is atomic.
out="$temp_dir/config.json"
# Freedom denies VLESS reverse by default in newer cores. Each redirect
# fixes its destination before finalRules; allow only that service's TCP port.
cat >"$out" <<EOF
{
"log": {
@@ -656,14 +709,16 @@ render_client_config() (
"tag": "router-admin",
"protocol": "freedom",
"settings": {
"redirect": "$(json_escape "$admin_host"):$admin_port"
"redirect": "$(json_escape "$admin_host"):$admin_port",
"finalRules": [{"action": "allow", "network": "tcp", "port": $admin_port}]
}
},
{
"tag": "router-ssh",
"protocol": "freedom",
"settings": {
"redirect": "$(json_escape "$ssh_host"):$ssh_port"
"redirect": "$(json_escape "$ssh_host"):$ssh_port",
"finalRules": [{"action": "allow", "network": "tcp", "port": $ssh_port}]
}
},
{
@@ -1583,6 +1638,7 @@ xray_cache_save() (
bin="$1"
[ -s "$bin" ] && [ -x "$bin" ] || return 1
"$bin" version >/dev/null 2>&1 || return 1
xray_requires_legacy_replacement "$bin" && return 1
store="$(xray_cache_dir)" || { log 'Xray: постоянный кэш недоступен; после перезагрузки потребуется загрузка из сети'; return 1; }
asset="$(xray_release_asset)" || return 1
digest="$(xray_digest "$bin")" || return 1
@@ -1635,6 +1691,7 @@ xray_cache_restore() (
size="$(wc -c <"$temp")"
[ "$size" -le 67108864 ] && [ "$(xray_digest "$temp")" = "$digest" ] || continue
chmod 755 "$temp" && "$temp" version >/dev/null 2>&1 || continue
xray_validate_transport_binary "$temp" || continue
mv -f "$temp" "$dir/xray" || return 1
if [ "$(uci_get xray_bin '')" != "$dir/xray" ]; then
uci set "$CONFIG.$SECTION.xray_bin=$dir/xray" && uci commit "$CONFIG" || return 1
@@ -1794,18 +1851,11 @@ xray_package_extract_binary() (
if [ -s "$work/data.tar.gz" ] &&
(cd "$work/data" && cat "$work/data.tar.gz" | tar -xzf - ./usr/bin/xray) >/dev/null 2>&1 &&
[ -s "$work/data/usr/bin/xray" ]; then
cp "$work/data/usr/bin/xray" "$output" || return 1
mv "$work/data/usr/bin/xray" "$output" || return 1
return 0
fi
# A minimal image may not include ar/tar extraction helpers. opkg
# remains a safe last resort; the candidate is still validated before
# the configured RAM binary is replaced.
if command -v opkg >/dev/null 2>&1; then
opkg install "$archive" >/dev/null 2>&1 || return 1
[ -x /usr/bin/xray ] || return 1
cp /usr/bin/xray "$output"
return $?
fi
# Never fall back to `opkg install`: it could overwrite an active
# /usr/bin/xray before our transport check has accepted the package.
;;
*.apk)
# apk packages are handled by apk itself on Alpine-based images.
@@ -1833,7 +1883,7 @@ install_xray_tmp_locked() (
# An interrupted package download is disposable; the working binary and
# compressed boot copy are never removed before a candidate is validated.
rm -f "$package.new" "$dir/xray.new"
trap 'rm -f "$package.new" "$dir/xray.new"' EXIT
trap 'rm -f "$package.new" "$package" "$dir/xray.new"' EXIT
trap 'exit 1' INT TERM
ensure_ca_certificates || log "CA certificates not found, trying download anyway"
ensure_fetch_tool || {
@@ -1866,6 +1916,7 @@ install_xray_tmp_locked() (
return 1
}
version="$(printf '%s\n' "$version" | sed -n '1p')"
xray_validate_transport_binary "$dir/xray.new" || return $?
mv -f "$dir/xray.new" "$dir/xray" || return 1
uci set "$CONFIG.$SECTION.xray_bin=$dir/xray" && uci commit "$CONFIG" || return 1
xray_cache_save "$dir/xray" || true
@@ -1879,11 +1930,12 @@ ensure_xray_available() {
local configured candidate found
configured="$(uci_get xray_bin /usr/bin/xray)"
if [ -x "$configured" ]; then
return 0
if ! xray_requires_legacy_replacement "$configured"; then return 0; fi
log "Xray: установленная версия запрещает текущий VLESS без TLS; подготовка совместимой $XRAY_RELEASE_VERSION из yichya/openwrt-xray"
fi
for candidate in /usr/bin/xray /usr/bin/xray-core /usr/local/bin/xray /opt/bin/xray /tmp/owrt-xray/xray /tmp/owrt-xray/xray_softfloat /tmp/xray /tmp/xray_softfloat; do
if [ -x "$candidate" ]; then
if [ -x "$candidate" ] && ! xray_requires_legacy_replacement "$candidate"; then
found="$candidate"
break
fi
@@ -1893,7 +1945,7 @@ ensure_xray_available() {
found="$(command -v xray 2>/dev/null || command -v xray-core 2>/dev/null || true)"
fi
if [ -n "$found" ] && [ -x "$found" ]; then
if [ -n "$found" ] && [ -x "$found" ] && ! xray_requires_legacy_replacement "$found"; then
[ "$found" = "$configured" ] || {
uci set "$CONFIG.$SECTION.xray_bin=$found"
uci commit "$CONFIG"
@@ -1910,7 +1962,7 @@ prepare_xray_tmp() (
trap 'exit 1' INT TERM
# Recheck after acquiring the lock: a concurrent installer may have finished.
configured="$(uci_get xray_bin /usr/bin/xray)"
[ ! -x "$configured" ] || return 0
if [ -x "$configured" ] && ! xray_requires_legacy_replacement "$configured"; then return 0; fi
xray_cache_restore && return 0
log 'Xray: загрузочной копии нет; требуется загрузка из сети'
install_xray_tmp_locked
+14 -4
View File
@@ -375,15 +375,25 @@ run_action() {
;;
install_xray_tmp)
if "$AGENT" install-xray-tmp >"$output" 2>&1; then
"$AGENT" render-client >>"$output" 2>&1 || rc=$?
/etc/init.d/owrt-remote restart >>"$output" 2>&1 || rc=$?
if "$AGENT" render-client >>"$output" 2>&1; then
if /etc/init.d/owrt-remote restart >>"$output" 2>&1; then
set_result "Xray установлен, конфигурация проверена" "$(cat "$output")" "ok"
else
rc=$?
set_result "Ошибка перезапуска Xray" "$(cat "$output")" "bad"
fi
else
rc=$?
printf '\nrc=%s\nРабочий JSON сохранён. Перезапуск сервиса не выполнен.\n' "$rc" >>"$output"
set_result "Xray скачан, но конфигурация не прошла проверку" "$(cat "$output")" "bad"
fi
else
rc=$?
set_result "Ошибка установки Xray" "$(cat "$output")" "bad"
fi
set_result "Xray установлен в /tmp" "$(cat "$output")" "ok"
;;
esac
if [ "$rc" != "0" ]; then
if [ "$rc" != "0" ] && [ "$RESULT_KIND" != bad ]; then
set_result "$RESULT_TITLE" "$(cat "$output")" "bad"
fi
# Deliver the completed stop result without keeping a mobile HTTP request open.
+119
View File
@@ -0,0 +1,119 @@
# Совместимость Xray с текущим VLESS reverse (v119)
Причина `rc=23` подтверждена настоящими бинарниками: в Xray 26.7.11 и новее
публичный VLESS outbound с `encryption=none` и `security=none` запрещён.
Это несовместимость ядра с действующим транспортом, а не ошибка мобильного
буфера обмена, JSON, UUID или reverse_tag. TLS только на HTTPS-сайте Hub
не защищает отдельное VLESS-соединение на 8443.
Локальное исправление сохраняет существующий протокол и VPS-конфигурацию.
По умолчанию используется последняя сборка до запрета — **26.6.27** из
`yichya/openwrt-xray`. TLS/REALITY этим исправлением не добавляются; для
использования 26.7.11+ нужен отдельный согласованный переход обоих концов.
Источники проверки:
- https://github.com/XTLS/Xray-core/blob/v26.7.11/infra/conf/xray.go
- https://github.com/XTLS/Xray-core/blob/v26.6.27/infra/conf/xray.go
- https://github.com/yichya/openwrt-xray/releases/tag/v26.6.27
## Поведение
- Учитываются реальные имена IPK этого релиза с двойным указанием архитектуры,
включая ARM64, MIPSel и особые имена `i386_pentium`/`arm_cortex-a5-vfpv4`.
- Найденный работающий старый core сохраняется. Известный core 26.7.11+
для `encryption=none` заменяется совместимым: сначала проверенный boot-кэш,
затем загрузка закреплённого пакета. Ошибка сети не удаляет старый бинарник.
- До замены runtime/кэша/UCI кандидат выполняет `-test` на несекретной пробной
конфигурации публичного VLESS reverse. `xray version` больше недостаточно.
- Возвращаемый на Flash core также проверяется перед установкой в RAM.
Известный несовместимый core не записывается под именем совместимого кэша.
- При извлечении IPK используется отдельный каталог в RAM. Перемещение бинарника
не создаёт дополнительную полную RAM-копию. Fallback через `opkg install`
удалён: он мог заменить системный core ещё до проверки кандидата.
- Реальная проверка нового рабочего JSON остаётся обязательной. Ошибка не
заменяет JSON, не считается автоматически ошибкой переносов строк, а кнопка
установки больше не перезапускает сервис после проваленной проверки.
- Неудачная установка, неудачная проверка JSON и ошибка рестарта имеют разные
заголовки. Успех установки отображается только после успешных этапов.
## Установка локального исправления
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-xray-compat-fix.ps1" -Router "root@192.168.2.1" -Action Install
```
Скрипт сохраняет агент и CGI в
`/root/owrt-remote-backup-before-xray-compat-v119`, устанавливает код и
подготавливает совместимый core. Он не меняет рабочий JSON и не перезапускает
туннель. После успеха (`XRAY_COMPAT_ROUTER_Install_OK`) повторно применить
команды из «OpenWrt config» в «Xray настройки» панели роутера.
Откат возвращает только предыдущие агент и CGI. Проверенный совместимый
бинарник, boot-кэш и настройки сохраняются:
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-xray-compat-fix.ps1" -Router "root@192.168.2.1" -Action Rollback
```
## Проверки
`test_xray_bootstrap.py`: выбор IPK/APK, замена уже установленного несовместимого
core, офлайн-восстановление, отклонение неподходящего кандидата до замены UCI,
сохранение старого файла и Flash-кэша, уборка временных файлов и блокировок.
`test_xray_apply.py`: реальный CGI POST для всех трёх ошибок установки;
проверка, что при `rc=23` рестарта нет и успех не отображается.
`test_xray_compat_deploy.py`: установка/откат, сохранность первой копии,
автоматический возврат кода при ошибке подготовки core, отсутствие рестарта.
Дополнительно тесты принимают `OWRT_TEST_XRAY_BIN` (26.6.27) и
`OWRT_TEST_NEW_XRAY_BIN` (26.10.21). Они воспроизводят реальный отказ нового
core и проверяют полный сгенерированный JSON на публичном домене и IP.
`OWRT_TEST_BUSYBOX` включает BusyBox ash для bootstrap-тестов.
Локально проверены настоящие Windows-бинарники обеих версий и извлечение
настоящих ARM64/MIPSel IPK через BusyBox ash. Linux ARM64/MIPSel-бинарники
на Windows не исполнялись; финальная проверка туннеля нужна на роутере.
## Туннель запущен, но Админка и SSH зависают
Дополнительный дефект воспроизведён с настоящими ядрами: `xray -test`
принимает JSON и VLESS reverse устанавливается, но Freedom в 26.6.27
по умолчанию блокирует весь трафик от `vless-reverse`. В debug-журнале:
`blocked target: tcp:127.0.0.1:80, blackholing connection ...`.
На VPS видны локальные `accepted`, однако HTTP/SSH не получают ответ.
Heartbeat использует отдельное соединение и продолжает работать.
Источник: https://github.com/XTLS/Xray-core/blob/v26.6.27/proxy/freedom/freedom.go
(`getDefaultFinalRule` и проверка `finalRules` после `DestinationOverride`).
В агенте и генераторе клиентского JSON Hub добавлены `finalRules` к двум
выходам Freedom: разрешён TCP только на настроенный порт соответствующей
службы. `redirect` по-прежнему фиксирует её адрес и порт перед проверкой.
Разрешение не добавляется к остальным выходам. Heartbeat/WAN/Podkop,
UUID, reverse tags и серверная конфигурация остаются прежними.
`test_xray_reverse_transport.py` проверяет реальный HTTP-ответ и SSH banner:
26.6.27 → 26.6.27 и 26.6.27 → 26.10.21; отдельно используется JSON,
сгенерированный настоящим shell-агентом. Понижение версии VPS не нужно.
Установка исправления на роутер сохраняет агент, CGI и исходный JSON;
проверяет новый JSON через Xray, атомарно заменяет его и перезапускает
туннель. Ошибка проверки не вызывает рестарт. Ошибка рестарта возвращает
предыдущий JSON и код. Совместимый бинарник и boot-кэш сохраняются.
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-xray-reverse-fix.ps1" -Router "root@192.168.2.1" -Action Install
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-xray-reverse-fix.ps1" -Router "root@192.168.2.1" -Action Rollback
```
На VPS обновляется генератор клиентского JSON. Сам Xray и его серверный
JSON не заменяются. Проверяется SHA-256 реально запущенного Hub через
локальный `/health?panel-update=1`; при ошибке возвращается предыдущий Hub.
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-xray-reverse-vps.ps1" -Vps "root@138.124.79.58" -Action Install
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-xray-reverse-vps.ps1" -Vps "root@138.124.79.58" -Action Rollback
```
+46
View File
@@ -88,6 +88,52 @@ render_page() { printf 'KIND=%s\nTITLE=%s\nBODY=%s\nDRAFT=%s\n' "$RESULT_KIND" "
self.assertFalse(leftovers, "CGI temporary files must be removed")
return result.stdout.decode("utf-8")
def install_action(self, install_rc=0, render_rc=0, service_rc=0):
agent = self.directory / 'bin' / 'install-agent'
agent.write_text('''#!/bin/sh
printf '%s\\n' "$1" >>"$TEST_ROOT/install-calls"
case "$1" in
install-xray-tmp) exit INSTALL_RC ;;
render-client) echo 'Xray config validation'; exit RENDER_RC ;;
esac
'''.replace('INSTALL_RC', str(install_rc)).replace('RENDER_RC', str(render_rc)),
encoding='utf-8', newline='\n')
agent.chmod(0o755)
self.env['AGENT'] = agent.as_posix()
source = self.cgi.read_text(encoding='utf-8')
source = source.replace('/etc/init.d/owrt-remote', 'test_service')
source = source.replace('\nrun_action() {',
'\ntest_service() { echo "$1" >>"$TEST_ROOT/restarts"; return ' + str(service_rc) + '; }\nrun_action() {')
self.cgi.write_text(source, encoding='utf-8', newline='\n')
return self.post('', action='install_xray_tmp')
def test_install_does_not_restart_or_claim_success_on_invalid_config(self):
response = self.install_action(render_rc=23)
self.assertIn('KIND=bad', response)
self.assertIn('Xray скачан, но конфигурация не прошла проверку', response)
self.assertIn('rc=23', response)
self.assertNotIn('TITLE=Xray установлен', response)
self.assertFalse((self.directory / 'restarts').exists())
def test_failed_install_does_not_render_or_restart(self):
response = self.install_action(install_rc=23)
self.assertIn('KIND=bad', response)
self.assertIn('TITLE=Ошибка установки Xray', response)
self.assertEqual((self.directory / 'install-calls').read_text(), 'install-xray-tmp\n')
self.assertFalse((self.directory / 'restarts').exists())
def test_valid_install_restarts_once_and_reports_success(self):
response = self.install_action()
self.assertIn('KIND=ok', response)
self.assertIn('TITLE=Xray установлен, конфигурация проверена', response)
self.assertEqual((self.directory / 'install-calls').read_text(), 'install-xray-tmp\nrender-client\n')
self.assertEqual((self.directory / 'restarts').read_text(), 'restart\n')
def test_restart_failure_is_reported_separately(self):
response = self.install_action(service_rc=1)
self.assertIn('KIND=bad', response)
self.assertIn('TITLE=Ошибка перезапуска Xray', response)
def test_mobile_smart_quotes_reproduce_uci_255_and_are_repaired(self):
script = 'uci set owrtremote.main.router_name=‘Дом у моря’\nuci commit owrtremote\n'
# UCI returns 255 for too many arguments; shell syntax validation alone
+90 -4
View File
@@ -29,7 +29,7 @@ class XrayBootstrapTests(unittest.TestCase):
self.env['PATH'] = str(Path(base.SH).parent) + os.pathsep + os.environ['PATH']
self.mocks = r'''
xray_cache_dir() { printf '%s' "$TEST_ROOT/flash"; }
xray_release_asset() { printf openwrt-xray_26.10.21-1_aarch64_cortex-a53.ipk; }
xray_release_asset() { printf openwrt-xray_26.6.27-1_aarch64_cortex-a53-aarch64_cortex-a53.ipk; }
xray_arch() { printf aarch64; }
xray_package_extract_binary() { cp "$TEST_ROOT/release.pkg" "$2"; }
ensure_ca_certificates() { return 0; }
@@ -82,7 +82,7 @@ opkg() {
''')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.strip().splitlines()[-1],
'openwrt-xray_26.10.21-1_aarch64_cortex-a53.ipk')
'openwrt-xray_26.6.27-1_aarch64_cortex-a53-aarch64_cortex-a53.ipk')
def test_yichya_ipk_extracts_only_usr_bin_xray(self):
binary = self.make_binary('package')
@@ -106,7 +106,7 @@ opkg() {
def cache(self, data=None):
data = data or self.make_binary()
self.store.mkdir(exist_ok=True)
path = self.store / ('openwrt-xray_26.10.21-1_aarch64_cortex-a53.ipk.' + hashlib.sha256(data).hexdigest() + '.gz')
path = self.store / ('openwrt-xray_26.6.27-1_aarch64_cortex-a53-aarch64_cortex-a53.ipk.' + hashlib.sha256(data).hexdigest() + '.gz')
path.write_bytes(gzip.compress(data))
return path
@@ -114,6 +114,92 @@ opkg() {
self.assertFalse((self.runtime / 'bootstrap-lock').exists())
self.assertFalse(list(self.runtime.glob('*.new')))
self.assertFalse(list(self.runtime.glob('.restore.*')))
self.assertFalse(list(self.runtime.glob('.compat.*')))
self.assertFalse((self.runtime / 'xray.pkg').exists())
def test_compatible_mipsel_ipk_and_apk_asset_names(self):
for fmt, expected in (
('ipk', 'openwrt-xray_26.6.27-1_mipsel_24kc-mipsel_24kc.ipk'),
('apk', 'openwrt-xray-26.6.27-r1-mipsel_24kc.apk'),
):
result = self.raw_shell('xray_release_asset', mocks=
f'xray_arch() {{ printf mipsel_24kc; }}; xray_package_format() {{ printf {fmt}; }}')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout.strip(), expected)
def incompatible_binary(self):
data = b'''#!/bin/sh
if [ "$1" = version ]; then echo 'Xray 26.10.21 (Xray, Penetrates Everything.) Custom'; exit 0; fi
echo 'vless without TLS or other encryption is prohibited unless the server address is a private IP or domain' >&2
exit 23
'''
self.binary.write_bytes(data)
self.binary.chmod(0o755)
return data
def test_new_core_rejected_before_binary_cache_and_uci_replacement(self):
bad = self.incompatible_binary()
good = self.make_binary('Xray 26.6.27 compatible')
cached = self.cache(good)
(self.directory / 'release.pkg').write_bytes(bad)
original_uci = (self.directory / 'uci').read_bytes()
result = self.shell('install_xray_tmp', mocks='fetch_file() { cp "$TEST_ROOT/release.pkg" "$2"; }')
self.assertEqual(result.returncode, 23, result.stderr)
self.assertIn('vless without TLS', result.stderr)
self.assertEqual(self.binary.read_bytes(), good)
self.assertEqual((self.directory / 'uci').read_bytes(), original_uci)
self.assertTrue(cached.exists())
self.assertNotIn('OK: Xray installed', result.stdout)
self.assert_clean()
def test_existing_incompatible_core_is_replaced_once(self):
good = self.make_binary('Xray 26.6.27 compatible')
self.incompatible_binary()
(self.directory / 'release.pkg').write_bytes(good)
result = self.shell('ensure_xray_available; ensure_xray_available', mocks=r'''
fetch_file() { echo download >>"$TEST_ROOT/downloads"; cp "$TEST_ROOT/release.pkg" "$2"; }
''')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(self.binary.read_bytes(), good)
self.assertEqual((self.directory / 'downloads').read_text().splitlines(), ['download'])
self.assert_clean()
def test_incompatible_core_can_recover_from_verified_compatible_cache_offline(self):
good = self.make_binary('Xray 26.6.27 compatible')
self.cache(good)
self.incompatible_binary()
result = self.shell('ensure_xray_available', mocks='fetch_file() { echo forbidden-network >&2; return 99; }')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(self.binary.read_bytes(), good)
self.assert_clean()
def test_failed_compatibility_recovery_keeps_original_binary(self):
bad = self.incompatible_binary()
result = self.shell('ensure_xray_available', mocks='fetch_file() { return 28; }')
self.assertNotEqual(result.returncode, 0)
self.assertEqual(self.binary.read_bytes(), bad)
self.assert_clean()
def test_incompatible_core_is_not_saved_under_compatible_cache_name(self):
self.incompatible_binary()
result = self.shell('xray_cache_save "$OWRT_REMOTE_XRAY_RUNTIME/xray"')
self.assertNotEqual(result.returncode, 0)
self.assertFalse(list(self.store.glob('*.gz')))
@unittest.skipUnless(os.environ.get('OWRT_TEST_XRAY_BIN'), 'Set real compatible Xray')
def test_real_compatible_core_passes_transport_probe(self):
result = self.shell('xray_validate_transport_binary "$TEST_CORE"',
TEST_CORE=Path(os.environ['OWRT_TEST_XRAY_BIN']).as_posix())
self.assertEqual(result.returncode, 0, result.stderr)
self.assert_clean()
@unittest.skipUnless(os.environ.get('OWRT_TEST_NEW_XRAY_BIN'), 'Set real incompatible Xray')
def test_real_modern_core_reproduces_public_vless_rejection(self):
result = self.shell('xray_validate_transport_binary "$TEST_CORE"',
TEST_CORE=Path(os.environ['OWRT_TEST_NEW_XRAY_BIN']).as_posix())
self.assertEqual(result.returncode, 23, result.stderr)
self.assertIn('vless without TLS', result.stderr)
self.assert_clean()
def test_reboot_restores_verified_cache_without_network_or_flash_rewrite(self):
data = self.make_binary()
@@ -290,7 +376,7 @@ curl() {
def test_each_download_redirect_uses_wan_dns_and_keeps_tls_verification(self):
self.config(wan_direct='1')
result = self.shell('fetch_file https://github.com/yichya/openwrt-xray/releases/download/v26.10.21/openwrt-xray_26.10.21-1_aarch64_cortex-a53.ipk "$TEST_ROOT/download"',
result = self.shell('fetch_file https://github.com/yichya/openwrt-xray/releases/download/v26.6.27/openwrt-xray_26.6.27-1_aarch64_cortex-a53-aarch64_cortex-a53.ipk "$TEST_ROOT/download"',
mocks=self.CURL_MOCK, http_proxy='', https_proxy='')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual((self.directory / 'resolved').read_text().splitlines(),
+37
View File
@@ -0,0 +1,37 @@
"""Compatibility deploy prepares the core without restarting or rewriting JSON."""
from test_xray_validation_deploy import XrayValidationDeploymentTests as BaseDeployment
class XrayCompatibilityDeploymentTests(BaseDeployment):
deploy_name = 'deploy-xray-compat-fix.ps1'
backup_name = 'owrt-remote-backup-before-xray-compat-v119'
success_marker = 'XRAY_COMPAT_ROUTER_Install_OK'
def setUp(self):
super().setUp()
self.script = self.script.replace('/usr/sbin/owrt-remote prepare-xray', 'test_prepare_xray')
self.script = '''test_prepare_xray() { return "${PREPARE_RC:-0}"; }
''' + self.script
def test_preparation_failure_restores_both_code_files(self):
self.env['PREPARE_RC'] = '23'
result = self.deploy('Install')
self.assertEqual(result.returncode, 23, result.stderr)
self.assertIn('prepare-compatible-xray', result.stderr)
self.assertNotIn(self.success_marker, result.stdout)
for item, path in self.targets.items():
self.assertEqual(path.read_bytes(), self.original[item])
def test_prepare_runs_only_on_install(self):
# Running restored old code on rollback would make an unbounded network
# request or revert the compatible binary. Rollback returns only code.
result = self.deploy('Install')
self.assertEqual(result.returncode, 0, result.stderr)
self.env['PREPARE_RC'] = '99'
result = self.deploy('Rollback')
self.assertEqual(result.returncode, 0, result.stderr)
if __name__ == '__main__':
import unittest
unittest.main()
+86
View File
@@ -0,0 +1,86 @@
"""Keep JSON and code together through install, rollback and render/restart failures."""
import unittest
import test_xray_validation_deploy as router_deploy
import test_update_status_ui_deploy as vps_deploy
class ReverseRouterDeploymentTests(router_deploy.XrayValidationDeploymentTests):
deploy_name = 'deploy-xray-reverse-fix.ps1'
backup_name = 'owrt-remote-backup-before-xray-reverse-v119'
success_marker = 'XRAY_REVERSE_ROUTER_Install_OK'
@staticmethod
def shell_path(path):
value = path.as_posix()
return '/' + value[0].lower() + value[2:] if path.drive else value
def setUp(self):
super().setUp()
self.config_path = self.root / 'working.json'
self.old_config = b'{"working":true}\n'
self.config_path.write_bytes(self.old_config)
self.env['TEST_CONFIG'] = self.shell_path(self.config_path)
self.env['TEST_RESTART'] = (self.root / 'restart').as_posix()
self.script = self.script.replace('/usr/sbin/owrt-remote render-client', 'test_render')
self.script = self.script.replace('/etc/init.d/owrt-remote restart', 'test_restart')
mocks = '''
uci() { printf '%s\\n' "$TEST_CONFIG"; }
test_render() {
[ "${RENDER_RC:-0}" = 0 ] || return "$RENDER_RC"
printf '{"finalRules":[]}\\n' >"$TEST_CONFIG"
}
test_restart() {
if [ "${RESTART_RC:-0}" != 0 ] && [ ! -f "$TEST_RESTART" ]; then
touch "$TEST_RESTART"; return "$RESTART_RC"
fi
echo restart >>"$TEST_RESTART"
}
'''
self.script = mocks + self.script
def test_install_twice_then_rollback_preserves_first_backup(self):
super().test_install_twice_then_rollback_preserves_first_backup()
self.assertEqual(self.config_path.read_bytes(), self.old_config)
self.assertEqual(self.backup.joinpath('config.json').read_bytes(), self.old_config)
def test_failed_render_does_not_restart_or_replace_json(self):
self.env['RENDER_RC'] = '23'
result = self.deploy('Install')
self.assertEqual(result.returncode, 23, result.stderr)
self.assertIn('validate-client-config', result.stderr)
self.assertNotIn(self.success_marker, result.stdout)
self.assertEqual(self.config_path.read_bytes(), self.old_config)
self.assertFalse((self.root / 'restart').exists())
for name, path in self.targets.items():
self.assertEqual(path.read_bytes(), self.original[name])
def test_failed_restart_restores_original_json_and_code(self):
self.env['RESTART_RC'] = '7'
result = self.deploy('Install')
self.assertEqual(result.returncode, 7, result.stderr)
self.assertIn('restart-tunnel', result.stderr)
self.assertEqual(self.config_path.read_bytes(), self.old_config)
self.assertIn('restart', (self.root / 'restart').read_text())
for name, path in self.targets.items():
self.assertEqual(path.read_bytes(), self.original[name])
def test_rollback_refuses_a_different_config_path(self):
self.assertEqual(self.deploy('Install').returncode, 0)
other = self.root / 'different.json'
other.write_bytes(b'{"other":true}\n')
self.env['TEST_CONFIG'] = self.shell_path(other)
result = self.deploy('Rollback')
self.assertNotEqual(result.returncode, 0)
self.assertIn('xray_config changed', result.stderr)
self.assertEqual(other.read_bytes(), b'{"other":true}\n')
class ReverseVpsDeploymentTests(vps_deploy.UpdateStatusDeployTests):
deploy_file = 'deploy-xray-reverse-vps.ps1'
backup_name = 'hub.py.bak-before-xray-reverse-v119'
success_marker = 'XRAY_REVERSE_VPS_Install_OK'
if __name__ == '__main__':
unittest.main()
+154
View File
@@ -0,0 +1,154 @@
"""Exercise both generated reverse channels with real Xray processes on loopback."""
import http.client
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import socket
import socketserver
import subprocess
import tempfile
import threading
import time
import unittest
import uuid
import test_host_policy as shell_tests
hub, SH = shell_tests.hub, shell_tests.SH
class HTTPProbe(BaseHTTPRequestHandler):
def do_GET(self):
body = b'OWRT_HTTP_REVERSE_OK'
self.send_response(200)
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
class SSHProbe(socketserver.BaseRequestHandler):
def handle(self):
self.request.sendall(b'SSH-2.0-OWRT_TEST\r\n')
self.request.settimeout(2)
try:
self.request.recv(128)
except OSError:
pass
def free_port():
with socket.socket() as sock:
sock.bind(('127.0.0.1', 0))
return sock.getsockname()[1]
@unittest.skipUnless(os.environ.get('OWRT_TEST_XRAY_BIN'), 'Set a real compatible Xray binary')
class ReverseTransportTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix='owrt-reverse-')
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.http_server = ThreadingHTTPServer(('127.0.0.1', 0), HTTPProbe)
self.ssh_server = socketserver.ThreadingTCPServer(('127.0.0.1', 0), SSHProbe)
self.ssh_server.daemon_threads = True
for server in (self.http_server, self.ssh_server):
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
self.addCleanup(self.close_server, server, thread)
self.client_bin = Path(os.environ['OWRT_TEST_XRAY_BIN']).resolve()
@staticmethod
def close_server(server, thread):
server.shutdown()
server.server_close()
thread.join(timeout=3)
def check_pair(self, server_bin, shell_client=False):
processes, streams = [], []
row = dict(id='probe', name='probe', entry_port=free_port(), ssh_entry_port=free_port(),
vps_host='127.0.0.1', vless_port=free_port(), vless_uuid=str(uuid.uuid4()),
ssh_vless_uuid=str(uuid.uuid4()), vless_encryption='none', vless_flow='',
reverse_tag='reverse-in', ssh_reverse_tag='reverse-in-ssh',
admin_host='127.0.0.1', admin_port=self.http_server.server_port,
ssh_host='127.0.0.1', ssh_port=self.ssh_server.server_address[1])
configs = dict(server=hub.make_server_xray_config([row], listen_host='127.0.0.1',
listen_port=row['vless_port']),
client=hub.make_router_xray_config(row))
if shell_client:
harness = shell_tests.RouterShellTests()
harness.setUp()
try:
harness.config(vps_host=row['vps_host'], vps_port=row['vless_port'],
vless_uuid=row['vless_uuid'], ssh_vless_uuid=row['ssh_vless_uuid'],
reverse_tag=row['reverse_tag'], ssh_reverse_tag=row['ssh_reverse_tag'],
admin_host=row['admin_host'], admin_port=row['admin_port'],
ssh_host=row['ssh_host'], ssh_port=row['ssh_port'])
result = harness.run_shell('render_client_config --stdout')
self.assertEqual(result.returncode, 0, result.stderr)
configs['client'] = json.loads(result.stdout)
finally:
harness.doCleanups()
try:
for name, config in configs.items():
config['log'] = {'loglevel': 'debug'}
path = self.root / (name + '.json')
path.write_text(json.dumps(config), encoding='utf-8')
binary = server_bin if name == 'server' else self.client_bin
check = subprocess.run([str(binary), '-test', '-config', str(path)],
capture_output=True, text=True, timeout=10)
self.assertEqual(check.returncode, 0, check.stdout + check.stderr)
stream = (self.root / (name + '.log')).open('wb')
streams.append(stream)
processes.append(subprocess.Popen([str(binary), 'run', '-config', str(path)],
stdout=stream, stderr=subprocess.STDOUT))
deadline = time.monotonic() + 18
response, error = None, ''
while time.monotonic() < deadline:
connection = http.client.HTTPConnection('127.0.0.1', row['entry_port'], timeout=1)
try:
connection.request('GET', '/')
with connection.getresponse() as result:
response = result.status, result.read()
break
except OSError as exc:
error = repr(exc)
finally:
connection.close()
if any(process.poll() is not None for process in processes):
break
time.sleep(.1)
logs = '\n'.join((self.root / (name + '.log')).read_text(encoding='utf-8', errors='replace')[-6000:]
for name in configs)
self.assertEqual(response, (200, b'OWRT_HTTP_REVERSE_OK'), error + '\n' + logs)
with socket.create_connection(('127.0.0.1', row['ssh_entry_port']), timeout=3) as sock:
sock.settimeout(3)
self.assertEqual(sock.recv(128), b'SSH-2.0-OWRT_TEST\r\n', logs)
finally:
for process in processes:
process.terminate()
try:
process.wait(timeout=3)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=3)
for stream in streams:
stream.close()
def test_compatible_router_with_same_server_version(self):
self.check_pair(self.client_bin)
@unittest.skipUnless(os.environ.get('OWRT_TEST_NEW_XRAY_BIN'), 'Set a modern server Xray binary')
def test_compatible_router_with_modern_server(self):
self.check_pair(Path(os.environ['OWRT_TEST_NEW_XRAY_BIN']).resolve())
@unittest.skipUnless(SH and os.environ.get('OWRT_TEST_NEW_XRAY_BIN'), 'POSIX shell and modern server required')
def test_real_router_shell_config_with_modern_server(self):
self.check_pair(Path(os.environ['OWRT_TEST_NEW_XRAY_BIN']).resolve(), shell_client=True)
if __name__ == '__main__':
unittest.main()
+29
View File
@@ -79,6 +79,10 @@ printf 'Configuration OK.\n'
config = json.loads(self.target.read_text())
self.assertEqual(config["outbounds"][2]["settings"]["port"], 8443)
self.assertEqual(config["outbounds"][0]["settings"]["redirect"], "127.0.0.1:80")
self.assertEqual(config["outbounds"][0]["settings"]["finalRules"],
[{"action": "allow", "network": "tcp", "port": 80}])
self.assertEqual(config["outbounds"][1]["settings"]["finalRules"],
[{"action": "allow", "network": "tcp", "port": 22}])
self.assertEqual(config["outbounds"][2]["settings"]["reverse"]["tag"], "main:admin")
self.assert_no_candidate()
if os.name != "nt":
@@ -189,6 +193,27 @@ done
self.assertEqual(self.target.read_bytes(), working)
self.assert_no_candidate()
@unittest.skipUnless(os.environ.get('OWRT_TEST_XRAY_BIN') and os.environ.get('OWRT_TEST_NEW_XRAY_BIN'),
'Set compatible and incompatible real Xray binaries')
def test_real_generated_public_reverse_config_matches_the_reported_failure(self):
old = Path(os.environ['OWRT_TEST_XRAY_BIN']).as_posix()
new = Path(os.environ['OWRT_TEST_NEW_XRAY_BIN']).as_posix()
for address in ('example.com', '8.8.8.8'):
self.prepare(vps_host=address, xray_bin=old)
result = self.run_shell('render_client_config')
self.assertEqual(result.returncode, 0, result.stderr)
working = self.target.read_bytes()
# Deliberately skip migration once to reproduce the exact rc=23
# with a new core against the very same generated configuration.
self.config(vps_host=address, vless_uuid=ADMIN_UUID, ssh_vless_uuid=SSH_UUID,
reverse_tag='main:admin', ssh_reverse_tag='main:ssh',
xray_bin=new, xray_config=self.target.as_posix())
result = self.run_shell('ensure_xray_available() { return 0; }; render_client_config')
self.assertEqual(result.returncode, 23, result.stderr)
self.assertIn('vless without TLS', result.stderr)
self.assertEqual(self.target.read_bytes(), working)
self.assert_no_candidate()
def test_hub_client_and_server_payload_agree_on_uuids_ports_and_routes(self):
row = dict(id="test-router", name="test", role="node", vps_host="hub.example", vless_port=8443,
vless_uuid=ADMIN_UUID, ssh_vless_uuid=SSH_UUID, reverse_tag="main:admin", ssh_reverse_tag="main:ssh",
@@ -201,6 +226,10 @@ done
result = self.run_shell("render_client_config --stdout")
self.assertEqual(result.returncode, 0, result.stderr)
client = json.loads(result.stdout)
hub_client = shell_tests.hub.make_router_xray_config(row)
for index in (0, 1):
self.assertEqual(client["outbounds"][index]["settings"],
hub_client["outbounds"][index]["settings"])
server = shell_tests.hub.make_server_xray_config([row], listen_port=8443)
inbound = server["inbounds"][0]
self.assertEqual(inbound["port"], client["outbounds"][2]["settings"]["port"])
+7 -3
View File
@@ -11,6 +11,10 @@ from test_xray_mobile_deploy import SH, GIT_BIN, ROOT
@unittest.skipUnless(SH, "POSIX shell required")
class XrayValidationDeploymentTests(unittest.TestCase):
deploy_name = 'deploy-xray-validation-fix.ps1'
backup_name = 'owrt-remote-backup-before-xray-validation-v119'
success_marker = 'XRAY_VALIDATION_ROUTER_Install_OK'
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix="xray-validation-deploy-")
self.addCleanup(self.temp.cleanup)
@@ -23,9 +27,9 @@ class XrayValidationDeploymentTests(unittest.TestCase):
self.env = dict(os.environ)
if os.name == "nt":
self.env["PATH"] = str(GIT_BIN) + os.pathsep + self.env["PATH"]
source = (ROOT / "vps/deploy-xray-validation-fix.ps1").read_text(encoding="utf-8")
source = (ROOT / 'vps' / self.deploy_name).read_text(encoding="utf-8")
self.script = source.split("$RemoteScript = @'\n", 1)[1].split("\n'@", 1)[0]
self.script = self.script.replace("backup_dir=/root/owrt-remote-backup-before-xray-validation-v119",
self.script = self.script.replace('backup_dir=/root/' + self.backup_name,
"backup_dir=" + shlex.quote(self.backup.as_posix()))
self.script = self.script.replace("printf /www/cgi-bin/owrt-remote", "printf %s " + shlex.quote(self.targets["cgi"].as_posix()))
self.script = self.script.replace("printf /usr/sbin/owrt-remote", "printf %s " + shlex.quote(self.targets["agent"].as_posix()))
@@ -52,7 +56,7 @@ class XrayValidationDeploymentTests(unittest.TestCase):
for attempt in range(2):
result = self.deploy("Install")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("XRAY_VALIDATION_ROUTER_Install_OK", result.stdout)
self.assertIn(self.success_marker, result.stdout)
for item, path in self.targets.items():
self.assertNotEqual(path.read_bytes(), self.original[item])
self.assertEqual(self.backup.joinpath(item).read_bytes(), self.original[item])
+133
View File
@@ -0,0 +1,133 @@
param(
[ValidateNotNullOrEmpty()][string]$Router = 'root@192.168.2.1',
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-xray-compat-' + [guid]::NewGuid().ToString('N')
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
$Utf8 = [System.Text.UTF8Encoding]::new($false)
$Payloads = @{
'cgi' = 'files\www\cgi-bin\owrt-remote'
'agent' = 'files\usr\sbin\owrt-remote'
}
$RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
backup_dir=/root/owrt-remote-backup-before-xray-compat-v119
changed=0
phase=preflight
item_path() {
case "$1" in
cgi) printf /www/cgi-bin/owrt-remote ;;
agent) printf /usr/sbin/owrt-remote ;;
esac
}
complete_backup() {
[ -f "$1/complete" ] && [ -s "$1/cgi" ] && [ -s "$1/agent" ]
}
restore_files() {
local dir item path
dir=$1
complete_backup "$dir" || return 1
for item in cgi agent; do
path=$(item_path "$item")
cp -p "$dir/$item" "$path.new-__UPLOAD_NAME__" || return 1
mv -f "$path.new-__UPLOAD_NAME__" "$path" || return 1
done
}
cleanup() {
code=$?
trap - EXIT
if [ "$code" -ne 0 ]; then
printf 'Failed during %s (rc=%s).\n' "$phase" "$code" >&2
if [ "$changed" = 1 ]; then
echo 'Restoring the agent and CGI from this attempt.' >&2
restore_files "$stage/previous" || echo 'Restore failed; retained backup is available.' >&2
fi
fi
for item in cgi agent; do path=$(item_path "$item"); rm -f "$path.new-__UPLOAD_NAME__"; done
rm -rf "$stage"
exit "$code"
}
trap cleanup EXIT
trap 'exit 1' INT TERM
for item in cgi agent; do
path=$(item_path "$item")
test -s "$path"
done
if [ '__ACTION__' = Install ]; then
for item in cgi agent; do test -s "$stage/$item"; sh -n "$stage/$item"; done
grep -F -q 'xray_validate_transport_binary()' "$stage/agent"
grep -F -q '26.6.27' "$stage/agent"
grep -F -q 'OWRT_REMOTE_APPLY_TRACE' "$stage/cgi"
if [ ! -e "$backup_dir" ]; then
mkdir -p "$stage/retained-backup"
chmod 700 "$stage/retained-backup"
for item in cgi agent; do path=$(item_path "$item"); cp -p "$path" "$stage/retained-backup/$item"; done
touch "$stage/retained-backup/complete"
mv "$stage/retained-backup" "$backup_dir"
fi
complete_backup "$backup_dir" || { echo "Incomplete backup: $backup_dir. Nothing changed." >&2; exit 1; }
source_dir=$stage
else
complete_backup "$backup_dir" || { echo "No complete backup: $backup_dir. Nothing changed." >&2; exit 1; }
for item in cgi agent; do sh -n "$backup_dir/$item"; done
source_dir=$backup_dir
fi
printf 'Backup: %s\n' "$backup_dir"
mkdir -p "$stage/previous"
for item in cgi agent; do path=$(item_path "$item"); cp -p "$path" "$stage/previous/$item"; done
touch "$stage/previous/complete"
phase=install
changed=1
for item in cgi agent; do
path=$(item_path "$item")
cp "$source_dir/$item" "$path.new-__UPLOAD_NAME__"
chmod 755 "$path.new-__UPLOAD_NAME__"
mv -f "$path.new-__UPLOAD_NAME__" "$path"
done
phase=verify
for item in cgi agent; do
path=$(item_path "$item")
sh -n "$path"
cmp "$source_dir/$item" "$path"
done
if [ '__ACTION__' = Install ]; then
phase=prepare-compatible-xray
# Replaces a known incompatible core, or restores/downloads a validated
# compatible one. Does not render JSON or restart an existing tunnel.
/usr/sbin/owrt-remote prepare-xray
fi
# Rollback restores agent/CGI code only; retain the validated compatible core,
# its boot cache, and all router settings. Never remove a working executable.
printf '\nXRAY_COMPAT_ROUTER_%s_OK\n' '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
try {
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
[System.IO.File]::WriteAllText((Join-Path $StageRoot 'run.sh'), $RemoteScript.Replace("`r`n", "`n") + "`n", $Utf8)
if ($Action -eq 'Install') {
foreach ($Item in $Payloads.GetEnumerator()) {
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot $Item.Value)).Replace("`r`n", "`n")
[System.IO.File]::WriteAllText((Join-Path $StageRoot $Item.Key), $Content, $Utf8)
}
}
if ($PrepareOnly) { Write-Host "Prepared only: $StageRoot"; return }
& scp -O -r -- $StageRoot "${Router}:/tmp/"
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. The installation has not started.' }
& ssh -T -o ConnectTimeout=10 $Router "sh /tmp/$UploadName/run.sh"
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
Write-Host "Xray compatibility fix $Action finished successfully."
} finally {
if (-not $PrepareOnly) {
$Resolved = [System.IO.Path]::GetFullPath($StageRoot)
$Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName))
if ($Resolved -ne $Expected -or (Split-Path -Leaf $Resolved) -ne $UploadName) { throw 'Unsafe staging cleanup path.' }
if (Test-Path -LiteralPath $Resolved) { Remove-Item -LiteralPath $Resolved -Recurse -Force }
}
}
+165
View File
@@ -0,0 +1,165 @@
param(
[ValidateNotNullOrEmpty()][string]$Router = 'root@192.168.2.1',
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-xray-reverse-' + [guid]::NewGuid().ToString('N')
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
$Utf8 = [System.Text.UTF8Encoding]::new($false)
$Payloads = @{
'cgi' = 'files\www\cgi-bin\owrt-remote'
'agent' = 'files\usr\sbin\owrt-remote'
}
$RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
backup_dir=/root/owrt-remote-backup-before-xray-reverse-v119
changed=0
restart_attempted=0
phase=preflight
config=$(uci -q get owrtremote.main.xray_config || true)
[ -n "$config" ] || config=/etc/xray/owrt-remote-client.json
case "$config" in /*) ;; *) echo 'xray_config must be absolute.' >&2; exit 1 ;; esac
item_path() {
case "$1" in
cgi) printf /www/cgi-bin/owrt-remote ;;
agent) printf /usr/sbin/owrt-remote ;;
esac
}
complete_backup() {
[ -f "$1/complete" ] && [ -s "$1/cgi" ] && [ -s "$1/agent" ] &&
[ -s "$1/config-path" ] && { [ -s "$1/config.json" ] || [ -f "$1/config-missing" ]; }
}
save_config() {
printf '%s\n' "$config" >"$1/config-path"
if [ -f "$config" ]; then cp -p "$config" "$1/config.json"; else touch "$1/config-missing"; fi
}
restore_config() {
[ "$(cat "$1/config-path")" = "$config" ] || return 1
if [ -f "$1/config-missing" ]; then
rm -f "$config"
else
cp -p "$1/config.json" "$config.new-__UPLOAD_NAME__" || return 1
mv -f "$config.new-__UPLOAD_NAME__" "$config" || return 1
fi
}
restore_files() {
local dir item path
dir=$1
complete_backup "$dir" || return 1
for item in cgi agent; do
path=$(item_path "$item")
cp -p "$dir/$item" "$path.new-__UPLOAD_NAME__" || return 1
mv -f "$path.new-__UPLOAD_NAME__" "$path" || return 1
done
restore_config "$dir"
}
cleanup() {
code=$?
trap - EXIT
if [ "$code" -ne 0 ]; then
printf 'Failed during %s (rc=%s).\n' "$phase" "$code" >&2
if [ "$changed" = 1 ]; then
echo 'Restoring the agent and CGI from this attempt.' >&2
restore_files "$stage/previous" || echo 'Restore failed; retained backup is available.' >&2
if [ "$restart_attempted" = 1 ] && [ -s "$config" ]; then /etc/init.d/owrt-remote restart >&2 || true; fi
fi
fi
for item in cgi agent; do path=$(item_path "$item"); rm -f "$path.new-__UPLOAD_NAME__"; done
rm -f "$config.new-__UPLOAD_NAME__"
rm -rf "$stage"
exit "$code"
}
trap cleanup EXIT
trap 'exit 1' INT TERM
for item in cgi agent; do
path=$(item_path "$item")
test -s "$path"
done
if [ '__ACTION__' = Install ]; then
for item in cgi agent; do test -s "$stage/$item"; sh -n "$stage/$item"; done
grep -F -q 'xray_validate_transport_binary()' "$stage/agent"
grep -F -q '26.6.27' "$stage/agent"
grep -F -q '"finalRules"' "$stage/agent"
grep -F -q 'OWRT_REMOTE_APPLY_TRACE' "$stage/cgi"
if [ ! -e "$backup_dir" ]; then
mkdir -p "$stage/retained-backup"
chmod 700 "$stage/retained-backup"
for item in cgi agent; do path=$(item_path "$item"); cp -p "$path" "$stage/retained-backup/$item"; done
save_config "$stage/retained-backup"
touch "$stage/retained-backup/complete"
mv "$stage/retained-backup" "$backup_dir"
fi
complete_backup "$backup_dir" || { echo "Incomplete backup: $backup_dir. Nothing changed." >&2; exit 1; }
source_dir=$stage
else
complete_backup "$backup_dir" || { echo "No complete backup: $backup_dir. Nothing changed." >&2; exit 1; }
[ "$(cat "$backup_dir/config-path")" = "$config" ] || { echo 'xray_config changed since backup. Nothing changed.' >&2; exit 1; }
for item in cgi agent; do sh -n "$backup_dir/$item"; done
source_dir=$backup_dir
fi
printf 'Backup: %s\n' "$backup_dir"
mkdir -p "$stage/previous"
chmod 700 "$stage/previous"
for item in cgi agent; do path=$(item_path "$item"); cp -p "$path" "$stage/previous/$item"; done
save_config "$stage/previous"
touch "$stage/previous/complete"
phase=install
changed=1
for item in cgi agent; do
path=$(item_path "$item")
cp "$source_dir/$item" "$path.new-__UPLOAD_NAME__"
chmod 755 "$path.new-__UPLOAD_NAME__"
mv -f "$path.new-__UPLOAD_NAME__" "$path"
done
phase=verify
for item in cgi agent; do
path=$(item_path "$item")
sh -n "$path"
cmp "$source_dir/$item" "$path"
done
if [ '__ACTION__' = Install ]; then
phase=validate-client-config
# render-client validates the candidate with Xray before atomic replacement.
/usr/sbin/owrt-remote render-client
grep -F -q '"finalRules"' "$config"
else
phase=restore-client-config
restore_config "$backup_dir"
fi
phase=restart-tunnel
restart_attempted=1
/etc/init.d/owrt-remote restart
# Keep the compatible core and its boot cache on rollback; restore the saved
# agent, CGI and JSON. The VPS server binary does not need a downgrade.
printf '\nXRAY_REVERSE_ROUTER_%s_OK\n' '__ACTION__'
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
try {
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
[System.IO.File]::WriteAllText((Join-Path $StageRoot 'run.sh'), $RemoteScript.Replace("`r`n", "`n") + "`n", $Utf8)
if ($Action -eq 'Install') {
foreach ($Item in $Payloads.GetEnumerator()) {
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot $Item.Value)).Replace("`r`n", "`n")
[System.IO.File]::WriteAllText((Join-Path $StageRoot $Item.Key), $Content, $Utf8)
}
}
if ($PrepareOnly) { Write-Host "Prepared only: $StageRoot"; return }
& scp -O -r -- $StageRoot "${Router}:/tmp/"
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. The installation has not started.' }
& ssh -T -o ConnectTimeout=10 $Router "sh /tmp/$UploadName/run.sh"
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
Write-Host "Xray reverse fix $Action finished successfully."
} finally {
if (-not $PrepareOnly) {
$Resolved = [System.IO.Path]::GetFullPath($StageRoot)
$Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName))
if ($Resolved -ne $Expected -or (Split-Path -Leaf $Resolved) -ne $UploadName) { throw 'Unsafe staging cleanup path.' }
if (Test-Path -LiteralPath $Resolved) { Remove-Item -LiteralPath $Resolved -Recurse -Force }
}
}
+178
View File
@@ -0,0 +1,178 @@
param(
[Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()][string]$Vps,
[ValidateSet('Install', 'Rollback')][string]$Action = 'Install',
[switch]$PrepareOnly
)
$ErrorActionPreference = 'Stop'
$RepoRoot = Split-Path -Parent $PSScriptRoot
$UploadName = 'owrt-xray-reverse-vps-' + [guid]::NewGuid().ToString('N')
$StageRoot = Join-Path ([System.IO.Path]::GetTempPath()) $UploadName
$Utf8 = [System.Text.UTF8Encoding]::new($false)
$RemoteScript = @'
#!/bin/sh
set -eu
stage=/tmp/__UPLOAD_NAME__
target=/opt/owrt-remote/owrt-remote-hub.py
backup=/opt/owrt-remote/owrt-remote-hub.py.bak-before-xray-reverse-v119
candidate=$target.new-__UPLOAD_NAME__
changed=0
show_failure() {
echo '--- owrt-remote status ---' >&2
systemctl --no-pager -l status owrt-remote >&2 || true
echo '--- owrt-remote journal ---' >&2
journalctl -u owrt-remote -n 80 --no-pager -l >&2 || true
}
cleanup() {
code=$?
trap - EXIT
if [ "$code" -ne 0 ]; then
echo "Remote step failed with rc=$code" >&2
show_failure
fi
if [ "$code" -ne 0 ] && [ "$changed" = 1 ] && [ -s "$stage/previous.py" ]; then
echo 'Restoring the previous Hub file...' >&2
cp -p "$stage/previous.py" "$candidate"
mv -f "$candidate" "$target"
systemctl restart owrt-remote || true
fi
rm -f "$candidate"
rm -rf "$stage"
exit "$code"
}
trap cleanup EXIT
test -s "$target"
python_bin=/opt/owrt-remote/venv/bin/python
[ -x "$python_bin" ] || python_bin=python3
if [ '__ACTION__' = Install ]; then
test -s "$stage/hub.py"
echo 'Validating candidate...'
"$python_bin" -m py_compile "$stage/hub.py"
"$python_bin" - "$stage/hub.py" <<'PY'
from pathlib import Path
import sys
source = Path(sys.argv[1]).read_text(encoding='utf-8')
required = (
'"finalRules": [{"action": "allow", "network": "tcp", "port": int(row["admin_port"])}]',
'"finalRules": [{"action": "allow", "network": "tcp", "port": int(row["ssh_port"] or 22)}]',
)
missing = [marker for marker in required if marker not in source]
if missing:
for marker in missing:
print('Missing marker:', repr(marker), file=sys.stderr)
raise SystemExit(1)
print('Candidate validation OK')
PY
if [ ! -e "$backup" ]; then
cp -p "$target" "$backup"
fi
source_file="$stage/hub.py"
else
test -s "$backup"
"$python_bin" -m py_compile "$backup"
source_file="$backup"
fi
expected_revision=$("$python_bin" - "$source_file" <<'PY'
import hashlib
from pathlib import Path
import sys
print(hashlib.sha256(Path(sys.argv[1]).read_bytes()).hexdigest())
PY
)
cp -p "$target" "$stage/previous.py"
cp "$source_file" "$candidate"
chmod 0755 "$candidate"
changed=1
mv -f "$candidate" "$target"
echo 'Restarting owrt-remote...'
if ! systemctl restart owrt-remote; then
show_failure
exit 1
fi
healthy=0
for attempt in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
if systemctl is-active --quiet owrt-remote && "$python_bin" - "$expected_revision" > "$stage/health-check" 2>&1 <<'PY'
import json
import sys
import urllib.request
try:
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with opener.open('http://127.0.0.1:8088/health?panel-update=1', timeout=3) as response:
data = json.loads(response.read(4096))
revision = data.get('revision', '')
if not data.get('ok') or revision != sys.argv[1]:
raise RuntimeError('Running Hub revision does not match the uploaded file: '
+ (revision or '(not reported)') + '; expected ' + sys.argv[1])
print('Running Hub revision verified: ' + revision)
except Exception as error:
print('Health verification failed: ' + str(error), file=sys.stderr)
raise SystemExit(1)
PY
then
healthy=1
break
fi
sleep 2
done
if [ "$healthy" -ne 1 ]; then
echo 'The uploaded Hub build did not become ready; installation was not confirmed.' >&2
cat "$stage/health-check" >&2 2>/dev/null || true
show_failure
exit 1
fi
cat "$stage/health-check"
cmp "$source_file" "$target"
printf '\nBackup: %s\nXRAY_REVERSE_VPS_%s_OK\n' "$backup" '__ACTION__'
if [ '__ACTION__' = Install ]; then
echo 'Hub client generator updated. The router fix must also be installed.'
echo 'The VPS Xray core and running server configuration are unchanged.'
fi
'@
$RemoteScript = $RemoteScript.Replace('__UPLOAD_NAME__', $UploadName).Replace('__ACTION__', $Action)
try {
[System.IO.Directory]::CreateDirectory($StageRoot) | Out-Null
[System.IO.File]::WriteAllText(
(Join-Path $StageRoot 'run.sh'),
$RemoteScript.Replace("`r`n", "`n") + "`n",
$Utf8
)
if ($Action -eq 'Install') {
$Content = [System.IO.File]::ReadAllText((Join-Path $RepoRoot 'vps\owrt-remote-hub.py')).Replace("`r`n", "`n")
[System.IO.File]::WriteAllText((Join-Path $StageRoot 'hub.py'), $Content, $Utf8)
}
if ($PrepareOnly) {
Write-Host "Prepared only: $StageRoot"
return
}
& scp -O -r -- $StageRoot "${Vps}:/tmp/"
if ($LASTEXITCODE -ne 0) { throw 'Upload failed. VPS was not changed.' }
& ssh -T -o ConnectTimeout=10 $Vps "sh /tmp/$UploadName/run.sh"
if ($LASTEXITCODE -ne 0) { throw "$Action failed. See the output above; success was not confirmed." }
Write-Host "Xray reverse Hub fix $Action finished successfully."
}
finally {
if (-not $PrepareOnly) {
$Resolved = [System.IO.Path]::GetFullPath($StageRoot)
$Expected = [System.IO.Path]::GetFullPath((Join-Path ([System.IO.Path]::GetTempPath()) $UploadName))
if ($Resolved -ne $Expected -or (Split-Path -Leaf $Resolved) -ne $UploadName) {
throw 'Unsafe staging cleanup path.'
}
if (Test-Path -LiteralPath $Resolved) {
Remove-Item -LiteralPath $Resolved -Recurse -Force
}
}
}
+4
View File
@@ -4488,6 +4488,9 @@ def make_router_xray_config(row):
"protocol": "freedom",
"settings": {
"redirect": f"{row['admin_host']}:{int(row['admin_port'])}",
# VLESS reverse is denied by Freedom's default final rule.
# Redirect fixes the destination; allow only its TCP port.
"finalRules": [{"action": "allow", "network": "tcp", "port": int(row["admin_port"])}],
},
},
{
@@ -4495,6 +4498,7 @@ def make_router_xray_config(row):
"protocol": "freedom",
"settings": {
"redirect": f"{row['ssh_host'] or '127.0.0.1'}:{int(row['ssh_port'] or 22)}",
"finalRules": [{"action": "allow", "network": "tcp", "port": int(row["ssh_port"] or 22)}],
},
},
{