Attention is currently required from: Name of user not set #1000061, Ralf Lici.
Arne Schwabe has uploaded a new patch set (#7). ( https://gerrit.openvpn.net/c/openvpn/+/2037?usp=email ) Change subject: Add python scripts that demonstrate the ACC protocol ...................................................................... Add python scripts that demonstrate the ACC protocol This adds a small protocol called sys_info that let's the server query various details about the client to demonstrate the capabilities of the ACC functionality. Change-Id: I695967524bb9e83887b8c07d0d09baff6e41acf4 Signed-off-by: Arne Schwabe <[email protected]> --- A sample/management/acc_sysinfo_client_demo.py A sample/management/acc_sysinfo_server_demo.py 2 files changed, 297 insertions(+), 0 deletions(-) git pull ssh://gerrit.openvpn.net:29418/openvpn refs/changes/37/2037/7 diff --git a/sample/management/acc_sysinfo_client_demo.py b/sample/management/acc_sysinfo_client_demo.py new file mode 100755 index 0000000..60c4a1d --- /dev/null +++ b/sample/management/acc_sysinfo_client_demo.py @@ -0,0 +1,156 @@ +#!/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. + +# This implements a small demonstration of using the +# OpenVPN Access Server Management Interface (OMI) and an app Custom Control +# protocol (sys_info) to retrieve a number of system information from the +# client and push them to the server. To use this use on the server + +# --management-client-auth +# --app-custom-control sys_info +# --management /path/to/acc_sysinfo_server_demo.py unix-script + +# and on the client +# --app-custom-control sys_info +# --management /path/to/acc_sysinfo_client_demo.py unix-script + +# Note this is just a demonstration and not a production-ready solution. +# When modifying this code, keep the security in mind. It is easy to +# introduce a security problem when executing commands on the client. + +import asyncio +import json +import logging +import os +import platform +import subprocess +from asyncio import CancelledError, Future + +logging.basicConfig() + +from omi_tools import run_main, start_management_protocol, ConnectData +from omi_client_protocol import OMIClientProtocol + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +class OmiSysInfoClientProtocol(OMIClientProtocol): + def __init__(self, finish_future: Future, connect_data: ConnectData): + super().__init__(finish_future, connect_data) + + async def receive_acc_sys_info(self, acc_message: bytes) -> None: + logger.debug(f"Received sys_info message: {acc_message!r}") + try: + msg = json.loads(acc_message) + + await self.send_info_response(msg) + except Exception as e: + logger.error(f"Error processing sysinfo request: {e}") + + async def send_info_response(self, msg: dict) -> None: + response = {} + if msg.get("uname", False): + response['uname'] = platform.uname()._asdict() + + if msg.get("username", False): + try: + response['username'] = os.getlogin() + except OSError as ose: + response['username'] = f"(error encountered fetching username: {ose})" + + if msg.get("hostname", False): + response['hostname'] = platform.node() + + if msg.get("dns-google.com", False): + try: + loop = asyncio.get_running_loop() + addrs = [x[4][0] for x in await loop.getaddrinfo('google.com', 443)] + response["dns-google.com"] = addrs + + except Exception as e: + logger.error(f"Error resolving DNS for google.com: {e}", exc_info=True) + response["dns-google.com"] = None + + if msg.get("route", False): + response['route'] = await self.get_routes(False) + + if msg.get("route6", False): + response['route6'] = await self.get_routes(True) + + msg = json.dumps(response).encode() + + await self.send_acc_msg("sys_info", msg) + + @staticmethod + async def get_routes(v6: bool) -> str: + try: + if platform.system() == 'Linux': + if not os.path.exists('/usr/sbin/ip'): + return "Command /usr/sbin/ip does not exist" + cmd = '/usr/sbin/ip' + if v6: + args = ['-6', 'route', 'show'] + else: + args = ['-4', 'route', 'show'] + elif platform.system() == 'Darwin' or platform.system() == 'FreeBSD': + # FreeBSD and macOS + if os.path.exists('/usr/sbin/netstat'): + cmd = '/usr/sbin/netstat' + else: + cmd = '/usr/bin/netstat' + + if v6: + args = ['-f', 'inet6', '-rn'] + else: + + args = ['-f', 'inet', '-rn'] + else: + return "Unsupported platform" + + proc = await asyncio.subprocess.create_subprocess_exec(cmd, *args, stdout=subprocess.PIPE) + + output, _ = await asyncio.wait_for(proc.communicate(), timeout=15) + except asyncio.TimeoutError, OSError: + proc.kill() + return "Timeout while waiting for command output" + + return output.decode() + + +async def main(connect_data: ConnectData): + transport, protocol, finish_future = await start_management_protocol(connect_data, OmiSysInfoClientProtocol) + + management_version = await protocol.management_ready() + logger.debug(f"Management interface version: {management_version}") + + await protocol.set_bytecount_interval(5) + + try: + await finish_future + except CancelledError: + # Ignore errors like ones caused by Control+C in the demo script + pass + + +if __name__ == '__main__': + run_main(main) diff --git a/sample/management/acc_sysinfo_server_demo.py b/sample/management/acc_sysinfo_server_demo.py new file mode 100755 index 0000000..9918e11 --- /dev/null +++ b/sample/management/acc_sysinfo_server_demo.py @@ -0,0 +1,141 @@ +#! /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. + +# This implements a small demonstration of using the +# OpenVPN Access Server Management Interface (OMI) and an app Custom Control +# protocol (sys_info) to retrieve a number of system information from the +# client and push them to the server. To use this use on the server + +# --management-client-auth +# --app-custom-control sys_info +# --management /path/to/acc_sysinfo_server_demo.py unix-script + +# and on the client +# --app-custom-control sys_info +# --management /path/to/acc_sysinfo_client_demo.py unix-script + +# Note this is just a demonstration and not a production-ready solution. +# When modifying this code, keep the security in mind. It is easy to +# introduce a security problem when executing commands on the client. + +import asyncio +import json +import logging +import random +from dataclasses import dataclass + +from omi_server_protocol import OMIServerProtocol, ConnectedClient +from omi_tools import run_main, start_management_protocol, ConnectData + +logging.basicConfig() +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +@dataclass +class SysInfoConnectedClient(ConnectedClient): + # Remember the key-id that we authenticated + authenticated_kid: int = -1 + username: str = "" + common_name: str = "" + + +class OMISysInfoServerProtocol(OMIServerProtocol): + def __init__(self, finish_future, connect_data: ConnectData): + super().__init__(finish_future, connect_data) + self._connected_client_class = SysInfoConnectedClient + + def client_event_ESTABLISHED(self, client: SysInfoConnectedClient, kid: int, env: dict, extra: str): + logger.debug(f"CLient connected: {client}") + + kid = client.authenticated_kid + client.username = env.get("username", "(no username found)") + client.common_name = env.get("common_name", "(no common name found)") + self.add_background_task(self._send_sys_info_command(client, kid)) + + def client_event_CONNECT(self, client: SysInfoConnectedClient, kid: int, env: dict, extra: str): + logger.debug(f"Authenticating client {client.cid}, {kid}") + self.queue_command(f"client-auth-nt {client.cid} {kid}") + client.authenticated_kid = kid + + def client_event_REAUTH(self, client: SysInfoConnectedClient, kid: int, env: dict, extra: str): + logger.debug(f"Re-authenticating client {client} on re-negotiation") + _ = self.queue_command(f"client-auth-nt {client.cid} {kid}") + client.authenticated_kid = kid + + async def _send_sys_info_command(self, client: SysInfoConnectedClient, kid: int): + # Give the client some time to settle its routes + await asyncio.sleep(5) + + if "sys_info" not in client.acc_negotiated_protocols: + logger.info( + f"Client {client.cid} (Username: {client.username!r}, CN: {client.common_name!r}) does not support sys_info protocol") + return + + info = ["route", "route6", "dns-google.com", "username", "hostname", "uname"] + + # Pick 3 random infos to request from the client + random.shuffle(info) + infos = info[:3] + request = {k: True for k in infos} + + req_str = json.dumps(request).encode() + + logger.info(f"Sending sysinfo request for client {client.cid} with infos: {infos}") + + acc_protocol = "sys_info" + + await self.send_acc_msg(client, kid, acc_protocol, req_str) + + def receive_acc_client_sys_info(self, client: SysInfoConnectedClient, kid: int, acc_msg: bytes): + try: + logger.info( + f"Received sysinfo from client {client.cid} (Username: {client.username!r}, CN: {client.common_name!r})") + + response = json.loads(acc_msg) + for key in response.keys(): + logger.info(f"============== {key!r} ================") + if isinstance(response[key], str): + for line in response[key].split("\n"): + logger.info(repr(line)) + else: + logger.info(repr(response[key])) + + except Exception as e: + logger.error(f"Error processing sysinfo from client {client.cid}: {e}") + + +async def main(connect_data: ConnectData): + transport, protocol, finish_future = await start_management_protocol(connect_data, OMISysInfoServerProtocol) + + management_version = await protocol.management_ready() + logger.debug(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) -- To view, visit https://gerrit.openvpn.net/c/openvpn/+/2037?usp=email To unsubscribe, or for help writing mail filters, visit https://gerrit.openvpn.net/settings?usp=email Gerrit-MessageType: newpatchset Gerrit-Project: openvpn Gerrit-Branch: master Gerrit-Change-Id: I695967524bb9e83887b8c07d0d09baff6e41acf4 Gerrit-Change-Number: 2037 Gerrit-PatchSet: 7 Gerrit-Owner: Arne Schwabe <[email protected]> Gerrit-CC: Name of user not set #1000061 Gerrit-CC: Ralf Lici <[email protected]> Gerrit-CC: openvpn-devel <[email protected]> Gerrit-Attention: Name of user not set #1000061 Gerrit-Attention: Ralf Lici <[email protected]>
_______________________________________________ Openvpn-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/openvpn-devel
