diff --git a/ENGINEER_INSTRUCTIONS.md b/ENGINEER_INSTRUCTIONS.md index 75fa958..c3ed7e7 100644 --- a/ENGINEER_INSTRUCTIONS.md +++ b/ENGINEER_INSTRUCTIONS.md @@ -387,12 +387,8 @@ RUN THIS ON VPS ### Что делает команда на VPS -Она: -- создает пользователя вида `tunnel_`; -- создает ему папку `.ssh`; -- добавляет public key Edge в `authorized_keys`; -- разрешает только нужные порты; -- при необходимости добавляет IP Edge в исключения `fail2ban`. +Она регистрирует public key Edge в установленном на текущем сервере окружения +`reverse-tunnel-service` и разрешает только рассчитанные для устройства порты. ### Что будет, если этого не сделать @@ -413,7 +409,7 @@ RUN THIS ON VPS - финального hostname Edge; - пользователя `iomatex`; - уже установленных локальных сервисов; -- готовности VPS принять ключ и порты. +- готовности SSH-шлюза текущего окружения принять ключ и порты. ### Что делать после настройки VPS diff --git a/how_to_install_by_stages/README.md b/how_to_install_by_stages/README.md index c9a1170..84ac731 100644 --- a/how_to_install_by_stages/README.md +++ b/how_to_install_by_stages/README.md @@ -417,13 +417,17 @@ Zigbee2MQTT: 8081 Web UI: 8099 ``` -VPS по умолчанию: +SSH-шлюз: ```text -VPS_HOST=65.109.116.180 -VPS_PORT=22 +TUNNEL_HOST= +TUNNEL_PORT=22 ``` +Адрес автоматически читается из сохраненной регистрации клиента. При +необходимости его можно явно передать через `REGISTRATION_SERVER` или +`TUNNEL_HOST`. Фиксированного общего VPS в стадии больше нет. + ## Когда ставить `stage_reverse_tunnels` Ставить только после того, как: @@ -469,27 +473,22 @@ sudo bash stage_reverse_tunnels/stage_reverse_tunnels_install.sh - не закрыть вывод раньше времени; - скопировать целиком строку из блока `RUN THIS ON VPS`. -## Что делать на VPS +## Что делать на сервере окружения -На VPS нужно выполнить ровно ту команду, которую напечатал Edge-инсталлятор. +На сервере окружения должен быть установлен `reverse-tunnel-service`. Затем +нужно выполнить ровно ту команду регистрации, которую напечатал Edge-инсталлятор. -Эта команда делает следующее: -- создает пользователя `tunnel_`; -- создает `/home/tunnel_/.ssh`; -- записывает public key Edge в `authorized_keys`; -- ограничивает ключ по `permitopen` и `permitlisten`; -- при необходимости добавляет IP Edge в `fail2ban ignoreip`; -- перезапускает `fail2ban`. +Эта команда регистрирует public key Edge, проверяет коллизию рассчитанных портов +и пересобирает управляемый `authorized_keys` с ограничениями `permitlisten`. Именно это и есть обязательная серверная часть. Без нее reverse tunnel не заработает. ## Почему недостаточно просто "обратиться к sysadmin" Недостаточно общего замечания "пусть sysadmin добавит устройство". Для запуска reverse tunnel нужны конкретные действия на VPS: -- создать туннельного пользователя; -- прописать ключ Edge; -- разрешить нужные `permitlisten` для рассчитанных портов; -- не заблокировать Edge через `fail2ban`. +- установить environment-сервис; +- зарегистрировать ключ Edge; +- убедиться, что DNS шлюза и порт SSH доступны устройству. То есть sysadmin должен либо выполнить команду из вывода инсталлятора, либо воспроизвести ее смысл вручную один в один. diff --git a/stage_reverse_tunnels/port.js b/stage_reverse_tunnels/port.js index 46c3752..eb7498c 100755 --- a/stage_reverse_tunnels/port.js +++ b/stage_reverse_tunnels/port.js @@ -3,12 +3,10 @@ // node port.js // // Output (3 lines, PowerShell-friendly): -// ssh -N -p 22 -L 9090:127.0.0.1: builder@65.109.116.180 # cockpit -// ssh -N -p 22 -L 8081:127.0.0.1: builder@65.109.116.180 # z2m -// ssh -N -p 22 -L 8099:127.0.0.1: builder@65.109.116.180 # webui +// TUNNEL_HOST=uae.iomatex.com node port.js // // Env overrides (optional): -// VPS_USER, VPS_HOST, VPS_PORT +// TUNNEL_OPERATOR_USER, TUNNEL_HOST, TUNNEL_PORT // COCKPIT_LOCAL_PORT (default 9090) // Z2M_LOCAL_PORT (default 8081) // WEBUI_LOCAL_PORT (default 8099) @@ -17,9 +15,9 @@ "use strict"; -const VPS_USER = process.env.VPS_USER || "builder"; -const VPS_HOST = process.env.VPS_HOST || "65.109.116.180"; -const SSH_PORT = parseInt(process.env.VPS_PORT || "22", 10); +const VPS_USER = process.env.TUNNEL_OPERATOR_USER || process.env.VPS_USER || "builder"; +const VPS_HOST = process.env.TUNNEL_HOST || process.env.VPS_HOST; +const SSH_PORT = parseInt(process.env.TUNNEL_PORT || process.env.VPS_PORT || "22", 10); // Correct local ports (match Stage4) 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 \n"); 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"); } if (require.main === module) main(); -module.exports = { buildLines, computePorts, cksumPosixFirstField }; \ No newline at end of file +module.exports = { buildLines, computePorts, cksumPosixFirstField }; diff --git a/stage_reverse_tunnels/stage_reverse_tunnels_install.sh b/stage_reverse_tunnels/stage_reverse_tunnels_install.sh index 13df582..bc983ef 100644 --- a/stage_reverse_tunnels/stage_reverse_tunnels_install.sh +++ b/stage_reverse_tunnels/stage_reverse_tunnels_install.sh @@ -16,8 +16,11 @@ LOG="/var/log/iomatex-stage4-reverse-tunnel-install.log" EDGE_USER="${EDGE_USER:-iomatex}" -VPS_HOST="${VPS_HOST:-65.109.116.180}" -VPS_PORT="${VPS_PORT:-22}" +REGISTRATION_SERVER="${REGISTRATION_SERVER:-}" +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}" Z2M_LOCAL_PORT="${Z2M_LOCAL_PORT:-8081}" @@ -28,6 +31,8 @@ PORT_SLOTS="${PORT_SLOTS:-4000}" WRAPPER_DIR="/usr/local/sbin" 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 touch "$LOG" >/dev/null 2>&1 || true @@ -84,7 +89,7 @@ validate_port() { validate_settings() { 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 "$Z2M_LOCAL_PORT" "Z2M_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}" } +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. 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" </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 \ "$hostname_value" \ diff --git a/stage_reverse_tunnels/test_dynamic_environment_contract.py b/stage_reverse_tunnels/test_dynamic_environment_contract.py new file mode 100644 index 0000000..7367d91 --- /dev/null +++ b/stage_reverse_tunnels/test_dynamic_environment_contract.py @@ -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() diff --git a/stage_ui/console_core/backend/test_core_services.py b/stage_ui/console_core/backend/test_core_services.py index c1e2af9..f810f0b 100644 --- a/stage_ui/console_core/backend/test_core_services.py +++ b/stage_ui/console_core/backend/test_core_services.py @@ -56,7 +56,8 @@ class ReverseTunnelBootstrapTest(unittest.TestCase): command = provider._reverse_tunnel_bootstrap_command(context) 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) diff --git a/stage_ui/console_core/frontend/console.i18n.js b/stage_ui/console_core/frontend/console.i18n.js index 091354f..5cf11be 100644 --- a/stage_ui/console_core/frontend/console.i18n.js +++ b/stage_ui/console_core/frontend/console.i18n.js @@ -221,7 +221,7 @@ "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 шагов.", "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": "Скопировать команду", "VPS bootstrap command copied": "Команда настройки VPS скопирована", "Bootstrap command is unavailable": "Команда настройки недоступна", @@ -598,7 +598,7 @@ "Copy command": "Kopiuj polecenie", "VPS bootstrap command copied": "Polecenie bootstrap VPS zostało skopiowane", "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.", "Success": "Sukces", "Available": "Dostępne", @@ -1215,7 +1215,7 @@ ,"Bootstrap command is unavailable": "أمر التهيئة الأولية لـ VPS غير متاح" ,"VPS bootstrap command copied": "تم نسخ أمر التهيئة الأولية لـ 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 في إعدادات الجهاز. ستجد هناك الروابط المطلوبة والتعليمات الكاملة من خطوتين." ,"Account security": "أمان الحساب" ,"Change the WEB UI login password for the local iomatex user.": "تغيير كلمة مرور تسجيل الدخول إلى WEB UI للمستخدم المحلي iomatex." @@ -1507,7 +1507,7 @@ "Copy command": "कमांड कॉपी करें", "VPS bootstrap command copied": "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 मिल जाएँगी।", "Display": "डिस्प्ले", "Display status": "डिस्प्ले स्थिति", diff --git a/stage_ui/console_core/frontend/console.js b/stage_ui/console_core/frontend/console.js index 6298951..d4ffc23 100644 --- a/stage_ui/console_core/frontend/console.js +++ b/stage_ui/console_core/frontend/console.js @@ -1355,7 +1355,7 @@
- ${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."))}