fork: REALITY transport for the router<->hub VLESS hop

Upstream ships the router<->hub hop as plain VLESS (tcp, security=none):
UUID-authenticated but cleartext — LuCI credentials and logs inside the
hop are readable by anyone on-path. This fork wraps the hop in
VLESS+Reality (TLS handshake camouflaged against a public dest, no CA
certs, no renewal):

- vps/owrt-remote-hub.py: transport profile (STATE_DIR/transport.json,
  x25519 keypair via the xray binary), reality streamSettings in the
  server inbound and in make_router_xray_config(), uci transport lines
  in the generated OpenWrt config, transport block in heartbeat
  hub_update, and xray -test gate before swapping /etc/xray config.
- files/usr/sbin/owrt-remote: security/reality_* uci options,
  validation, reality streamSettings in render_client_config,
  security-aware compat probe and core-compat checks.
- files/etc/config/owrtremote, cgi form fields, PKG_RELEASE bump.

Env on the hub: OWRT_REMOTE_TRANSPORT=reality|none,
OWRT_REMOTE_REALITY_DEST/FINGERPRINT, OWRT_REMOTE_XRAY_BINARY.

NOTE: xray-core >= 26.9.8 REALITY servers reject client hellos
(XTLS/Xray-core#7259) — pin the hub core to 26.7.28 until upstream fixes it.
This commit is contained in:
cyril-fork committed 2026-11-22 11:22:49 +03:00
1 parent 9dead7741d
commit 9b7a89257b
5 files changed
+190 -14

No files matched your search

+4
View File
@@ -17,6 +17,10 @@ config remote 'main'
option vless_uuid ''
option vless_encryption 'none'
option vless_flow ''
option security 'none'
option reality_public_key ''
option reality_server_name ''
option reality_fingerprint 'chrome'
option reverse_tag 'reverse-in'
option ssh_vless_uuid ''
option ssh_reverse_tag 'reverse-in-ssh'
+39 -4
View File
@@ -622,7 +622,18 @@ validate_xray_config() {
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).
# for the transport generated here.
if [ "$(uci_get security none)" = reality ]; then
# Reality needs a core with X25519/Reality support; replace only old builds.
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]) < 240214)
}'
return $?
fi
# (VLESS encryption=none, security=none path, upstream rule)
[ "$(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
@@ -640,15 +651,21 @@ xray_validate_transport_binary() (
trap 'rm -rf "$probe"' EXIT
trap 'exit 1' INT TERM
umask 077
if [ "$(uci_get security none)" = reality ]; then
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":"reality","realitySettings":{"show":false,"fingerprint":"chrome","serverName":"www.microsoft.com","publicKey":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}}}]}
EOF
else
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
fi
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). Нужна сборка с поддержкой текущего транспорта; рабочий бинарник и кэш сохранены"
log "ОШИБКА: пакет Xray несовместим с текущим транспортом VLESS reverse (security=$(uci_get security none), rc=$rc). Нужна сборка с поддержкой текущего транспорта; рабочий бинарник и кэш сохранены"
return "$rc"
fi
)
@@ -683,6 +700,10 @@ render_client_config() (
ssh_uuid="$(uci_get ssh_vless_uuid '')"
encryption="$(uci_get vless_encryption none)"
flow="$(uci_get vless_flow '')"
security="$(uci_get security none)"
reality_pk="$(uci_get reality_public_key '')"
reality_sni="$(uci_get reality_server_name '')"
reality_fp="$(uci_get reality_fingerprint chrome)"
reverse_tag="$(uci_get reverse_tag reverse-in)"
ssh_reverse_tag="$(uci_get ssh_reverse_tag "${reverse_tag}-ssh")"
admin_host="$(uci_get admin_host 127.0.0.1)"
@@ -707,6 +728,20 @@ render_client_config() (
fi
done
case "$vps_host" in *://*|*/*) die "vps_host должен содержать IP или домен без http(s):// и пути" ;; esac
case "$security" in none|reality) ;; *) die "security: ожидается none или reality" ;; esac
if [ "$security" = reality ]; then
case "$reality_pk" in ''|*[!A-Za-z0-9_-]*) die "reality_public_key: ожидается 43-символьный base64url-ключ X25519 из карточки роутера на VPS" ;; esac
[ "${#reality_pk}" -eq 43 ] || die "reality_public_key: длина ключа X25519 должна быть 43 символа"
case "$reality_sni" in ''|*://*) die "reality_server_name: укажите camouflage-домен без схемы и путей (например www.microsoft.com)" ;; esac
if [ "$(printf '%s' "$reality_sni" | LC_ALL=C tr -d '\001-\040\177')" != "$reality_sni" ]; then
die "reality_server_name: содержит пробел или управляющий символ"
fi
case "$reality_fp" in ''|*[!a-zA-Z0-9_-]*) die "reality_fingerprint: ожидается отпечаток без пробелов (chrome, firefox, safari, ios, android)" ;; esac
transport_stream='"security": "reality",
"realitySettings": {"show": false, "fingerprint": "'"$(json_escape "$reality_fp")"'", "serverName": "'"$(json_escape "$reality_sni")"'", "publicKey": "'"$(json_escape "$reality_pk")"'"}'
else
transport_stream='"security": "none"'
fi
if [ "$stdout" = "1" ]; then
xray_config_dir="${TMPDIR:-/tmp}"
@@ -761,7 +796,7 @@ render_client_config() (
},
"streamSettings": {
"network": "tcp",
"security": "none"$wan_sockopt
$transport_stream$wan_sockopt
}
},
{
@@ -779,7 +814,7 @@ render_client_config() (
},
"streamSettings": {
"network": "tcp",
"security": "none"$wan_sockopt
$transport_stream$wan_sockopt
}
}
],
+6 -2
View File
@@ -192,7 +192,7 @@ save_config() {
fi
uci_set enabled "$enabled"
for field in router_id router_name role hub_url hub_token heartbeat_interval xray_bin xray_config vps_host vps_port vless_uuid vless_encryption vless_flow reverse_tag ssh_vless_uuid ssh_reverse_tag admin_host admin_port ssh_host ssh_port public_url; do
for field in router_id router_name role hub_url hub_token heartbeat_interval xray_bin xray_config vps_host vps_port vless_uuid vless_encryption vless_flow security reality_public_key reality_server_name reality_fingerprint reverse_tag ssh_vless_uuid ssh_reverse_tag admin_host admin_port ssh_host ssh_port public_url; do
uci_set "$field" "$(param "$field")"
done
if has_param vps_host_auto; then uci_set vps_host_mode auto; else uci_set vps_host_mode manual; fi
@@ -208,7 +208,7 @@ save_config() {
clear_config() {
local field
for field in role public_url hub_url hub_token heartbeat_interval xray_bin xray_config vps_host vps_host_mode wan_direct wan_interface wan_dns vps_port vless_uuid vless_encryption vless_flow reverse_tag ssh_vless_uuid ssh_reverse_tag admin_host admin_port ssh_host ssh_port; do
for field in role public_url hub_url hub_token heartbeat_interval xray_bin xray_config vps_host vps_host_mode wan_direct wan_interface wan_dns vps_port vless_uuid vless_encryption vless_flow security reality_public_key reality_server_name reality_fingerprint reverse_tag ssh_vless_uuid ssh_reverse_tag admin_host admin_port ssh_host ssh_port; do
uci -q delete "owrtremote.main.$field"
done
uci commit owrtremote
@@ -715,6 +715,10 @@ EOF
field vless_uuid "VLESS UUID" text "Уникальный UUID роутера. Бери из карточки роутера на VPS или из команды print-openwrt-config."
field vless_encryption "VLESS encryption" text "Для этой схемы оставь none. Меняй только если сам меняешь Xray-конфиг на VPS."
field vless_flow "VLESS flow" text "Обычно оставь пустым. Нужно только для специальных режимов Xray."
field security "Транспорт (security)" text "none или reality. reality — TLS-упаковка VLESS (рекомендуется). Остальные значения — из карточки роутера на VPS."
field reality_public_key "Reality public key" text "43-символьный публичный ключ X25519 хаба. Только для security=reality."
field reality_server_name "Reality SNI" text "Camouflage-домен хаба, например www.microsoft.com. Только для security=reality."
field reality_fingerprint "Reality fingerprint" text "Отпечаток клиента: chrome, firefox, safari, ios или android."
field reverse_tag "Reverse tag" text "Метка reverse-туннеля внутри Xray. Обычно оставь reverse-in, если на VPS не задавал другое."
field ssh_vless_uuid "SSH VLESS UUID" text "UUID отдельного SSH reverse-туннеля. Бери из OpenWrt config на VPS для этого роутера."
field ssh_reverse_tag "SSH reverse tag" text "Метка reverse-туннеля для SSH. Обычно reverse-in-ssh."
+1 -1
View File
@@ -2,7 +2,7 @@ include $(TOPDIR)/rules.mk
PKG_NAME:=luci-app-owrt-remote
PKG_VERSION:=122
PKG_RELEASE:=2
PKG_RELEASE:=3
PKG_LICENSE:=MIT
PKG_MAINTAINER:=kzolotarev95
PKGARCH:=all
+140 -7
View File
@@ -114,6 +114,17 @@ ACME_WEBROOT = STATE_DIR / "acme-webroot"
# take longer than the old 75-second window while the reverse tunnel remains usable.
ONLINE_AFTER_SECONDS = max(75, int(os.environ.get("OWRT_REMOTE_ONLINE_AFTER", "180")))
DEFAULT_VLESS_PORT = int(os.environ.get("OWRT_REMOTE_VLESS_PORT", "8443"))
# Fork change (reality-transport): upstream ships the router<->hub hop as plain
# VLESS (network=tcp, security=none) — UUID-authenticated but not encrypted, so
# LuCI credentials and logs travel in cleartext inside that hop. This fork wraps
# it in VLESS+Reality: a real TLS handshake camouflaged against a public dest,
# no CA-issued certificates, no renewal. Per-router UUIDs still authenticate.
# Set OWRT_REMOTE_TRANSPORT=none to fall back to upstream behavior.
TRANSPORT_MODE = os.environ.get("OWRT_REMOTE_TRANSPORT", "reality").strip().lower()
REALITY_DEST = os.environ.get("OWRT_REMOTE_REALITY_DEST", "www.microsoft.com").strip()
REALITY_FINGERPRINT = os.environ.get("OWRT_REMOTE_REALITY_FINGERPRINT", "chrome").strip()
TRANSPORT_FILE = STATE_DIR / "transport.json"
XRAY_BINARY = os.environ.get("OWRT_REMOTE_XRAY_BINARY", "/usr/local/bin/xray")
REQUEST_QUEUE_SIZE = int(os.environ.get("OWRT_REMOTE_REQUEST_QUEUE_SIZE", "128"))
ROUTER_PROXY_LIMIT = max(1, int(os.environ.get("OWRT_REMOTE_ROUTER_PROXY_LIMIT", "4")))
PROXY_TIMEOUT = float(os.environ.get("OWRT_REMOTE_PROXY_TIMEOUT", "25"))
@@ -4118,6 +4129,7 @@ def router_current_hub_bundle(router, app_public_url="", request_origin="", fall
"hub_url": hub_url,
"public_url": public_url,
"vps_host": config_vps_host,
"transport": transport_public_summary(),
}
return hub_update, hub_url, config_vps_host
@@ -4621,6 +4633,98 @@ def delete_router_note_entry(conn, router_id, note_id):
return get_router(conn, router_id)
def generate_reality_profile():
# X25519 keypair via the local xray binary (stdlib has no X25519). Labels
# follow `xray x25519` output of the deployed core.
binary = XRAY_BINARY if Path(XRAY_BINARY).exists() else (shutil.which("xray") or "")
if not binary:
raise RuntimeError(f"xray binary not found for Reality keypair generation: {XRAY_BINARY}")
result = subprocess.run(
[binary, "x25519"], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=20, check=False,
)
out = result.stdout or ""
private = re.search(r"PrivateKey:\s*(\S+)", out)
public = re.search(r"Password \(PublicKey\):\s*(\S+)", out) or re.search(r"Password \(b64\):\s*(\S+)", out)
if not private or not public:
detail = (result.stderr or out or "").strip()
raise RuntimeError(f"`{binary} x25519` returned no keypair: {detail}")
return {
"mode": "reality",
"privateKey": private.group(1),
"publicKey": public.group(1),
"shortId": secrets.token_hex(4),
"serverName": REALITY_DEST,
"dest": f"{REALITY_DEST}:443",
"fingerprint": REALITY_FINGERPRINT or "chrome",
}
def transport_profile():
if TRANSPORT_MODE != "reality":
return {"mode": "none"}
if TRANSPORT_FILE.exists():
try:
data = json.loads(TRANSPORT_FILE.read_text(encoding="utf-8"))
if data.get("mode") == "reality" and data.get("privateKey") and data.get("publicKey"):
return data
except (OSError, ValueError):
pass
data = generate_reality_profile()
TRANSPORT_FILE.parent.mkdir(parents=True, exist_ok=True)
atomic_write_text(TRANSPORT_FILE, json.dumps(data, ensure_ascii=False, indent=2) + "\n", mode=0o600)
try:
os.chmod(TRANSPORT_FILE, 0o600)
except OSError:
pass
return data
def transport_public_summary():
profile = transport_profile()
if profile.get("mode") != "reality":
return {"mode": "none"}
return {
"mode": "reality",
"publicKey": profile["publicKey"],
"serverName": profile["serverName"],
"fingerprint": profile.get("fingerprint", "chrome"),
}
def transport_server_stream():
profile = transport_profile()
if profile.get("mode") != "reality":
return {"network": "tcp", "security": "none"}
return {
"network": "tcp",
"security": "reality",
"realitySettings": {
"show": False,
"dest": profile["dest"],
"xver": 0,
"serverNames": [profile["serverName"]],
"shortIds": [profile["shortId"]],
"privateKey": profile["privateKey"],
},
}
def transport_client_stream():
profile = transport_profile()
if profile.get("mode") != "reality":
return {"network": "tcp", "security": "none"}
return {
"network": "tcp",
"security": "reality",
"realitySettings": {
"show": False,
"fingerprint": profile.get("fingerprint", "chrome"),
"serverName": profile["serverName"],
"publicKey": profile["publicKey"],
},
}
def make_server_xray_config(rows, listen_host="0.0.0.0", listen_port=DEFAULT_VLESS_PORT, decryption="none"):
clients = []
inbounds = [
@@ -4633,10 +4737,7 @@ def make_server_xray_config(rows, listen_host="0.0.0.0", listen_port=DEFAULT_VLE
"clients": clients,
"decryption": decryption,
},
"streamSettings": {
"network": "tcp",
"security": "none",
},
"streamSettings": transport_server_stream(),
}
]
rules = []
@@ -4777,7 +4878,7 @@ def make_router_xray_config(row):
"flow": row["vless_flow"],
"reverse": {"tag": bridge_tag},
},
"streamSettings": {"network": "tcp", "security": "none"},
"streamSettings": transport_client_stream(),
},
{
"tag": "vps-ssh-interconn",
@@ -4790,7 +4891,7 @@ def make_router_xray_config(row):
"flow": row["vless_flow"],
"reverse": {"tag": ssh_bridge_tag},
},
"streamSettings": {"network": "tcp", "security": "none"},
"streamSettings": transport_client_stream(),
},
],
"routing": {
@@ -4826,11 +4927,33 @@ def reload_vps_xray(db_path=DB_PATH):
init_db(conn)
rows = list_router_rows(conn)
config = make_server_xray_config(rows)
atomic_write_text(out, json.dumps(config, ensure_ascii=False, indent=2) + "\n", mode=0o600)
config_text = json.dumps(config, ensure_ascii=False, indent=2) + "\n"
# Never replace a live tunnel config with an invalid one: render to a
# candidate, let the deployed xray validate it, then swap atomically.
out.parent.mkdir(parents=True, exist_ok=True)
candidate = out.parent / (out.name + ".candidate")
atomic_write_text(candidate, config_text, mode=0o600)
try:
os.chmod(candidate, 0o600)
except OSError:
pass
binary = XRAY_BINARY if Path(XRAY_BINARY).exists() else (shutil.which("xray") or "")
if binary:
test = subprocess.run(
[binary, "-test", "-config", str(candidate)],
text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30, check=False,
)
if test.returncode != 0:
candidate.unlink(missing_ok=True)
detail = (test.stderr or test.stdout or "").strip()
raise RuntimeError(f"xray -test rejected generated config: {detail}")
os.replace(candidate, out)
try:
os.chmod(out, 0o600)
except OSError:
pass
else:
candidate.rename(out)
result = subprocess.run(
["systemctl", "restart", service],
text=True,
@@ -4937,6 +5060,12 @@ def build_openwrt_config_payload(row, hub_url, vps_host_override="", public_url_
),
"public_url": effective_public_url,
}
profile = transport_profile()
if profile.get("mode") == "reality":
payload["security"] = "reality"
payload["reality_public_key"] = profile["publicKey"]
payload["reality_server_name"] = profile["serverName"]
payload["reality_fingerprint"] = profile.get("fingerprint", "chrome")
return payload
@@ -4972,6 +5101,10 @@ def build_openwrt_config_lines(payload, mode="manual"):
f"uci set owrtremote.main.ssh_host='{sh_quote(payload['ssh_host'])}'",
f"uci set owrtremote.main.ssh_port='{payload['ssh_port']}'",
f"uci set owrtremote.main.public_url='{sh_quote(payload['public_url'])}'",
f"uci set owrtremote.main.security='{sh_quote(payload.get('security', 'none'))}'",
f"uci set owrtremote.main.reality_public_key='{sh_quote(payload.get('reality_public_key', ''))}'",
f"uci set owrtremote.main.reality_server_name='{sh_quote(payload.get('reality_server_name', ''))}'",
f"uci set owrtremote.main.reality_fingerprint='{sh_quote(payload.get('reality_fingerprint', ''))}'",
"uci commit owrtremote",
"owrt-remote render-client",
"/etc/init.d/owrt-remote enable",