From d322156bbf57e868426a4d16cade83bb80b70602 Mon Sep 17 00:00:00 2001 From: kzolotarev95 Date: Tue, 30 Jun 2026 11:32:13 +0400 Subject: [PATCH] Add optional HTTPS setup for VPS hub --- README.md | 60 +++++++++++- vps/enable-https.sh | 202 +++++++++++++++++++++++++++++++++++++++++ vps/install-vps.sh | 3 + vps/owrt-remote-hub.py | 44 ++++++++- vps/uninstall-vps.sh | 7 +- 5 files changed, 313 insertions(+), 3 deletions(-) create mode 100755 vps/enable-https.sh diff --git a/README.md b/README.md index dbaadd0..6543fa1 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,8 @@ flowchart LR │ └── установка Hub на VPS одной командой ├── uninstall-vps.sh │ └── удаление Hub с VPS одной командой + ├── enable-https.sh + │ └── включение HTTPS/443 для Hub ├── owrt-remote-hub.py │ └── веб-панель VPS, карточки роутеров, proxy, SSH terminal └── owrt-remote.service @@ -80,6 +82,7 @@ flowchart LR | Задача | Где запускать | Команда | | --- | --- | --- | | Поставить Hub | VPS | `curl -fsSL "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main/vps/install-vps.sh?v=$(date +%s)" \| sudo sh` | +| Включить HTTPS | VPS | `curl -fsSL "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main/vps/enable-https.sh?v=$(date +%s)" \| sudo sh -s -- YOUR_VPS_IP` | | Поставить агент | OpenWrt | `wget -O - "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main/install.sh?v=$(date +%s)" \| sh` | | Удалить Hub полностью | VPS | `curl -fsSL "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main/vps/uninstall-vps.sh?v=$(date +%s)" \| sudo sh` | | Удалить агент полностью | OpenWrt | `wget -O - "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main/uninstall.sh?v=$(date +%s)" \| PURGE=1 sh` | @@ -200,6 +203,60 @@ sudo systemctl status owrt-remote --no-pager -l curl -sS http://127.0.0.1:8088/health ``` +## HTTPS / SSL + +По умолчанию Hub сразу открывается по HTTP: + +```text +http://YOUR_VPS_IP/ +http://YOUR_VPS_IP:8088/ +``` + +HTTPS включается отдельной командой после установки. Так проще и надежнее: сначала поднимается панель, потом выпускается сертификат и включается порт `443/tcp`. + +### HTTPS на IP VPS + +```sh +curl -fsSL "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main/vps/enable-https.sh?v=$(date +%s)" | sudo sh -s -- YOUR_VPS_IP +``` + +Пример: + +```sh +curl -fsSL "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main/vps/enable-https.sh?v=$(date +%s)" | sudo sh -s -- 45.9.73.74 +``` + +После этого панель будет тут: + +```text +https://YOUR_VPS_IP/ +``` + +Важно: IP-сертификаты Let's Encrypt короткие. Certbot сам ставит renew timer, а скрипт добавляет hook для перезапуска Hub после обновления сертификата. + +### HTTPS на домен + +Сначала направь DNS `A`-запись домена на IP VPS. Потом: + +```sh +curl -fsSL "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main/vps/enable-https.sh?v=$(date +%s)" | sudo EMAIL="you@example.com" sh -s -- hub.example.com +``` + +После этого панель будет тут: + +```text +https://hub.example.com/ +``` + +Проверка на VPS: + +```sh +sudo ss -lntp | grep -E ':(80|443|8088)\b' +curl -k https://127.0.0.1/health +``` + +Если HTTPS не включился, проверь, что снаружи открыт порт `80/tcp` для проверки Let's Encrypt и `443/tcp` для самой панели. + ## Установка Xray на VPS ```sh @@ -490,7 +547,8 @@ curl -fsSL "https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/ - файлы `/opt/owrt-remote`; - конфиг `/etc/xray/owrt-remote.json`; - база роутеров `/var/lib/owrt-remote`; -- правила `ufw` для `80/tcp`, `8088/tcp`, `8443/tcp`. +- правила `ufw` для `80/tcp`, `443/tcp`, `8088/tcp`, `8443/tcp`. +- HTTPS systemd override и renewal hook. Если хочешь удалить Hub, но оставить базу роутеров: diff --git a/vps/enable-https.sh b/vps/enable-https.sh new file mode 100755 index 0000000..ee044ad --- /dev/null +++ b/vps/enable-https.sh @@ -0,0 +1,202 @@ +#!/bin/sh +set -u + +APP_NAME="OpenWrt Remote Hub" +STATE_DIR="${OWRT_REMOTE_STATE_DIR:-/var/lib/owrt-remote}" +ACME_WEBROOT="$STATE_DIR/acme-webroot" +HOSTNAME_ARG="${1:-${HTTPS_HOST:-}}" +EMAIL="${EMAIL:-}" +STAGING="${STAGING:-0}" + +if [ "$(id -u)" -eq 0 ]; then + SUDO="" +else + SUDO="sudo" +fi + +info() { + printf '%s\n' "$*" +} + +warn() { + printf 'WARN: %s\n' "$*" >&2 +} + +die() { + printf 'ERROR: %s\n' "$*" >&2 + exit 1 +} + +detect_host() { + if [ -n "$HOSTNAME_ARG" ]; then + printf '%s\n' "$HOSTNAME_ARG" + return + fi + if command -v curl >/dev/null 2>&1; then + host="$(curl -4fsS --max-time 5 https://api.ipify.org 2>/dev/null || true)" + if [ -n "$host" ]; then + printf '%s\n' "$host" + return + fi + fi + hostname -I 2>/dev/null | awk '{print $1}' +} + +is_ipv4() { + printf '%s\n' "$1" | grep -Eq '^[0-9]{1,3}(\.[0-9]{1,3}){3}$' +} + +install_certbot() { + if command -v certbot >/dev/null 2>&1 && certbot --help all 2>/dev/null | grep -q -- '--ip-address'; then + return + fi + + info "Ставлю свежий Certbot через snap..." + if command -v apt-get >/dev/null 2>&1; then + $SUDO apt-get update + $SUDO apt-get install -y snapd + else + die "нужен Ubuntu/Debian с apt-get или уже установленный certbot с --ip-address" + fi + + $SUDO systemctl enable --now snapd.socket >/dev/null 2>&1 || true + $SUDO snap wait system seed.loaded >/dev/null 2>&1 || true + $SUDO snap install core >/dev/null 2>&1 || true + $SUDO snap refresh core >/dev/null 2>&1 || true + if $SUDO snap list certbot >/dev/null 2>&1; then + $SUDO snap refresh certbot >/dev/null 2>&1 || true + else + $SUDO snap install --classic certbot >/dev/null 2>&1 || true + fi + $SUDO ln -sf /snap/bin/certbot /usr/bin/certbot + + command -v certbot >/dev/null 2>&1 || die "certbot не установился" +} + +ensure_hub_http() { + $SUDO mkdir -p "$ACME_WEBROOT/.well-known/acme-challenge" + $SUDO chmod 755 "$STATE_DIR" "$ACME_WEBROOT" "$ACME_WEBROOT/.well-known" "$ACME_WEBROOT/.well-known/acme-challenge" 2>/dev/null || true + if ! curl -fsS --max-time 3 http://127.0.0.1:8088/health >/dev/null 2>&1; then + $SUDO systemctl restart owrt-remote + fi + i=1 + while [ "$i" -le 20 ]; do + if curl -fsS --max-time 2 http://127.0.0.1:8088/health >/dev/null 2>&1; then + return + fi + sleep 1 + i=$((i + 1)) + done + die "Hub не ответил на http://127.0.0.1:8088/health" +} + +certbot_email_args() { + if [ -n "$EMAIL" ]; then + printf '%s\n' "-m $EMAIL" + else + printf '%s\n' "--register-unsafely-without-email" + fi +} + +issue_cert() { + host="$1" + email_args="$(certbot_email_args)" + staging_arg="" + if [ "$STAGING" = "1" ]; then + staging_arg="--staging" + fi + + if is_ipv4 "$host"; then + info "Получаю Let's Encrypt SSL для IP: $host" + # shellcheck disable=SC2086 + $SUDO certbot certonly --non-interactive --agree-tos $staging_arg $email_args \ + --cert-name "$host" \ + --webroot --webroot-path "$ACME_WEBROOT" \ + --preferred-profile shortlived \ + --ip-address "$host" + else + info "Получаю Let's Encrypt SSL для домена: $host" + # shellcheck disable=SC2086 + $SUDO certbot certonly --non-interactive --agree-tos $staging_arg $email_args \ + --cert-name "$host" \ + --webroot --webroot-path "$ACME_WEBROOT" \ + -d "$host" + fi +} + +enable_hub_tls() { + host="$1" + live_dir="/etc/letsencrypt/live/$host" + [ -f "$live_dir/fullchain.pem" ] || die "не найден сертификат: $live_dir/fullchain.pem" + [ -f "$live_dir/privkey.pem" ] || die "не найден ключ: $live_dir/privkey.pem" + + $SUDO mkdir -p /etc/systemd/system/owrt-remote.service.d + $SUDO tee /etc/systemd/system/owrt-remote.service.d/https.conf >/dev/null </dev/null <<'EOF' +#!/bin/sh +systemctl restart owrt-remote >/dev/null 2>&1 || true +EOF + $SUDO chmod +x /etc/letsencrypt/renewal-hooks/deploy/owrt-remote-restart.sh + + if command -v ufw >/dev/null 2>&1; then + $SUDO ufw allow 443/tcp >/dev/null 2>&1 || true + fi + + $SUDO systemctl daemon-reload + $SUDO systemctl restart owrt-remote +} + +check_https() { + i=1 + while [ "$i" -le 20 ]; do + if curl -kfsS --max-time 3 https://127.0.0.1/health >/dev/null 2>&1; then + return 0 + fi + sleep 1 + i=$((i + 1)) + done + return 1 +} + +main() { + host="$(detect_host)" + [ -n "$host" ] || die "не смог определить IP/домен. Запусти: sh -s -- YOUR_DOMAIN_OR_IP" + + info "Включаю HTTPS для $APP_NAME..." + info "Адрес: $host" + install_certbot + if is_ipv4 "$host" && ! certbot --help all 2>/dev/null | grep -q -- '--ip-address'; then + die "этот certbot не умеет IP-сертификаты. Нужен свежий certbot 5.4+ через snap." + fi + ensure_hub_http + issue_cert "$host" + enable_hub_tls "$host" + if ! check_https; then + $SUDO systemctl status owrt-remote --no-pager -l || true + die "HTTPS не ответил на https://127.0.0.1/health" + fi + + info "" + info "============================================================" + info "HTTPS включен" + info "============================================================" + info "Панель:" + info " https://$host/" + info " http://$host/" + info " http://$host:8088/" + info "" + info "Проверь:" + info " sudo ss -lntp | grep -E ':(80|443|8088)'" + info " curl -k https://127.0.0.1/health" + info "============================================================" +} + +main "$@" diff --git a/vps/install-vps.sh b/vps/install-vps.sh index 8857c5c..d7db2d7 100755 --- a/vps/install-vps.sh +++ b/vps/install-vps.sh @@ -165,6 +165,9 @@ print_result() { info "" info "Если снаружи не открывается, открой в firewall VPS-провайдера:" info " 80/tcp, 8088/tcp, 8443/tcp" + info "" + info "Включить HTTPS после установки:" + info " curl -fsSL \"https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main/vps/enable-https.sh?v=\\$(date +%s)\" | sudo sh -s -- $host" info "============================================================" } diff --git a/vps/owrt-remote-hub.py b/vps/owrt-remote-hub.py index daf7c20..e8ab36e 100644 --- a/vps/owrt-remote-hub.py +++ b/vps/owrt-remote-hub.py @@ -12,6 +12,7 @@ import secrets import select import signal import socket +import ssl import sqlite3 import struct import subprocess @@ -30,6 +31,7 @@ DB_PATH = Path(os.environ.get("OWRT_REMOTE_DB", str(STATE_DIR / "hub.db"))) AUTH_FILE = STATE_DIR / "hub-auth.json" SESSION_TOKEN_FILE = STATE_DIR / "hub-session.token" AGENT_TOKEN_FILE = STATE_DIR / "agent.token" +ACME_WEBROOT = STATE_DIR / "acme-webroot" ONLINE_AFTER_SECONDS = int(os.environ.get("OWRT_REMOTE_ONLINE_AFTER", "75")) DEFAULT_VLESS_PORT = int(os.environ.get("OWRT_REMOTE_VLESS_PORT", "8443")) PBKDF2_ITERATIONS = 240000 @@ -1674,6 +1676,20 @@ class Handler(BaseHTTPRequestHandler): def clear_session_cookie(self): return f"{SESSION_COOKIE}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0" + def serve_acme_challenge(self, path): + prefix = "/.well-known/acme-challenge/" + token = urllib.parse.unquote(path[len(prefix):]) + if not token or "/" in token or "\\" in token: + self.send_text(404, "not found") + return + challenge_path = ACME_WEBROOT / ".well-known" / "acme-challenge" / token + try: + body = challenge_path.read_bytes() + except OSError: + self.send_text(404, "not found") + return + self.send_bytes(200, body, "text/plain; charset=utf-8") + def redirect(self, location, extra_headers=None): self.send_response(302) self.send_header("Location", location) @@ -2027,6 +2043,9 @@ class Handler(BaseHTTPRequestHandler): if path == "/health": self.send_json(200, {"ok": True}) return + if path.startswith("/.well-known/acme-challenge/"): + self.serve_acme_challenge(path) + return if path == "/login": self.send_bytes(200, login_html().encode("utf-8"), "text/html; charset=utf-8") return @@ -2533,9 +2552,15 @@ def parse_extra_ports(value): return ports -def make_http_server(app, host, port): +def make_http_server(app, host, port, tls_cert="", tls_key=""): server = ThreadingHTTPServer((host, port), Handler) server.app = app + server.is_tls = False + if tls_cert and tls_key: + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(tls_cert, tls_key) + server.socket = context.wrap_socket(server.socket, server_side=True) + server.is_tls = True return server @@ -2558,6 +2583,20 @@ def cmd_serve(args): thread = threading.Thread(target=extra_server.serve_forever, daemon=True) thread.start() print(f"{APP_NAME} also listening on http://{args.host}:{port}") + if args.tls_cert and args.tls_key: + for port in parse_extra_ports(args.tls_ports): + try: + tls_server = make_http_server(app, args.host, port, args.tls_cert, args.tls_key) + except OSError as exc: + print(f"WARNING: HTTPS port {port} not started: {exc}", file=sys.stderr) + continue + except ssl.SSLError as exc: + print(f"WARNING: HTTPS cert/key error: {exc}", file=sys.stderr) + continue + extra_servers.append(tls_server) + thread = threading.Thread(target=tls_server.serve_forever, daemon=True) + thread.start() + print(f"{APP_NAME} also listening on https://{args.host}:{port}") print(f"{APP_NAME} listening on http://{args.host}:{args.port}") print(f"HUB_LOGIN: {auth.get('username', 'admin')}") print(f"AGENT_TOKEN: {app.agent_token}") @@ -2631,6 +2670,9 @@ def parser(): serve.add_argument("--host", default=os.environ.get("OWRT_REMOTE_BIND", "0.0.0.0")) serve.add_argument("--port", type=int, default=int(os.environ.get("OWRT_REMOTE_PORT", "8088"))) serve.add_argument("--extra-ports", default=os.environ.get("OWRT_REMOTE_EXTRA_PORTS", "")) + serve.add_argument("--tls-ports", default=os.environ.get("OWRT_REMOTE_TLS_PORTS", "")) + serve.add_argument("--tls-cert", default=os.environ.get("OWRT_REMOTE_TLS_CERT", "")) + serve.add_argument("--tls-key", default=os.environ.get("OWRT_REMOTE_TLS_KEY", "")) serve.add_argument("--public-url", default=os.environ.get("OWRT_REMOTE_PUBLIC_URL", "")) serve.set_defaults(func=cmd_serve) diff --git a/vps/uninstall-vps.sh b/vps/uninstall-vps.sh index c4f5c55..c0b5e34 100755 --- a/vps/uninstall-vps.sh +++ b/vps/uninstall-vps.sh @@ -55,6 +55,8 @@ main() { $SUDO rm -f /etc/systemd/system/owrt-remote.service $SUDO rm -f /etc/systemd/system/owrt-remote-xray.service + $SUDO rm -rf /etc/systemd/system/owrt-remote.service.d + $SUDO rm -f /etc/letsencrypt/renewal-hooks/deploy/owrt-remote-restart.sh $SUDO rm -rf /opt/owrt-remote $SUDO rm -f /etc/xray/owrt-remote.json @@ -63,6 +65,7 @@ main() { fi remove_ufw_rule 80 + remove_ufw_rule 443 remove_ufw_rule 8088 remove_ufw_rule 8443 @@ -81,6 +84,8 @@ main() { info " /opt/owrt-remote" info " /etc/systemd/system/owrt-remote.service" info " /etc/systemd/system/owrt-remote-xray.service" + info " /etc/systemd/system/owrt-remote.service.d" + info " /etc/letsencrypt/renewal-hooks/deploy/owrt-remote-restart.sh" info " /etc/xray/owrt-remote.json" if [ "$PURGE" = "1" ]; then info " $STATE_DIR" @@ -89,7 +94,7 @@ main() { info " $STATE_DIR" fi info "" - info "Порты ufw закрыты: 80/tcp, 8088/tcp, 8443/tcp" + info "Порты ufw закрыты: 80/tcp, 443/tcp, 8088/tcp, 8443/tcp" if [ "$REMOVE_XRAY" != "1" ]; then info "Xray binary не удалялся. Чтобы удалить и его: REMOVE_XRAY=1" fi