SUDO_PLUGIN_PYTHON(5)

πŸ“¦
version 1.9.17p2 Β· 3 versions
, in centos-stream 10, centos-stream 9, fedora 43, fedora 44

πŸ’– 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 β€” value 1 βœ…
  • sudo.RC.ACCEPT β€” value 1 πŸ’–
  • sudo.RC.REJECT β€” value 0 🚫
  • 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 of ModulePath will 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 only sudo.Plugin that 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 the sudo.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. The sudo.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 the sudo.RC.* constants. sudo.RC.ACCEPT if the command is allowed, sudo.RC.REJECT if not allowed, sudo.RC.ERROR for a general error, or sudo.RC.USAGE_ERROR for 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, and runas_gid keys. For a list of recognized keys and supported values, see the check_policy() documentation in sudo_plugin(5). πŸ“‹
  • argv_out β€” Optional (only required when the command is accepted). The arguments to pass to the execve(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 to pwd.struct_passwd or None if 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 the sudo.RC.* constants. sudo.RC.OK on success, 0 on failure, or sudo.RC.ERROR if an error occurred. βœ…πŸ’€
  • user_env_out β€” Optional. If the init_session() function needs to modify the user environment, it can return the new environment in user_env_out. If this is omitted, no changes will be made to user_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 to None, 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. If None, 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 is 1 if sudo -V is 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 of errno set by the execve(2) system call, otherwise 0.

πŸŽ€ 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 as sudoers(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 the sudo.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 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

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, or SIGCONT if 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 is 1 if sudo -V is 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 of errno set by the execve(2) system call, otherwise 0.

πŸŽ€ 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 the sudo.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 into submit_argv that 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 the sudo.EXIT_REASON.* constants.
  • status β€” depending on the value of status_type, this value is either ignored, the command's exit status as returned by the wait(2) system call, the value of errno set by the execve(2) system call, or the value of errno resulting 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's 1 when you run sudo -V as 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 of sudo.PLUGIN_TYPE.POLICY, sudo.PLUGIN_TYPE.APPROVAL, or sudo.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_info might 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() and reject() will both fire. Plot twist, but a valid one.
  • command_info β€” a vector of info describing the command being run. Peep the sudo_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 either sudo.PLUGIN_TYPE.POLICY, sudo.PLUGIN_TYPE.APPROVAL, or sudo.PLUGIN_TYPE.IO.
    • Unlike accept(), the reject() function is not called on behalf of the sudo front-end. Just so you know.
  • audit_msg β€” an optional string explaining why the plugin rejected the command. If the plugin didn't give a reason, audit_msg will be None.
  • 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, or SUDO_FRONT_END for the sudo front-end.
  • audit_msg β€” an optional string describing the plugin error. If the plugin didn't give a description, it'll be None.
  • 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 the sudo.conf(5) plugin registration. This is a tuple of strings, usually (but not necessarily!) in "key=value" format.
  • submit_optind β€” the index into submit_argv that 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 the sudo_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. If user is not present in the password database, user_pwd will be NULL.

🌈 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 the sudo.CONV.* constants below.
  • msg β€” the message to display to the user. The caller must include a trailing newline in msg if one is to be displayed.
  • timeout β€” optional. The maximum amount of time for the conversation, in seconds. If the timeout is exceeded, the sudo.conv() function will raise a sudo.ConversationInterrupted exception. The default is to wait forever (no timeout). Patient king.

To specify the message type, the following constants are available:

  • sudo.CONV.PROMPT_ECHO_OFF
  • sudo.CONV.PROMPT_ECHO_ON
  • sudo.CONV.ERROR_MSG
  • sudo.CONV.INFO_MSG
  • sudo.CONV.PROMPT_MASK
  • sudo.CONV.PROMPT_ECHO_OK
  • sudo.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 a sudo.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 single sudo.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 errors
  • err β†’ sudo.DEBUG.ERROR β€” non-critical errors
  • warn β†’ sudo.DEBUG.WARN β€” non-fatal warnings
  • notice β†’ sudo.DEBUG.NOTICE β€” non-error condition notices
  • diag β†’ sudo.DEBUG.DIAG β€” diagnostic messages
  • info β†’ sudo.DEBUG.INFO β€” informational message
  • trace β†’ sudo.DEBUG.TRACE β€” log function enter/exit
  • debug β†’ 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 at https://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