authentik.providers.rac.guacamole

Helpers for parsing and filtering Guacamole WebSocket tunnel instructions.

  1"""Helpers for parsing and filtering Guacamole WebSocket tunnel instructions."""
  2
  3from typing import Never
  4
  5INSTRUCTION_MAX_LENGTH = 8192
  6INSTRUCTION_MAX_DIGITS = 5
  7INSTRUCTION_MAX_ELEMENTS = 64
  8PING_ELEMENT_COUNT = 3
  9MAX_BMP_CODEPOINT = 0xFFFF
 10
 11
 12class GuacamoleProtocolError(ValueError):
 13    """Raised when Guacamole protocol data is malformed."""
 14
 15
 16class GuacamoleInstructionParser:
 17    """Incrementally split a Guacamole stream into complete instructions."""
 18
 19    def __init__(self):
 20        self._buffer = ""
 21
 22    def feed(self, data: str) -> list[tuple[str, list[str]]]:
 23        """Return the instructions completed by `data`, buffering any partial tail."""
 24        instructions, self._buffer = self._parse(self._buffer + data)
 25        return instructions
 26
 27    def _parse(self, buffer: str) -> tuple[list[tuple[str, list[str]]], str]:
 28        """Parse guacamole instruction(s) into a list of
 29        [
 30            (op code, [*args]),
 31            [...]
 32        ]
 33        """
 34        instructions: list[tuple[str, list[str]]] = []
 35        elements: list[str] = []
 36        instruction_start = 0
 37        position = 0
 38
 39        while position < len(buffer):
 40            length_end = buffer.find(".", position)
 41            if length_end == -1:
 42                # Partial length prefix, validate what we have and wait for more.
 43                self._check_length_prefix(buffer[position:])
 44                break
 45
 46            prefix = buffer[position:length_end]
 47            self._check_length_prefix(prefix)
 48            element_length = int(prefix)
 49            if element_length > INSTRUCTION_MAX_LENGTH:
 50                self._fail("Guacamole element exceeds maximum length")
 51
 52            content_start = length_end + 1
 53            content_end = self._content_end(buffer, content_start, element_length)
 54            if content_end is None or content_end >= len(buffer):
 55                break
 56
 57            terminator = buffer[content_end]
 58            if terminator not in (",", ";"):
 59                self._fail("Invalid Guacamole element terminator")
 60
 61            elements.append(buffer[content_start:content_end])
 62            if len(elements) > INSTRUCTION_MAX_ELEMENTS:
 63                self._fail("Guacamole instruction contains too many elements")
 64
 65            position = content_end + 1
 66            if self._wire_length(buffer[instruction_start:position]) > INSTRUCTION_MAX_LENGTH:
 67                self._fail("Guacamole instruction exceeds maximum length")
 68
 69            if terminator == ";":
 70                instructions.append((buffer[instruction_start:position], elements))
 71                elements = []
 72                instruction_start = position
 73
 74        if self._wire_length(buffer[instruction_start:]) > INSTRUCTION_MAX_LENGTH:
 75            self._fail("Guacamole instruction exceeds maximum length")
 76        return instructions, buffer[instruction_start:]
 77
 78    def _content_end(self, buffer: str, content_start: int, element_length: int) -> int | None:
 79        """Return the index just past an element of `element_length` UTF-16 code units."""
 80        content_end = content_start
 81        code_units = 0
 82        while content_end < len(buffer) and code_units < element_length:
 83            code_units += 2 if ord(buffer[content_end]) > MAX_BMP_CODEPOINT else 1
 84            content_end += 1
 85        if code_units > element_length:
 86            self._fail("Guacamole element length splits a UTF-16 character")
 87        return content_end if code_units == element_length else None
 88
 89    def _wire_length(self, data: str) -> int:
 90        """Return the length Guacamole uses for a payload, in UTF-16 code units."""
 91        return sum(2 if ord(character) > MAX_BMP_CODEPOINT else 1 for character in data)
 92
 93    def _check_length_prefix(self, prefix: str) -> None:
 94        if (
 95            not prefix
 96            or len(prefix) > INSTRUCTION_MAX_DIGITS
 97            or not (prefix.isascii() and prefix.isdigit())
 98        ):
 99            self._fail("Invalid Guacamole element length")
100
101    def _fail(self, message: str) -> Never:
102        self._buffer = ""
103        raise GuacamoleProtocolError(message)
104
105    def split_internal(self, instructions: list[tuple[str, list[str]]]) -> tuple[list[str], str]:
106        """Split parsed instructions into tunnel ping responses and data to forward to guacd."""
107        responses: list[str] = []
108        forwarded: list[str] = []
109        for raw, elements in instructions:
110            if elements[0]:
111                forwarded.append(raw)
112                continue
113            # Instructions with an empty opcode are internal to the tunnel and hidden from
114            # guacd; Guacamole.WebSocketTunnel pings are answered by the tunnel endpoint.
115            if len(elements) >= PING_ELEMENT_COUNT and elements[1] == "ping":
116                responses.append(raw)
117        return responses, "".join(forwarded)
INSTRUCTION_MAX_LENGTH = 8192
INSTRUCTION_MAX_DIGITS = 5
INSTRUCTION_MAX_ELEMENTS = 64
PING_ELEMENT_COUNT = 3
MAX_BMP_CODEPOINT = 65535
class GuacamoleProtocolError(builtins.ValueError):
13class GuacamoleProtocolError(ValueError):
14    """Raised when Guacamole protocol data is malformed."""

Raised when Guacamole protocol data is malformed.

class GuacamoleInstructionParser:
 17class GuacamoleInstructionParser:
 18    """Incrementally split a Guacamole stream into complete instructions."""
 19
 20    def __init__(self):
 21        self._buffer = ""
 22
 23    def feed(self, data: str) -> list[tuple[str, list[str]]]:
 24        """Return the instructions completed by `data`, buffering any partial tail."""
 25        instructions, self._buffer = self._parse(self._buffer + data)
 26        return instructions
 27
 28    def _parse(self, buffer: str) -> tuple[list[tuple[str, list[str]]], str]:
 29        """Parse guacamole instruction(s) into a list of
 30        [
 31            (op code, [*args]),
 32            [...]
 33        ]
 34        """
 35        instructions: list[tuple[str, list[str]]] = []
 36        elements: list[str] = []
 37        instruction_start = 0
 38        position = 0
 39
 40        while position < len(buffer):
 41            length_end = buffer.find(".", position)
 42            if length_end == -1:
 43                # Partial length prefix, validate what we have and wait for more.
 44                self._check_length_prefix(buffer[position:])
 45                break
 46
 47            prefix = buffer[position:length_end]
 48            self._check_length_prefix(prefix)
 49            element_length = int(prefix)
 50            if element_length > INSTRUCTION_MAX_LENGTH:
 51                self._fail("Guacamole element exceeds maximum length")
 52
 53            content_start = length_end + 1
 54            content_end = self._content_end(buffer, content_start, element_length)
 55            if content_end is None or content_end >= len(buffer):
 56                break
 57
 58            terminator = buffer[content_end]
 59            if terminator not in (",", ";"):
 60                self._fail("Invalid Guacamole element terminator")
 61
 62            elements.append(buffer[content_start:content_end])
 63            if len(elements) > INSTRUCTION_MAX_ELEMENTS:
 64                self._fail("Guacamole instruction contains too many elements")
 65
 66            position = content_end + 1
 67            if self._wire_length(buffer[instruction_start:position]) > INSTRUCTION_MAX_LENGTH:
 68                self._fail("Guacamole instruction exceeds maximum length")
 69
 70            if terminator == ";":
 71                instructions.append((buffer[instruction_start:position], elements))
 72                elements = []
 73                instruction_start = position
 74
 75        if self._wire_length(buffer[instruction_start:]) > INSTRUCTION_MAX_LENGTH:
 76            self._fail("Guacamole instruction exceeds maximum length")
 77        return instructions, buffer[instruction_start:]
 78
 79    def _content_end(self, buffer: str, content_start: int, element_length: int) -> int | None:
 80        """Return the index just past an element of `element_length` UTF-16 code units."""
 81        content_end = content_start
 82        code_units = 0
 83        while content_end < len(buffer) and code_units < element_length:
 84            code_units += 2 if ord(buffer[content_end]) > MAX_BMP_CODEPOINT else 1
 85            content_end += 1
 86        if code_units > element_length:
 87            self._fail("Guacamole element length splits a UTF-16 character")
 88        return content_end if code_units == element_length else None
 89
 90    def _wire_length(self, data: str) -> int:
 91        """Return the length Guacamole uses for a payload, in UTF-16 code units."""
 92        return sum(2 if ord(character) > MAX_BMP_CODEPOINT else 1 for character in data)
 93
 94    def _check_length_prefix(self, prefix: str) -> None:
 95        if (
 96            not prefix
 97            or len(prefix) > INSTRUCTION_MAX_DIGITS
 98            or not (prefix.isascii() and prefix.isdigit())
 99        ):
100            self._fail("Invalid Guacamole element length")
101
102    def _fail(self, message: str) -> Never:
103        self._buffer = ""
104        raise GuacamoleProtocolError(message)
105
106    def split_internal(self, instructions: list[tuple[str, list[str]]]) -> tuple[list[str], str]:
107        """Split parsed instructions into tunnel ping responses and data to forward to guacd."""
108        responses: list[str] = []
109        forwarded: list[str] = []
110        for raw, elements in instructions:
111            if elements[0]:
112                forwarded.append(raw)
113                continue
114            # Instructions with an empty opcode are internal to the tunnel and hidden from
115            # guacd; Guacamole.WebSocketTunnel pings are answered by the tunnel endpoint.
116            if len(elements) >= PING_ELEMENT_COUNT and elements[1] == "ping":
117                responses.append(raw)
118        return responses, "".join(forwarded)

Incrementally split a Guacamole stream into complete instructions.

def feed(self, data: str) -> list[tuple[str, list[str]]]:
23    def feed(self, data: str) -> list[tuple[str, list[str]]]:
24        """Return the instructions completed by `data`, buffering any partial tail."""
25        instructions, self._buffer = self._parse(self._buffer + data)
26        return instructions

Return the instructions completed by data, buffering any partial tail.

def split_internal(self, instructions: list[tuple[str, list[str]]]) -> tuple[list[str], str]:
106    def split_internal(self, instructions: list[tuple[str, list[str]]]) -> tuple[list[str], str]:
107        """Split parsed instructions into tunnel ping responses and data to forward to guacd."""
108        responses: list[str] = []
109        forwarded: list[str] = []
110        for raw, elements in instructions:
111            if elements[0]:
112                forwarded.append(raw)
113                continue
114            # Instructions with an empty opcode are internal to the tunnel and hidden from
115            # guacd; Guacamole.WebSocketTunnel pings are answered by the tunnel endpoint.
116            if len(elements) >= PING_ELEMENT_COUNT and elements[1] == "ping":
117                responses.append(raw)
118        return responses, "".join(forwarded)

Split parsed instructions into tunnel ping responses and data to forward to guacd.