You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/engine/virsh_panel/console.py

196 lines
7.1 KiB
Python

"""Relay a browser VNC WebSocket to a host-local VNC socket over SSH.
The caller authenticates and accepts the WebSocket, then obtains the VNC port
from libvirt. No VNC listener needs to be exposed outside the hypervisor.
"""
from __future__ import annotations
import asyncio
import os
import re
from typing import Any, Protocol
try:
from starlette.websockets import WebSocketDisconnect
except ImportError: # The relay can also be tested without the web framework.
class WebSocketDisconnect(Exception):
pass
_SSH_TARGET = re.compile(
r"(?:[A-Za-z_][A-Za-z0-9_.-]*@)?[A-Za-z0-9][A-Za-z0-9.-]*\Z"
)
_CHUNK_SIZE = 64 * 1024
_EXIT_TIMEOUT = 5.0
class ConsoleRelayError(Exception):
"""The SSH transport or VNC WebSocket could not be relayed."""
class ConsoleWebSocket(Protocol):
async def receive(self) -> dict[str, Any]: ...
async def send_bytes(self, data: bytes) -> None: ...
def _validate_connection(
port: int,
ssh_target: str,
ssh_binary: str,
known_hosts_file: str | None,
ssh_config_file: str | None,
) -> None:
if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
raise ValueError("VNC port must be an integer between 1 and 65535")
if not isinstance(ssh_target, str) or not _SSH_TARGET.fullmatch(ssh_target):
raise ValueError("SSH target must be a hostname or user@hostname")
if not isinstance(ssh_binary, str) or not ssh_binary or "\x00" in ssh_binary:
raise ValueError("SSH binary must be a non-empty executable name")
if known_hosts_file is not None and (
not isinstance(known_hosts_file, str)
or not os.path.isabs(known_hosts_file)
or any(char in known_hosts_file for char in "\r\n\x00")
):
raise ValueError("known_hosts_file must be an absolute path")
if ssh_config_file is not None and (
not isinstance(ssh_config_file, str)
or not os.path.isabs(ssh_config_file)
or any(char in ssh_config_file for char in "\r\n\x00")
):
raise ValueError("ssh_config_file must be an absolute path")
async def relay_console(
websocket: ConsoleWebSocket,
*,
port: int,
ssh_target: str,
ssh_binary: str = "ssh",
known_hosts_file: str | None = None,
ssh_config_file: str | None = None,
) -> None:
"""Bridge binary WebSocket frames to SSH's ``-W`` TCP forwarding stream.
``websocket`` must already be accepted. The target is deliberately limited
to a host or user@host so an untrusted value cannot become an SSH option or
a command. The VNC destination is always the hypervisor's loopback address.
"""
_validate_connection(port, ssh_target, ssh_binary, known_hosts_file, ssh_config_file)
command = [ssh_binary]
if ssh_config_file is not None:
command.extend(("-F", ssh_config_file))
command.extend([
"-T",
"-o",
"BatchMode=yes",
"-o",
"StrictHostKeyChecking=yes",
"-o",
"ServerAliveInterval=15",
"-o",
"ServerAliveCountMax=2",
])
if known_hosts_file is not None:
command.extend(("-o", f"UserKnownHostsFile={known_hosts_file}"))
command.extend(("-W", f"127.0.0.1:{port}", ssh_target))
try:
process = await asyncio.create_subprocess_exec(
*command,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.DEVNULL,
)
except OSError as exc:
raise ConsoleRelayError("Could not start the SSH client") from exc
assert process.stdin is not None
assert process.stdout is not None
async def browser_to_host() -> bool:
while True:
message = await websocket.receive()
message_type = message.get("type")
if message_type == "websocket.disconnect":
return False
if message_type != "websocket.receive":
raise ConsoleRelayError("Unexpected WebSocket message")
payload = message.get("bytes")
if not isinstance(payload, bytes):
raise ConsoleRelayError("VNC console requires binary WebSocket frames")
try:
process.stdin.write(payload)
await process.stdin.drain()
except (BrokenPipeError, ConnectionResetError):
return True
async def host_to_browser() -> bool:
while chunk := await process.stdout.read(_CHUNK_SIZE):
try:
await websocket.send_bytes(chunk)
except (OSError, RuntimeError, WebSocketDisconnect):
# ASGI servers may use either exception when the client closes.
return False
return True
upload = asyncio.create_task(browser_to_host())
download = asyncio.create_task(host_to_browser())
try:
done, _ = await asyncio.wait(
{upload, download}, return_when=asyncio.FIRST_COMPLETED
)
# Resolve exceptions before interpreting a concurrent disconnect.
for task in done:
task.result()
if any(task.result() is False for task in done):
return
if upload in done and download not in done:
# A broken SSH pipe can precede stdout EOF. Wait for the SSH
# process so an authentication/forwarding failure is reported.
try:
if await asyncio.wait_for(download, _EXIT_TIMEOUT) is False:
return
except asyncio.TimeoutError as exc:
raise ConsoleRelayError("SSH client did not close VNC") from exc
if download.done():
try:
returncode = await asyncio.wait_for(process.wait(), _EXIT_TIMEOUT)
except asyncio.TimeoutError as exc:
raise ConsoleRelayError("SSH client did not exit after closing VNC") from exc
if returncode != 0:
raise ConsoleRelayError(f"SSH client exited with status {returncode}")
finally:
for task in (upload, download):
if not task.done():
task.cancel()
await asyncio.gather(upload, download, return_exceptions=True)
process.stdin.close()
if process.returncode is None:
# Continue draining the pipe after the browser disconnects;
# otherwise a full stdout pipe can delay subprocess.wait().
async def discard_output() -> None:
while await process.stdout.read(_CHUNK_SIZE):
pass
discard = asyncio.create_task(discard_output())
try:
try:
process.terminate()
except ProcessLookupError:
pass
try:
await asyncio.wait_for(process.wait(), _EXIT_TIMEOUT)
except asyncio.TimeoutError:
if process.returncode is None:
try:
process.kill()
except ProcessLookupError:
pass
await process.wait()
finally:
discard.cancel()
await asyncio.gather(discard, return_exceptions=True)