Route reverse tunnels through registration environment

This commit is contained in:
Andrei Smaliak 2026-09-05 11:45:17 +02:00
parent 810db661dc
commit 015c3c3384
9 changed files with 125 additions and 94 deletions

View File

@ -387,12 +387,8 @@ RUN THIS ON VPS
### Что делает команда на VPS ### Что делает команда на VPS
Она: Она регистрирует public key Edge в установленном на текущем сервере окружения
- создает пользователя вида `tunnel_<hostname>`; `reverse-tunnel-service` и разрешает только рассчитанные для устройства порты.
- создает ему папку `.ssh`;
- добавляет public key Edge в `authorized_keys`;
- разрешает только нужные порты;
- при необходимости добавляет IP Edge в исключения `fail2ban`.
### Что будет, если этого не сделать ### Что будет, если этого не сделать
@ -413,7 +409,7 @@ RUN THIS ON VPS
- финального hostname Edge; - финального hostname Edge;
- пользователя `iomatex`; - пользователя `iomatex`;
- уже установленных локальных сервисов; - уже установленных локальных сервисов;
- готовности VPS принять ключ и порты. - готовности SSH-шлюза текущего окружения принять ключ и порты.
### Что делать после настройки VPS ### Что делать после настройки VPS

View File

@ -417,13 +417,17 @@ Zigbee2MQTT: 8081
Web UI: 8099 Web UI: 8099
``` ```
VPS по умолчанию: SSH-шлюз:
```text ```text
VPS_HOST=65.109.116.180 TUNNEL_HOST=<DNS текущего сервера регистрации>
VPS_PORT=22 TUNNEL_PORT=22
``` ```
Адрес автоматически читается из сохраненной регистрации клиента. При
необходимости его можно явно передать через `REGISTRATION_SERVER` или
`TUNNEL_HOST`. Фиксированного общего VPS в стадии больше нет.
## Когда ставить `stage_reverse_tunnels` ## Когда ставить `stage_reverse_tunnels`
Ставить только после того, как: Ставить только после того, как:
@ -469,27 +473,22 @@ sudo bash stage_reverse_tunnels/stage_reverse_tunnels_install.sh
- не закрыть вывод раньше времени; - не закрыть вывод раньше времени;
- скопировать целиком строку из блока `RUN THIS ON VPS`. - скопировать целиком строку из блока `RUN THIS ON VPS`.
## Что делать на VPS ## Что делать на сервере окружения
На VPS нужно выполнить ровно ту команду, которую напечатал Edge-инсталлятор. На сервере окружения должен быть установлен `reverse-tunnel-service`. Затем
нужно выполнить ровно ту команду регистрации, которую напечатал Edge-инсталлятор.
Эта команда делает следующее: Эта команда регистрирует public key Edge, проверяет коллизию рассчитанных портов
- создает пользователя `tunnel_<hostname>`; и пересобирает управляемый `authorized_keys` с ограничениями `permitlisten`.
- создает `/home/tunnel_<hostname>/.ssh`;
- записывает public key Edge в `authorized_keys`;
- ограничивает ключ по `permitopen` и `permitlisten`;
- при необходимости добавляет IP Edge в `fail2ban ignoreip`;
- перезапускает `fail2ban`.
Именно это и есть обязательная серверная часть. Без нее reverse tunnel не заработает. Именно это и есть обязательная серверная часть. Без нее reverse tunnel не заработает.
## Почему недостаточно просто "обратиться к sysadmin" ## Почему недостаточно просто "обратиться к sysadmin"
Недостаточно общего замечания "пусть sysadmin добавит устройство". Для запуска reverse tunnel нужны конкретные действия на VPS: Недостаточно общего замечания "пусть sysadmin добавит устройство". Для запуска reverse tunnel нужны конкретные действия на VPS:
- создать туннельного пользователя; - установить environment-сервис;
- прописать ключ Edge; - зарегистрировать ключ Edge;
- разрешить нужные `permitlisten` для рассчитанных портов; - убедиться, что DNS шлюза и порт SSH доступны устройству.
- не заблокировать Edge через `fail2ban`.
То есть sysadmin должен либо выполнить команду из вывода инсталлятора, либо воспроизвести ее смысл вручную один в один. То есть sysadmin должен либо выполнить команду из вывода инсталлятора, либо воспроизвести ее смысл вручную один в один.

View File

@ -3,12 +3,10 @@
// node port.js <device_Id> // node port.js <device_Id>
// //
// Output (3 lines, PowerShell-friendly): // Output (3 lines, PowerShell-friendly):
// ssh -N -p 22 -L 9090:127.0.0.1:<cockpit_remote> builder@65.109.116.180 # cockpit // TUNNEL_HOST=uae.iomatex.com node port.js <device_Id>
// ssh -N -p 22 -L 8081:127.0.0.1:<z2m_remote> builder@65.109.116.180 # z2m
// ssh -N -p 22 -L 8099:127.0.0.1:<webui_remote> builder@65.109.116.180 # webui
// //
// Env overrides (optional): // Env overrides (optional):
// VPS_USER, VPS_HOST, VPS_PORT // TUNNEL_OPERATOR_USER, TUNNEL_HOST, TUNNEL_PORT
// COCKPIT_LOCAL_PORT (default 9090) // COCKPIT_LOCAL_PORT (default 9090)
// Z2M_LOCAL_PORT (default 8081) // Z2M_LOCAL_PORT (default 8081)
// WEBUI_LOCAL_PORT (default 8099) // WEBUI_LOCAL_PORT (default 8099)
@ -17,9 +15,9 @@
"use strict"; "use strict";
const VPS_USER = process.env.VPS_USER || "builder"; const VPS_USER = process.env.TUNNEL_OPERATOR_USER || process.env.VPS_USER || "builder";
const VPS_HOST = process.env.VPS_HOST || "65.109.116.180"; const VPS_HOST = process.env.TUNNEL_HOST || process.env.VPS_HOST;
const SSH_PORT = parseInt(process.env.VPS_PORT || "22", 10); const SSH_PORT = parseInt(process.env.TUNNEL_PORT || process.env.VPS_PORT || "22", 10);
// Correct local ports (match Stage4) // Correct local ports (match Stage4)
const COCKPIT_LOCAL_PORT = parseInt(process.env.COCKPIT_LOCAL_PORT || "9090", 10); const COCKPIT_LOCAL_PORT = parseInt(process.env.COCKPIT_LOCAL_PORT || "9090", 10);
@ -110,9 +108,13 @@ function main() {
process.stderr.write("Usage: node port.js <device_Id>\n"); process.stderr.write("Usage: node port.js <device_Id>\n");
process.exit(2); process.exit(2);
} }
if (!VPS_HOST) {
process.stderr.write("TUNNEL_HOST is required\n");
process.exit(2);
}
process.stdout.write(buildLines(deviceId).join("\n") + "\n"); process.stdout.write(buildLines(deviceId).join("\n") + "\n");
} }
if (require.main === module) main(); if (require.main === module) main();
module.exports = { buildLines, computePorts, cksumPosixFirstField }; module.exports = { buildLines, computePorts, cksumPosixFirstField };

View File

@ -16,8 +16,11 @@ LOG="/var/log/iomatex-stage4-reverse-tunnel-install.log"
EDGE_USER="${EDGE_USER:-iomatex}" EDGE_USER="${EDGE_USER:-iomatex}"
VPS_HOST="${VPS_HOST:-65.109.116.180}" REGISTRATION_SERVER="${REGISTRATION_SERVER:-}"
VPS_PORT="${VPS_PORT:-22}" TUNNEL_HOST="${TUNNEL_HOST:-${VPS_HOST:-}}"
TUNNEL_PORT="${TUNNEL_PORT:-${VPS_PORT:-22}}"
TUNNEL_OPERATOR_USER="${TUNNEL_OPERATOR_USER:-builder}"
TUNNEL_SSH_USER="${TUNNEL_SSH_USER:-iomatex-tunnel}"
COCKPIT_LOCAL_PORT="${COCKPIT_LOCAL_PORT:-9090}" COCKPIT_LOCAL_PORT="${COCKPIT_LOCAL_PORT:-9090}"
Z2M_LOCAL_PORT="${Z2M_LOCAL_PORT:-8081}" Z2M_LOCAL_PORT="${Z2M_LOCAL_PORT:-8081}"
@ -28,6 +31,8 @@ PORT_SLOTS="${PORT_SLOTS:-4000}"
WRAPPER_DIR="/usr/local/sbin" WRAPPER_DIR="/usr/local/sbin"
SYSTEMD_DIR="/etc/systemd/system" SYSTEMD_DIR="/etc/systemd/system"
CONFIG_DIR="/etc/iomatex"
CONFIG_FILE="${CONFIG_DIR}/reverse-tunnel.env"
mkdir -p /var/log >/dev/null 2>&1 || true mkdir -p /var/log >/dev/null 2>&1 || true
touch "$LOG" >/dev/null 2>&1 || true touch "$LOG" >/dev/null 2>&1 || true
@ -84,7 +89,7 @@ validate_port() {
validate_settings() { validate_settings() {
local max_remote_port local max_remote_port
validate_port "$VPS_PORT" "VPS_PORT" validate_port "$TUNNEL_PORT" "TUNNEL_PORT"
validate_port "$COCKPIT_LOCAL_PORT" "COCKPIT_LOCAL_PORT" validate_port "$COCKPIT_LOCAL_PORT" "COCKPIT_LOCAL_PORT"
validate_port "$Z2M_LOCAL_PORT" "Z2M_LOCAL_PORT" validate_port "$Z2M_LOCAL_PORT" "Z2M_LOCAL_PORT"
validate_port "$WEBUI_LOCAL_PORT" "WEBUI_LOCAL_PORT" validate_port "$WEBUI_LOCAL_PORT" "WEBUI_LOCAL_PORT"
@ -97,6 +102,52 @@ validate_settings() {
(( max_remote_port <= 65535 )) || die "Computed remote port range exceeds 65535: ${PORT_BASE}..${max_remote_port}" (( max_remote_port <= 65535 )) || die "Computed remote port range exceeds 65535: ${PORT_BASE}..${max_remote_port}"
} }
normalize_host() {
local value="$1"
value="${value#http://}"
value="${value#https://}"
value="${value%%/*}"
value="${value%%:*}"
printf '%s' "$value"
}
discover_registration_server() {
local candidate value
[[ -n "$REGISTRATION_SERVER" ]] && { normalize_host "$REGISTRATION_SERVER"; return; }
for candidate in \
"/home/${EDGE_USER}/.local/share/it-screen/it-screen/registration.ini" \
"/home/${EDGE_USER}/.local/share/it-screen/registration.ini"; do
[[ -f "$candidate" ]] || continue
value="$(sed -n 's/^[[:space:]]*server[[:space:]]*=[[:space:]]*//p' "$candidate" | tail -n 1)"
[[ -n "$value" ]] && { normalize_host "$value"; return; }
done
return 1
}
resolve_tunnel_host() {
local registration_host
if [[ -n "$TUNNEL_HOST" ]]; then
TUNNEL_HOST="$(normalize_host "$TUNNEL_HOST")"
else
registration_host="$(discover_registration_server)" || die "Cannot discover registration server; pass REGISTRATION_SERVER or TUNNEL_HOST"
# By default the environment host itself is the SSH gateway. Deployments
# may override this with tunnel.<environment> without reinstalling units.
TUNNEL_HOST="$registration_host"
fi
[[ "$TUNNEL_HOST" =~ ^[A-Za-z0-9.-]+$ ]] || die "Invalid tunnel DNS name: $TUNNEL_HOST"
}
write_environment_config() {
install -d -m 755 "$CONFIG_DIR"
cat >"$CONFIG_FILE" <<EOF
TUNNEL_HOST=${TUNNEL_HOST}
TUNNEL_PORT=${TUNNEL_PORT}
TUNNEL_OPERATOR_USER=${TUNNEL_OPERATOR_USER}
TUNNEL_SSH_USER=${TUNNEL_SSH_USER}
EOF
chmod 0644 "$CONFIG_FILE"
}
shell_quote() { shell_quote() {
printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\"'\"'/g")" printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\"'\"'/g")"
} }
@ -181,9 +232,9 @@ exec autossh -M 0 -N \\
-o StrictHostKeyChecking=accept-new \\ -o StrictHostKeyChecking=accept-new \\
-o UserKnownHostsFile="${edge_home}/.ssh/known_hosts" \\ -o UserKnownHostsFile="${edge_home}/.ssh/known_hosts" \\
-i "${key}" \\ -i "${key}" \\
-p "${VPS_PORT}" \\ -p "\${TUNNEL_PORT}" \\
-R 127.0.0.1:${remote_port}:127.0.0.1:${local_port} \\ -R 127.0.0.1:${remote_port}:127.0.0.1:${local_port} \\
"${vps_user}@${VPS_HOST}" "${vps_user}@\${TUNNEL_HOST}"
EOF EOF
chmod 0755 "$wrapper_path" chmod 0755 "$wrapper_path"
@ -201,6 +252,7 @@ Wants=network-online.target
[Service] [Service]
User=${EDGE_USER} User=${EDGE_USER}
EnvironmentFile=${CONFIG_FILE}
Environment=AUTOSSH_GATETIME=0 Environment=AUTOSSH_GATETIME=0
Environment=AUTOSSH_POLL=30 Environment=AUTOSSH_POLL=30
ExecStart=${WRAPPER_DIR}/iomatex-rt-${name}.sh ExecStart=${WRAPPER_DIR}/iomatex-rt-${name}.sh
@ -238,7 +290,7 @@ print_summary() {
echo "HOSTNAME: ${hostname_value}" echo "HOSTNAME: ${hostname_value}"
echo "EDGE IP: ${edge_ip}" echo "EDGE IP: ${edge_ip}"
echo echo
echo "VPS HOST: ${VPS_HOST}:${VPS_PORT}" echo "TUNNEL HOST: ${TUNNEL_HOST}:${TUNNEL_PORT}"
echo "VPS USER: ${vps_user}" echo "VPS USER: ${vps_user}"
echo echo
echo "VPS PORTS:" echo "VPS PORTS:"
@ -269,10 +321,12 @@ main() {
require_root require_root
preflight_checks preflight_checks
validate_settings validate_settings
resolve_tunnel_host
write_environment_config
ensure_autossh_installed ensure_autossh_installed
hostname_value="$(hostname)" hostname_value="$(hostname)"
vps_user="tunnel_${hostname_value}" vps_user="$TUNNEL_SSH_USER"
read -r cockpit_remote_port z2m_remote_port webui_remote_port <<<"$(compute_ports "$hostname_value")" read -r cockpit_remote_port z2m_remote_port webui_remote_port <<<"$(compute_ports "$hostname_value")"
IFS='|' read -r edge_home key keypub < <(ensure_key "$hostname_value" | tail -n 1) IFS='|' read -r edge_home key keypub < <(ensure_key "$hostname_value" | tail -n 1)
@ -300,7 +354,7 @@ main() {
edge_ip="detected from SSH_CLIENT on VPS" edge_ip="detected from SSH_CLIENT on VPS"
vps_bootstrap_cmd="EDGE_HOSTNAME=$(shell_quote "$hostname_value"); EDGE_IP=\"\${SSH_CLIENT%% *}\"; EDGE_PUBKEY_LINE=$(shell_quote "$public_key_line"); COCKPIT_REMOTE_PORT=$(shell_quote "$cockpit_remote_port"); Z2M_REMOTE_PORT=$(shell_quote "$z2m_remote_port"); WEBUI_REMOTE_PORT=$(shell_quote "$webui_remote_port"); VPS_USER=\"tunnel_\${EDGE_HOSTNAME}\"; sudo useradd -m -s /usr/sbin/nologin \"\$VPS_USER\" 2>/dev/null || true; sudo install -d -m 700 -o \"\$VPS_USER\" -g \"\$VPS_USER\" \"/home/\$VPS_USER/.ssh\"; printf 'no-pty,no-agent-forwarding,no-X11-forwarding,permitopen=\"127.0.0.1:9090\",permitopen=\"127.0.0.1:8081\",permitopen=\"127.0.0.1:8099\",permitlisten=\"127.0.0.1:%s\",permitlisten=\"127.0.0.1:%s\",permitlisten=\"127.0.0.1:%s\" %s\n' \"\$COCKPIT_REMOTE_PORT\" \"\$Z2M_REMOTE_PORT\" \"\$WEBUI_REMOTE_PORT\" \"\$EDGE_PUBKEY_LINE\" | sudo tee \"/home/\$VPS_USER/.ssh/authorized_keys\" >/dev/null; sudo chown -R \"\$VPS_USER:\$VPS_USER\" \"/home/\$VPS_USER/.ssh\"; sudo chmod 600 \"/home/\$VPS_USER/.ssh/authorized_keys\"; if [ -n \"\$EDGE_IP\" ]; then sudo fail2ban-client set sshd unbanip \"\$EDGE_IP\" 2>/dev/null || true; (sudo grep -q '^ignoreip' /etc/fail2ban/jail.local && sudo sed -i \"s/^ignoreip.*/& \$EDGE_IP/\" /etc/fail2ban/jail.local) || echo -e \"[DEFAULT]\nignoreip = 127.0.0.1/8 \$EDGE_IP\" | sudo tee /etc/fail2ban/jail.local >/dev/null; fi; sudo systemctl restart fail2ban; echo \"OK: \$VPS_USER ready\"" vps_bootstrap_cmd="printf '%s\\n' $(shell_quote "$public_key_line") | sudo reverse-tunnel-service register --device $(shell_quote "$hostname_value") --public-key-file -"
print_summary \ print_summary \
"$hostname_value" \ "$hostname_value" \

View File

@ -0,0 +1,24 @@
import pathlib
import unittest
ROOT = pathlib.Path(__file__).parent
class DynamicEnvironmentContractTest(unittest.TestCase):
def test_installer_has_no_legacy_vps_default(self):
source = (ROOT / "stage_reverse_tunnels_install.sh").read_text()
self.assertNotIn("65.109.116.180", source)
self.assertIn('CONFIG_DIR="/etc/iomatex"', source)
self.assertIn('reverse-tunnel.env', source)
self.assertIn("discover_registration_server", source)
self.assertIn("EnvironmentFile=${CONFIG_FILE}", source)
def test_operator_helper_requires_environment_host(self):
source = (ROOT / "port.js").read_text()
self.assertNotIn("65.109.116.180", source)
self.assertIn("TUNNEL_HOST is required", source)
if __name__ == "__main__":
unittest.main()

View File

@ -56,7 +56,8 @@ class ReverseTunnelBootstrapTest(unittest.TestCase):
command = provider._reverse_tunnel_bootstrap_command(context) command = provider._reverse_tunnel_bootstrap_command(context)
self.assertNotIn("api.ipify.org", command) self.assertNotIn("api.ipify.org", command)
self.assertIn("SSH_CLIENT", command) self.assertIn("reverse-tunnel-service register", command)
self.assertIn("--device g-box-12345678", command)
self.assertEqual([["getent", "passwd", "iomatex"]], commands) self.assertEqual([["getent", "passwd", "iomatex"]], commands)

View File

@ -221,7 +221,7 @@
"Latency": "Задержка", "Latency": "Задержка",
"Reverse Tunnel is needed for remote access from outside the local network. If you already have access to this UI, you are already on the same network as the Edge device, so Reverse Tunnel is usually not needed. To use it later, open Web UI, go to Devices, select your Edge device, then open the SSH tab in device settings. The required links and the full 2-step instructions are there.": "Reverse Tunnel нужен для удалённого доступа извне локальной сети. Если у вас уже открыт этот UI, значит вы уже находитесь в одной сети с устройством Edge, и Reverse Tunnel обычно не нужен. Если он понадобится позже, откройте Web UI, перейдите в Devices, выберите своё устройство Edge и откройте вкладку SSH в настройках устройства. Там есть нужные ссылки и полная инструкция из 2 шагов.", "Reverse Tunnel is needed for remote access from outside the local network. If you already have access to this UI, you are already on the same network as the Edge device, so Reverse Tunnel is usually not needed. To use it later, open Web UI, go to Devices, select your Edge device, then open the SSH tab in device settings. The required links and the full 2-step instructions are there.": "Reverse Tunnel нужен для удалённого доступа извне локальной сети. Если у вас уже открыт этот UI, значит вы уже находитесь в одной сети с устройством Edge, и Reverse Tunnel обычно не нужен. Если он понадобится позже, откройте Web UI, перейдите в Devices, выберите своё устройство Edge и откройте вкладку SSH в настройках устройства. Там есть нужные ссылки и полная инструкция из 2 шагов.",
"Command to configure VPS access": "Команда для настройки доступа к VPS", "Command to configure VPS access": "Команда для настройки доступа к VPS",
"To configure Reverse SSH access, connect to VPS with ssh builder@65.109.116.180, use the password from the sysadmin, then copy, paste, and run the script below by pressing Enter.": "Чтобы настроить доступ по Reverse SSH, подключитесь к VPS командой ssh builder@65.109.116.180, используйте пароль от системного администратора, затем скопируйте, вставьте и запустите приведённый ниже скрипт, нажав Enter.", "Connect to the SSH gateway of this environment, then copy, paste, and run the registration command below.": "Подключитесь к SSH-шлюзу текущего окружения, затем скопируйте, вставьте и выполните приведённую ниже команду регистрации.",
"Copy command": "Скопировать команду", "Copy command": "Скопировать команду",
"VPS bootstrap command copied": "Команда настройки VPS скопирована", "VPS bootstrap command copied": "Команда настройки VPS скопирована",
"Bootstrap command is unavailable": "Команда настройки недоступна", "Bootstrap command is unavailable": "Команда настройки недоступна",
@ -598,7 +598,7 @@
"Copy command": "Kopiuj polecenie", "Copy command": "Kopiuj polecenie",
"VPS bootstrap command copied": "Polecenie bootstrap VPS zostało skopiowane", "VPS bootstrap command copied": "Polecenie bootstrap VPS zostało skopiowane",
"Failed to copy VPS bootstrap command": "Nie udało się skopiować polecenia bootstrap VPS", "Failed to copy VPS bootstrap command": "Nie udało się skopiować polecenia bootstrap VPS",
"To configure Reverse SSH access, connect to VPS with ssh builder@65.109.116.180, use the password from the sysadmin, then copy, paste, and run the script below by pressing Enter.": "Aby skonfigurować dostęp Reverse SSH, połącz się z VPS przez ssh builder@65.109.116.180, użyj hasła od administratora, a następnie skopiuj, wklej i uruchom poniższy skrypt naciskając Enter.", "Connect to the SSH gateway of this environment, then copy, paste, and run the registration command below.": "Połącz się z bramą SSH bieżącego środowiska, a następnie skopiuj, wklej i uruchom poniższe polecenie rejestracji.",
"Reverse Tunnel is needed for remote access from outside the local network. If you already have access to this UI, you are already on the same network as the Edge device, so Reverse Tunnel is usually not needed. To use it later, open Web UI, go to Devices, select your Edge device, then open the SSH tab in device settings. The required links and the full 2-step instructions are there.": "Reverse Tunnel jest potrzebny do zdalnego dostępu spoza sieci lokalnej. Jeśli masz już dostęp do tego UI, jesteś już w tej samej sieci co urządzenie Edge, więc Reverse Tunnel zwykle nie jest potrzebny. Aby użyć go później, otwórz Web UI, przejdź do Devices, wybierz swoje urządzenie Edge, a następnie otwórz kartę SSH w ustawieniach urządzenia. Znajdziesz tam wymagane linki i pełną instrukcję w 2 krokach.", "Reverse Tunnel is needed for remote access from outside the local network. If you already have access to this UI, you are already on the same network as the Edge device, so Reverse Tunnel is usually not needed. To use it later, open Web UI, go to Devices, select your Edge device, then open the SSH tab in device settings. The required links and the full 2-step instructions are there.": "Reverse Tunnel jest potrzebny do zdalnego dostępu spoza sieci lokalnej. Jeśli masz już dostęp do tego UI, jesteś już w tej samej sieci co urządzenie Edge, więc Reverse Tunnel zwykle nie jest potrzebny. Aby użyć go później, otwórz Web UI, przejdź do Devices, wybierz swoje urządzenie Edge, a następnie otwórz kartę SSH w ustawieniach urządzenia. Znajdziesz tam wymagane linki i pełną instrukcję w 2 krokach.",
"Success": "Sukces", "Success": "Sukces",
"Available": "Dostępne", "Available": "Dostępne",
@ -1215,7 +1215,7 @@
,"Bootstrap command is unavailable": "أمر التهيئة الأولية لـ VPS غير متاح" ,"Bootstrap command is unavailable": "أمر التهيئة الأولية لـ VPS غير متاح"
,"VPS bootstrap command copied": "تم نسخ أمر التهيئة الأولية لـ VPS" ,"VPS bootstrap command copied": "تم نسخ أمر التهيئة الأولية لـ VPS"
,"Failed to copy VPS bootstrap command": "فشل نسخ أمر التهيئة الأولية لـ VPS" ,"Failed to copy VPS bootstrap command": "فشل نسخ أمر التهيئة الأولية لـ VPS"
,"To configure Reverse SSH access, connect to VPS with ssh builder@65.109.116.180, use the password from the sysadmin, then copy, paste, and run the script below by pressing Enter.": "لإعداد وصول Reverse SSH، اتصل بـ VPS عبر ssh builder@65.109.116.180، واستخدم كلمة المرور من مسؤول النظام، ثم انسخ السكربت أدناه والصقه وشغّله بالضغط على Enter." ,"Connect to the SSH gateway of this environment, then copy, paste, and run the registration command below.": "اتصل ببوابة SSH الخاصة بهذه البيئة، ثم انسخ أمر التسجيل أدناه والصقه وشغّله."
,"Reverse Tunnel is needed for remote access from outside the local network. If you already have access to this UI, you are already on the same network as the Edge device, so Reverse Tunnel is usually not needed. To use it later, open Web UI, go to Devices, select your Edge device, then open the SSH tab in device settings. The required links and the full 2-step instructions are there.": "يلزم Reverse Tunnel للوصول عن بُعد من خارج الشبكة المحلية. إذا كان لديك وصول إلى هذا الـ UI بالفعل، فأنت ضمن نفس الشبكة مع جهاز Edge، لذلك غالباً لا تكون هناك حاجة إليه. لاستخدامه لاحقاً، افتح Web UI ثم اذهب إلى Devices واختر جهاز Edge الخاص بك وافتح تبويب SSH في إعدادات الجهاز. ستجد هناك الروابط المطلوبة والتعليمات الكاملة من خطوتين." ,"Reverse Tunnel is needed for remote access from outside the local network. If you already have access to this UI, you are already on the same network as the Edge device, so Reverse Tunnel is usually not needed. To use it later, open Web UI, go to Devices, select your Edge device, then open the SSH tab in device settings. The required links and the full 2-step instructions are there.": "يلزم Reverse Tunnel للوصول عن بُعد من خارج الشبكة المحلية. إذا كان لديك وصول إلى هذا الـ UI بالفعل، فأنت ضمن نفس الشبكة مع جهاز Edge، لذلك غالباً لا تكون هناك حاجة إليه. لاستخدامه لاحقاً، افتح Web UI ثم اذهب إلى Devices واختر جهاز Edge الخاص بك وافتح تبويب SSH في إعدادات الجهاز. ستجد هناك الروابط المطلوبة والتعليمات الكاملة من خطوتين."
,"Account security": "أمان الحساب" ,"Account security": "أمان الحساب"
,"Change the WEB UI login password for the local iomatex user.": "تغيير كلمة مرور تسجيل الدخول إلى WEB UI للمستخدم المحلي iomatex." ,"Change the WEB UI login password for the local iomatex user.": "تغيير كلمة مرور تسجيل الدخول إلى WEB UI للمستخدم المحلي iomatex."
@ -1507,7 +1507,7 @@
"Copy command": "कमांड कॉपी करें", "Copy command": "कमांड कॉपी करें",
"VPS bootstrap command copied": "VPS bootstrap command कॉपी हो गया", "VPS bootstrap command copied": "VPS bootstrap command कॉपी हो गया",
"Failed to copy VPS bootstrap command": "VPS bootstrap command कॉपी नहीं हो सका", "Failed to copy VPS bootstrap command": "VPS bootstrap command कॉपी नहीं हो सका",
"To configure Reverse SSH access, connect to VPS with ssh builder@65.109.116.180, use the password from the sysadmin, then copy, paste, and run the script below by pressing Enter.": "Reverse SSH access सेट करने के लिए ssh builder@65.109.116.180 से VPS में लॉगिन करें, sysadmin का पासवर्ड उपयोग करें, फिर नीचे दिया गया script कॉपी, पेस्ट और Enter दबाकर रन करें।", "Connect to the SSH gateway of this environment, then copy, paste, and run the registration command below.": "इस environment के SSH gateway से कनेक्ट करें, फिर नीचे दिया registration command कॉपी, पेस्ट और चलाएँ।",
"Reverse Tunnel is needed for remote access from outside the local network. If you already have access to this UI, you are already on the same network as the Edge device, so Reverse Tunnel is usually not needed. To use it later, open Web UI, go to Devices, select your Edge device, then open the SSH tab in device settings. The required links and the full 2-step instructions are there.": "Reverse Tunnel लोकल नेटवर्क के बाहर से remote access के लिए चाहिए। अगर यह UI पहले से खुल रहा है, तो आप Edge डिवाइस के उसी नेटवर्क में हैं, इसलिए आमतौर पर Reverse Tunnel की जरूरत नहीं है। बाद में उपयोग करना हो तो Web UI में Devices खोलें, अपना Edge चुनें, फिर device settings में SSH tab खोलें। वहाँ जरूरी links और 2-step instructions मिल जाएँगी।", "Reverse Tunnel is needed for remote access from outside the local network. If you already have access to this UI, you are already on the same network as the Edge device, so Reverse Tunnel is usually not needed. To use it later, open Web UI, go to Devices, select your Edge device, then open the SSH tab in device settings. The required links and the full 2-step instructions are there.": "Reverse Tunnel लोकल नेटवर्क के बाहर से remote access के लिए चाहिए। अगर यह UI पहले से खुल रहा है, तो आप Edge डिवाइस के उसी नेटवर्क में हैं, इसलिए आमतौर पर Reverse Tunnel की जरूरत नहीं है। बाद में उपयोग करना हो तो Web UI में Devices खोलें, अपना Edge चुनें, फिर device settings में SSH tab खोलें। वहाँ जरूरी links और 2-step instructions मिल जाएँगी।",
"Display": "डिस्प्ले", "Display": "डिस्प्ले",
"Display status": "डिस्प्ले स्थिति", "Display status": "डिस्प्ले स्थिति",

View File

@ -1355,7 +1355,7 @@
</button> </button>
<div class="tunnelAccordionBody" ${bootstrapOpen ? "" : "hidden"}> <div class="tunnelAccordionBody" ${bootstrapOpen ? "" : "hidden"}>
<div class="formHint"> <div class="formHint">
${esc(t("To configure Reverse SSH access, connect to VPS with ssh builder@65.109.116.180, use the password from the sysadmin, then copy, paste, and run the script below by pressing Enter."))} ${esc(t("Connect to the SSH gateway of this environment, then copy, paste, and run the registration command below."))}
</div> </div>
<div class="actionRow"> <div class="actionRow">
<button class="actionBtn secondary" type="button" onclick="window.__copyReverseTunnelBootstrap()"> <button class="actionBtn secondary" type="button" onclick="window.__copyReverseTunnelBootstrap()">

View File

@ -720,58 +720,11 @@ def _reverse_tunnel_bootstrap_command(ctx):
if not public_key_line: if not public_key_line:
return "" return ""
wrappers = {}
for name in ("cockpit", "z2m", "webui"):
raw = ctx["read_text"](f"/usr/local/sbin/iomatex-rt-{name}.sh") or ""
if raw:
wrappers[name] = raw
if len(wrappers) < 3:
return ""
def parse_wrapper(raw):
port_match = re.search(r"-R\s+127\.0\.0\.1:(\d+):127\.0\.0\.1:(\d+)", raw)
target_match = re.search(r'"([^"@\s]+)@([^"\s]+)"', raw)
ssh_port_match = re.search(r"-p\s+\"?(\d+)\"?", raw)
if not port_match or not target_match:
return None
return {
"remote_port": port_match.group(1),
"local_port": port_match.group(2),
"vps_user": target_match.group(1),
"vps_host": target_match.group(2),
"vps_port": ssh_port_match.group(1) if ssh_port_match else "22",
}
parsed = {name: parse_wrapper(raw) for name, raw in wrappers.items()}
if any(item is None for item in parsed.values()):
return ""
cockpit = parsed["cockpit"]
z2m = parsed["z2m"]
webui = parsed["webui"]
vps_user = cockpit["vps_user"]
return ( return (
f"EDGE_HOSTNAME={shlex.quote(hostname)}; " f"printf '%s\\n' {shlex.quote(public_key_line)} | "
f"EDGE_IP=\"${{SSH_CLIENT%% *}}\"; " f"sudo reverse-tunnel-service register --device {shlex.quote(hostname)} --public-key-file -"
f"EDGE_PUBKEY_LINE={shlex.quote(public_key_line)}; "
f"COCKPIT_REMOTE_PORT={shlex.quote(cockpit['remote_port'])}; "
f"Z2M_REMOTE_PORT={shlex.quote(z2m['remote_port'])}; "
f"WEBUI_REMOTE_PORT={shlex.quote(webui['remote_port'])}; "
f"VPS_USER={shlex.quote(vps_user)}; "
f"sudo useradd -m -s /usr/sbin/nologin \"$VPS_USER\" 2>/dev/null || true; "
f"sudo install -d -m 700 -o \"$VPS_USER\" -g \"$VPS_USER\" \"/home/$VPS_USER/.ssh\"; "
f"printf 'no-pty,no-agent-forwarding,no-X11-forwarding,permitopen=\"127.0.0.1:9090\",permitopen=\"127.0.0.1:8081\",permitopen=\"127.0.0.1:80\",permitlisten=\"127.0.0.1:%s\",permitlisten=\"127.0.0.1:%s\",permitlisten=\"127.0.0.1:%s\" %s\\n' "
f"\"$COCKPIT_REMOTE_PORT\" \"$Z2M_REMOTE_PORT\" \"$WEBUI_REMOTE_PORT\" \"$EDGE_PUBKEY_LINE\" | sudo tee \"/home/$VPS_USER/.ssh/authorized_keys\" >/dev/null; "
f"sudo chown -R \"$VPS_USER:$VPS_USER\" \"/home/$VPS_USER/.ssh\"; "
f"sudo chmod 600 \"/home/$VPS_USER/.ssh/authorized_keys\"; "
f"if [ -n \"$EDGE_IP\" ]; then sudo fail2ban-client set sshd unbanip \"$EDGE_IP\" 2>/dev/null || true; "
f"(sudo grep -q '^ignoreip' /etc/fail2ban/jail.local && sudo sed -i \"s/^ignoreip.*/& $EDGE_IP/\" /etc/fail2ban/jail.local) || "
f"echo -e \"[DEFAULT]\\nignoreip = 127.0.0.1/8 $EDGE_IP\" | sudo tee /etc/fail2ban/jail.local >/dev/null; fi; "
f"sudo systemctl restart fail2ban; "
f"echo \"OK: $VPS_USER ready\""
) )
def reverse_tunnel_card(ctx): def reverse_tunnel_card(ctx):
service_states = [] service_states = []
installed_checks = [] installed_checks = []
@ -848,9 +801,11 @@ def reverse_tunnel_card(ctx):
if item["installed"] and not item["active"] if item["installed"] and not item["active"]
) )
tunnel_env = ctx["read_env_file"]("/etc/iomatex/reverse-tunnel.env")
details = [ details = [
{"label": "SSH key", "value": "Present" if key_present else "Missing"}, {"label": "SSH key", "value": "Present" if key_present else "Missing"},
{"label": "Active tunnels", "value": f"{active_count}/{total}" if total else "0/0"}, {"label": "Active tunnels", "value": f"{active_count}/{total}" if total else "0/0"},
{"label": "Tunnel host", "value": tunnel_env.get("TUNNEL_HOST", "Not configured")},
] ]
return _service_card( return _service_card(