The supported plugins types are:
Python plugin support needs to be explicitly enabled at build time with the configure option ``--enable-python'' Python version 3.0 or higher is required.
The only implemented method is a constructor, which stores the keyword arguments it receives as fields (member variables) in the object. This is intended as a convenience to allow you to avoid writing the constructor yourself.
For example:
import sudo class MySudoPlugin(sudo.Plugin): # example constructor (optional) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # example destructor (optional) def __del__(self): pass
Both the constructor and destructor are optional and can be omitted.
The customized Plugin class should define a few plugin-specific methods. When the plugin loads, sudo will create an instance of this class and call the methods. The actual methods required depent on the type of the plugin, but most return an ``int'' result code, as documented in sudo_plugin@mansctsu@, that indicates whether or not the method was successful. The Python sudo module defines the following constants to improve readability:
If a function returns None (for example, if it does not call return), it will be considered to have returned sudo.RC.OK If an exception is raised (other than sudo.PluginException), the backtrace will be shown to the user and the plugin function will return sudo.RC.ERROR If that is not acceptable, you must catch the exception and handle it yourself.
Instead of just returning sudo.RC.ERROR or sudo.RC.REJECT result code the plugin can also provide a message describing the problem. This can be done by raising one of the special exceptions:
raise sudo.PluginError("Message") raise sudo.PluginReject("Message")
This added message will be used by the audit plugins. Both exceptions inherit from sudo.PluginException
Example usage in sudo.conf5:
Plugin python_policy python_plugin.so ModulePath=<path> ClassName=<class> Plugin python_io python_plugin.so ModulePath=<path> ClassName=<class> Plugin python_audit python_plugin.so ModulePath=<path> ClassName=<class> Plugin python_approval python_plugin.so ModulePath=<path> ClassName=<class>
Example group provider plugin usage in the sudoers file:
Defaults group_plugin="python_plugin.so ModulePath=<path> ClassName=<class>"
The plugin arguments are as follows:
Plugin python_policy python_plugin.so ModulePath=<path> ClassName=<class>
Currently, only a single policy plugin may be specified in sudo.conf5.
A policy plugin may have the following member functions:
__init__(self, user_env: Tuple[str, ...], settings: Tuple[str, ...], version: str, user_info: Tuple[str, ...], plugin_options: Tuple[str, ...])
Implementing this function is optional. The default constructor will set the keyword arguments it receives as member variables in the object.
The constructor matches the Fn open function in the C sudo plugin API.
The function arguments are as follows:
The Fn sudo.options_as_dict convenience function can be used to convert ``key=value'' pairs to a dictionary. For a list of recognized keys and their supported values, see the policy plugin Fn open documentation in sudo_plugin5.
check_policy(self, argv: Tuple[str, ...], env_add: Tuple[str, ...])
The Fn check_policy function is called by sudo to determine whether the user is allowed to run the specified command. Implementing this function is mandatory for a policy plugin.
The function arguments are as follows:
This function should return a result code or a tuple in the following format:
return (rc, command_info_out, argv_out, user_env_out)
The tuple values are as follows:
To accept a command, at the very minimum the plugin must set in the command runas_uid and runas_gid keys.
For a list of recognized keys and supported values, see the Fn check_policy documentation in sudo_plugin5.
init_session(self, user_pwd: Tuple, user_env: Tuple[str, ...])
Perform session setup (optional). The Fn init_session function is called before sudo sets up the execution environment for the command before any uid or gid changes.
The function arguments are as follows:
Example conversion:
user_pwd = pwd.struct_passwd(user_pwd) if user_pwd else None
This function should return a result code or a tuple in the following format:
return (rc, user_env_out)
The tuple values are as follows:
list(self, argv: Tuple[str, ...], is_verbose: int, user: str)
List available privileges for the invoking user.
The function arguments are as follows:
validate(self)
For policy plugins that cache authentication credentials, this function is used to validate and cache the credentials (optional).
invalidate(self, remove: int)
For policy plugins that cache authentication credentials, this function is used to invalidate the credentials (optional).
The function arguments are as follows:
show_version(self, is_verbose: int)
Display the plugin version information to the user. The Fn sudo.log_info function should be used.
The function arguments are as follows:
close(self, exit_status: int, error: int)
Called when a command finishes executing.
Works the same as the Fn close function in the C sudo plugin API, except that it only gets called if sudo attempts to execute the command.
The function arguments are as follows:
Plugin python_policy python_plugin.so \ ModulePath=/usr/share/doc/sudo/examples/example_policy_plugin.py \ ClassName=SudoPolicyPlugin
Be aware, however, that you cannot enable the Python policy plugin in addition to another policy plugin, such as sudoers(5).
Plugin python_io python_plugin.so ModulePath=<path> ClassName=<class>
Sudo supports loading multiple I/O plugins. Currently only 8 python I/O plugins can be loaded at once.
An I/O plugin may have the following member functions:
__init__(self, user_env: Tuple[str, ...], settings: Tuple[str, ...], version: str, user_info: Tuple[str, ...], plugin_options: Tuple[str, ...])
Implementing this function is optional. The default constructor will set the keyword arguments it receives as member variables in the object.
The constructor matches the Fn open function in the C sudo plugin API.
The function arguments are as follows:
The Fn sudo.options_as_dict convenience function can be used to convert ``key=value'' pairs to a dictionary. For a list of recognized keys and their supported values, see the I/O plugin Fn open documentation in sudo_plugin5.
open(self, argv: Tuple[str, ...], command_info: Tuple[str, ...]) -> int
Receives the command the user wishes to run.
Works the same as the Fn open function in the C sudo plugin API except that:
The function arguments are as follows:
The Fn sudo.options_as_dict convenience function can be used to convert ``key=value'' pairs to a dictionary. For a list of recognized keys and their supported values, see the I/O plugin Fn open documentation in sudo_plugin5.
The Fn open function should return a result code, one of the sudo.RC.* constants. If the function returns sudo.RC.REJECT no I/O will be sent to the plugin.
log_ttyin(self, buf: str) -> int log_ttyout(self, buf: str) -> int log_stdin(self, buf: str) -> int log_stdout(self, buf: str) -> int log_stderr(self, buf: str) -> int
Receive the user input or output of the terminal device and application standard input / output / error. See the matching calls in sudo_plugin5.
The function arguments are as follows:
The function should return a result code, one of the sudo.RC.* constants.
If sudo.RC.ERROR is returned, the running command will be terminated and all of the plugin's logging functions will be disabled. Other I/O logging plugins will still receive any remaining input or output that has not yet been processed.
If an input logging function rejects the data by returning sudo.RC.REJECT the command will be terminated and the data will not be passed to the command, though it will still be sent to any other I/O logging plugins. If an output logging function rejects the data by returning sudo.RC.REJECT the command will be terminated and the data will not be written to the terminal, though it will still be sent to any other I/O logging plugins.
change_winsize(self, line: int, cols: int) -> int
Called whenever the window size of the terminal changes. The function arguments are as follows:
log_suspend(self, signo: int) -> intCalled whenever a command is suspended or resumed.
The function arguments are as follows:
show_version(self, is_verbose: int)Display the plugin version information to the user. The Fn sudo.log_info function should be used.
The function arguments are as follows:
close(self, exit_status: int, error: int) -> NoneCalled when a command execution finished.
Works the same as the Fn close function in the C sudo plugin API, except that it only gets called if sudo attempts to execute the command.
The function arguments are as follows:
Plugin python_io python_plugin.so \ ModulePath=/usr/share/doc/sudo/examples/example_io_plugin.py \ ClassName=SudoIOPlugin
Plugin python_audit python_plugin.so ModulePath=<path> ClassName=<class>
Sudo supports loading multiple audit plugins. Currently only 8 python audit plugins can be loaded at once.
An audit plugin may have the following member functions (all of them are optional):
__init__(self, user_env: Tuple[str, ...], settings: Tuple[str, ...], version: str, user_info: Tuple[str, ...], plugin_options: Tuple[str, ...])
The default constructor will set the keyword arguments it receives as member variables in the object.
The constructor matches the Fn open function in the C sudo plugin API.
The function arguments are as follows:
open(self, submit_optind: int, submit_argv: Tuple[str, ...]) -> int
The function arguments are as follows:
close(self, status_type: int, status: int) -> None
Called when sudo is finished, shortly before it exits.
The function arguments are as follows:
show_version(self, is_verbose: int) -> int
Display the plugin version information to the user. The Fn sudo.log_info function should be used.
The function arguments are as follows:
accept(self, plugin_name: str, plugin_type: int, command_info: Tuple[str, ...], run_argv: Tuple[str, ...], run_envp: Tuple[str, ...]) -> int
This function is called when a command or action is accepted by a policy or approval plugin. The function arguments are as follows:
Typically, an audit plugin is interested in either the accept status from the sudo front-end or from the various policy and approval plugins, but not both. It is possible for the policy plugin to accept a command that is later rejected by an approval plugin, in which case the audit plugin's Fn accept and Fn reject functions will both be called.
reject(self, plugin_name: str, plugin_type: int, audit_msg: str, command_info: Tuple[str, ...]) -> int
This function is called when a command or action is rejected by the policy plugin. The function arguments are as follows:
Unlike the Fn accept function, the Fn reject function is not called on behalf of the sudo front-end.
error(self, plugin_name: str, plugin_type: int, audit_msg: str, command_info: Tuple[str, ...]) -> int
This function is called when a plugin or the sudo front-end returns an error. The function arguments are as follows:
Plugin python_audit python_plugin.so \ ModulePath=/usr/share/doc/sudo/examples/example_audit_plugin.py \ ClassName=SudoAuditPlugin
It will log the plugin accept / reject / error results to the output.
Plugin python_approval python_plugin.so ModulePath=<path> ClassName=<class>
Sudo supports loading multiple approval plugins. Currently only 8 python approval plugins can be loaded at once.
An approval plugin may have the following member functions:
__init__(self, user_env: Tuple[str, ...], settings: Tuple[str, ...], version: str, user_info: Tuple[str, ...], plugin_options: Tuple[str, ...], submit_optind: int, submit_argv: Tuple[str, ...])
Optional. The default constructor will set the keyword arguments it receives as member variables in the object.
The constructor matches the Fn open function in the C sudo plugin API.
The function arguments are as follows:
show_version(self, is_verbose: int) -> int
Display the version. (Same as for all the other plugins.)
check(self, command_info: Tuple[str, ...], run_argv: Tuple[str, ...], run_env: Tuple[str, ...]) -> int
This function is called after policy plugin's check_policy has succeeded. It can reject execution of the command by returning sudo.RC.REJECT or raising the special exception:
raise sudo.PluginReject("some message")
with the message describing the problem. In the latter case, the audit plugins will get the description.
The function arguments are as follows:
Plugin python_approval python_plugin.so \ ModulePath=/usr/share/doc/sudo/examples/example_approval_plugin.py \ ClassName=BusinessHoursApprovalPlugin
It will only allow execution of commands in the "business hours" (from Monday to Friday between 8:00 and 17:59:59).
Defaults group_plugin="python_plugin.so ModulePath=<path> ClassName=<class>"
Currently, only a single group plugin can be registered in sudoers
A group provider plugin may have the following member functions:
__init__(self, args: Tuple[str, ...], version: str)
Implementing this function is optional. The default constructor will set the keyword arguments it receives as member variables in the object.
The function arguments are as follows:
query(self, user: str, group: str, user_pwd: Tuple)
The Fn query function is used to ask the group plugin whether Fa user is a member of Fa group . This method is required.
The function arguments are as follows:
Defaults group_plugin="python_plugin.so \ ModulePath=/usr/share/doc/sudo/examples/example_group_plugin.py \ ClassName=SudoGroupPlugin"
The example plugin will tell sudo that the user test is part of the non-unix group mygroup If you add a rule that uses this group, it will affect the test user. For example:
%:mygroup ALL=(ALL) NOPASSWD: ALL
Will allow user test to run sudo without a password.
The sudo.ConvMessage class specifies how the user interaction should occur:
sudo.ConvMessage(msg_type: int, msg: str, timeout: int)
sudo.ConvMessage member variables:
To specify the message type, the following constants are available:
See the sudo_plugin5 manual for a description of the message types.
The Fn sudo.conv function performs the actual user interaction:
sudo.conv(message(s), on_suspend=suspend_function, on_resume=resume_function)
The function arguments are as follows:
The Fn sudo.conv function can raise the following exceptions:
Plugin python_io python_plugin.so \ ModulePath=/usr/share/doc/sudo/examples/example_conversation.py \ ClassName=ReasonLoggerIOPlugin
sudo.log_info(string(s), sep=" ", end="\n") sudo.log_error(string(s), sep=" ", end="\n")
To display information to the user, the Fn sudo.log_info function can be used. To display error messages, use Fn sudo.log_error . The syntax is similar to the Python Fn print function.
The function arguments are as follows:
Enabling debugging in sudo.conf
To enable debug messages, add a Debug line to sudo.conf5 with the program set to python_plugin.so For example, to store debug output in /var/log/sudo_python_debug use a line like the following:
Debug python_plugin.so /var/log/sudo_python_debug \ plugin@trace,c_calls@trace
The debug options are in the form of multiple ``subsystem@level'' strings, separated by commas (`,' ) For example to just see the debug output of Fn sudo.debug calls, use:
Debug python_plugin.so /var/log/sudo_python_debug plugin@trace
See sudo_conf5 for more details.
The most interesting subsystems for Python plugin development are:
You can also specify ``all'' as the subsystem name to log debug messages for all subsystems.
The Fn sudo.debug function is defined as:
sudo.debug(level, message(s))
The function arguments are as follows:
Available log levels:
Using the logging module
Alternatively, a plugin can use the built in logging module of Python as well. Sudo adds its log handler to the root logger, so by default all output of a logger will get forwarded to sudo log system, as it would call sudo.debug.
The log handler of sudo will map each Python log level of a message to the appropriate sudo debug level. Note however, that sudo debug system will only get the messages not filtered out by the Python loggers. For example, the log level of the python logger will be an additional filter for the log messages, and is usually very different from what level is set in sudo.conf for the sudo debug system.
Plugin python_io python_plugin.so \ ModulePath=/usr/share/doc/sudo/examples/example_debugging.py \ ClassName=DebugDemoPlugin Debug python_plugin.so \ /var/log/sudo_python_debug plugin@trace,c_calls@trace
options_as_dict(options)
The function arguments are as follows:
The function returns the resulting dictionary. Each string of the passed in Fa options will be split at the first equal sign (`=' ) into a key and value Dictionary keys will never contain this symbol (but values may).
options_from_dict(options_dict)
The function arguments are as follows:
The function returns a tuple containing the strings in ``key=value'' form for each key and value in the Fa options_dict dictionary passed in. This is how the plugin API accepts options and settings.
The Event API and the hook function API is currently not accessible for Python plugins.
An Todd C. Miller
See the CONTRIBUTORS file in the sudo distribution (https://www.sudo.ws/contributors.html) for an exhaustive list of people who have contributed to sudo
If you feel you have found a bug in sudo please submit a bug report at https://bugzilla.sudo.ws/
By default, a Python plugin can only import Python modules which are owned by root and are only writable by the owner. The reason for this is to prevent a file getting imported accidentally which is modifiable by a non-root user. As sudo plugins run as root accidentally importing such file would make it possible for any user (having write access) to execute any code with administrative rights.
However, during development of a plugin this might not be very convenient. The sudo.conf5 developer_mode option can be used to disable it. For example:
Set developer_mode true
Please note that this creates a security risk, so it is not recommended on critical systems such as a desktop machine for daily use, but is intended to be used in development environments (VM, container, etc). Before enabling developer mode, ensure you understand the implications.