SUDO_PLUGIN_PYTHON(5)
π SUDO_PLUGIN_PYTHON(5) β Sudo Plugin API (Python) π
okay bestie, this is the File Formats Manual page for the Python sudo plugin API. no cap, it's a whole vibe. π
π NAME π
sudo_plugin_python β Sudo Plugin API (Python) β¨
β¨ DESCRIPTION β¨
Starting with version 1.9, sudo plugins can be written in python. The API closely follows the C sudo plugin API described by sudo_plugin(5). iykyk π
The supported plugins types are:
- Policy plugin π‘οΈ
- I/O plugin π₯π€
- Audit plugin π
- Approval plugin β
- Group provider plugin π₯
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. fr fr β οΈ
π§ Sudo Python Plugin Base π§
A plugin written in Python should be a class in a python file that inherits from sudo.Plugin. The sudo.Plugin base class has no real purpose other than to identify this class as a plugin. it's giving "just here to be a vibe" π«
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. slay, less code π
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 depend on the type of the plugin, but most return an int result code, as documented in sudo_plugin(5), that indicates whether or not the method was successful. The Python sudo module defines the following constants to improve readability:
sudo.RC.OKβ value1βsudo.RC.ACCEPTβ value1πsudo.RC.REJECTβ value0π«sudo.RC.ERRORβ value-1πsudo.RC.USAGE_ERRORβ value-2π
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. no pressure tho π
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. audit girlies stay winning π
π Python Plugin Loader π
Running the Python interpreter and bridging between C and Python is handled by the sudo plugin python_plugin.so. This shared object can be loaded like any other dynamic sudo plugin and should receive the path and the class name of the Python plugin it is loading as arguments. the bridge between worlds, literally π¦
Example usage in sudo.conf(5):
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:
ModulePathβ The path of a python file which contains the class of the sudo Python plugin. It must be either an absolute path or a path relative to the sudo Python plugin directory,/usr/libexec/sudo/python. The parent directory ofModulePathwill be appended to Python's module search path (there is currently no way to force Python to load a module from a fully-qualified path). It is good practice to use a prefix for the module file that is unlikely to conflict with other installed Python modules, for example,sudo_policy.py. Otherwise, if the there is an installed Python module with the same file name as the sudo Python plugin file (without the directory), the wrong file will be loaded. avoid the accidental imposter module, bestie πClassNameβ (Optional.) The name of the class implementing the sudo Python plugin. If not supplied, the one and onlysudo.Pluginthat is present in the module will be used. If there are multiple such plugins in the module (or none), it will result in an error. so picky, but valid π
π Policy plugin API π
Policy plugins must be registered in sudo.conf(5). For example:
Plugin python_policy python_plugin.so ModulePath=<path> ClassName=<class>
Currently, only a single policy plugin may be specified in sudo.conf(5). one and only, main character energy β
A policy plugin may have the following member functions:
π οΈ constructor π οΈ
__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 open() function in the C sudo plugin API.
The function arguments are as follows:
user_envβ The user's environment as a tuple of strings in βkey=valueβ format. πsettingsβ A tuple of user-supplied sudo settings in the form of βkey=valueβ strings. βοΈversionβ The version of the Python Policy Plugin API. π’user_infoβ A tuple of information about the user running the command in the form of βkey=valueβ strings. π€plugin_optionsβ The plugin options passed as arguments in thesudo.conf(5)plugin registration. This is a tuple of strings, usually (but not necessarily) in βkey=valueβ format. ποΈ
The 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 open() documentation in sudo_plugin(5). convenience queen π
π₯ check_policy π₯
check_policy(self, argv: Tuple[str, ...], env_add: Tuple[str, ...])
The 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. mandatory, bestie, no skipping π¨
The function arguments are as follows:
argvβ A tuple describing the command the user wishes to run. πenv_addβ Additional environment variables specified by the user on the command line in the form of a tuple of βkey=valueβ pairs. Thesudo.options_as_dict()convenience function can be used to convert them to a dictionary. π±
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:
rcβ The result of the policy check, one of thesudo.RC.*constants.sudo.RC.ACCEPTif the command is allowed,sudo.RC.REJECTif not allowed,sudo.RC.ERRORfor a general error, orsudo.RC.USAGE_ERRORfor a usage error. β π«πcommand_info_outβ Optional (only required when the command is accepted). Information about the command being run in the form of βkey=valueβ strings. To accept a command, at the very minimum the plugin must set in the command,runas_uid, andrunas_gidkeys. For a list of recognized keys and supported values, see thecheck_policy()documentation insudo_plugin(5). πargv_outβ Optional (only required when the command is accepted). The arguments to pass to theexecve(2)system call when executing the command. πuser_env_outβ Optional (only required when the command is accepted). The environment to use when executing the command in the form of a tuple of strings in βkey=valueβ format. πΏ
πΈ init_session πΈ
init_session(self, user_pwd: Tuple, user_env: Tuple[str, ...])
Perform session setup (optional). The init_session() function is called before sudo sets up the execution environment for the command before any user-ID or group-ID changes. pre-game setup, before the ID glow-up β¨
The function arguments are as follows:
user_pwdβ A tuple describing the user's passwd entry. Convertible topwd.struct_passwdorNoneif the user is not present in the password database. Example conversion:
user_pwd = pwd.struct_passwd(user_pwd) if user_pwd else None
user_envβ The environment the command will run in. This is a tuple of strings in βkey=valueβ format. π
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:
rcβ The result of the session init, one of thesudo.RC.*constants.sudo.RC.OKon success,0on failure, orsudo.RC.ERRORif an error occurred. β πuser_env_outβ Optional. If theinit_session()function needs to modify the user environment, it can return the new environment inuser_env_out. If this is omitted, no changes will be made touser_env. π±
π list π
list(self, argv: Tuple[str, ...], is_verbose: int, user: str)
List available privileges for the invoking user. show me what I can do, periodt π
The function arguments are as follows:
argvβ If not set toNone, an argument vector describing a command the user wishes to check against the policy. πis_verboseβ Flag indicating whether to list in verbose mode or not. πuserβ The name of a different user to list privileges for if the policy allows it. IfNone, the plugin should list the privileges of the invoking user. π€
β¨ validate β¨
validate(self)
For policy plugins that cache authentication credentials, this function is used to validate and cache the credentials (optional). cache it, validate it, slay π
π invalidate π
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:
removeβ if this flag is set, the plugin may remove the credentials instead of just invalidating them.
π
show_version
show_version(self, is_verbose: int)
Display the plugin version information to the user. Bestie, use the sudo.log_info() function for this, okay? π
The function arguments are as follows:
is_verboseβ a flag saying "hey, show me more verbose info". Currently this is1ifsudo -Vis run as the root user.
π
close
close(self, exit_status: int, error: int)
Called when a command finishes executing. π¬
Works the same as the 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:
exit_statusβ the exit status of the command if it was executed, otherwise-1.errorβ if the command could not be executed, this is set to the value oferrnoset by theexecve(2)system call, otherwise0.
π Policy plugin example π
Sudo ships with an example Python policy plugin. To try it, register it by adding the following lines to /etc/sudo.conf:
Plugin python_policy python_plugin.so \
ModulePath=/usr/share/doc/sudo/examples/example_policy_plugin.py \
ClassName=SudoPolicyPlugin
β οΈ Only one policy plugin can be enabled at a time, so you must disable any other policy plugin listed in/etc/sudo.conf, such assudoers(5). No stacking, bestie, it's not that kind of party. π
π¦ I/O plugin API π¦
I/O plugins must be registered in sudo.conf(5). For example:
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. (Yes, exactly eight. The limit is real. π)
An I/O plugin may have the following member functions:
πΈ constructor
__init__(self, user_env: Tuple[str, ...], settings: Tuple[str, ...],
version: str, user_info: Tuple[str, ...],
plugin_options: Tuple[str, ...])
Implementing this function is optional. If you skip it, the default constructor will set the keyword arguments it receives as member variables in the object. Cute, right? It just does that for you. π«Ά
The constructor matches the open() function in the C sudo plugin API.
The function arguments are as follows:
user_envβ the user's environment as a tuple of strings inβkey=valueβformat.settingsβ a tuple of user-supplied sudo settings in the form ofβkey=valueβstrings.versionβ the version of the Python I/O Plugin API.user_infoβ a tuple of information about the user running the command, in the form ofβkey=valueβstrings.plugin_optionsβ the plugin options passed as arguments in thesudo.conf(5)plugin registration. This is a tuple of strings, usually (but not necessarily) inβkey=valueβformat.
The 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 open() documentation in sudo_plugin(5).
πΈ open
open(self, argv: Tuple[str, ...],
command_info: Tuple[str, ...]) -> int
Receives the command the user wishes to run. πββοΈ
Works the same as the open() function in the C sudo plugin API except that:
- It only gets called when there is a command to be executed (and not for a version query for example).
- Other arguments of the C API
open()function are received through the constructor.
The function arguments are as follows:
argvβ a tuple of the arguments describing the command the user wishes to run.command_infoβ information about the command being run, in the form ofβkey=valueβstrings.
The 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 open() documentation in sudo_plugin(5).
The 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, log_ttyout, log_stdin, log_stdout, log_stderr
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, standard output, or standard error. See the matching calls in sudo_plugin(5). π
The function arguments are as follows:
bufβ the input (or output) buffer in the form of a string.
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 returningsudo.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 returningsudo.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
change_winsize(self, line: int, cols: int) -> int
Called whenever the window size of the terminal changes. π (yes, we're resizing bestie, hold on)
The function arguments are as follows:
lineβ the number of lines of the terminal.colsβ the number of columns of the terminal.
πΈ log_suspend
log_suspend(self, signo: int) -> int
Called whenever a command is suspended or resumed. βΈοΈβΆοΈ
The function arguments are as follows:
signoβ the number of the signal that caused the command to be suspended, orSIGCONTif the command was resumed.
πΈ show_version
show_version(self, is_verbose: int)
Display the plugin version information to the user. Use the sudo.log_info() function. β¨
The function arguments are as follows:
is_verboseβ a flag to indicate displaying more verbose information. Currently this is1ifsudo -Vis run as the root user.
πΈ close
close(self, exit_status: int, error: int) -> None
Called when a command finishes execution. π¬
Works the same as the 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:
exit_statusβ the exit status of the command if it was executed, otherwise-1.errorβ if the command could not be executed, this is set to the value oferrnoset by theexecve(2)system call, otherwise0.
π I/O plugin example π
Sudo ships with a Python I/O plugin example. To try it, register it by adding the following lines to /etc/sudo.conf:
Plugin python_io python_plugin.so \
ModulePath=/usr/share/doc/sudo/examples/example_io_plugin.py \
ClassName=SudoIOPlugin
π Audit plugin API π
Audit plugins must be registered in sudo.conf(5). For example:
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 which are optional):
π¦ constructor
__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 open() function in the C sudo plugin API.
The function arguments are as follows:
user_envβ the user's environment as a tuple of strings inβkey=valueβformat.settingsβ a tuple of user-supplied sudo settings in the form ofβkey=valueβstrings.versionβ the version of the Python Audit Plugin API.user_infoβ a tuple of information about the user running the command in the form ofβkey=valueβstrings.plugin_optionsβ the plugin options passed as arguments in thesudo.conf(5)plugin registration. This is a tuple of strings, usually (but not necessarily) inβkey=valueβformat.
π¦ open
open(self, submit_optind: int,
submit_argv: Tuple[str, ...]) -> int
The function arguments are as follows:
submit_optindβ the index intosubmit_argvthat corresponds to the first entry that is not a command line option.submit_argvβ the argument vector sudo was invoked with, including all command line options.
π¦ close
close(self, status_type: int, status: int) -> None
Called when sudo is finished, shortly before it exits. π
The function arguments are as follows:
status_typeβ the type of status being passed. One of thesudo.EXIT_REASON.*constants.statusβ depending on the value ofstatus_type, this value is either ignored, the command's exit status as returned by thewait(2)system call, the value oferrnoset by theexecve(2)system call, or the value oferrnoresulting from an error in the sudo front-end.
π¦ show_version
show_version(self, is_verbose: int) -> int
Display the plugin version information to the user. Use the sudo.log_info() function. β¨
The function arguments are as follows:
is_verboseβ a lil flag that says "hey, show me the extra wordy info." Right now it's1when you runsudo -Vas the root user. That's it, that's the whole vibe.
π accept
accept(self, plugin_name: str, plugin_type: int, command_info: Tuple[str, ...],
run_argv: Tuple[str, ...], run_envp: Tuple[str, ...]) -> int
Okay so this one gets called when a command or action gets accepted by a policy plugin or an approval plugin. Big moment, honestly. Here's what all the args mean:
plugin_nameβ the name of the plugin that said yes, or"sudo"if it was the sudo front-end doing the accepting.plugin_typeβ which kind of plugin gave the green light. Currently it's one ofsudo.PLUGIN_TYPE.POLICY,sudo.PLUGIN_TYPE.APPROVAL, orsudo.PLUGIN_TYPE.SUDO. Heads up:accept()gets called multiple times β once for each policy or approval plugin that succeeds, and once for the sudo front-end. And when it's called on behalf of the sudo front-end,command_infomight also carry info from an I/O logging plugin. Multitasking, we love to see it.- Typically an audit plugin cares about either the accept status from the sudo front-end or from the various policy and approval plugins β but not both. Also fr fr: it's totally possible for a policy plugin to accept a command that an approval plugin later rejects, in which case your audit plugin's
accept()andreject()will both fire. Plot twist, but a valid one.
- Typically an audit plugin cares about either the accept status from the sudo front-end or from the various policy and approval plugins β but not both. Also fr fr: it's totally possible for a policy plugin to accept a command that an approval plugin later rejects, in which case your audit plugin's
command_infoβ a vector of info describing the command being run. Peep thesudo_plugin(5)manual for the possible values.run_argvβ the argument vector describing a command that will be run.run_envpβ the environment the command will be run with.
π reject
reject(self, plugin_name: str, plugin_type: int, audit_msg: str,
command_info: Tuple[str, ...]) -> int
Called when a command or action gets rejected by the policy plugin. The arguments go like this:
plugin_nameβ name of the plugin that rejected the command. (rude, but okay.)plugin_typeβ what kind of plugin rejected it. Currently eithersudo.PLUGIN_TYPE.POLICY,sudo.PLUGIN_TYPE.APPROVAL, orsudo.PLUGIN_TYPE.IO.- Unlike
accept(), thereject()function is not called on behalf of the sudo front-end. Just so you know.
- Unlike
audit_msgβ an optional string explaining why the plugin rejected the command. If the plugin didn't give a reason,audit_msgwill beNone.command_infoβ a vector of info describing the rejected command. Again,sudo_plugin(5)has the possible values.
π error
error(self, plugin_name: str, plugin_type: int, audit_msg: str,
command_info: Tuple[str, ...]) -> int
This one fires when a plugin or the sudo front-end returns an error. Arguments:
plugin_nameβ name of the plugin that generated the error, or"sudo"for the sudo front-end.plugin_typeβ the type of plugin that generated the error, orSUDO_FRONT_ENDfor the sudo front-end.audit_msgβ an optional string describing the plugin error. If the plugin didn't give a description, it'll beNone.command_infoβ a vector of info describing the command.sudo_plugin(5)manual, possible values, you know the drill.
β¨ Audit plugin example β¨
Sudo ships with a Python Audit plugin example. Wanna try it? Register it by adding these lines to /etc/sudo.conf:
Plugin python_audit python_plugin.so \
ModulePath=/usr/share/doc/sudo/examples/example_audit_plugin.py \
ClassName=SudoAuditPlugin
It'll log the plugin accept / reject / error results to the output. Cute lil paper trail. π
π Approval plugin API π
Approval plugins must be registered in sudo.conf(5). Like so:
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. That's the limit bestie, don't push it.
An approval plugin may have the following member functions:
πΈ constructor
__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 just set the keyword arguments it receives as member variables in the object. Easy.
The constructor matches the open() function in the C sudo plugin API.
The function arguments are as follows:
user_envβ the user's environment as a tuple of strings in"key=value"format.settingsβ a tuple of user-supplied sudo settings, formatted as"key=value"strings.versionβ the version of the Python Approval Plugin API.user_infoβ a tuple of info about the user running the command, in the form of"key=value"strings.plugin_optionsβ the plugin options passed as arguments in thesudo.conf(5)plugin registration. This is a tuple of strings, usually (but not necessarily!) in"key=value"format.submit_optindβ the index intosubmit_argvthat corresponds to the first entry that is not a command line option.submit_argvβ the argument vector sudo was invoked with, including all command line options.
π show_version
show_version(self, is_verbose: int) -> int
Display the version. (Same as for all the other plugins. Consistent queen behavior.)
π¦ check
check(self, command_info: Tuple[str, ...], run_argv: Tuple[str, ...],
run_env: Tuple[str, ...]) -> int
This function is called after the policy plugin's check_policy has succeeded. It can reject execution of the command by returning sudo.RC.REJECT, or by raising the special exception:
raise sudo.PluginReject("some message")
β¦with the message describing the problem. In that second case, the audit plugins will get the description. Sharing is caring.
The function arguments are as follows:
command_infoβ a vector of info describing the command that will run. See thesudo_plugin(5)manual for possible values.run_argvβ argument vector describing a command that will be run.run_envβ the environment the command will be run with.
π Approval plugin example π
Sudo ships with a Python Approval plugin example. To try it, register it by adding the following lines to /etc/sudo.conf:
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). So like⦠a 9-to-5 situation. Very demure, very mindful.
π Sudoers group provider plugin API π
A group provider plugin is registered in the sudoers(5) file. For example:
Defaults group_plugin="python_plugin.so ModulePath=<path> ClassName=<class>"
Currently, only a single group plugin can be registered in sudoers. One and done.
A group provider plugin may have the following member functions:
π§ constructor
__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:
argsβ the plugin options passed as arguments in the sudoers file plugin registration. All the arguments are free form strings (not necessarily in"key=value"format).versionβ the version of the Python Group Plugin API.
π query
query(self, user: str, group: str, user_pwd: Tuple)
The query() function is used to ask the group plugin whether user is a member of group. This method is required. No skipping it.
The function arguments are as follows:
userβ the name of the user being looked up in the external group database.groupβ the name of the group being queried.user_pwdβ the password database entry for the user, if any. Ifuseris not present in the password database,user_pwdwill beNULL.
π Group plugin example π
Sudo ships with a Python group plugin example. To try it, register it in the sudoers file by adding the following lines:
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. Lowkey iconic of them.
β Hook function API β
The hook function API is currently not supported for plugins written in Python. That's it. Not yet. π
π Conversation API π
A Python plugin can interact with the user using the sudo.conv() function, which displays one or more messages described by the sudo.ConvMessage class. This is the Python equivalent of the conversation() function in the C sudo plugin API. A plugin should not attempt to read directly from the standard input or the user's tty (neither of which are guaranteed to exist). Rude of it to assume, honestly.
The sudo.ConvMessage class specifies how the user interaction should occur:
sudo.ConvMessage(msg_type: int, msg: str, timeout: int)
sudo.ConvMessage member variables:
msg_typeβ specifies the type of the conversation. See thesudo.CONV.*constants below.msgβ the message to display to the user. The caller must include a trailing newline inmsgif one is to be displayed.timeoutβ optional. The maximum amount of time for the conversation, in seconds. If the timeout is exceeded, thesudo.conv()function will raise asudo.ConversationInterruptedexception. The default is to wait forever (no timeout). Patient king.
To specify the message type, the following constants are available:
sudo.CONV.PROMPT_ECHO_OFFsudo.CONV.PROMPT_ECHO_ONsudo.CONV.ERROR_MSGsudo.CONV.INFO_MSGsudo.CONV.PROMPT_MASKsudo.CONV.PROMPT_ECHO_OKsudo.CONV.PREFER_TTY
need the whole breakdown of what each message type actually means? that lives in the sudo_plugin(5) manual, bestie β go peek there. π«Ά
The sudo.conv() function is the one that actually does the talking to the human:
sudo.conv(message(s), on_suspend=suspend_function,
on_resume=resume_function)
Here's the tea on the arguments:
message(s)β one or more messages (each one asudo.ConvMessage) and each one describes a conversation. You need at least one, no zero-message situations allowed. β¨on_suspendβ optional callback, gets called when the conversation gets suspended (classic example: user smashes control-Z π). The function you hand over must take exactly one argument, and that argument gets filled with the number of the signal that caused the process to be suspended.on_resumeβ optional callback, fires when that previously suspended conversation comes back to life. Same deal: it takes a single argument, filled with the number of the signal that caused the process to be suspended.
And sudo.conv() can throw these at you:
sudo.SudoExceptionβ if the conversation just fails, like when the conversation function isn't available. πsudo.ConversationInterruptedβ if the conversation function returns an error, e.g. the timeout passed or the user hit control-C and interrupted the whole thing. π
πΈ Conversation example πΈ
Sudo ships with an example plugin that shows off the Python conversation API, because of course it does. Want to try it? Register it by adding these lines to /etc/sudo.conf:
Plugin python_io python_plugin.so \
ModulePath=/usr/share/doc/sudo/examples/example_conversation.py \
ClassName=ReasonLoggerIOPlugin
π¬ Information / error display API π¬
sudo.log_info(string(s), sep=" ", end="\n")
sudo.log_error(string(s), sep=" ", end="\n")
Wanna show the user some info? That's sudo.log_info(). Wanna show them an error? That's sudo.log_error(). The syntax is basically giving Python's print() function, very familiar, very cute. π
The arguments:
string(s)β one or more strings to display.sepβ optional string used as the separator between the strings you passed in. Default is a space character, (' ').endβ optional string displayed at the end of the message. Default is a newline character, ('\n').
π¦ Debug API π¦
Debug messages are not visible to the user β they only get logged if debugging is explicitly enabled in sudo.conf(5). Python plugins can call sudo.debug() to plug right into sudo's debug system. iconic behaviour honestly.
β¨ Enabling debugging in sudo.conf β¨
To turn debug messages on, add a Debug line to sudo.conf(5) with the program set to python_plugin.so. For example, to stash debug output in /var/log/sudo_python_debug, use a line like this:
Debug python_plugin.so /var/log/sudo_python_debug \
plugin@trace,c_calls@trace
The debug options look like multiple βsubsystem@levelβ strings, separated by commas (,). So if you only want to see the output of sudo.debug() calls, you'd do:
Debug python_plugin.so /var/log/sudo_python_debug plugin@trace
More details live in sudo_conf(5). π
The subsystems that are most interesting if you're building Python plugins:
pluginβ logs every singlesudo.debug()API call.py_callsβ logs whenever a C function calls into the python module. Like when the__init__()function gets called.c_callsβ logs whenever python calls into a C sudo API function.internalβ logs internal functions of the python language wrapper plugin.sudo_cbβ logs when sudo calls into the python plugin API.loadβ logs python plugin loading / unloading events.
You can also pass βallβ as the subsystem name and get debug messages for every subsystem. one word, maximum coverage. π
The sudo.debug() function is defined as:
sudo.debug(level, message(s))
Its arguments:
levelβ an integer, use one of the log level constants below.message(s)β one or more messages to log.
Available log levels (name in sudo.conf, the Python constant, and what it's for):
critβsudo.DEBUG.CRITβ critical errorserrβsudo.DEBUG.ERRORβ non-critical errorswarnβsudo.DEBUG.WARNβ non-fatal warningsnoticeβsudo.DEBUG.NOTICEβ non-error condition noticesdiagβsudo.DEBUG.DIAGβ diagnostic messagesinfoβsudo.DEBUG.INFOβ informational messagetraceβsudo.DEBUG.TRACEβ log function enter/exitdebugβsudo.DEBUG.DEBUGβ very verbose debugging
π Using the logging module π
Alternatively, a plugin can just use Python's built in logging module too, because options are a vibe. Sudo adds its log handler to the root logger, so by default all output of a logger gets forwarded to the sudo log system, exactly as if it had called sudo.debug.
The sudo log handler maps each Python log level of a message to the appropriate sudo debug level. The sudo debug system will only receive messages that aren't filtered out by the Python loggers. For example, the log level of the python logger acts as an additional filter for the log messages, and it's usually very different from whatever level is set in sudo.conf for the sudo debug system. π
π Debug example π
Sudo ships with an example debug plugin. To try it, register it by adding these lines to /etc/sudo.conf:
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
π Option conversion API π
The Python plugin API has two convenience functions to convert options in βkey=valueβ format to a dictionary and vice versa. little translation service, so thoughtful.
options_as_dict
options_as_dict(options)
The arguments:
optionsβ an iterable (tuple, list, etc.) of strings, each in βkey=valueβ format. This is how the plugin API passes options and settings to a Python plugin.
The function returns the resulting dictionary. Each string of the passed-in options gets split at the first equal sign (=) into a key and a value. Dictionary keys will never contain this symbol β but values may. π«Ά
options_from_dict
options_from_dict(options_dict)
The arguments:
options_dictβ a dictionary where both the key and the value are strings. The key should not contain an equal sign (=), otherwise the resulting string will have a different meaning. However, this is not currently enforced. π
The function returns a tuple containing the strings in βkey=valueβ form for each key and value in the options_dict dictionary you passed in. This is how the plugin API accepts options and settings.
π PLUGIN API CHANGELOG (Python) π
None yet
nothing's happened yet bestie, the changelog is a blank page waiting for its main character moment. β
π§ LIMITATIONS π§
A maximum of 8 python I/O plugins can be loaded at once. If /etc/sudo.conf contains more than that, those extra ones will be rejected with a warning message. π
The Event API and the hook function API is currently not accessible for Python plugins. sad but true.
π SEE ALSO π
sudo.conf(5), sudo_plugin(5), sudoers(5), sudo(8)
π AUTHORS π
Many people have worked on sudo over the years; this version consists of code written primarily by:
Todd C. Miller
See the CONTRIBUTORS.md file in the sudo distribution (https://www.sudo.ws/about/contributors/) for an exhaustive list of people who have contributed to sudo. everyone say thank you π
π BUGS π
Python plugin support is currently considered experimental.
If you believe you have found a bug in sudo_plugin_python, you can either file a bug report in the sudo bug database, https://bugzilla.sudo.ws/, or open an issue at https://github.com/sudo-project/sudo/issues. If you'd prefer email, messages may be sent to the sudo-workers mailing list, https://www.sudo.ws/mailman/listinfo/sudo-workers (public) or <sudo@sudo.ws> (private).
π¨ Please do not report security vulnerabilities through public GitHub issues, Bugzilla or mailing lists. Instead, report them via email to<Todd.Miller@sudo.ws>. You may encrypt your message with PGP if you'd like, using the key found athttps://www.sudo.ws/dist/PGPKEYS.
π SECURITY CONSIDERATIONS π
All Python plugin handling is implemented inside the python_plugin.so dynamic plugin. So if no Python plugin is registered in sudo.conf(5) or the sudoers file, sudo will not load the Python interpreter or the Python libraries. zero python, zero worries. β¨
As sudo runs plugins as root, care must be taken when writing Python plugins to avoid creating security vulnerabilities, just as one would when writing plugins in C. this is the serious part, bestie β pay attention. π
π« SUPPORT π«
Limited free support is available via the sudo-users mailing list, see https://www.sudo.ws/mailman/listinfo/sudo-users to subscribe or search the archives.
π DISCLAIMER π
sudo is provided βAS ISβ and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. See the LICENSE.md file distributed with sudo or https://www.sudo.ws/about/license/ for complete details.
and that's the whole page, bestie!! π this was Sudo 1.9.17p2, dated February 26, 2025, and you just read SUDO_PLUGIN_PYTHON(5) β go forth and write the most iconic plugin of your life. no cap, you've got this. πβ¨π¦
π¦ where this page comes from
- centos-stream 10: sudo-python-plugin 1.9.17-13.p2.el10 Β· ISC
- centos-stream 9: sudo-python-plugin 1.9.17p2-6.el9 Β· ISC
- fedora 43: sudo-python-plugin 1.9.17-7.p2.fc43 Β· ISC
- fedora 44: sudo-python-plugin 1.9.17-10.p2.fc44 Β· ISC
- fedora 44: sudo-python-plugin 1.9.17-7.p2.fc44 Β· ISC
- π the page's license: ISC
- Copyright (c) 2019-2021 Robert Manner <robert.manner@oneidentity.com>
- Copyright (c) 2019-2025 Todd C. Miller <Todd.Miller@sudo.ws>
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms