From: Arne Schwabe <[email protected]> Change-Id: Ib09bafabf612e9501ea757647c86a450c73228a5 Signed-off-by: Arne Schwabe <[email protected]> Acked-by: Mateusz Mazurek <Mateusz Mazurek> Gerrit URL: https://gerrit.openvpn.net/c/openvpn/+/1859 ---
This change was reviewed on Gerrit and approved by at least one developer. I request to merge it to master. Gerrit URL: https://gerrit.openvpn.net/c/openvpn/+/1859 This mail reflects revision 12 of this Change. Acked-by according to Gerrit (reflected above): Mateusz Mazurek <Mateusz Mazurek> diff --git a/sample/Makefile.am b/sample/Makefile.am index f3528ba..28574d9 100644 --- a/sample/Makefile.am +++ b/sample/Makefile.am @@ -16,6 +16,7 @@ $(builddir)/sample-plugins/Makefile EXTRA_DIST = \ + management \ sample-plugins \ sample-config-files \ sample-keys \ diff --git a/sample/management/omi.py b/sample/management/omi.py new file mode 100644 index 0000000..75eeece --- /dev/null +++ b/sample/management/omi.py @@ -0,0 +1,364 @@ +# Copyright (c) 2026 OpenVPN Inc <[email protected]> +# Copyright (c) 2026 Arne Schwabe <[email protected]> +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +# This is an example implementation in python and asyncio to drive OpenVPN's +# management interface (OMI). The permissive license allows you to use this +# code in other projects. + +""" +Implementation of the OpenVPN management interface (OMI) protocol. + +This implements the generic part of the OMI protocol that is common +to both client and server. +""" +import asyncio +import inspect +import logging +import re +from asyncio import Future, Event, Task, Queue +from dataclasses import dataclass +from datetime import datetime +from functools import partial +from typing import override, List, Optional, Awaitable, Coroutine + +OMI_PASSWORD_PROMPT = b"ENTER PASSWORD:" + +logger = logging.getLogger(__name__) + +@dataclass +class OmiCommandResult: + command: str + result: List[str] + error: bool + status_text: str + + +@dataclass +class OmiSendCommand: + command: str + result: Future[OmiCommandResult] + + +@dataclass +class ConnectionProperties: + """ + Properties for connecting to the management interface. + """ + password: Optional[str] + + +class OmiProtocol(asyncio.Protocol): + def __init__(self, finish_future: Future, connect_data: ConnectionProperties): + super().__init__() + self._connect_data: ConnectionProperties = connect_data + + self.bytes_received: int = 0 + self.bytes_sent: int = 0 + self.version: int = -1 + self.recv_buffer: bytes = b"" + self.finish_future: Future = finish_future + self.transport: Optional[asyncio.Transport] = None + + # Event to allow waiting for status of the underlying socket + # to become available for writing + self._can_send: Event = asyncio.Event() + self._can_send.clear() + + # Event to track when the management interface is ready to receive + # commands from us + self._management_ready: Event = asyncio.Event() + self._management_ready.clear() + self._response = [] + + self._response_ready: Event = asyncio.Event() + self._response_ready.clear() + + self._send_queue: Queue = asyncio.Queue() + self._send_task: Task = asyncio.create_task(self._send_loop()) + + self.running_tasks = set() + + + @override + def eof_received(self) -> None: + logger.info('EOF received. Shutting down.') + self._stop() + + @override + def connection_lost(self, exc: Exception | None) -> None: + if exc: + logger.warning(f'Connection lost ({exc}). Shutting down.') + else: + logger.warning(f'Connection lost. Shutting down.') + self._stop() + + def _stop(self) -> None: + if not self.finish_future.done(): + # If we are disconnected or stop, there is no sense trying + # to still send commands to the management interface + self._send_task.cancel() + self.finish_future.set_result(True) + + async def _send_loop(self) -> None: + while True: + command: OmiSendCommand = await self._send_queue.get() + await self._can_send.wait() + self.send_line(command.command) + + response: List[str] = [] + response_complete = False + + # This is a bit brittle as it will loop forever if not getting a + # line that starts with ERROR or SUCCESS. With a normal OpenVPN + # daemon that speak the correct protocol this should not be a + # problem + while not response_complete: + await self._response_ready.wait() + + line = self._response.pop(0) + response.append(line) + + if not self._response: + self._response_ready.clear() + + lastline = response[-1] + if lastline.startswith('ERROR: '): + error = True + response_complete = True + _, status_text = lastline.split(": ", 1) + + elif lastline.startswith('SUCCESS: '): + error = False + response_complete = True + _, status_text = lastline.split(": ", 1) + elif lastline == "END": + error = False + response_complete = True + status_text = None + else: + # Other lines do not complete a response + pass + + # logger.debug(f'Result received command: {response}') + result = OmiCommandResult(command.command, response[:-1], error, status_text) + + if not command.result.cancelled(): + command.result.set_result(result) + + logger.debug(f"Command done.") + + @override + def pause_writing(self) -> None: + self._can_send.clear() + + @override + def resume_writing(self) -> None: + self._can_send.set() + + @override + def connection_made(self, transport) -> None: + peername = transport.get_extra_info('peername') + logger.info('Connection from {}'.format(peername)) + self.transport = transport + self._can_send.set() + + def _check_pw_response(self, fut: Future[OmiCommandResult]) -> None: + if fut.exception(): + logger.error(f"Error authenticating with password: {fut.exception()}") + self.transport.close() + return + + result = fut.result() + + if result.error or result.status_text != "password is correct": + logger.error(f"Received unexpected status after trying to authenticate: {result.status_text!r}") + self.transport.close() + return + + def handle_password_prompt(self) -> None: + # OMI expects us to authenticate with the password just on + # its own on a line + if self._connect_data.password: + fut = self.queue_command(f"{self._connect_data.password}") + fut.add_done_callback(self._check_pw_response) + else: + logger.error("No password provided for authentication") + self.transport.close() + + @override + def data_received(self, data: bytes) -> None: + # OMI protocol is pure text so decode everything as UTF-8 + message = data + self.recv_buffer += message + + # Management protocol does not add a newline after the password prompt + if not self._management_ready.is_set() and self.recv_buffer.startswith(OMI_PASSWORD_PROMPT): + logger.debug(f"Received password prompt") + self.recv_buffer = self.recv_buffer[len(OMI_PASSWORD_PROMPT) + 1:] + self.handle_password_prompt() + return + + parts = self.recv_buffer.split(b"\r\n") + + # pass complete lines to recvLine + for part in parts[:-1]: + part = part.decode() + logger.debug(f'Line received: {part!r}') + self.recv_line(part) + + # keep the last incomplete line for the next call + self.recv_buffer = parts[-1] + + def recv_line(self, line: str) -> None: + if line.startswith(">"): + # this is an asynchronous message + self.recv_notify(line) + else: + # normal message get passed to the _send_loop task + self._response.append(line) + self._response_ready.set() + + def recv_notify(self, line: str) -> None: + if not ":" in line: + logger.warning("Invalid line received: " + line) + return + + command, args = line[1:].split(":", 1) + + # do dynamic dispatch based on command to call a handler + if not self.dispatch_to_handler(f"recv_notify_{command}", args): + logger.info("Unknown notify line received: " + line) + + + + + + def dispatch_to_handler(self, handlername:str, *args, **kwargs): + """ + Looks up if this class or a subclass has a handler for the given + command and either directly calls it or schedules it as a coroutine. + :return: true if a handler was found and called + """ + if hasattr(self, handlername): + handler = getattr(self, handlername) + if inspect.iscoroutinefunction(handler): + logger.debug(f"Calling async handler {handler}") + task = self.add_background_task(handler(*args, **kwargs), handlername) + else: + try: + logger.debug(f"Calling handler {handler}") + handler(*args, **kwargs) + except Exception as e: + logger.error(f"Error executing handler {handlername}: {e}", exc_info=True) + + return True + else: + return False + + def _background_task_done(self, handler_name:str, task: Task): + self.running_tasks.remove(task) + if task.exception(): + logger.error(f"Error executing background task {handler_name}: {task.exception()}") + + def add_background_task(self, func:Coroutine, name:Optional[str]=None) -> Task: + """ + Schedules an async task to run in the background and keep a + reference to the task so it will not be garbage collected. + """ + task = asyncio.create_task(func) + self.running_tasks.add(task) + + if not name: + name = repr(func) + + task.add_done_callback(partial(self._background_task_done, name)) + return task + + + def recv_notify_INFO(self, args: str) -> None: + m = re.match(r"OpenVPN Management Interface Version (?P<version>\d+)", args) + if m: + self.version = int(m.group("version")) + self.queue_command("version 6") + self._management_ready.set() + else: + logger.warning(f"Unknown INFO line received: {args}") + + def recv_notify_BYTECOUNT(self, args: str) -> None: + bytes_received, bytes_sent = args.split(",", 1) + self.bytes_sent = int(bytes_sent) + self.bytes_received = int(bytes_received) + + async def _release_hold_task(self, hold_time: int = 0) -> None: + await asyncio.sleep(hold_time) + await self.queue_command("hold release") + + def recv_notify_HOLD(self, args): + _text, hold_time = args.split(":", 1) + hold_time = int(hold_time) + + self.add_background_task(self._release_hold_task(hold_time)) + + def queue_command(self, command: str) -> Future[OmiCommandResult]: + cmd = OmiSendCommand(command, Future()) + self._send_queue.put_nowait(cmd) + return cmd.result + + async def management_ready(self) -> int: + """ + Waits until the management interface is ready. Returns the management interface version. + """ + await self._management_ready.wait() + return self.version + + def send_line(self, line: str) -> None: + logger.debug(f"Sending line: {line}") + self.transport.write(f"{line}\n".encode()) + + """ + Set the bytecount interval. Use 0 to disable + """ + + async def set_bytecount_interval(self, interval: int): + return await self.queue_command(f"bytecount {interval}") + + async def enable_log(self): + return await self.queue_command("log on") + + def recv_notify_LOG(self, args): + # >LOG:1786453401,D,MANAGEMENT: CMD 'bytecount 30' + timestamp, level, message = args.split(",", 2) + + timestamp = datetime.fromtimestamp(int(timestamp)) + level = level.strip() + message = message.strip() + self.log_message(timestamp, level, message) + + def log_message(self, time:datetime, level:str, message:str): + """ + A new log message has been received. This method is intended + to be overridden by a subclass to handle the log messages. + :param time: time in local time format + :param level: level of the log message + :param message: the log message itself + :return: + """ + logger.debug(f"Received log message: {time}, {level}, {message}") diff --git a/sample/management/omi_client_protocol.py b/sample/management/omi_client_protocol.py new file mode 100644 index 0000000..75a31d5 --- /dev/null +++ b/sample/management/omi_client_protocol.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 OpenVPN Inc <[email protected]> +# Copyright (c) 2026 Arne Schwabe <[email protected]> +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +import asyncio +import base64 +import logging +from asyncio import Future +from typing import Tuple + +from omi import OmiProtocol, OmiCommandResult, ConnectionProperties + +logger = logging.getLogger(__name__) + + +class OMIClientProtocol(OmiProtocol): + """ + Implement the management protocol for the client + """ + + def __init__(self, finish_future: Future, connect_data: ConnectionProperties): + super().__init__(finish_future=finish_future, connect_data=connect_data) + self._partial_acc_msg = b"" + self._protocol_acc_msg = "" + self._acc_fragment_length = 980 + self._acc_negotiated_protocols = [] + + async def send_acc_msg(self, protocol: str, msg: bytes): + """ + Sends out an ACC to the server using the specified ACC message length + :param protocol: + :param msg: + :param fragment_length: + :return: + """ + if protocol not in self._acc_negotiated_protocols: + logger.error(f"Error: trying to send ACC message with protocol " + f"{protocol} is not in the negotiated list of " + f"protocols ({self._acc_negotiated_protocols})") + return + + # See init.c for the explanation for the length calculation + max_header_size = len("ACC,") + len(protocol) + 1 + 4 + 1 + 2 + 1 + + # calculate fragment size with base64 encoding + fragment_length = self._acc_fragment_length * 6 // 8 - max_header_size + + commands = [] + for part_start in range(0, len(msg), fragment_length): + + msg_part = msg[part_start:part_start + fragment_length] + # This creates a multiline base64 message but that is what + # we want for the management interface to have a not overlong + # lines + b64msg = base64.encodebytes(msg_part).decode() + + flags = "6" + if part_start + fragment_length < len(msg): + flags += "F" + + commands.append(f"acc-msg\n{protocol}\n{flags}\n{b64msg}\nEND") + + cmd_futures = [] + for command in commands: + cmd_futures.append(self.queue_command(command)) + + cmd_results: Tuple[OmiCommandResult] = await asyncio.gather(*cmd_futures) + + for cmd_result in cmd_results: + if cmd_result.error: + logger.error(f"Error: sending ACC message failed: {cmd_result}") + + def recv_notify_ACC_PROTOCOLS(self, args: str): + params = args.split(",") + acc_params = {} + + for p in params: + k, v = p.split("=", 1) + acc_params[k.strip()] = v.strip() + + self._acc_negotiated_protocols = acc_params['protocols'].split(":") + + self._acc_fragment_length = int(acc_params['message_len']) + + def recv_notify_ACC(self, args: str): + protocol, fragment, b64msg = args.split(",", 2) + + if self._partial_acc_msg and self._protocol_acc_msg != protocol: + logger.error(f"Received ACC message with protocol {protocol} before " + f"previous ACC message with protocol {self._protocol_acc_msg} was complete") + self._partial_acc_msg = b"" + + try: + msg = base64.decodebytes(b64msg.encode()) + self._partial_acc_msg += msg + self._protocol_acc_msg = protocol + except Exception as e: + logger.error(f"Error parsing ACC message: {e}", exc_info=True) + self._partial_acc_msg = b"" + return + + fragmented = fragment != "0" + logger.debug( + f"Received ACC message (fragment {fragmented}, protocol {protocol!r}), with payload {msg.decode()!r}") + + # Message is not yet complete. Wait for more fragments. + if fragmented: + return + + if not self.dispatch_to_handler(f"receive_acc_{protocol}", self._partial_acc_msg): + logger.info(f"Received unhandled ACC protocol: {protocol}") + + self._partial_acc_msg = b"" + self._protocol_acc_msg = "" diff --git a/sample/management/omi_server_demo.py b/sample/management/omi_server_demo.py new file mode 100755 index 0000000..c0fd4f5 --- /dev/null +++ b/sample/management/omi_server_demo.py @@ -0,0 +1,305 @@ +#! /usr/bin/env python3 +# Copyright (c) 2026 OpenVPN Inc <[email protected]> +# Copyright (c) 2026 Arne Schwabe <[email protected]> +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +import asyncio +import logging +from asyncio import Future +from base64 import standard_b64decode +from dataclasses import field, dataclass +from typing import Dict, Optional + +from omi_server_protocol import OMIServerProtocol, ConnectedClient +from omi_tools import run_main, start_management_protocol, ConnectData +from omi_tools import openvpn_escape + +# This implement a small demonstration of using the +# OpenVPN Access Server Management Interface (OMI) +# and a script that does various action on the client depending +# on the username the user connects with +# ensure that you have a proper certificate based authentication setup +# before using this script +# (e.g. https://github.com/openvpn/openvpn/blob/master/doc/man-sections/example-fingerprint.rst) + +# usage: +# --management /path/to/omi_server_demo.py unix-script + +# The main purpose of this script is to test/force certain client/server +# behaviour. As a test script this is done on the username but also serves +# as an example how to implement something similar for normal usage. +# +# if a username is prefixed with url it uses the old OPEN_URL method (e.g. urlrick) +# +# - fail: sends AUTH_FAILED +# - failn: sends AUTH_FAILED wiht \n +# - failtemp: sends AUTH_FAILED,TEMP:Go away for a while +# - failtemp42: sends AUTH_FAILED,TEMP and backoff for 42s +# - failtempnr: sends AUTH_FAILED,TEMP and instructs to go the next remote +# - success: sends AUTH_SUCCESS +# - faildelay: sends AUTH_FAILED after 20s +# - successdelay: sends AUTH_SUCCESS after 20s +# - rick: sends you to a certain youtube site and auth you +# - openvpn: sends you to community.openvpn.net +# - totp: Does crtext based 2FA with secret "totpinsecuretotp" +# - google: sends you to https://www.google.com/search?q=hidden without any flags +# - googleext: sends you to https://www.google.com/search?q=external with external flags and WEBAUTH \ +# - dnssec: send only dnssec servers +# - nodns: no dns servers +# - dnssecfb: dns server with fallback to dns without dnnsec +# - dnsdhcp: dns options and dhcp_options +# - dnsport: dns server with custom port +# - failaccdpc1: auth failed message indicating that the client is missing dpc1 ACC support. +# - failaccdpc1user: auth failed message indicating that the client is missing dpc1 ACC support indicating a auth-token and user for reconnecting +# - failaccflower: auth failed message indicating that the client is missing flower and power ACC support. +# - default: push DNS 8.8.8.8 and default route +# - notify: Gives the client a message to display to the user via notify protocol + +# The hard-coded secret +totp_secret = "totpinsecuretotp" + +logging.basicConfig() +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +try: + import pyotp +except ImportError: + logger.info("pyotp module not found. TOTP testing disabled") + + +@dataclass +class ServerDemoConnectedClient(ConnectedClient): + # Remember the key-id that we authenticated + authenticated_kid: int = -1 + env: Dict[str, str] = field(default_factory=dict) + + +class ServerDemoProtocol(OMIServerProtocol): + def __init__(self, finish_future: Future, connect_data: ConnectData = None): + super().__init__(finish_future, connect_data) + self._connected_client_class = ServerDemoConnectedClient + + def client_event_ESTABLISHED(self, client: ServerDemoConnectedClient, kid: int, env: Dict, extra: str): + print(f"CLient connected: {client}") + + def client_event_CONNECT(self, client: ServerDemoConnectedClient, kid: int, env: Dict, extra: str) -> None: + print(f"Authenticating client {client.cid}, {kid}") + client.authenticated_kid = kid + client.env = env + + self.add_background_task(self.do_client_auth(client, kid)) + + def client_event_REAUTH(self, client: ServerDemoConnectedClient, kid: int, env: dict, extra: str): + print(f"Re-authenticating client {client}, {kid}") + client.env = env + _ = self.queue_command(f"client-auth-nt {client.cid} {kid}") + + + async def deny_client(self, client: ServerDemoConnectedClient, kid: int, reason: str, + client_reason: Optional[str] = None) -> None: + # Note, for this test script sending your real reason if you do not + # specify a client reason is okay. In a real environment, this kind + # of information is potentially bad + + if not client_reason: + client_reason = reason + client_deny = f'client-deny {client.cid} {kid} "{openvpn_escape(reason)}" "{openvpn_escape(client_reason)}"' + await self.queue_command(client_deny) + + async def do_client_auth(self, client: ServerDemoConnectedClient, kid: int) -> None: + username = client.env.get("username", "(empty username)") + + # success + if username.startswith("url"): + username = username[3:] + method = "openurl" + webauth = "OPEN_URL:" + else: + method = "webauth" + webauth = "WEB_AUTH::" + + if username == 'fail' or 'UV_FAIL' in client.env: + await self.deny_client(client, kid, "fail") + elif username == 'failtemp': + await self.deny_client(client, kid, "TEMP:Go away for a while") + elif username == 'failn': + await self.deny_client(client, kid, "Bonus new line for you!\n") + elif username == 'failn2': + await self.deny_client(client, kid, "Bonus new line for you!\nand another one\n") + elif username == 'failtemp42': + await self.deny_client(client, kid, "TEMP[backoff 42]:Go away for a 42s") + elif username == 'failtempnr': + await self.deny_client(client, kid, "TEMP[backoff 11,advance remote]:Annoy the next server!") + elif username == 'failaccdpc1': + await self.deny_client(client, kid, + "ACC[protocol dpc1]: To connect to this server you need to upgrade to a client that supports the OpenVPN Inc device posture protocol, e.g. OpenVPN Connect version 1.2.3 or later") + elif username == 'failaccflower': + await self.deny_client(client, kid, "ACC[protocol flower power]: You need to embrace the flower power") + elif username == 'failaccdpc1user': + await self.deny_client(client, kid, + "ACC[protocol flower power, user c3VjY2Vzcw==, pass MTIzNDU2Nzg=]: Please come back again after you enabled dpc1") + elif username == 'success': + await self.send_client_auth(client, kid) + elif username == 'faildelay': + await asyncio.sleep(20) + await self.deny_client(client, kid, "I thought 20s about it and rejected you after that time") + elif username == 'successdelay': + await asyncio.sleep(20) + await self.send_client_auth(client, kid) + elif username.startswith('totp'): + timeout = 90 + extra = f"CR_TEXT:E,R:Please enter your TOTP code, {username}!" + logger.info(f"The TOTP the client needs to provide is: {self.get_current_totp_code()}") + await self.send_pending_auth(client, kid, extra, timeout) + elif username == 'rick': + await asyncio.sleep(3) + await self.send_pending_auth(client, kid, webauth + "https://www.youtube.com/watch?v=dQw4w9WgXcQ") + await asyncio.sleep(10) + await self.deny_client(client, kid, "I got you") + elif username == 'openvpn': + await self.send_pending_auth(client, kid, webauth + "https://community.openvpn.net") + await self.send_client_auth(client, kid) + elif username == 'googleext': + await self.send_pending_auth(client, kid, "WEB_AUTH:external:https://www.google.com/search?q=external") + await asyncio.sleep(10) + await self.send_client_auth(client, kid) + elif username == 'google': + await self.send_pending_auth(client, kid, "WEB_AUTH::https://www.google.com/search?q=external") + await asyncio.sleep(10) + await self.send_client_auth(client, kid) + elif username == 'special': + extra = f"CR_TEXT:E:This special username is known, doing nothing, really" + await self.send_pending_auth(client, kid, extra) + elif username in ['dnssec', 'nodns', 'dnssecfb', 'dnsdhcp', 'dnsport', 'default']: + await asyncio.sleep(1) + await self.send_client_auth(client, kid) + elif username == "notify": + await self.send_pending_auth(client, kid, + "NOTIFY::Please wait for 23s to let the server think if it want to admit you") + await asyncio.sleep(23) + await self.send_client_auth(client, kid) + else: + await self.deny_client(client, kid, + f"The username you used ({username}) is unknown, please pick one that I know") + + async def send_client_auth(self, client: ServerDemoConnectedClient, kid: int) -> None: + username = client.env.get("username", "(empty username)") + + config = "" + if username == 'dnssec': + config += """ + push "dns server 7 address 8.8.8.8:53" + push "dns server 7 dnssec yes" + """ + elif username == 'nodns': + pass + elif username == 'dnssecfb': + config += """ + push "dns server 7 address 8.8.8.8:53" + push "dns server 7 dnssec yes" + push "dns server 10 address 8.8.8.8" + push "dns server 10 transport DoT" + push "dns server 12 address 8.8.8.8" + push "dns server 12 transport DoH" + push "dns server 19 address 8.8.8.8:53" + """ + elif username == 'dnsdhcp': + config += """ + push "dns server 19 address 8.8.8.8:53" + push "dhcp-options dns server 1.1.1.1" + """ + elif username == 'dnsport': + config += """ + push "dns server 20 address 8.8.8.8:5353" + """ + elif username == 'default': + config += """ + push "dns server 19 address 8.8.8.8:53" + push "dhcp-options dns server 1.1.1.1" + push "redirect-gateway def1" + """ + + if not config: + await self.queue_command(f"client-auth-nt {client.cid} {kid}") + else: + await self.queue_command(f"client-auth {client.cid} {kid}\n{config}\nEND\n") + + async def send_pending_auth(self, client: ServerDemoConnectedClient, kid: int, extra: str, + timeout: int = 180) -> None: + auth_pending_totp_cmd = f'client-pending-auth {client.cid} {kid} "{openvpn_escape(extra)}" {timeout}' + await self.queue_command(auth_pending_totp_cmd) + + def client_event_CR_RESPONSE(self, client: ServerDemoConnectedClient, kid: int, env: Dict, extra: str) -> None: + client.env = env + self.add_background_task(self.client_crresponse(client, kid, extra)) + + @staticmethod + def get_current_totp_code() -> str: + try: + import pyotp + except ImportError: + return "pyotp not found" + + totp = pyotp.TOTP(totp_secret) + return totp.now() + + async def client_crresponse(self, client: ServerDemoConnectedClient, kid: int, response: str) -> None: + # Try importing the pyotp here to allow the script run without pyotp + # installed + try: + import pyotp + except ImportError: + await self.deny_client(client, kid, "pytop module not found. Cannot do MFA testing") + return + + try: + response = standard_b64decode(response) + response = response.decode().strip() + except Exception as e: + await self.deny_client(client, kid, f"Decoding totp response failed: {e}") + return + + totp = pyotp.TOTP(totp_secret) + + logger.info(f"\nCR: expected totp '{totp.now()}', response was '{response}'\n") + # Check if the code is valid (and also allow code +/-1) + + if totp.verify(response, valid_window=1): + await self.send_client_auth(client, kid) + else: + await self.deny_client(client, kid, "TOTP verification failed") + + +async def main(connect_data: ConnectData): + transport, protocol, finish_future = await start_management_protocol(connect_data, ServerDemoProtocol) + + management_version = await protocol.management_ready() + logger.info(f"Management interface version: {management_version}") + + await protocol.enable_log() + + await protocol.set_bytecount_interval(5) + + await finish_future + + +if __name__ == '__main__': + run_main(main) diff --git a/sample/management/omi_server_protocol.py b/sample/management/omi_server_protocol.py new file mode 100644 index 0000000..ce84bbe --- /dev/null +++ b/sample/management/omi_server_protocol.py @@ -0,0 +1,239 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 OpenVPN Inc <[email protected]> +# Copyright (c) 2026 Arne Schwabe <[email protected]> +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +import asyncio +import base64 +import logging +from asyncio import Future +from dataclasses import dataclass, field +from typing import List, Tuple, Dict, Optional + +from omi import OmiProtocol, ConnectionProperties, OmiCommandResult + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +@dataclass +class ConnectedClient: + """This represents a connected client instance.""" + cid: int + bytes_sent: int = 0 + bytes_received: int = 0 + _partial_acc_msg: bytes = b"" + _protocol_acc_msg: str = "" + _kid_acc_msg: int = -1 + _acc_fragment_length: int = 980 + acc_negotiated_protocols: List[str] = field(default_factory=list) + + +class OMIServerProtocol(OmiProtocol): + """ + This class implement common method for the OMI when OpenVPN is running + as a server. These are mainly helper function and functionality that + is only available/useful for OpenVPN running as a server + """ + + # Connected client class, can be overridden by subclasses to store + # more information about the connected client + _connected_client_class = ConnectedClient + + def __init__(self, finish_future: Future, connect_data: ConnectionProperties): + super().__init__(finish_future, connect_data) + self._reset_pending_client_event() + self._connected_clients: Dict = {} + + def _reset_pending_client_event(self) -> None: + self._pending_client_event: str = "" + self._pending_client_event_cid: int = -1 + self._pending_client_event_kid: int = -1 + self._pending_client_event_extra_args: str = None + self._client_env: Dict = {} + + def recv_notify_CLIENT(self, args: str) -> None: + event, args = args.split(",", 1) + + if event == "ENV": + if args == "END": + # Client environment is finished, trigger previous client + # event that contained an ENV + self._trigger_client_event(self._pending_client_event, self._pending_client_event_cid, + self._pending_client_event_kid, self._client_env, + self._pending_client_event_extra_args) + self._reset_pending_client_event() + else: + key, value = args.split("=", 1) + self._client_env[key] = value + + elif event in ("ESTABLISHED", "DISCONNECT"): + # This event is followed by a client environment. Wait for + # the client environment to be completed before triggering the event + cid = int(args) + + self._pending_client_event = event + self._pending_client_event_cid = int(cid) + self._pending_client_event_kid = None + if event == "ESTABLISHED": + self._add_client(cid) + + elif event in ("CONNECT", "REAUTH"): + # This event is similar to other event but also carries the key-id + cid, kid = args.split(",", 1) + cid, kid = int(cid), int(kid) + self._add_client(cid) + + self._pending_client_event = event + self._pending_client_event_cid = int(cid) + self._pending_client_event_kid = int(kid) + elif event == "CR_RESPONSE": + # This event is similar to CONNECT and REAUTH but has an extra + # parameter with the crtext response + cid, kid, response = args.split(",", 2) + cid, kid = int(cid), int(kid) + + self._pending_client_event = event + self._pending_client_event_cid = int(cid) + self._pending_client_event_kid = int(kid) + self._pending_client_event_extra_args = response + elif event == "ACC": + cid, kid, acc_args = args.split(",", 2) + self._trigger_client_event(event, int(cid), int(kid), None, acc_args) + elif event == "ADDRESS": + # >CLIENT:ADDRESS,{CID},{ADDR},{PRI} + cid, extra = args.split(",", 1) + self._trigger_client_event(event, int(cid), -1, None, extra) + else: + logger.info(f"Client event {event} not handled. (message: {args!r})") + + def client_event_ACC(self, client: ConnectedClient, kid: int, env: Dict, extra: str) -> None: + protocol, fragment, b64msg = extra.split(",", 2) + + if client._partial_acc_msg and client._protocol_acc_msg != protocol: + logger.error(f"Recieved ACC message with protocol {protocol} before " + f"previous ACC message with protocol {client._protocol_acc_msg} was complete") + client._partial_acc_msg = b"" + + if client._partial_acc_msg and client._kid_acc_msg != kid: + logger.error(f"Recieved ACC message with different key id {kid} before " + f"previous ACC message with key id {client._kid_acc_msg} " + f"was complete. This is currently not handled") + client._partial_acc_msg = b"" + + try: + msg = base64.decodebytes(b64msg.encode()) + client._partial_acc_msg += msg + client._protocol_acc_msg = protocol + client._kid_acc_msg = kid + + # Message is not yet complete. Wait for more fragments. + if fragment != "0": + return + + handler_name = f"receive_acc_client_{protocol}" + if not self.dispatch_to_handler(handler_name, client, kid, client._partial_acc_msg): + logger.info(f"Received unhandled ACC protocol: {protocol}, handler {handler_name} not found") + + client._partial_acc_msg = b"" + client._protocol_acc_msg = protocol + + except Exception as e: + logger.error(f"Error parsing ACC message from client: {e}", exc_info=True) + + client._partial_acc_msg = b"" + + def recv_notify_BYTECOUNT_CLI(self, args: str) -> None: + cid, bytes_received, bytes_sent = args.split(",", 2) + + client = self._connected_clients.get(int(cid)) + if client: + client.bytes_sent = int(bytes_sent) + client.bytes_received = int(bytes_received) + + def _trigger_client_event(self, event: str, cid: int, kid: int, env: Optional[Dict], extra): + client = self._connected_clients.get(cid, None) + + # Remember ACC protocol options if present + if event == "CONNECT" and "acc_protocols" in env: + client.acc_negotiated_protocols = [p.strip() for p in env["acc_protocols"].split(":")] + client._acc_fragment_length = int(env['acc_message_len']) + + handler_name = f"client_event_{event}" + if not self.dispatch_to_handler(handler_name, client, kid, env, extra): + logger.info(f"Client event {event} not handled. Method {handler_name} does not exist.") + + def _add_client(self, cid: int) -> None: + if not cid in self._connected_clients: + self._connected_clients[cid] = self._connected_client_class(cid=cid) + + def _remove_client(self, cid: int) -> bool: + if cid in self._connected_clients: + del self._connected_clients[cid] + return True + else: + return False + + async def get_client_status(self) -> OmiCommandResult: + cmd_result = self.queue_command("status 3") + return await cmd_result + + async def send_acc_msg(self, client: ConnectedClient, kid: int, protocol: str, msg: bytes) -> None: + """ + Sends out an ACC to the client. + """ + if protocol not in client.acc_negotiated_protocols: + logger.error(f"Error: trying to send ACC message with protocol" + f" {protocol} is not in the negotiated list of " + f"protocols ({client.acc_negotiated_protocols})") + return + + # See init.c for the explanation for the length + max_header_size = len("ACC,") + len(protocol) + 1 + 4 + 1 + 2 + 1 + + # calculate fragment size with base64 encoding + fragment_length = client._acc_fragment_length * 6 // 8 - max_header_size + + commands = [] + for part_start in range(0, len(msg), fragment_length): + + msg_part = msg[part_start:part_start + fragment_length] + # This creates a multiline base64 message but that is what + # we want for the management interface to have a not overlong + # lines + b64msg = base64.encodebytes(msg_part).decode() + + flags = "6" + if part_start + fragment_length < len(msg): + flags += "F" + + commands.append(f"client-acc-msg {client.cid} {kid}\n{protocol}\n{flags}\n{b64msg}\nEND") + + cmd_futures = [] + for command in commands: + cmd_futures.append(self.queue_command(command)) + + cmd_results: Tuple[OmiCommandResult] = await asyncio.gather(*cmd_futures) + for cmd_result in cmd_results: + if cmd_result.error: + logger.error(f"Error: sending ACC message failed: {cmd_result}") + + def client_event_DISCONNECT(self, client: ConnectedClient, kid: int, _env: dict, _extra: str): + self._remove_client(client.cid) diff --git a/sample/management/omi_tools.py b/sample/management/omi_tools.py new file mode 100644 index 0000000..28cf5ba --- /dev/null +++ b/sample/management/omi_tools.py @@ -0,0 +1,92 @@ +#! /usr/bin/python3 +# Copyright (c) 2026 OpenVPN Inc <[email protected]> +# Copyright (c) 2026 Arne Schwabe <[email protected]> +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +import asyncio +import os +import re +from dataclasses import dataclass + +from omi import OmiProtocol, ConnectionProperties + + +@dataclass +class ConnectData(ConnectionProperties): + socket: str + + +openvpn_escape_re = re.compile(r'(["\\])') +filt_ctrl_re = re.compile(r"[\x00-\x1f\x7f]+") + + +def openvpn_escape(text:str) -> str : + """Escapes a string to be safely used for OpenVPN inside + a quoted string + + Something like 'client-deny 2 3 "{openvpn_escape(reason)}" "{openvpn_escape(client_reason)}"' + """ + text = re.sub(filt_ctrl_re, ' ', text) + text = re.sub(openvpn_escape_re, r'\\\1', text) + return text.rstrip() + + +def get_unix_script_environment() -> ConnectData | None: + password = os.environ.get("MANAGEMENT_PASSWORD", None) + socket = os.environ.get("MANAGEMENT_SOCKET", None) + + if password and socket: + return ConnectData(password=password, socket=socket) + else: + return None + + +async def start_management_protocol(connect_data: ConnectData, protocol: OmiProtocol): + # Get a reference to the event loop as we plan to use + # low-level APIs. + loop = asyncio.get_running_loop() + + finish_future = loop.create_future() + + print(f"Connecting to management socket {connect_data.socket}...") + transport, protocol = await loop.create_unix_connection(lambda: protocol(finish_future, connect_data), + connect_data.socket) + + return transport, protocol, finish_future + + +def run_main(main_func, connect_parameters: ConnectData = None): + """ + Example function to run a main function to be either using the + environment variable for the unix-script or to use. If the unix-script + environment are detected, the function will run the main_func + with the ConnectData from the environment. If the environment variables + are not available, it will fall back to the connect_parameters + if present. + :param connect_parameters: fallback connect parameters if unix-script is not available + :param main_func: The function to call. + :return: + """ + unix_script_parameters = get_unix_script_environment() + if unix_script_parameters: + asyncio.run(main_func(unix_script_parameters)) + elif connect_parameters: + asyncio.run(main_func(connect_parameters)) + else: + print(f"Must be called via unix-script") _______________________________________________ Openvpn-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/openvpn-devel
