Arne Schwabe has uploaded this change for review. ( 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, 258 insertions(+), 0 deletions(-) git pull ssh://gerrit.openvpn.net:29418/openvpn refs/changes/37/2037/1 diff --git a/sample/management/acc_sysinfo_client_demo.py b/sample/management/acc_sysinfo_client_demo.py new file mode 100755 index 0000000..c5c562a --- /dev/null +++ b/sample/management/acc_sysinfo_client_demo.py @@ -0,0 +1,143 @@ +#!/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 implement 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 + +# --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 socket +import subprocess + +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.DEBUG) + + +class OmiSysInfoClientProtocol(OMIClientProtocol): + def __init__(self, finish_future, connect_data: ConnectData): + super().__init__(finish_future, connect_data) + + + def receive_acc_sys_info(self, accmsg): + print(f"Received sys_info message: {accmsg!r}") + + logger.debug(f"Received sys_info message: {accmsg!r}") + + msg = json.loads(accmsg) + + + asyncio.create_task(self.send_info_response(msg)) + + async def send_info_response(self, msg): + response = {} + if msg.get("uname", False): + response['uname'] = platform.uname()._asdict() + + if msg.get("username", False): + response['username'] = os.getlogin() + + if msg.get("hostname", False): + response['hostname'] = platform.node() + + if msg.get("dns-google.com", False): + try: + addrs = [x[4][0] for x in socket.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) + + async def get_routes(self, v6): + if platform.system() == 'linux': + cmd = '/usr/sbin/ip' + if v6: + args = ['-6', 'route', 'show'] + else: + args = ['-4', 'route', 'show'] + elif platform.system() == 'Darwin' or os.platform() == '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 proc.communicate() + return output.decode() + + +async def main(connect_data: ConnectData): + transport, protocol, finish_future = await start_management_protocol(connect_data, OmiSysInfoClientProtocol) + while True: + await asyncio.sleep(5) + print(".", end="", flush=True) + + management_version = await protocol.management_ready() + print(f"Management interface version: {management_version}") + + await protocol.set_bytecount_interval(5) + + await finish_future + + +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..f084767 --- /dev/null +++ b/sample/management/acc_sysinfo_server_demo.py @@ -0,0 +1,115 @@ +#! /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 +# This implement 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 + +# --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 + +import base64 +import json +import logging +import random +from pprint import pformat + +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) + +class SysInfoConnectedClient(ConnectedClient): + # Remember the key-id that we authenticated + authenticated_kid = None + +class OMISysInfoServerProtocol(OMIServerProtocol): + def __init__(self, finish_future, connect_data: ConnectData = None): + super().__init__(finish_future, connect_data) + self._connected_client_class = SysInfoConnectedClient + + def client_event_ESTABLISHED(self, client, kid, env, extra): + print(f"CLient connected: {client}") + + kid = client.authenticated_kid + asyncio.create_task(self._send_sys_info_command(client, kid)) + + def client_event_CONNECT(self, client, kid, env, extra): + print(f"Authenticating client {client.cid}, {kid}") + self.queue_command(f"client-auth-nt {client.cid} {kid}") + client.authenticated_kid = kid + + async def _send_sys_info_command(self, client, kid): + # Give the client some time to settle its routes + await asyncio.sleep(5) + + 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, kid, acc_msg): + logger.info(f"Received sysinfo from client {client.cid}") + + response = json.loads(acc_msg) + for key in response.keys(): + logger.info (f"============== {key!r} ================") + if type(response[key]) == str: + for line in response[key].split("\n"): + logger.info(repr(line)) + else: + logger.info(repr(response[key])) + + +async def main(connect_data: ConnectData): + transport, protocol, finish_future = await start_management_protocol(connect_data, OMISysInfoServerProtocol) + + management_version = await protocol.management_ready() + print(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: newchange Gerrit-Project: openvpn Gerrit-Branch: master Gerrit-Change-Id: I695967524bb9e83887b8c07d0d09baff6e41acf4 Gerrit-Change-Number: 2037 Gerrit-PatchSet: 1 Gerrit-Owner: Arne Schwabe <[email protected]> Gerrit-CC: openvpn-devel <[email protected]>
_______________________________________________ Openvpn-devel mailing list [email protected] https://lists.sourceforge.net/lists/listinfo/openvpn-devel
