mirror of
https://github.com/bunny-lab-io/Borealis.git
synced 2026-02-06 20:00:31 -07:00
Removed RDP in favor of VNC / Made WireGuard Tunnel Persistent
This commit is contained in:
@@ -33,7 +33,8 @@ from ..auth import DevModeManager
|
||||
from .enrollment import routes as enrollment_routes
|
||||
from .tokens import routes as token_routes
|
||||
from .devices.tunnel import register_tunnel
|
||||
from .devices.rdp import register_rdp
|
||||
from .devices.vnc import register_vnc
|
||||
from .devices.shell import register_shell
|
||||
|
||||
from ...server import EngineContext
|
||||
from .access_management.login import register_auth
|
||||
@@ -292,7 +293,8 @@ def _register_devices(app: Flask, adapters: EngineServiceAdapters) -> None:
|
||||
register_admin_endpoints(app, adapters)
|
||||
device_routes.register_agents(app, adapters)
|
||||
register_tunnel(app, adapters)
|
||||
register_rdp(app, adapters)
|
||||
register_vnc(app, adapters)
|
||||
register_shell(app, adapters)
|
||||
|
||||
def _register_filters(app: Flask, adapters: EngineServiceAdapters) -> None:
|
||||
filters_management.register_filters(app, adapters)
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
# API Endpoints (if applicable):
|
||||
# - POST /api/agent/heartbeat (Device Authenticated) - Updates device last-seen metadata and inventory snapshots.
|
||||
# - POST /api/agent/script/request (Device Authenticated) - Provides script execution payloads or idle signals to agents.
|
||||
# - POST /api/agent/vpn/ensure (Device Authenticated) - Ensures persistent WireGuard tunnel material.
|
||||
# ======================================================
|
||||
|
||||
"""Device-affiliated agent endpoints for the Borealis Engine runtime."""
|
||||
@@ -13,12 +14,14 @@ from __future__ import annotations
|
||||
import json
|
||||
import sqlite3
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
from typing import TYPE_CHECKING, Any, Dict, Optional
|
||||
|
||||
from flask import Blueprint, jsonify, request, g
|
||||
|
||||
from ....auth.device_auth import AGENT_CONTEXT_HEADER, require_device_auth
|
||||
from ....auth.guid_utils import normalize_guid
|
||||
from .tunnel import _get_tunnel_service
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - typing aide
|
||||
from .. import EngineServiceAdapters
|
||||
@@ -42,6 +45,20 @@ def _json_or_none(value: Any) -> Optional[str]:
|
||||
return None
|
||||
|
||||
|
||||
def _infer_endpoint_host(req) -> str:
|
||||
forwarded = (req.headers.get("X-Forwarded-Host") or req.headers.get("X-Original-Host") or "").strip()
|
||||
host = forwarded.split(",")[0].strip() if forwarded else (req.host or "").strip()
|
||||
if not host:
|
||||
return ""
|
||||
try:
|
||||
parsed = urlsplit(f"//{host}")
|
||||
if parsed.hostname:
|
||||
return parsed.hostname
|
||||
except Exception:
|
||||
return host
|
||||
return host
|
||||
|
||||
|
||||
def register_agents(app, adapters: "EngineServiceAdapters") -> None:
|
||||
"""Register agent heartbeat and script polling routes."""
|
||||
|
||||
@@ -218,4 +235,76 @@ def register_agents(app, adapters: "EngineServiceAdapters") -> None:
|
||||
}
|
||||
)
|
||||
|
||||
@blueprint.route("/api/agent/vpn/ensure", methods=["POST"])
|
||||
@require_device_auth(auth_manager)
|
||||
def vpn_ensure():
|
||||
ctx = _auth_context()
|
||||
if ctx is None:
|
||||
return jsonify({"error": "auth_context_missing"}), 500
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
requested_agent = (body.get("agent_id") or "").strip()
|
||||
guid = normalize_guid(ctx.guid)
|
||||
|
||||
conn = db_conn_factory()
|
||||
resolved_agent = ""
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"SELECT agent_id FROM devices WHERE UPPER(guid) = ? ORDER BY last_seen DESC LIMIT 1",
|
||||
(guid,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row and row[0]:
|
||||
resolved_agent = str(row[0]).strip()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
if not resolved_agent:
|
||||
log("VPN_Tunnel/tunnel", f"vpn_agent_ensure_missing_agent guid={guid}", _context_hint(ctx), level="ERROR")
|
||||
return jsonify({"error": "agent_id_missing"}), 404
|
||||
|
||||
if requested_agent and requested_agent != resolved_agent:
|
||||
log(
|
||||
"VPN_Tunnel/tunnel",
|
||||
"vpn_agent_ensure_agent_mismatch requested={0} resolved={1}".format(
|
||||
requested_agent, resolved_agent
|
||||
),
|
||||
_context_hint(ctx),
|
||||
level="WARNING",
|
||||
)
|
||||
|
||||
try:
|
||||
tunnel_service = _get_tunnel_service(adapters)
|
||||
endpoint_host = _infer_endpoint_host(request)
|
||||
log(
|
||||
"VPN_Tunnel/tunnel",
|
||||
"vpn_agent_ensure_request agent_id={0} endpoint_host={1}".format(
|
||||
resolved_agent, endpoint_host or "-"
|
||||
),
|
||||
_context_hint(ctx),
|
||||
)
|
||||
payload = tunnel_service.connect(
|
||||
agent_id=resolved_agent,
|
||||
operator_id=None,
|
||||
endpoint_host=endpoint_host,
|
||||
)
|
||||
except Exception as exc:
|
||||
log(
|
||||
"VPN_Tunnel/tunnel",
|
||||
"vpn_agent_ensure_failed agent_id={0} error={1}".format(resolved_agent, str(exc)),
|
||||
_context_hint(ctx),
|
||||
level="ERROR",
|
||||
)
|
||||
return jsonify({"error": "tunnel_start_failed", "detail": str(exc)}), 500
|
||||
|
||||
log(
|
||||
"VPN_Tunnel/tunnel",
|
||||
"vpn_agent_ensure_response agent_id={0} tunnel_id={1}".format(
|
||||
payload.get("agent_id", resolved_agent), payload.get("tunnel_id", "-")
|
||||
),
|
||||
_context_hint(ctx),
|
||||
)
|
||||
return jsonify(payload), 200
|
||||
|
||||
app.register_blueprint(blueprint)
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
# ======================================================
|
||||
# Data\Engine\services\API\devices\rdp.py
|
||||
# Description: RDP session bootstrap for Guacamole WebSocket tunnels.
|
||||
# Data\Engine\services\API\devices\shell.py
|
||||
# Description: Remote PowerShell session endpoints for persistent WireGuard tunnels.
|
||||
#
|
||||
# API Endpoints (if applicable):
|
||||
# - POST /api/rdp/session (Token Authenticated) - Issues a one-time Guacamole tunnel token for RDP.
|
||||
# - POST /api/shell/establish (Token Authenticated) - Ensure shell readiness over WireGuard.
|
||||
# - POST /api/shell/disconnect (Token Authenticated) - Disconnect the operator shell session.
|
||||
# ======================================================
|
||||
|
||||
"""RDP session bootstrap endpoints for the Borealis Engine."""
|
||||
"""Remote PowerShell session endpoints for the Borealis Engine."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
@@ -16,7 +17,6 @@ from urllib.parse import urlsplit
|
||||
from flask import Blueprint, jsonify, request, session
|
||||
from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer
|
||||
|
||||
from ...RemoteDesktop.guacamole_proxy import GUAC_WS_PATH, ensure_guacamole_proxy
|
||||
from .tunnel import _get_tunnel_service
|
||||
|
||||
if False: # pragma: no cover - hint for type checkers
|
||||
@@ -81,25 +81,18 @@ def _infer_endpoint_host(req) -> str:
|
||||
return host
|
||||
|
||||
|
||||
def _is_secure(req) -> bool:
|
||||
if req.is_secure:
|
||||
return True
|
||||
forwarded = (req.headers.get("X-Forwarded-Proto") or "").split(",")[0].strip().lower()
|
||||
return forwarded == "https"
|
||||
|
||||
|
||||
def register_rdp(app, adapters: "EngineServiceAdapters") -> None:
|
||||
blueprint = Blueprint("rdp", __name__)
|
||||
logger = adapters.context.logger.getChild("rdp.api")
|
||||
def register_shell(app, adapters: "EngineServiceAdapters") -> None:
|
||||
blueprint = Blueprint("vpn_shell", __name__)
|
||||
logger = adapters.context.logger.getChild("vpn_shell.api")
|
||||
service_log = adapters.service_log
|
||||
|
||||
def _service_log_event(message: str, *, level: str = "INFO") -> None:
|
||||
if not callable(service_log):
|
||||
return
|
||||
try:
|
||||
service_log("RDP", message, level=level)
|
||||
service_log("VPN_Tunnel/remote_shell", message, level=level)
|
||||
except Exception:
|
||||
logger.debug("rdp service log write failed", exc_info=True)
|
||||
logger.debug("vpn_shell service log write failed", exc_info=True)
|
||||
|
||||
def _request_remote() -> str:
|
||||
forwarded = (request.headers.get("X-Forwarded-For") or "").strip()
|
||||
@@ -107,8 +100,8 @@ def register_rdp(app, adapters: "EngineServiceAdapters") -> None:
|
||||
return forwarded.split(",")[0].strip()
|
||||
return (request.remote_addr or "").strip()
|
||||
|
||||
@blueprint.route("/api/rdp/session", methods=["POST"])
|
||||
def rdp_session():
|
||||
@blueprint.route("/api/shell/establish", methods=["POST"])
|
||||
def shell_establish():
|
||||
requirement = _require_login(app)
|
||||
if requirement:
|
||||
payload, status = requirement
|
||||
@@ -119,77 +112,82 @@ def register_rdp(app, adapters: "EngineServiceAdapters") -> None:
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
agent_id = _normalize_text(body.get("agent_id"))
|
||||
protocol = _normalize_text(body.get("protocol") or "rdp").lower()
|
||||
username = _normalize_text(body.get("username"))
|
||||
password = str(body.get("password") or "")
|
||||
if not agent_id:
|
||||
return jsonify({"error": "agent_id_required"}), 400
|
||||
|
||||
try:
|
||||
tunnel_service = _get_tunnel_service(adapters)
|
||||
endpoint_host = _infer_endpoint_host(request)
|
||||
_service_log_event(
|
||||
"vpn_shell_establish_request agent_id={0} operator={1} endpoint_host={2} remote={3}".format(
|
||||
agent_id,
|
||||
operator_id or "-",
|
||||
endpoint_host or "-",
|
||||
_request_remote() or "-",
|
||||
)
|
||||
)
|
||||
payload = tunnel_service.connect(
|
||||
agent_id=agent_id,
|
||||
operator_id=operator_id,
|
||||
endpoint_host=endpoint_host,
|
||||
)
|
||||
except Exception as exc:
|
||||
_service_log_event(
|
||||
"vpn_shell_establish_failed agent_id={0} operator={1} error={2}".format(
|
||||
agent_id,
|
||||
operator_id or "-",
|
||||
str(exc),
|
||||
),
|
||||
level="ERROR",
|
||||
)
|
||||
return jsonify({"error": "establish_failed", "detail": str(exc)}), 500
|
||||
|
||||
agent_socket = False
|
||||
registry = getattr(adapters.context, "agent_socket_registry", None)
|
||||
if registry and hasattr(registry, "is_registered"):
|
||||
try:
|
||||
agent_socket = bool(registry.is_registered(agent_id))
|
||||
except Exception:
|
||||
agent_socket = False
|
||||
|
||||
response = dict(payload)
|
||||
response["status"] = "ok"
|
||||
response["agent_socket"] = agent_socket
|
||||
_service_log_event(
|
||||
"vpn_shell_establish_response agent_id={0} tunnel_id={1} agent_socket={2}".format(
|
||||
agent_id,
|
||||
response.get("tunnel_id", "-"),
|
||||
str(agent_socket).lower(),
|
||||
)
|
||||
)
|
||||
return jsonify(response), 200
|
||||
|
||||
@blueprint.route("/api/shell/disconnect", methods=["POST"])
|
||||
def shell_disconnect():
|
||||
requirement = _require_login(app)
|
||||
if requirement:
|
||||
payload, status = requirement
|
||||
return jsonify(payload), status
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
agent_id = _normalize_text(body.get("agent_id"))
|
||||
reason = _normalize_text(body.get("reason") or "operator_disconnect")
|
||||
operator_id = (_current_user(app) or {}).get("username") or None
|
||||
|
||||
if not agent_id:
|
||||
return jsonify({"error": "agent_id_required"}), 400
|
||||
if protocol != "rdp":
|
||||
return jsonify({"error": "unsupported_protocol"}), 400
|
||||
|
||||
tunnel_service = _get_tunnel_service(adapters)
|
||||
session_payload = tunnel_service.session_payload(agent_id, include_token=False)
|
||||
if not session_payload:
|
||||
return jsonify({"error": "tunnel_down"}), 409
|
||||
|
||||
allowed_ports = session_payload.get("allowed_ports") or []
|
||||
if 3389 not in allowed_ports:
|
||||
return jsonify({"error": "rdp_not_allowed"}), 403
|
||||
|
||||
virtual_ip = _normalize_text(session_payload.get("virtual_ip"))
|
||||
host = virtual_ip.split("/")[0] if virtual_ip else ""
|
||||
if not host:
|
||||
return jsonify({"error": "virtual_ip_missing"}), 500
|
||||
|
||||
registry = ensure_guacamole_proxy(adapters.context, logger=logger)
|
||||
if registry is None:
|
||||
return jsonify({"error": "rdp_proxy_unavailable"}), 503
|
||||
|
||||
_service_log_event(
|
||||
"rdp_session_request agent_id={0} operator={1} protocol={2} remote={3}".format(
|
||||
"vpn_shell_disconnect_request agent_id={0} operator={1} reason={2} remote={3}".format(
|
||||
agent_id,
|
||||
operator_id or "-",
|
||||
protocol,
|
||||
reason or "-",
|
||||
_request_remote() or "-",
|
||||
)
|
||||
)
|
||||
|
||||
rdp_session = registry.create(
|
||||
agent_id=agent_id,
|
||||
host=host,
|
||||
port=3389,
|
||||
username=username,
|
||||
password=password,
|
||||
protocol=protocol,
|
||||
operator_id=operator_id,
|
||||
ignore_cert=True,
|
||||
)
|
||||
|
||||
ws_scheme = "wss" if _is_secure(request) else "ws"
|
||||
ws_host = _infer_endpoint_host(request)
|
||||
ws_port = int(getattr(adapters.context, "rdp_ws_port", 4823))
|
||||
ws_url = f"{ws_scheme}://{ws_host}:{ws_port}{GUAC_WS_PATH}"
|
||||
|
||||
_service_log_event(
|
||||
"rdp_session_ready agent_id={0} token={1} expires_at={2}".format(
|
||||
agent_id,
|
||||
rdp_session.token[:8],
|
||||
int(rdp_session.expires_at),
|
||||
)
|
||||
)
|
||||
|
||||
return (
|
||||
jsonify(
|
||||
{
|
||||
"token": rdp_session.token,
|
||||
"ws_url": ws_url,
|
||||
"expires_at": int(rdp_session.expires_at),
|
||||
"virtual_ip": host,
|
||||
"tunnel_id": session_payload.get("tunnel_id"),
|
||||
}
|
||||
),
|
||||
200,
|
||||
)
|
||||
return jsonify({"status": "disconnected", "reason": reason}), 200
|
||||
|
||||
app.register_blueprint(blueprint)
|
||||
|
||||
|
||||
__all__ = ["register_shell"]
|
||||
@@ -1,12 +1,11 @@
|
||||
# ======================================================
|
||||
# Data\Engine\services\API\devices\tunnel.py
|
||||
# Description: WireGuard VPN tunnel API (connect/status/disconnect).
|
||||
# Description: WireGuard VPN tunnel API (connect/status).
|
||||
#
|
||||
# API Endpoints (if applicable):
|
||||
# - POST /api/tunnel/connect (Token Authenticated) - Issues VPN session material for an agent.
|
||||
# - GET /api/tunnel/status (Token Authenticated) - Returns VPN status for an agent.
|
||||
# - GET /api/tunnel/active (Token Authenticated) - Lists active VPN tunnel sessions.
|
||||
# - DELETE /api/tunnel/disconnect (Token Authenticated) - Tears down VPN session for an agent.
|
||||
# ======================================================
|
||||
|
||||
"""WireGuard VPN tunnel API (Engine side)."""
|
||||
@@ -254,52 +253,4 @@ def register_tunnel(app, adapters: "EngineServiceAdapters") -> None:
|
||||
)
|
||||
return jsonify({"count": len(sessions), "tunnels": sessions}), 200
|
||||
|
||||
@blueprint.route("/api/tunnel/disconnect", methods=["DELETE"])
|
||||
def disconnect_tunnel():
|
||||
requirement = _require_login(app)
|
||||
if requirement:
|
||||
payload, status = requirement
|
||||
return jsonify(payload), status
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
agent_id = _normalize_text(body.get("agent_id"))
|
||||
tunnel_id = _normalize_text(body.get("tunnel_id"))
|
||||
reason = _normalize_text(body.get("reason") or "operator_stop")
|
||||
|
||||
tunnel_service = _get_tunnel_service(adapters)
|
||||
_service_log_event(
|
||||
"vpn_api_disconnect_request agent_id={0} tunnel_id={1} reason={2} operator={3} remote={4}".format(
|
||||
agent_id or "-",
|
||||
tunnel_id or "-",
|
||||
reason or "-",
|
||||
(_current_user(app) or {}).get("username") or "-",
|
||||
_request_remote() or "-",
|
||||
)
|
||||
)
|
||||
stopped = False
|
||||
if tunnel_id:
|
||||
stopped = tunnel_service.disconnect_by_tunnel(tunnel_id, reason=reason)
|
||||
elif agent_id:
|
||||
stopped = tunnel_service.disconnect(agent_id, reason=reason)
|
||||
else:
|
||||
return jsonify({"error": "agent_id_required"}), 400
|
||||
|
||||
if not stopped:
|
||||
_service_log_event(
|
||||
"vpn_api_disconnect_not_found agent_id={0} tunnel_id={1}".format(
|
||||
agent_id or "-",
|
||||
tunnel_id or "-",
|
||||
),
|
||||
level="WARNING",
|
||||
)
|
||||
return jsonify({"error": "not_found"}), 404
|
||||
|
||||
_service_log_event(
|
||||
"vpn_api_disconnect_response agent_id={0} tunnel_id={1} status=stopped".format(
|
||||
agent_id or "-",
|
||||
tunnel_id or "-",
|
||||
)
|
||||
)
|
||||
return jsonify({"status": "stopped", "reason": reason}), 200
|
||||
|
||||
app.register_blueprint(blueprint)
|
||||
|
||||
338
Data/Engine/services/API/devices/vnc.py
Normal file
338
Data/Engine/services/API/devices/vnc.py
Normal file
@@ -0,0 +1,338 @@
|
||||
# ======================================================
|
||||
# Data\Engine\services\API\devices\vnc.py
|
||||
# Description: VNC session bootstrap for noVNC WebSocket tunnels.
|
||||
#
|
||||
# API Endpoints (if applicable):
|
||||
# - POST /api/vnc/establish (Token Authenticated) - Establish a VNC session for noVNC.
|
||||
# - POST /api/vnc/disconnect (Token Authenticated) - Disconnect the operator VNC session.
|
||||
# - POST /api/vnc/session (Token Authenticated) - Legacy alias for establish.
|
||||
# ======================================================
|
||||
|
||||
"""VNC session bootstrap endpoints for the Borealis Engine."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import secrets
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from flask import Blueprint, jsonify, request, session
|
||||
from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer
|
||||
|
||||
from ...RemoteDesktop.vnc_proxy import VNC_WS_PATH, ensure_vnc_proxy
|
||||
from .tunnel import _get_tunnel_service
|
||||
|
||||
if False: # pragma: no cover - hint for type checkers
|
||||
from .. import EngineServiceAdapters
|
||||
|
||||
|
||||
def _current_user(app) -> Optional[Dict[str, str]]:
|
||||
username = session.get("username")
|
||||
role = session.get("role") or "User"
|
||||
if username:
|
||||
return {"username": username, "role": role}
|
||||
|
||||
token = None
|
||||
auth_header = request.headers.get("Authorization") or ""
|
||||
if auth_header.lower().startswith("bearer "):
|
||||
token = auth_header.split(" ", 1)[1].strip()
|
||||
if not token:
|
||||
token = request.cookies.get("borealis_auth")
|
||||
if not token:
|
||||
return None
|
||||
|
||||
try:
|
||||
serializer = URLSafeTimedSerializer(app.secret_key or "borealis-dev-secret", salt="borealis-auth")
|
||||
token_ttl = int(os.environ.get("BOREALIS_TOKEN_TTL_SECONDS", 60 * 60 * 24 * 30))
|
||||
data = serializer.loads(token, max_age=token_ttl)
|
||||
username = data.get("u")
|
||||
role = data.get("r") or "User"
|
||||
if username:
|
||||
return {"username": username, "role": role}
|
||||
except (BadSignature, SignatureExpired, Exception):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _require_login(app) -> Optional[Tuple[Dict[str, Any], int]]:
|
||||
user = _current_user(app)
|
||||
if not user:
|
||||
return {"error": "unauthorized"}, 401
|
||||
return None
|
||||
|
||||
|
||||
def _normalize_text(value: Any) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
try:
|
||||
return str(value).strip()
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def _infer_endpoint_host(req) -> str:
|
||||
forwarded = (req.headers.get("X-Forwarded-Host") or req.headers.get("X-Original-Host") or "").strip()
|
||||
host = forwarded.split(",")[0].strip() if forwarded else (req.host or "").strip()
|
||||
if not host:
|
||||
return ""
|
||||
try:
|
||||
parsed = urlsplit(f"//{host}")
|
||||
if parsed.hostname:
|
||||
return parsed.hostname
|
||||
except Exception:
|
||||
return host
|
||||
return host
|
||||
|
||||
|
||||
def _is_secure(req) -> bool:
|
||||
if req.is_secure:
|
||||
return True
|
||||
forwarded = (req.headers.get("X-Forwarded-Proto") or "").split(",")[0].strip().lower()
|
||||
return forwarded == "https"
|
||||
|
||||
|
||||
def _generate_vnc_password() -> str:
|
||||
# UltraVNC uses the first 8 characters for VNC auth; keep the token to 8 for compatibility.
|
||||
return secrets.token_hex(4)
|
||||
|
||||
|
||||
def _load_vnc_password(adapters: "EngineServiceAdapters", agent_id: str) -> Optional[str]:
|
||||
conn = adapters.db_conn_factory()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"SELECT agent_vnc_password FROM devices WHERE agent_id=? ORDER BY last_seen DESC LIMIT 1",
|
||||
(agent_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row and row[0]:
|
||||
return str(row[0]).strip()
|
||||
except Exception:
|
||||
adapters.context.logger.debug("Failed to load agent VNC password", exc_info=True)
|
||||
finally:
|
||||
try:
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _store_vnc_password(adapters: "EngineServiceAdapters", agent_id: str, password: str) -> None:
|
||||
conn = adapters.db_conn_factory()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"UPDATE devices SET agent_vnc_password=? WHERE agent_id=?",
|
||||
(password, agent_id),
|
||||
)
|
||||
conn.commit()
|
||||
except Exception:
|
||||
adapters.context.logger.debug("Failed to store agent VNC password", exc_info=True)
|
||||
finally:
|
||||
try:
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def register_vnc(app, adapters: "EngineServiceAdapters") -> None:
|
||||
blueprint = Blueprint("vnc", __name__)
|
||||
logger = adapters.context.logger.getChild("vnc.api")
|
||||
service_log = adapters.service_log
|
||||
|
||||
def _service_log_event(message: str, *, level: str = "INFO") -> None:
|
||||
if not callable(service_log):
|
||||
return
|
||||
try:
|
||||
service_log("VNC", message, level=level)
|
||||
except Exception:
|
||||
logger.debug("vnc service log write failed", exc_info=True)
|
||||
|
||||
def _request_remote() -> str:
|
||||
forwarded = (request.headers.get("X-Forwarded-For") or "").strip()
|
||||
if forwarded:
|
||||
return forwarded.split(",")[0].strip()
|
||||
return (request.remote_addr or "").strip()
|
||||
|
||||
def _issue_session(agent_id: str, operator_id: Optional[str]) -> Tuple[Dict[str, Any], int]:
|
||||
tunnel_service = _get_tunnel_service(adapters)
|
||||
session_payload = tunnel_service.session_payload(agent_id, include_token=False)
|
||||
if not session_payload:
|
||||
try:
|
||||
session_payload = tunnel_service.connect(
|
||||
agent_id=agent_id,
|
||||
operator_id=operator_id,
|
||||
endpoint_host=_infer_endpoint_host(request),
|
||||
)
|
||||
except Exception:
|
||||
return {"error": "tunnel_down"}, 409
|
||||
|
||||
vnc_port = int(getattr(adapters.context, "vnc_port", 5900))
|
||||
raw_ports = session_payload.get("allowed_ports") or []
|
||||
allowed_ports = []
|
||||
for value in raw_ports:
|
||||
try:
|
||||
allowed_ports.append(int(value))
|
||||
except Exception:
|
||||
continue
|
||||
if vnc_port not in allowed_ports:
|
||||
return {"error": "vnc_not_allowed", "vnc_port": vnc_port}, 403
|
||||
|
||||
virtual_ip = _normalize_text(session_payload.get("virtual_ip"))
|
||||
host = virtual_ip.split("/")[0] if virtual_ip else ""
|
||||
if not host:
|
||||
return {"error": "virtual_ip_missing"}, 500
|
||||
|
||||
vnc_password = _load_vnc_password(adapters, agent_id)
|
||||
if not vnc_password:
|
||||
vnc_password = _generate_vnc_password()
|
||||
_store_vnc_password(adapters, agent_id, vnc_password)
|
||||
if len(vnc_password) > 8:
|
||||
vnc_password = vnc_password[:8]
|
||||
_store_vnc_password(adapters, agent_id, vnc_password)
|
||||
|
||||
registry = ensure_vnc_proxy(adapters.context, logger=logger)
|
||||
if registry is None:
|
||||
return {"error": "vnc_proxy_unavailable"}, 503
|
||||
|
||||
_service_log_event(
|
||||
"vnc_establish_request agent_id={0} operator={1} remote={2}".format(
|
||||
agent_id,
|
||||
operator_id or "-",
|
||||
_request_remote() or "-",
|
||||
)
|
||||
)
|
||||
|
||||
vnc_session = registry.create(
|
||||
agent_id=agent_id,
|
||||
host=host,
|
||||
port=vnc_port,
|
||||
operator_id=operator_id,
|
||||
)
|
||||
|
||||
emit_agent = getattr(adapters.context, "emit_agent_event", None)
|
||||
payload = {
|
||||
"agent_id": agent_id,
|
||||
"port": vnc_port,
|
||||
"allowed_ips": session_payload.get("allowed_ips"),
|
||||
"virtual_ip": host,
|
||||
"password": vnc_password,
|
||||
"reason": "vnc_session_start",
|
||||
}
|
||||
agent_socket_ready = True
|
||||
if callable(emit_agent):
|
||||
agent_socket_ready = bool(emit_agent(agent_id, "vnc_start", payload))
|
||||
if agent_socket_ready:
|
||||
_service_log_event(
|
||||
"vnc_start_emit agent_id={0} port={1} virtual_ip={2}".format(
|
||||
agent_id,
|
||||
vnc_port,
|
||||
host or "-",
|
||||
)
|
||||
)
|
||||
else:
|
||||
_service_log_event(
|
||||
"vnc_start_emit_failed agent_id={0} port={1}".format(
|
||||
agent_id,
|
||||
vnc_port,
|
||||
),
|
||||
level="WARNING",
|
||||
)
|
||||
if not agent_socket_ready:
|
||||
return {"error": "agent_socket_missing"}, 409
|
||||
|
||||
ws_scheme = "wss" if _is_secure(request) else "ws"
|
||||
ws_host = _infer_endpoint_host(request)
|
||||
ws_port = int(getattr(adapters.context, "vnc_ws_port", 4823))
|
||||
ws_url = f"{ws_scheme}://{ws_host}:{ws_port}{VNC_WS_PATH}"
|
||||
|
||||
_service_log_event(
|
||||
"vnc_session_ready agent_id={0} token={1} expires_at={2}".format(
|
||||
agent_id,
|
||||
vnc_session.token[:8],
|
||||
int(vnc_session.expires_at),
|
||||
)
|
||||
)
|
||||
|
||||
return (
|
||||
{
|
||||
"token": vnc_session.token,
|
||||
"ws_url": ws_url,
|
||||
"expires_at": int(vnc_session.expires_at),
|
||||
"virtual_ip": host,
|
||||
"tunnel_id": session_payload.get("tunnel_id"),
|
||||
"engine_virtual_ip": session_payload.get("engine_virtual_ip"),
|
||||
"allowed_ports": session_payload.get("allowed_ports"),
|
||||
"vnc_password": vnc_password,
|
||||
"vnc_port": vnc_port,
|
||||
},
|
||||
200,
|
||||
)
|
||||
|
||||
@blueprint.route("/api/vnc/establish", methods=["POST"])
|
||||
def vnc_establish():
|
||||
requirement = _require_login(app)
|
||||
if requirement:
|
||||
payload, status = requirement
|
||||
return jsonify(payload), status
|
||||
|
||||
user = _current_user(app) or {}
|
||||
operator_id = user.get("username") or None
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
agent_id = _normalize_text(body.get("agent_id"))
|
||||
|
||||
if not agent_id:
|
||||
return jsonify({"error": "agent_id_required"}), 400
|
||||
|
||||
payload, status = _issue_session(agent_id, operator_id)
|
||||
return jsonify(payload), status
|
||||
|
||||
@blueprint.route("/api/vnc/session", methods=["POST"])
|
||||
def vnc_session():
|
||||
return vnc_establish()
|
||||
|
||||
@blueprint.route("/api/vnc/disconnect", methods=["POST"])
|
||||
def vnc_disconnect():
|
||||
requirement = _require_login(app)
|
||||
if requirement:
|
||||
payload, status = requirement
|
||||
return jsonify(payload), status
|
||||
|
||||
user = _current_user(app) or {}
|
||||
operator_id = user.get("username") or None
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
agent_id = _normalize_text(body.get("agent_id"))
|
||||
reason = _normalize_text(body.get("reason") or "operator_disconnect")
|
||||
|
||||
if not agent_id:
|
||||
return jsonify({"error": "agent_id_required"}), 400
|
||||
|
||||
registry = ensure_vnc_proxy(adapters.context, logger=logger)
|
||||
revoked = 0
|
||||
if registry is not None:
|
||||
try:
|
||||
revoked = registry.revoke_agent(agent_id)
|
||||
except Exception:
|
||||
revoked = 0
|
||||
|
||||
emit_agent = getattr(adapters.context, "emit_agent_event", None)
|
||||
if callable(emit_agent):
|
||||
try:
|
||||
emit_agent(agent_id, "vnc_stop", {"agent_id": agent_id, "reason": reason})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
_service_log_event(
|
||||
"vnc_disconnect agent_id={0} operator={1} reason={2} revoked={3}".format(
|
||||
agent_id,
|
||||
operator_id or "-",
|
||||
reason or "-",
|
||||
revoked,
|
||||
)
|
||||
)
|
||||
|
||||
return jsonify({"status": "disconnected", "revoked": revoked, "reason": reason}), 200
|
||||
|
||||
app.register_blueprint(blueprint)
|
||||
Reference in New Issue
Block a user