Path: blob/main/plugins/python/example_audit_plugin.py
1532 views
import sudo12import os345VERSION = 1.0678class SudoAuditPlugin(sudo.Plugin):9def __init__(self, plugin_options, user_info, **kwargs):10# For loading multiple times, an optional "Id" can be specified11# as argument to identify the log lines12plugin_id = sudo.options_as_dict(plugin_options).get("Id", "")13self._log_line_prefix = "(AUDIT{}) ".format(plugin_id)1415user_info_dict = sudo.options_as_dict(user_info)16user = user_info_dict.get("user", "???")17uid = user_info_dict.get("uid", "???")18self._log("-- Started by user {} ({}) --".format(user, uid))1920def __del__(self):21self._log("-- Finished --")2223def open(self, submit_optind: int, submit_argv: tuple) -> int:24# To cut out the sudo options, use "submit_optind":25program_args = submit_argv[submit_optind:]26if program_args:27self._log("Requested command: " + " ".join(program_args))2829def accept(self, plugin_name, plugin_type,30command_info, run_argv, run_envp) -> int:31info = sudo.options_as_dict(command_info)32cmd = list(run_argv)33cmd[0] = info.get("command")34self._log("Accepted command: {}".format(" ".join(cmd)))35self._log(" By the plugin: {} (type={})".format(36plugin_name, self.__plugin_type_str(plugin_type)))3738self._log(" Environment: " + " ".join(run_envp))3940def reject(self, plugin_name, plugin_type, audit_msg, command_info) -> int:41self._log("Rejected by plugin {} (type={}): {}".format(42plugin_name, self.__plugin_type_str(plugin_type), audit_msg))4344def error(self, plugin_name, plugin_type, audit_msg, command_info) -> int:45self._log("Plugin {} (type={}) got an error: {}".format(46plugin_name, self.__plugin_type_str(plugin_type), audit_msg))4748def close(self, status_kind: int, status: int) -> None:49if status_kind == sudo.EXIT_REASON.NO_STATUS:50self._log("The command was not executed")5152elif status_kind == sudo.EXIT_REASON.WAIT_STATUS:53if os.WIFEXITED(status):54self._log("Command returned with exit code "55"{}".format(os.WEXITSTATUS(status)))56elif os.WIFSIGNALED(status):57self._log("Command exited due to signal "58"{}".format(os.WTERMSIG(status)))59else:60raise sudo.PluginError("Failed to understand wait exit status")6162elif status_kind == sudo.EXIT_REASON.EXEC_ERROR:63self._log("Sudo has failed to execute the command, "64"execve returned {}".format(status))6566elif status_kind == sudo.EXIT_REASON.SUDO_ERROR:67self._log("Sudo has run into an error: {}".format(status))6869else:70raise Exception("Command returned unknown status kind {}".format(71status_kind))7273def show_version(self, is_verbose: bool) -> int:74version_str = " (version=1.0)" if is_verbose else ""75sudo.log_info("Python Example Audit Plugin" + version_str)7677def _log(self, string):78# For the example, we just log to output (this could be a file)79sudo.log_info(self._log_line_prefix, string)8081@staticmethod82def __plugin_type_str(plugin_type):83return sudo.PLUGIN_TYPE(plugin_type).name848586