#!/usr/bin/env python3 import argparse import base64 import datetime as dt import hmac import hashlib import html import http.client import json import os import secrets import select import signal import socket import sqlite3 import struct import subprocess import sys import time import urllib.parse import uuid from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path APP_NAME = "OpenWrt Remote Hub" STATE_DIR = Path(os.environ.get("OWRT_REMOTE_STATE_DIR", "/var/lib/owrt-remote")) 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" 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 MIN_PASSWORD_LENGTH = 4 SESSION_COOKIE = "owrt_remote_session" ROUTER_COOKIE = "owrt_remote_router" LUCI_ABSOLUTE_ROOTS = ("/ubus", "/cgi-bin/luci", "/luci-static") WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" def now_ts(): return int(time.time()) def iso_time(ts): if not ts: return "" return dt.datetime.fromtimestamp(int(ts), tz=dt.timezone.utc).isoformat() def ensure_state(): STATE_DIR.mkdir(parents=True, exist_ok=True) def read_or_make_token(path): ensure_state() if path.exists(): token = path.read_text(encoding="utf-8").strip() if token: return token token = secrets.token_urlsafe(32) path.write_text(token + "\n", encoding="utf-8") try: os.chmod(path, 0o600) except OSError: pass return token def agent_token(): return os.environ.get("OWRT_REMOTE_AGENT_TOKEN") or read_or_make_token(AGENT_TOKEN_FILE) def session_token(): return read_or_make_token(SESSION_TOKEN_FILE) def password_digest(password, salt=None, iterations=PBKDF2_ITERATIONS): salt = salt or secrets.token_hex(16) raw = hashlib.pbkdf2_hmac( "sha256", password.encode("utf-8"), bytes.fromhex(salt), int(iterations), ) return { "salt": salt, "hash": raw.hex(), "iterations": int(iterations), } def write_json_private(path, data): ensure_state() path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") try: os.chmod(path, 0o600) except OSError: pass def save_auth(username, password): username = clean_username(username) if len(password) < MIN_PASSWORD_LENGTH: raise ValueError(f"password must be at least {MIN_PASSWORD_LENGTH} characters") data = { "username": username, "password": password_digest(password), "updated_at": now_ts(), } write_json_private(AUTH_FILE, data) return data def load_auth(): ensure_state() if AUTH_FILE.exists(): return json.loads(AUTH_FILE.read_text(encoding="utf-8")) username = os.environ.get("OWRT_REMOTE_ADMIN_USER", "admin") password = os.environ.get("OWRT_REMOTE_ADMIN_PASSWORD") or "admin" data = save_auth(username, password) login_hint = STATE_DIR / "hub-login.txt" login_hint.write_text( f"username: {data['username']}\npassword: {password}\n", encoding="utf-8", ) try: os.chmod(login_hint, 0o600) except OSError: pass return data def clean_username(value): value = (value or "").strip() if not (1 <= len(value) <= 64): raise ValueError("username length must be 1..64") for ch in value: if not (ch.isalnum() or ch in "._-@"): raise ValueError("username may contain only letters, digits, . _ - @") return value def verify_login(username, password): try: auth = load_auth() stored_user = auth.get("username", "") stored = auth.get("password", {}) digest = password_digest(password or "", stored.get("salt"), stored.get("iterations", PBKDF2_ITERATIONS)) except Exception: return False return secrets.compare_digest(username or "", stored_user) and secrets.compare_digest( digest["hash"], stored.get("hash", ""), ) def current_username(): try: return load_auth().get("username", "admin") except Exception: return "admin" def clean_router_id(value): value = (value or "").strip() out = [] for ch in value: if ch.isalnum() or ch in "._-": out.append(ch) else: out.append("-") result = "".join(out).strip(".-_") if not result: raise ValueError("router id is empty") return result[:64] def connect(db_path=DB_PATH): ensure_state() conn = sqlite3.connect(str(db_path)) conn.row_factory = sqlite3.Row return conn def init_db(conn): conn.execute( """ create table if not exists routers ( id text primary key, name text not null, role text not null default 'node', entry_port integer not null default 0, vps_host text not null default '', vless_port integer not null default 8443, vless_uuid text not null, vless_encryption text not null default 'none', vless_decryption text not null default 'none', vless_flow text not null default '', reverse_tag text not null default 'reverse-in', public_url text not null default '', admin_host text not null default '127.0.0.1', admin_port integer not null default 80, ssh_entry_port integer not null default 0, ssh_vless_uuid text not null default '', ssh_reverse_tag text not null default '', ssh_host text not null default '127.0.0.1', ssh_port integer not null default 22, created_at integer not null, updated_at integer not null, last_seen integer, status_json text not null default '{}' ) """ ) ensure_column(conn, "routers", "ssh_entry_port", "integer not null default 0") ensure_column(conn, "routers", "ssh_vless_uuid", "text not null default ''") ensure_column(conn, "routers", "ssh_reverse_tag", "text not null default ''") ensure_column(conn, "routers", "ssh_host", "text not null default '127.0.0.1'") ensure_column(conn, "routers", "ssh_port", "integer not null default 22") conn.execute( """ update routers set ssh_entry_port = entry_port + 1000 where entry_port > 0 and (ssh_entry_port is null or ssh_entry_port = 0) """ ) for row in conn.execute("select id, reverse_tag, ssh_vless_uuid, ssh_reverse_tag from routers").fetchall(): ssh_uuid = row["ssh_vless_uuid"] or str(uuid.uuid4()) ssh_tag = row["ssh_reverse_tag"] or f"{row['reverse_tag'] or 'reverse-in'}-ssh" if ssh_uuid != row["ssh_vless_uuid"] or ssh_tag != row["ssh_reverse_tag"]: conn.execute( "update routers set ssh_vless_uuid = ?, ssh_reverse_tag = ? where id = ?", (ssh_uuid, ssh_tag, row["id"]), ) conn.commit() def ensure_column(conn, table, column, definition): cols = {row["name"] for row in conn.execute(f"pragma table_info({table})")} if column not in cols: conn.execute(f"alter table {table} add column {column} {definition}") def get_router(conn, router_id): return conn.execute("select * from routers where id = ?", (router_id,)).fetchone() def get_router_by_entry_port(conn, entry_port, exclude_id=""): return conn.execute( "select * from routers where (entry_port = ? or ssh_entry_port = ?) and id != ?", (int(entry_port), int(entry_port), exclude_id), ).fetchone() def get_router_by_any_port(conn, port, exclude_id=""): return conn.execute( "select * from routers where (entry_port = ? or ssh_entry_port = ?) and id != ?", (int(port), int(port), exclude_id), ).fetchone() def list_router_rows(conn): return conn.execute( """ select * from routers order by case role when 'main' then 0 else 1 end, lower(id) """ ).fetchall() def row_to_router(row): data = dict(row) try: status = json.loads(data.get("status_json") or "{}") except json.JSONDecodeError: status = {} last_seen = data.get("last_seen") online = bool(last_seen and now_ts() - int(last_seen) <= ONLINE_AFTER_SECONDS) data["status"] = status data["online"] = online data["last_seen_iso"] = iso_time(last_seen) data["access_url"] = f"/access/{urllib.parse.quote(data['id'])}/" data["ssh_url"] = f"/ssh/{urllib.parse.quote(data['id'])}/" data["config_url"] = f"/router/{urllib.parse.quote(data['id'])}/config" data["xray_client_url"] = f"/router/{urllib.parse.quote(data['id'])}/xray-client.json" data.pop("status_json", None) return data def upsert_router(conn, values): router_id = clean_router_id(values.get("id")) current = get_router(conn, router_id) ts = now_ts() def keep_str(key, default=""): value = values.get(key) if value not in (None, ""): return value if current: return current[key] return default def keep_int(key, default=0): value = values.get(key) if value not in (None, ""): return int(value) if current: return int(current[key] or default) return default reverse_tag = keep_str("reverse_tag", "reverse-in") ssh_vless_uuid = values.get("ssh_vless_uuid") or (current["ssh_vless_uuid"] if current and current["ssh_vless_uuid"] else str(uuid.uuid4())) ssh_reverse_tag = values.get("ssh_reverse_tag") or (current["ssh_reverse_tag"] if current and current["ssh_reverse_tag"] else f"{reverse_tag}-ssh") payload = { "id": router_id, "name": values.get("name") or router_id, "role": values.get("role") or "node", "entry_port": keep_int("entry_port", 0), "vps_host": keep_str("vps_host", ""), "vless_port": keep_int("vless_port", DEFAULT_VLESS_PORT), "vless_uuid": keep_str("vless_uuid", str(uuid.uuid4())), "vless_encryption": keep_str("vless_encryption", "none"), "vless_decryption": keep_str("vless_decryption", "none"), "vless_flow": keep_str("vless_flow", ""), "reverse_tag": reverse_tag, "public_url": keep_str("public_url", ""), "admin_host": keep_str("admin_host", "127.0.0.1"), "admin_port": keep_int("admin_port", 80), "ssh_entry_port": keep_int("ssh_entry_port", int(values.get("entry_port") or 0) + 1000 if values.get("entry_port") else 0), "ssh_vless_uuid": ssh_vless_uuid, "ssh_reverse_tag": ssh_reverse_tag, "ssh_host": keep_str("ssh_host", "127.0.0.1"), "ssh_port": keep_int("ssh_port", 22), "updated_at": ts, } if current: conn.execute( """ update routers set name = :name, role = :role, entry_port = :entry_port, vps_host = :vps_host, vless_port = :vless_port, vless_uuid = :vless_uuid, vless_encryption = :vless_encryption, vless_decryption = :vless_decryption, vless_flow = :vless_flow, reverse_tag = :reverse_tag, public_url = :public_url, admin_host = :admin_host, admin_port = :admin_port, ssh_entry_port = :ssh_entry_port, ssh_vless_uuid = :ssh_vless_uuid, ssh_reverse_tag = :ssh_reverse_tag, ssh_host = :ssh_host, ssh_port = :ssh_port, updated_at = :updated_at where id = :id """, payload, ) else: payload["created_at"] = ts conn.execute( """ insert into routers ( id, name, role, entry_port, vps_host, vless_port, vless_uuid, vless_encryption, vless_decryption, vless_flow, reverse_tag, public_url, admin_host, admin_port, ssh_entry_port, ssh_vless_uuid, ssh_reverse_tag, ssh_host, ssh_port, created_at, updated_at ) values ( :id, :name, :role, :entry_port, :vps_host, :vless_port, :vless_uuid, :vless_encryption, :vless_decryption, :vless_flow, :reverse_tag, :public_url, :admin_host, :admin_port, :ssh_entry_port, :ssh_vless_uuid, :ssh_reverse_tag, :ssh_host, :ssh_port, :created_at, :updated_at ) """, payload, ) conn.commit() return get_router(conn, router_id) def heartbeat(conn, payload): router_id = clean_router_id(payload.get("id")) row = get_router(conn, router_id) ts = now_ts() if not row: row = upsert_router( conn, { "id": router_id, "name": payload.get("name") or router_id, "role": payload.get("role") or "node", "entry_port": payload.get("entry_port") or 0, "vps_host": payload.get("vps_host") or "", "admin_host": payload.get("admin_host") or "127.0.0.1", "admin_port": payload.get("admin_port") or 80, "ssh_host": payload.get("ssh_host") or "127.0.0.1", "ssh_port": payload.get("ssh_port") or 22, }, ) conn.execute( """ update routers set name = coalesce(nullif(?, ''), name), role = coalesce(nullif(?, ''), role), public_url = coalesce(nullif(?, ''), public_url), admin_host = coalesce(nullif(?, ''), admin_host), admin_port = coalesce(?, admin_port), ssh_host = coalesce(nullif(?, ''), ssh_host), ssh_port = coalesce(?, ssh_port), last_seen = ?, status_json = ?, updated_at = ? where id = ? """, ( payload.get("name") or "", payload.get("role") or "", payload.get("public_url") or "", payload.get("admin_host") or "", int(payload["admin_port"]) if str(payload.get("admin_port", "")).isdigit() else None, payload.get("ssh_host") or "", int(payload["ssh_port"]) if str(payload.get("ssh_port", "")).isdigit() else None, ts, json.dumps(payload, ensure_ascii=False, separators=(",", ":")), ts, router_id, ), ) conn.commit() return row_to_router(get_router(conn, router_id)) def make_server_xray_config(rows, listen_host="0.0.0.0", listen_port=DEFAULT_VLESS_PORT, decryption="none"): clients = [] inbounds = [ { "tag": "owrt-remote-vless", "listen": listen_host, "port": int(listen_port), "protocol": "vless", "settings": { "clients": clients, "decryption": decryption, }, "streamSettings": { "network": "tcp", "security": "none", }, } ] rules = [] for row in rows: router_id = clean_router_id(row["id"]) entry_port = int(row["entry_port"] or 0) if entry_port <= 0: continue ssh_entry_port = int(row["ssh_entry_port"] or 0) reverse_out = f"reverse-{router_id}" ssh_reverse_out = f"{reverse_out}-ssh" portal_in = f"entry-{router_id}" client = { "id": row["vless_uuid"], "email": f"{router_id}@owrt-remote", "reverse": { "tag": reverse_out, }, } if row["vless_flow"]: client["flow"] = row["vless_flow"] clients.append(client) if ssh_entry_port > 0: ssh_client = { "id": row["ssh_vless_uuid"], "email": f"{router_id}-ssh@owrt-remote", "reverse": { "tag": ssh_reverse_out, }, } if row["vless_flow"]: ssh_client["flow"] = row["vless_flow"] clients.append(ssh_client) inbounds.append( { "tag": portal_in, "listen": "127.0.0.1", "port": entry_port, "protocol": "tunnel", "settings": { "allowedNetwork": "tcp", "rewriteAddress": row["admin_host"], "rewritePort": int(row["admin_port"]), }, } ) rules.append( { "type": "field", "inboundTag": [portal_in], "outboundTag": reverse_out, } ) if ssh_entry_port > 0: ssh_in = f"ssh-{router_id}" inbounds.append( { "tag": ssh_in, "listen": "127.0.0.1", "port": ssh_entry_port, "protocol": "tunnel", "settings": { "allowedNetwork": "tcp", "rewriteAddress": row["ssh_host"] or "127.0.0.1", "rewritePort": int(row["ssh_port"] or 22), }, } ) rules.append( { "type": "field", "inboundTag": [ssh_in], "outboundTag": ssh_reverse_out, } ) return { "log": {"loglevel": "warning"}, "inbounds": inbounds, "outbounds": [{"tag": "direct", "protocol": "freedom"}], "routing": {"rules": rules}, "remarks": "OpenWrt Remote Hub server config", } def make_router_xray_config(row): bridge_tag = row["reverse_tag"] ssh_bridge_tag = row["ssh_reverse_tag"] or f"{bridge_tag}-ssh" return { "log": {"loglevel": "warning"}, "inbounds": [], "outbounds": [ { "tag": "router-admin", "protocol": "freedom", "settings": { "redirect": f"{row['admin_host']}:{int(row['admin_port'])}", }, }, { "tag": "router-ssh", "protocol": "freedom", "settings": { "redirect": f"{row['ssh_host'] or '127.0.0.1'}:{int(row['ssh_port'] or 22)}", }, }, { "tag": "vps-interconn", "protocol": "vless", "settings": { "address": row["vps_host"], "port": int(row["vless_port"]), "id": row["vless_uuid"], "encryption": row["vless_encryption"], "flow": row["vless_flow"], "reverse": {"tag": bridge_tag}, }, "streamSettings": {"network": "tcp", "security": "none"}, }, { "tag": "vps-ssh-interconn", "protocol": "vless", "settings": { "address": row["vps_host"], "port": int(row["vless_port"]), "id": row["ssh_vless_uuid"], "encryption": row["vless_encryption"], "flow": row["vless_flow"], "reverse": {"tag": ssh_bridge_tag}, }, "streamSettings": {"network": "tcp", "security": "none"}, }, ], "routing": { "rules": [ { "type": "field", "inboundTag": [bridge_tag], "outboundTag": "router-admin", }, { "type": "field", "inboundTag": [ssh_bridge_tag], "outboundTag": "router-ssh", } ] }, "remarks": f"OpenWrt Remote client for {row['id']}", } def reload_vps_xray(db_path=DB_PATH): out = Path(os.environ.get("OWRT_REMOTE_XRAY_CONFIG", "/etc/xray/owrt-remote.json")) service = os.environ.get("OWRT_REMOTE_XRAY_SERVICE", "owrt-remote-xray") with connect(db_path) as conn: init_db(conn) rows = list_router_rows(conn) config = make_server_xray_config(rows) out.parent.mkdir(parents=True, exist_ok=True) out.write_text(json.dumps(config, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") try: os.chmod(out, 0o600) except OSError: pass result = subprocess.run( ["systemctl", "restart", service], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=20, check=False, ) if result.returncode != 0: detail = (result.stderr or result.stdout or "").strip() raise RuntimeError(f"systemctl restart {service} failed: {detail}") return {"config": str(out), "service": service, "routers": len(rows)} def restart_vps_xray(): service = os.environ.get("OWRT_REMOTE_XRAY_SERVICE", "owrt-remote-xray") result = subprocess.run( ["systemctl", "restart", service], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=20, check=False, ) if result.returncode != 0: detail = (result.stderr or result.stdout or "").strip() raise RuntimeError(f"systemctl restart {service} failed: {detail}") return {"service": service} def make_openwrt_config(row, hub_url): lines = [ "uci -q delete owrtremote.main", "uci set owrtremote.main=remote", "uci set owrtremote.main.enabled='1'", f"uci set owrtremote.main.router_id='{sh_quote(row['id'])}'", f"uci set owrtremote.main.router_name='{sh_quote(row['name'])}'", f"uci set owrtremote.main.role='{sh_quote(row['role'])}'", f"uci set owrtremote.main.hub_url='{sh_quote(hub_url)}'", f"uci set owrtremote.main.hub_token='{sh_quote(agent_token())}'", "uci set owrtremote.main.heartbeat_interval='30'", "uci set owrtremote.main.xray_bin='/usr/bin/xray'", "uci set owrtremote.main.xray_config='/etc/xray/owrt-remote-client.json'", f"uci set owrtremote.main.vps_host='{sh_quote(row['vps_host'])}'", f"uci set owrtremote.main.vps_port='{int(row['vless_port'])}'", f"uci set owrtremote.main.vless_uuid='{sh_quote(row['vless_uuid'])}'", f"uci set owrtremote.main.vless_encryption='{sh_quote(row['vless_encryption'])}'", f"uci set owrtremote.main.vless_flow='{sh_quote(row['vless_flow'])}'", f"uci set owrtremote.main.reverse_tag='{sh_quote(row['reverse_tag'])}'", f"uci set owrtremote.main.ssh_vless_uuid='{sh_quote(row['ssh_vless_uuid'])}'", f"uci set owrtremote.main.ssh_reverse_tag='{sh_quote(row['ssh_reverse_tag'] or (row['reverse_tag'] + '-ssh'))}'", f"uci set owrtremote.main.admin_host='{sh_quote(row['admin_host'])}'", f"uci set owrtremote.main.admin_port='{int(row['admin_port'])}'", f"uci set owrtremote.main.ssh_host='{sh_quote(row['ssh_host'] or '127.0.0.1')}'", f"uci set owrtremote.main.ssh_port='{int(row['ssh_port'] or 22)}'", f"uci set owrtremote.main.public_url='{sh_quote(row['public_url'])}'", "uci commit owrtremote", "owrt-remote render-client", "/etc/init.d/owrt-remote enable", "/etc/init.d/owrt-remote restart", "owrt-remote heartbeat", ] return "\n".join(lines) + "\n" def sh_quote(value): return str(value).replace("'", "'\"'\"'") def parse_cookies(header): cookies = {} for chunk in (header or "").split(";"): if "=" in chunk: key, value = chunk.split("=", 1) cookies[key.strip()] = value.strip() return cookies def clean_forward_cookie(cookie_header): parts = [] for chunk in (cookie_header or "").split(";"): if not chunk.strip(): continue if ( chunk.strip().startswith("owrt_remote_admin=") or chunk.strip().startswith(f"{SESSION_COOKIE}=") or chunk.strip().startswith(f"{ROUTER_COOKIE}=") ): continue parts.append(chunk.strip()) return "; ".join(parts) def current_router_cookie(router_id): return f"{ROUTER_COOKIE}={urllib.parse.quote(router_id)}; HttpOnly; SameSite=Lax; Path=/" def ssh_ws_token(secret, router_id): return hmac.new( secret.encode("utf-8"), f"ssh:{router_id}".encode("utf-8"), hashlib.sha256, ).hexdigest() def strip_access_prefix(path, router_id): prefix = f"/access/{urllib.parse.quote(router_id)}" if path == prefix: return "/" if path.startswith(prefix + "/"): return path[len(prefix):] or "/" return path or "/" def rewrite_forward_url(value, router_id, port): if not value: return value parsed = urllib.parse.urlsplit(value) path = strip_access_prefix(parsed.path, router_id) return urllib.parse.urlunsplit(("http", f"127.0.0.1:{port}", path, parsed.query, parsed.fragment)) def ws_accept_value(key): raw = hashlib.sha1((key + WS_GUID).encode("ascii")).digest() return base64.b64encode(raw).decode("ascii") def recv_exact(sock, size): chunks = [] left = size while left > 0: chunk = sock.recv(left) if not chunk: raise ConnectionError("websocket closed") chunks.append(chunk) left -= len(chunk) return b"".join(chunks) def ws_read_frame(sock): head = recv_exact(sock, 2) first, second = head[0], head[1] opcode = first & 0x0F masked = bool(second & 0x80) length = second & 0x7F if length == 126: length = struct.unpack("!H", recv_exact(sock, 2))[0] elif length == 127: length = struct.unpack("!Q", recv_exact(sock, 8))[0] mask = recv_exact(sock, 4) if masked else b"" payload = recv_exact(sock, length) if length else b"" if masked and payload: payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload)) return opcode, payload def ws_send_frame(sock, payload, opcode=1): if isinstance(payload, str): payload = payload.encode("utf-8", errors="replace") length = len(payload) if length < 126: head = struct.pack("!BB", 0x80 | opcode, length) elif length < 65536: head = struct.pack("!BBH", 0x80 | opcode, 126, length) else: head = struct.pack("!BBQ", 0x80 | opcode, 127, length) sock.sendall(head + payload) def dashboard_html(routers, username): routers_json = json.dumps(routers, ensure_ascii=False) safe_username = html.escape(username, quote=True) return f"""