SUDO_PLUGIN(5)
okay bestie, deep breath ๐ this is sudo_plugin(5) from the File Formats Manual โ the entire Sudo Plugin API โ and it is a long one, so we're taking it in pieces. grab a snack ๐
โจ NAME โจ
sudo_plugin โ Sudo Plugin API ๐
๐ DESCRIPTION ๐
okay so starting with version 1.8, sudo looked at the world and said "we're a plugin API now, for policy and session logging," and honestly? iconic.
Plugins can be compiled as dynamic shared objects (that's the default on systems that support them, no cap) or compiled statically right into the sudo binary itself. Both are valid, both slay.
By default, the sudoers plugin is the one serving up audit, security policy and I/O logging capabilities ๐ซถ. But via the plugin API, sudo can be configured to use alternate plugins provided by third parties. Which plugins actually get used? That's specified in the sudo.conf(5) file. iykyk.
The API is versioned with a major and a minor number, and here's the tea โ:
- the minor number is incremented when additions are made
- the major number is incremented when incompatible changes are made
A plugin should check the version passed to it and make sure that the major version matches ๐. fr fr, don't skip that.
The plugin API is defined by the sudo_plugin.h header file.
๐ Policy plugin API ๐
A policy plugin must declare and populate a policy_plugin struct in the global scope. That struct is basically a little bag of pointers to the functions that implement the sudo policy checks ๐
.
The name of the symbol should be specified in sudo.conf(5) along with a path to the plugin, so that sudo can load it.
struct policy_plugin {
#define SUDO_POLICY_PLUGIN 1
unsigned int type; /* always SUDO_POLICY_PLUGIN */
unsigned int version; /* always SUDO_API_VERSION */
int (*open)(unsigned int version, sudo_conv_t conversation,
sudo_printf_t plugin_printf, char * const settings[],
char * const user_info[], char * const user_env[],
char * const plugin_options[], const char **errstr);
void (*close)(int exit_status, int error);
int (*show_version)(int verbose);
int (*check_policy)(int argc, char * const argv[],
char *env_add[], char **command_info[],
char **argv_out[], char **user_env_out[], const char **errstr);
int (*list)(int argc, char * const argv[], int verbose,
const char *list_user, const char **errstr);
int (*validate)(const char **errstr);
void (*invalidate)(int remove);
int (*init_session)(struct passwd *pwd, char **user_env[],
const char **errstr);
void (*register_hooks)(int version,
int (*register_hook)(struct sudo_hook *hook));
void (*deregister_hooks)(int version,
int (*deregister_hook)(struct sudo_hook *hook));
struct sudo_plugin_event * (*event_alloc)(void);
};
The policy_plugin struct has the following fields:
type
The type field should always be set to SUDO_POLICY_PLUGIN. always. no notes. โจ
version
The version field should be set to SUDO_API_VERSION.
This is how sudo figures out which API version the plugin was built against ๐.
open
int (*open)(unsigned int version, sudo_conv_t conversation,
sudo_printf_t plugin_printf, char * const settings[],
char * const user_info[], char * const user_env[],
char * const plugin_options[], const char **errstr);
This one returns:
1on success ๐0on failure-1if a general error occurred-2if there was a usage error
and for that -2 case specifically: sudo will print a usage message before it exits. noted ๐
If an error occurs, the plugin may optionally call the conversation() or plugin_printf() function with SUDO_CONF_ERROR_MSG to present additional error information to the user.
The function arguments are as follows:
versionโ the version passed in by sudo. It lets the plugin determine the major and minor version number of the plugin API supported by sudo.conversationโ a pointer to theconversation()function, which the plugin can use to interact with the user (peep the โConversation APIโ section for the deets). Returns0on success and-1on failure.plugin_printfโ a pointer to aprintf()-style function that may be used to display informational or error messages (again, โConversation APIโ for the full story). Returns the number of characters printed on success and-1on failure.settingsโ a vector of user-supplied sudo settings in the form of โname=valueโ strings. The vector is terminated by aNULLpointer. These settings correspond to options the user specified when running sudo โ which means they will only be present when the corresponding option has actually been specified on the command line.
When parsing settings, the plugin should split on the first equal sign (โ=โ), since the name field will never include one itself but the value might. important detail, don't fumble it ๐
The following values may be set by sudo:
bsdauth_type=stringโ Authentication type, if specified by the-aoption, to use on systems where BSD authentication is supported.closefrom=numberโ If specified, the user has requested via the-Coption that sudo close all files descriptors with a value of number or higher. The plugin may optionally pass this, or another value, back in thecommand_infolist.cmnd_chroot=stringโ The root directory (seechroot(2)) to run the command in, as specified by the user via the-Roption. The plugin may ignore or restrict the user's ability to specify a new root directory. Only available starting with API version1.16.cmnd_cwd=stringโ The working directory to run the command in, as specified by the user via the-Doption. The plugin may ignore or restrict the user's ability to specify a new working directory. Only available starting with API version1.16.debug_flags=stringโ A debug file path name followed by a space and a comma-separated list of debug flags that correspond to the plugin'sDebugentry insudo.conf(5), if there is one. The flags are passed to the plugin exactly as they appear insudo.conf(5). The syntax used by sudo and the sudoers plugin issubsystem@priority, but a plugin is free to use a different format so long as it does not include a comma (โ,โ). Prior to sudo 1.8.12, there was no way to specify plugin-specificdebug_flags, so the value was always the same as that used by the sudo front-end and did not include a path name, only the flags themselves. As of version 1.7 of the plugin interface, sudo will only passdebug_flagsifsudo.conf(5)contains a plugin-specificDebugentry.ignore_ticket=boolโ Set totrueif the user specified the-koption along with a command, indicating that the user wishes to ignore any cached authentication credentials.
okay so the manpage genuinely prints this next bit right here, and we're keeping it word-for-word because that's the assignment ๐: โimplied_shell to true. This allows sudo with no arguments to be used similarly to su(1). If the plugin does not to support this usage, it may return a value of -2 from the check_policy() function, which will cause sudo to print a usage message and exit.โ
implied_shell=boolโ If the user does not specify a program on the command line, sudo will pass the plugin the path to the user's shell and setlogin_class=stringโ BSD login class to use when setting resource limits and nice value, if specified by the-coption.login_shell=boolโ Set totrueif the user specified the-ioption, indicating that the user wishes to run a login shell.max_groups=intโ The maximum number of groups a user may belong to. This will only be present if there is a corresponding setting insudo.conf(5).network_addrs=listโ A space-separated list of IP network addresses and netmasks in the form โaddr/netmaskโ, e.g., โ192.168.1.2/255.255.255.0โ. The address and netmask pairs may be either IPv4 or IPv6, depending on what the operating system supports. If the address contains a colon (โ:โ), it is an IPv6 address, else it is IPv4.noninteractive=boolโ Set totrueif the user specified the-noption, indicating that sudo should operate in non-interactive mode. The plugin may reject a command run in non-interactive mode if user interaction is required.plugin_dir=stringโ The default plugin directory used by the sudo front-end. This is the default directory set at compile time and may not correspond to the directory the running plugin was loaded from. It may be used by a plugin to locate support files.plugin_path=stringโ The path name of plugin loaded by the sudo front-end. The path name will be a fully-qualified unless the plugin was statically compiled into sudo.preserve_environment=boolโ Set totrueif the user specified the-Eoption, indicating that the user wishes to preserve the environment.preserve_groups=boolโ Set totrueif the user specified the-Poption, indicating that the user wishes to preserve the group vector instead of setting it based on the runas user.progname=stringโ The command name that sudo was run as, typically โsudoโ or โsudoeditโ.prompt=stringโ The prompt to use when requesting a password, if specified via the-poption.
remote_host=stringโ the name of the remote host we're running the command on, if the user passed the-hoption. Bestie, real talk: running on a remote host is meant to be handled by a helper program that gets executed instead of whatever command the user typed. The sudo front-end itself? Only local host vibes. It literally cannot do remote. Only a thing starting with API version 1.4. ๐ฐ๏ธrun_shell=boolโtrueif the user hit-s, aka they want to run a shell. Simple as. ๐runas_group=stringโ the group name or group-ID to run the command as, if the user specified it via the-goption.runas_user=stringโ the user name or user-ID to run the command as, if the user specified it via the-uoption.selinux_role=stringโ the SELinux role to use when executing the command, if the user gave it with the-roption.selinux_type=stringโ the SELinux type to use when executing the command, if the user gave it with the-toption.set_home=boolโtrueif the user specified the-Hoption. When it's true, set theHOMEenvironment variable to the target user's home directory. ๐sudoedit=boolโtruewhen the-eoption is specified, or when it's invoked assudoedit. The plugin shall substitute an editor intoargvin thecheck_policy()function, or return-2with a usage error if the plugin doesn't support sudoedit. Want the full tea? Go check thecheck_policysection. โ๏ธtimeout=stringโ the command timeout the user specified via the-Toption. Heads up: not all plugins support command timeouts, and the ability of the user to set a timeout may be restricted by policy. The format of that timeout string is plugin-specific. โณ
Additional settings may get added in the future, so the plugin should just silently ignore any settings it doesn't recognize. Don't be nosy, bestie. ๐
๐ซถ user_info
A vector of information about the user running the command, in the form of โname=valueโ strings. The vector is terminated by a NULL pointer.
When parsing user_info, the plugin should split on the first equal sign (โ=โ) since the name field will never include one itself but the value might. iykyk.
The following values may be set by sudo:
cols=intโ the number of columns the user's terminal supports. If there's no terminal device available, a default value of80is used.cwd=stringโ the user's current working directory. ๐egid=gid_tโ the effective group-ID of the user invoking sudo.euid=uid_tโ the effective user-ID of the user invoking sudo.gid=gid_tโ the real group-ID of the user invoking sudo.groups=listโ the user's supplementary group list, formatted as a string of comma-separated group-IDs.host=stringโ the local machine's hostname, as returned by thegethostname(2)system call.lines=intโ the number of lines the user's terminal supports. If there's no terminal device available, a default value of24is used.pgid=intโ the ID of the process group that the running sudo process is a member of. Only available starting with API version 1.2.pid=intโ the process ID of the running sudo process. Only available starting with API version 1.2.ppid=intโ the parent process ID of the running sudo process. Only available starting with API version 1.2.rlimit_as=soft,hardโ the maximum size the process's address space may grow to (in bytes), if the operating system supports it. The soft and hard limits are separated by a comma. A value of โinfinityโ means there's no limit. Only available starting with API version 1.16.rlimit_core=soft,hardโ the largest size core dump file that may be created (in bytes). Soft and hard limits separated by a comma. A value of โinfinityโ means no limit. Only available starting with API version 1.16.rlimit_cpu=soft,hardโ the maximum amount of CPU time the process may use (in seconds). Soft and hard limits separated by a comma. A value of โinfinityโ means no limit. Only available starting with API version 1.16.rlimit_data=soft,hardโ the maximum size of the data segment for the process (in bytes). Soft and hard limits separated by a comma. A value of โinfinityโ means no limit. Only available starting with API version 1.16.rlimit_fsize=soft,hardโ the largest size file the process may create (in bytes). Soft and hard limits separated by a comma. A value of โinfinityโ means no limit. Only available starting with API version 1.16.rlimit_locks=soft,hardโ the maximum number of locks the process may establish, if the operating system supports it. Soft and hard limits separated by a comma. A value of โinfinityโ means no limit. Only available starting with API version 1.16.rlimit_memlock=soft,hardโ the maximum size the process may lock in memory (in bytes), if the operating system supports it. Soft and hard limits separated by a comma. A value of โinfinityโ means no limit. Only available starting with API version 1.16.rlimit_nofile=soft,hardโ the maximum number of files the process may have open. Soft and hard limits separated by a comma. A value of โinfinityโ means no limit. Only available starting with API version 1.16.rlimit_nproc=soft,hardโ the maximum number of processes the user may run simultaneously. Soft and hard limits separated by a comma. A value of โinfinityโ means no limit. Only available starting with API version 1.16.rlimit_rss=soft,hardโ the maximum size the process's resident set size may grow to (in bytes). Soft and hard limits separated by a comma. A value of โinfinityโ means no limit. Only available starting with API version 1.16.rlimit_stack=soft,hardโ the maximum size the process's stack may grow to (in bytes). Soft and hard limits separated by a comma. A value of โinfinityโ means no limit. Only available starting with API version 1.16.sid=intโ the session ID of the running sudo process, or0if sudo isn't part of a POSIX job control session. Only available starting with API version 1.2.tcpgid=intโ the ID of the foreground process group associated with the terminal device associated with the sudo process, or0if there's no terminal present. Only available starting with API version 1.2.tty=stringโ the path to the user's terminal device. If the user has no terminal device associated with the session, the value will be empty, like โtty=โ. ๐ฅ๏ธuid=uid_tโ the real user-ID of the user invoking sudo.umask=octalโ the invoking user's file creation mask. Only available starting with API version 1.10.user=stringโ the name of the user invoking sudo.
๐ธ user_env
The user's environment, in the form of a NULL-terminated vector of โname=valueโ strings.
When parsing user_env, the plugin should split on the first equal sign (โ=โ) since the name field will never include one itself but the value might. Same rule as user_info, bestie โ don't overthink it. ๐
โจ plugin_options
Any (non-comment) strings immediately after the plugin path get passed as arguments to the plugin. These arguments are split on a white space boundary and passed to the plugin in the form of a NULL-terminated array of strings. If no arguments were specified, plugin_options will be the NULL pointer.
NOTE: theplugin_optionsparameter is only available starting with API version 1.2. A plugin must check the API version specified by the sudo front-end before usingplugin_options. Not doing that? Yeah, that may result in a crash. ๐ Please don't.
errstr (still part of the open() fam btw) ๐
If the open() function hands back literally anything that isn't 1, the plugin is allowed to stash a lil message describing the failure or the error into errstr. Then the sudo front-end will pass that value along to any registered audit plugins. The string you stash in errstr has to stay valid until the plugin's close() function gets called โ no letting it die early bestie, it's on the clock. โณ
NOTE: theerrstrparameter is only available starting with API version 1.15. A plugin must check the API version specified by the sudo front-end before usingerrstr. Failure to do so may result in a crash. ๐ Like, actually. So check it.
close ๐
void (*close)(int exit_status, int error);
The close() function gets called when sudo is finished, shortly before it exits. Starting with API version 1.15, close() is called regardless of whether or not a command was actually executed. Which is so nice actually, because it makes it possible for plugins to perform cleanup even when a command was not run. ๐งน
But here's the catch: it is not possible to tell whether a command was run based solely on the arguments passed to the close() function. So if you need to know, the plugin must keep track of whether or not the check_policy() function returned successfully. No shortcuts, keep your own receipts. ๐งพ
The function arguments are as follows:
exit_statusโ the command's exit status, as returned by thewait(2)system call, or zero if no command was run. The value ofexit_statusis undefined iferroris non-zero. ๐errorโ if the command could not be executed, this is set to the value oferrnoset by theexecve(2)system call. The plugin is responsible for displaying error information via theconversation()orplugin_printf()function. If the command was successfully executed, the value oferroris zero.
If no close() function is defined, no I/O logging plugins are loaded, and neither the timeout not use_pty options are set in the command_info list, the sudo front-end may execute the command directly instead of running it as a child process. ๐
show_version โจ
int (*show_version)(int verbose);
The show_version() function is called by sudo when the user specifies the -V option. The plugin may display its version information to the user via the conversation() or plugin_printf() function using SUDO_CONV_INFO_MSG. If the user requests detailed version information, the verbose flag will be set. ๐ข
Returns 1 on success, 0 on failure, -1 if a general error occurred, or -2 if there was a usage error, although the return value is currently ignored. (So like, return it anyway, it's polite. ๐ซถ)
check_policy ๐ฅ (the big one, main character energy fr)
int (*check_policy)(int argc, char * const argv[], char *env_add[],
char **command_info[], char **argv_out[], char **user_env_out[],
const char **errstr);
The check_policy() function is called by sudo to determine whether the user is allowed to run the specified commands. It's giving gatekeeper, but make it security. ๐ช
If the sudoedit option was enabled in the settings array passed to the open() function, the user has requested sudoedit mode. sudoedit is a mechanism for editing one or more files where an editor is run with the user's credentials instead of with elevated privileges. sudo achieves this by creating user-writable temporary copies of the files to be edited and then overwriting the originals with the temporary copies after editing is complete. ๐
If the plugin supports sudoedit, it should choose the editor to be used, potentially from a variable in the user's environment, such as EDITOR, and include it in argv_out (note that environment variables may include command line options). The files to be edited should be copied from argv into argv_out, separated from the editor and its arguments by a -- element. The -- will be removed by sudo before the editor is executed. The plugin should also set sudoedit=true in the command_info list. ๐
The check_policy() function returns 1 if the command is allowed, 0 if not allowed, -1 for a general error, or -2 for a usage error or if sudoedit was specified but is unsupported by the plugin. In the latter case, sudo will print a usage message before it exits. If an error occurs, the plugin may optionally call the conversation() or plugin_printf() function with SUDO_CONF_ERROR_MSG to present additional error information to the user. ๐ญ
The function arguments are as follows:
argcโ the number of elements inargv, not counting the finalNULLpointer.argvโ the argument vector describing the command the user wishes to run, in the same form as what would be passed to theexecve(2)system call. The vector is terminated by aNULLpointer.env_addโ additional environment variables specified by the user on the command line in the form of aNULL-terminated vector ofname=valuestrings. The plugin may reject the command if one or more variables are not allowed to be set, or it may silently ignore such variables.
When parsing env_add, the plugin should split on the first equal sign (=) since the name field will never include one itself but the value might. ๐
command_infoโ information about the command being run in the form ofname=valuestrings. These values are used by sudo to set the execution environment when running a command. The plugin is responsible for creating and populating the vector, which must be terminated with aNULLpointer. The following values are recognized by sudo:chroot=stringโ the root directory to use when running the command. ๐closefrom=numberโ if specified, sudo will close all files descriptors with a value ofnumberor higher.command=stringโ fully qualified path to the command to be executed.cwd=stringโ the current working directory to change to when executing the command. If sudo is unable to change to the new working directory, the command will not be run unlesscwd_optionalis also set (see below).cwd_optional=boolโ if enabled, sudo will treat an inability to change to the new working directory as a non-fatal error. This setting has no effect unlesscwdis also set.exec_background=boolโ by default, sudo runs a command as the foreground process as long as sudo itself is running in the foreground. Whenexec_backgroundis enabled and the command is being run in a pseudo-terminal (due to I/O logging or theuse_ptysetting), the command will be run as a background process. Attempts to read from the controlling terminal (or to change terminal settings) will result in the command being suspended with theSIGTTINsignal (orSIGTTOUin the case of terminal settings). If this happens when sudo is a foreground process, the command will be granted the controlling terminal and resumed in the foreground with no user intervention required. The advantage of initially running the command in the background is that sudo need not read from the terminal unless the command explicitly requests it. Otherwise, any terminal input must be passed to the command, whether it has required it or not (the kernel buffers terminals so it is not possible to tell whether the command really wants the input). This is different from historic sudo behavior or when the command is not being run in a pseudo-terminal.
For this to work seamlessly, the operating system must support the automatic restarting of system calls. Unfortunately, not all operating systems do this by default, and even those that do may have bugs. For example, macOS fails to restart the tcgetattr() and tcsetattr() system calls (this is a bug in macOS). Furthermore, because this behavior depends on the command stopping with the SIGTTIN or SIGTTOU signals, programs that catch these signals and suspend themselves with a different signal (usually SIGTOP) will not be automatically foregrounded. Some versions of the linux su(1) command behave this way. Because of this, a plugin should not set exec_background unless it is explicitly enabled by the administrator and there should be a way to enabled or disable it on a per-command basis. โ ๏ธ
This setting has no effect unless I/O logging is enabled or use_pty is enabled.
execfd=numberโ if specified, sudo will use thefexecve(2)system call to execute the command instead ofexecve(2). The specifiednumbermust refer to an open file descriptor.iolog_compress=boolโ set to true if the I/O logging plugins, if any, should compress the log data. This is a hint to the I/O logging plugin which may choose to ignore it.iolog_group=stringโ the group that will own newly created I/O log files and directories. This is a hint to the I/O logging plugin which may choose to ignore it.iolog_mode=octalโ the file permission mode to use when creating I/O log files and directories. This is a hint to the I/O logging plugin which may choose to ignore it.iolog_user=stringโ the user that will own newly created I/O log files and directories. This is a hint to the I/O logging plugin which may choose to ignore it.
iolog_path=stringโ okay so this is the fully qualified path to the file or directory in which the I/O log is to be stored. It's literally just a hint to the I/O logging plugin, bestie โ the plugin may choose to ignore it. And if no I/O logging plugin is loaded, this setting has no effect at all. ๐iolog_stdin=boolโ Set totrueif the I/O logging plugins, if any, should log the standard input if it is not connected to a terminal device. Again, just a hint to the I/O logging plugin, which may choose to ignore it. ๐ฆiolog_stdout=boolโ Set totrueif the I/O logging plugins, if any, should log the standard output if it is not connected to a terminal device. Hint energy only โ the I/O logging plugin may choose to ignore it. ๐ธiolog_stderr=boolโ Set totrueif the I/O logging plugins, if any, should log the standard error if it is not connected to a terminal device. This is a hint to the I/O logging plugin, which may choose to ignore it. ๐iolog_ttyin=boolโ Set totrueif the I/O logging plugins, if any, should log all terminal input. This only includes input typed by the user and not from a pipe or redirected from a file. It's a hint to the I/O logging plugin, which may choose to ignore it. ๐iolog_ttyout=boolโ Set totrueif the I/O logging plugins, if any, should log all terminal output. This only includes output to the screen, not output to a pipe or file. Just a hint โ the I/O logging plugin may choose to ignore it. โจlogin_class=stringโ BSD login class to use when setting resource limits and nice value (optional). This option is only set on systems that support login classes. ๐nice=intโ Nice value (priority) to use when executing the command. The nice value, if specified, overrides the priority associated with thelogin_classon BSD systems. ๐noexec=boolโ If set, prevent the command from executing other programs. ๐preserve_fds=listโ A comma-separated list of file descriptors that should be preserved, regardless of the value of theclosefromsetting. Only available starting with API version 1.5. ๐ซถpreserve_groups=boolโ If set,sudowill preserve the user's group vector instead of initializing the group vector based onrunas_user. ๐rlimit_as=soft,hardโ The maximum size to which the process's address space may grow (in bytes), if supported by the operating system. Soft and hard limits are comma-separated. Give just one value and both the hard and soft limits get set. A value of โinfinityโ means there is no limit. A value of โuserโ will cause the invoking user's resource limit to be preserved. A value of โdefaultโ will cause the target user's default resource limit to be used on systems that allow per-user resource limits to be configured. Only available starting with API version 1.17. โญrlimit_core=soft,hardโ The largest size core dump file that may be created (in bytes). The soft and hard limits are separated by a comma. If only a single value is specified, both the hard and soft limits are set. A value of โinfinityโ indicates that there is no limit. A value of โuserโ will cause the invoking user's resource limit to be preserved. A value of โdefaultโ will cause the target user's default resource limit to be used on systems that allow per-user resource limits to be configured. Only available starting with API version 1.17. ๐rlimit_cpu=soft,hardโ The maximum amount of CPU time that the process may use (in seconds). Comma separates soft and hard limits. One value means both get set. โinfinityโ = no limit. โuserโ preserves the invoking user's resource limit. โdefaultโ uses the target user's default resource limit on systems that allow per-user resource limits to be configured. Only available starting with API version 1.17. ๐ฅrlimit_data=soft,hardโ The maximum size of the data segment for the process (in bytes). Soft and hard limits are separated by a comma. If only a single value is specified, both the hard and soft limits are set. A value of โinfinityโ indicates that there is no limit. A value of โuserโ will cause the invoking user's resource limit to be preserved. A value of โdefaultโ will cause the target user's default resource limit to be used on systems that allow per-user resource limits to be configured. Only available starting with API version 1.17. ๐งrlimit_fsize=soft,hardโ The largest size file that the process may create (in bytes). Soft and hard limits? Comma-separated. One value sets both. โinfinityโ means no limit. โuserโ preserves the invoking user's resource limit. โdefaultโ uses the target user's default resource limit on systems that allow per-user resource limits to be configured. Only available starting with API version 1.17. ๐rlimit_locks=soft,hardโ The maximum number of locks that the process may establish, if supported by the operating system. The soft and hard limits are separated by a comma. If only a single value is specified, both the hard and soft limits are set. A value of โinfinityโ indicates that there is no limit. A value of โuserโ will cause the invoking user's resource limit to be preserved. A value of โdefaultโ will cause the target user's default resource limit to be used on systems that allow per-user resource limits to be configured. Only available starting with API version 1.17. ๐rlimit_memlock=soft,hardโ The maximum size that the process may lock in memory (in bytes), if supported by the operating system. Soft and hard limits are comma-separated. Give one value and both get set. โinfinityโ = no limit. โuserโ preserves the invoking user's resource limit. โdefaultโ uses the target user's default resource limit on systems that allow per-user resource limits to be configured. Only available starting with API version 1.17. ๐งrlimit_nofile=soft,hardโ The maximum number of files that the process may have open. The soft and hard limits are separated by a comma. If only a single value is specified, both the hard and soft limits are set. A value of โinfinityโ indicates that there is no limit. A value of โuserโ will cause the invoking user's resource limit to be preserved. A value of โdefaultโ will cause the target user's default resource limit to be used on systems that allow per-user resource limits to be configured. Only available starting with API version 1.17. ๐rlimit_nproc=soft,hardโ The maximum number of processes that the user may run simultaneously. Soft and hard limits are separated by a comma. One value sets both. โinfinityโ means no limit. โuserโ preserves the invoking user's resource limit. โdefaultโ uses the target user's default resource limit on systems that allow per-user resource limits to be configured. Only available starting with API version 1.17. ๐rlimit_rss=soft,hardโ bestie, this is the max size the process's resident set size may grow to, in bytes. ๐ The soft and hard limits are separated by a comma. If you only drop a single value, both the hard and soft limits get set. A value ofinfinitymeans there is no limit. A value ofuserwill cause the invoking user's resource limit to be preserved. A value ofdefaultwill cause the target user's default resource limit to be used on systems that allow per-user resource limits to be configured. Only available starting with API version 1.17. โจrlimit_stack=soft,hardโ same energy, but for the stack: the max size the process's stack may grow to, in bytes. ๐ฆ Soft and hard limits are separated by a comma. If only a single value is specified, both the hard and soft limits are set. A value ofinfinityindicates that there is no limit. A value ofuserwill cause the invoking user's resource limit to be preserved. A value ofdefaultwill cause the target user's default resource limit to be used on systems that allow per-user resource limits to be configured. Only available starting with API version 1.17. ๐ธrunas_egid=gidโ effective group-ID to run the command as. If you don't specify it, the value ofrunas_gidis used. ๐runas_euid=uidโ effective user-ID to run the command as. If not specified, the value ofrunas_uidis used. ๐runas_gid=gidโ group-ID to run the command as. ๐ซถrunas_group=stringโ the name of the group the command will run as, if it's different from therunas_user's default group. This value is provided for auditing purposes only, the sudo front-end usesrunas_egidandrunas_gidwhen executing the command. ๐ฅrunas_groups=listโ the supplementary group vector to use for the command in the form of a comma-separated list of group-IDs. Ifpreserve_groupsis set, this option is ignored. ๐runas_uid=uidโ user-ID to run the command as. ๐runas_user=stringโ the name of the user the command will run as, which should correspond torunas_euid(orrunas_uidifrunas_euidis not set). This value is provided for auditing purposes only, the sudo front-end usesrunas_euidandrunas_uidwhen executing the command. โญselinux_role=stringโ SELinux role to use when executing the command. ๐งselinux_type=stringโ SELinux type to use when executing the command. ๐set_utmp=boolโ create a utmp (or utmpx) entry when a pseudo-terminal is allocated. By default, the new entry will be a copy of the user's existing utmp entry (if any), with the tty, time, type, and pid fields updated. ๐sudoedit=boolโ set to true when in sudoedit mode. The plugin may enable sudoedit mode even if sudo was not invoked as sudoedit. This allows the plugin to perform command substitution and transparently enable sudoedit when the user attempts to run an editor. โจsudoedit_checkdir=boolโ set to false to disable directory writability checks in sudoedit. By default, sudoedit 1.8.16 and higher will check all directory components of the path to be edited for writability by the invoking user. Symbolic links will not be followed in writable directories and sudoedit will refuse to edit a file located in a writable directory. These restrictions are not enforced when sudoedit is run by root. Thesudoedit_followoption can be set to false to disable this check. Only available starting with API version 1.8. ๐ฆsudoedit_follow=boolโ set to true to allow sudoedit to edit files that are symbolic links. By default, sudoedit 1.8.15 and higher will refuse to open a symbolic link. Thesudoedit_followoption can be used to restore the older behavior and allow sudoedit to open symbolic links. Only available starting with API version 1.8. ๐ธtimeout=intโ command timeout. If non-zero then when the timeout expires the command will be killed. ๐umask=octalโ the file creation mask to use when executing the command. This value may be overridden by PAM or login.conf on some systems unless theumask_overrideoption is also set. ๐ฅumask_override=boolโ force the value specified by theumaskoption to override any umask set by PAM or login.conf. ๐use_pty=boolโ allocate a pseudo-terminal to run the command in, regardless of whether or not I/O logging is in use. By default, sudo will only run the command in a pseudo-terminal when an I/O log plugin is loaded. ๐ซถutmp_user=stringโ user name to use when constructing a new utmp (or utmpx) entry whenset_utmpis enabled. This option can be used to set the user field in the utmp entry to the user the command runs as rather than the invoking user. If not set, sudo will base the new entry on the invoking user's existing entry. ๐
Unsupported values will be ignored. ๐
argv_outโ the NULL-terminated argument vector to pass to theexecve(2)system call when executing the command. The plugin is responsible for allocating and populating the vector. โญuser_env_outโ the NULL-terminated environment vector to use when executing the command. The plugin is responsible for allocating and populating the vector. ๐errstrโ if thecheck_policy()function returns a value other than 1, the plugin may store a message describing the failure or error inerrstr. The sudo front-end will then pass this value to any registered audit plugins. The string stored inerrstrmust remain valid until the plugin'sclose()function is called. ๐ง
NOTE: theerrstrparameter is only available starting with API version 1.15. A plugin must check the API version specified by the sudo front-end before usingerrstr. Failure to do so may result in a crash. ๐ญ
list โจ
int (*list)(int argc, char * const argv[], int verbose,
const char *list_user, const char **errstr);
List available privileges for the invoking user. Returns 1 on success, 0 on failure, and -1 on error. On error, the plugin may optionally call the conversation() or plugin_printf() function with SUDO_CONF_ERROR_MSG to present additional error information to the user. ๐
Privileges should be output via the conversation() or plugin_printf() function using SUDO_CONV_INFO_MSG. ๐
The function arguments are as follows:
argcโ the number of elements inargv, not counting the final NULL pointer. ๐ธargvโ if non-NULL, an argument vector describing a command the user wishes to check against the policy in the same form as what would be passed to theexecve(2)system call. If the command is permitted by the policy, the fully-qualified path to the command should be displayed along with any command line arguments. ๐ฆverboseโ flag indicating whether to list in verbose mode or not. ๐list_userโ the name of a different user to list privileges for if the policy allows it. If NULL, the plugin should list the privileges of the invoking user. ๐errstrโ if thelist()function returns a value other than 1, the plugin may store a message describing the failure or error inerrstr. The sudo front-end will then pass this value to any registered audit plugins. The string stored inerrstrmust remain valid until the plugin'sclose()function is called. ๐ฅ
NOTE: theerrstrparameter is only available starting with API version 1.15. A plugin must check the API version specified by the sudo front-end before usingerrstr. Failure to do so may result in a crash. ๐
validate ๐ธ
int (*validate)(const char **errstr);
The validate() function is called when sudo is run with the -v option. For policy plugins such as sudoers that cache authentication credentials, this function will validate and cache the credentials. ๐ซถ
The validate() function should be NULL if the plugin does not support credential caching. ๐
Returns 1 on success, 0 on failure, and -1 on error. On error, the plugin may optionally call the conversation() or plugin_printf() function with SUDO_CONF_ERROR_MSG to present additional error information to the user. โญ
The function arguments are as follows:
errstrโ if thevalidate()function returns a value other than 1, the plugin may store a message describing the failure or error inerrstr. The sudo front-end will then pass this value to any registered audit plugins. The string stored inerrstrmust remain valid until the plugin'sclose()function is called. ๐
โ ๏ธ NOTE: theerrstrparameter is only available starting with API version 1.15. A plugin must check the API version specified by the sudo front-end before usingerrstr. Failure to do so may result in a crash. ๐
invalidate ๐๏ธ
void (*invalidate)(int remove);
The invalidate() function gets called when sudo is run with the -k or -K option. For policy plugins like sudoers that cache authentication credentials, this function will invalidate the credentials. If the remove flag is set, the plugin may remove the credentials instead of simply invalidating them.
The invalidate() function should be NULL if the plugin does not support credential caching.
init_session ๐ฑ
int (*init_session)(struct passwd *pwd, char **user_env_out[]);
The init_session() function is called before sudo sets up the execution environment for the command. It runs in the parent sudo process, and it runs before any user-ID or group-ID changes. This can be used to perform session setup that isn't supported by command_info, like opening the PAM session. The close() function can be used to tear down the session that was opened by init_session.
The pwd argument points to a passwd struct for the user the command will be run as if the user-ID the command will run as was found in the password database, otherwise it will be NULL.
The user_env_out argument points to the environment the command will run in, in the form of a NULL-terminated vector of โname=valueโ strings. This is the same string passed back to the front-end via the Policy Plugin's user_env_out parameter. If the init_session() function needs to modify the user environment, it should update the pointer stored in user_env_out. The expected use case is to merge the contents of the PAM environment (if any) with the contents of user_env_out.
โ ๏ธ NOTE: theuser_env_outparameter is only available starting with API version 1.2. A plugin must check the API version specified by the sudo front-end before usinguser_env_out. Failure to do so may result in a crash. ๐ญ
Returns 1 on success, 0 on failure, and -1 on error. On error, the plugin may optionally call the conversation() or plugin_printf() function with SUDO_CONF_ERROR_MSG to present additional error information to the user.
register_hooks ๐ช
void (*register_hooks)(int version,
int (*register_hook)(struct sudo_hook *hook));
The register_hooks() function is called by the sudo front-end to register any hooks the plugin needs. If the plugin does not support hooks, register_hooks should be set to the NULL pointer.
The version argument describes the version of the hooks API supported by the sudo front-end.
The register_hook() function should be used to register any supported hooks the plugin needs. It returns 0 on success, 1 if the hook type is not supported, and -1 if the major version in struct hook does not match the front-end's major hook API version.
See the โHook function APIโ section below for more information about hooks. ๐
โ ๏ธ NOTE: theregister_hooks()function is only available starting with API version 1.2. If the sudo front-end doesn't support API version 1.2 or higher,register_hookswill not be called.
deregister_hooks ๐ช๐
void (*deregister_hooks)(int version,
int (*deregister_hook)(struct sudo_hook *hook));
The deregister_hooks() function is called by the sudo front-end to deregister any hooks the plugin has registered. If the plugin does not support hooks, deregister_hooks should be set to the NULL pointer.
The version argument describes the version of the hooks API supported by the sudo front-end.
The deregister_hook() function should be used to deregister any hooks that were put in place by the register_hook() function. If the plugin tries to deregister a hook that the front-end does not support, deregister_hook will return an error.
See the โHook function APIโ section below for more information about hooks. โจ
โ ๏ธ NOTE: thederegister_hooks()function is only available starting with API version 1.2. If the sudo front-end doesn't support API version 1.2 or higher,deregister_hookswill not be called.
event_alloc ๐๏ธ
struct sudo_plugin_event * (*event_alloc)(void);
The event_alloc() function is used to allocate a struct sudo_plugin_event which provides access to the main sudo event loop. Unlike the other fields, the event_alloc() pointer is filled in by the sudo front-end, not by the plugin. (the audacity, right? ๐
)
See the โEvent APIโ section below for more information about events.
โ ๏ธ NOTE: theevent_alloc()function is only available starting with API version 1.15. If the sudo front-end doesn't support API version 1.15 or higher,event_alloc()will not be set.
errstr ๐ฃ๏ธ
If the init_session() function returns a value other than 1, the plugin may store a message describing the failure or error in errstr. The sudo front-end will then pass this value to any registered audit plugins. The string stored in errstr must remain valid until the plugin's close() function is called. ๐ (yes, it has to stay valid, don't let it dangle)
โ ๏ธ NOTE: theerrstrparameter is only available starting with API version 1.15. A plugin must check the API version specified by the sudo front-end before usingerrstr. Failure to do so may result in a crash. ๐
Policy Plugin Version Macros ๐งฎ
okay these are the version macros, copy them exactly bestie:
/* Plugin API version major/minor. */
#define SUDO_API_VERSION_MAJOR 1
#define SUDO_API_VERSION_MINOR 13
#define SUDO_API_MKVERSION(x, y) ((x << 16) | y)
#define SUDO_API_VERSION SUDO_API_MKVERSION(SUDO_API_VERSION_MAJOR,\
SUDO_API_VERSION_MINOR)
/* Getters and setters for API version */
#define SUDO_API_VERSION_GET_MAJOR(v) ((v) >> 16)
#define SUDO_API_VERSION_GET_MINOR(v) ((v) & 0xffff)
#define SUDO_API_VERSION_SET_MAJOR(vp, n) do { \
*(vp) = (*(vp) & 0x0000ffff) | ((n) << 16); \
} while(0)
#define SUDO_API_VERSION_SET_MINOR(vp, n) do { \
*(vp) = (*(vp) & 0xffff0000) | (n); \
} while(0)
I/O plugin API ๐ปโจ
struct io_plugin {
#define SUDO_IO_PLUGIN 2
unsigned int type; /* always SUDO_IO_PLUGIN */
unsigned int version; /* always SUDO_API_VERSION */
int (*open)(unsigned int version, sudo_conv_t conversation,
sudo_printf_t plugin_printf, char * const settings[],
char * const user_info[], char * const command_info[],
int argc, char * const argv[], char * const user_env[],
char * const plugin_options[], const char **errstr);
void (*close)(int exit_status, int error); /* wait status or error */
int (*show_version)(int verbose);
int (*log_ttyin)(const char *buf, unsigned int len,
const char **errstr);
int (*log_ttyout)(const char *buf, unsigned int len,
const char **errstr);
int (*log_stdin)(const char *buf, unsigned int len,
const char **errstr);
int (*log_stdout)(const char *buf, unsigned int len,
const char **errstr);
int (*log_stderr)(const char *buf, unsigned int len,
const char **errstr);
void (*register_hooks)(int version,
int (*register_hook)(struct sudo_hook *hook));
void (*deregister_hooks)(int version,
int (*deregister_hook)(struct sudo_hook *hook));
int (*change_winsize)(unsigned int lines, unsigned int cols,
const char **errstr);
int (*log_suspend)(int signo, const char **errstr);
struct sudo_plugin_event * (*event_alloc)(void);
};
When an I/O plugin is loaded, sudo runs the command in a pseudo-terminal. This makes it possible to log the input and output from the user's session. ๐ If any of the standard input, standard output, or standard error do not correspond to a tty, sudo will open a pipe to capture the I/O for logging before passing it on.
The log_ttyin function receives the raw user input from the terminal device โ and heads up, this will include input even when echo is disabled, like when a password is read. ๐ The log_ttyout function receives output from the pseudo-terminal that is suitable for replaying the user's session at a later time. The log_stdin(), log_stdout(), and log_stderr() functions are only called if the standard input, standard output, or standard error respectively correspond to something other than a tty.
Any of the logging functions may be set to the NULL pointer if no logging is to be performed. If the open function returns 0, no I/O will be sent to the plugin.
If a logging function returns an error (-1), 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 0, 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 0, 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.
The audit_plugin struct has the following fields: (yeah, the page really does say audit_plugin right here in the I/O section โ we're just telling you what it says, no editing, periodt ๐
)
type ๐ท๏ธ
The type field should always be set to SUDO_IO_PLUGIN.
version ๐ข
The version field should be set to SUDO_API_VERSION.
This allows sudo to determine the API version the plugin was built against.
open ๐ช
int (*open)(unsigned int version, sudo_conv_t conversation,
sudo_printf_t plugin_printf, char * const settings[],
char * const user_info[], char * const command_info[],
int argc, char * const argv[], char * const user_env[],
char * const plugin_options[]);
The open() function is run before the log_ttyin(), log_ttyout(), log_stdin(), log_stdout(), log_stderr(), log_suspend(), change_winsize(), or show_version() functions are called. It's only called if the version is being requested, or if the policy plugin's check_policy() function has returned successfully. ๐
It returns:
1on success โจ0on failure-1if a general error occurred-2if there was a usage error
In that last case (-2), sudo will print a usage message before it exits. And if an error occurs, the plugin may optionally call the conversation() or plugin_printf() function with SUDO_CONF_ERROR_MSG to present additional error info to the user. ๐ซถ
The function arguments are as follows:
versionโ the version passed in by sudo, which lets the plugin figure out the major and minor version number of the plugin API that sudo supports.conversationโ a pointer to theconversation()function, which theshow_version()function may use to display version information (seeshow_version()below). Theconversation()function may also be used to display an additional error message to the user. It returns0on success and-1on failure.plugin_printfโ a pointer to aprintf()-style function that theshow_version()function may use to display version information (seeshow_versionbelow). Theplugin_printf()function may also be used to display an additional error message to the user. It returns the number of characters printed on success and-1on failure.settingsโ a vector of user-supplied sudo settings in the form of โname=valueโ strings. The vector is terminated by aNULLpointer. These settings correspond to options the user specified when running sudo, so they'll only be present when the corresponding option has been specified on the command line. ๐ When parsingsettings, the plugin should split on the first equal sign (โ=โ) โ because the name field will never include one itself, but the value might. Sneaky, right? ๐ See the โPolicy plugin APIโ section for a list of all possible settings.user_infoโ a vector of information about the user running the command, in the form of โname=valueโ strings. The vector is terminated by aNULLpointer. When parsinguser_info, the plugin should split on the first equal sign (โ=โ) since the name field will never include one itself but the value might. See the โPolicy plugin APIโ section for a list of all possible strings.command_infoโ a vector of information describing the command being run, in the form of โname=valueโ strings. The vector is terminated by aNULLpointer. When parsingcommand_info, the plugin should split on the first equal sign (โ=โ) since the name field will never include one itself but the value might. See the โPolicy plugin APIโ section for a list of all possible strings.argcโ the number of elements inargv, not counting the finalNULLpointer. It can be zero, when sudo is called with-V. ๐argvโ if non-NULL, an argument vector describing a command the user wishes to run, in the same form as what would be passed to theexecve(2)system call.user_envโ the user's environment in the form of aNULL-terminated vector of โname=valueโ strings. When parsinguser_env, the plugin should split on the first equal sign (โ=โ) since the name field will never include one itself but the value might.plugin_optionsโ any (non-comment) strings immediately after the plugin path are treated as arguments to the plugin. These arguments are split on a white space boundary and are passed to the plugin in the form of aNULL-terminated array of strings. If no arguments were specified,plugin_optionswill be theNULLpointer.
NOTE: theplugin_optionsparameter is only available starting with API version 1.2. A plugin must check the API version specified by the sudo front-end before usingplugin_options. Failure to do so may result in a crash. ๐
errstrโ if theopen()function returns a value other than1, the plugin may store a message describing the failure or error inerrstr. The sudo front-end will then pass this value to any registered audit plugins. The string stored inerrstrmust remain valid until the plugin'sclose()function is called. ๐ธ
NOTE: theerrstrparameter is only available starting with API version 1.15. A plugin must check the API version specified by the sudo front-end before usingerrstr. Failure to do so may result in a crash. ๐
๐ close ๐
void (*close)(int exit_status, int error);
The close() function is called when sudo is finished, shortly before it exits. Byeee bestie ๐
The function arguments are as follows:
exit_statusโ the command's exit status, as returned by thewait(2)system call, or zero if no command was run. The value ofexit_statusis undefined iferroris non-zero. ๐ฌerrorโ if the command could not be executed, this is set to the value oferrnoset by theexecve(2)system call. If the command was successfully executed, the value oferroris zero.
โจ show_version โจ
int (*show_version)(int verbose);
The show_version() function is called by sudo when the user specifies the -V option. The plugin may display its version information to the user via the conversation() or plugin_printf() function using SUDO_CONV_INFO_MSG. ๐ข
Returns 1 on success, 0 on failure, -1 if a general error occurred, or -2 if there was a usage error โ although ngl, the return value is currently ignored. ๐คทโ๏ธ
๐ฆ log_ttyin ๐ฆ
int (*log_ttyin)(const char *buf, unsigned int len,
const char **errstr);
The log_ttyin() function is called whenever data can be read from the user but before it's passed to the running command. This lets the plugin reject data if it wants to (for instance if the input contains banned content ๐). Returns 1 if the data should be passed to the command, 0 if the data is rejected (which will terminate the running command), or -1 if an error occurred.
The function arguments are as follows:
bufโ the buffer containing user input.lenโ the length ofbufin bytes.errstrโ if thelog_ttyin()function returns a value other than1, the plugin may store a message describing the failure or error inerrstr. The sudo front-end will then pass this value to any registered audit plugins. The string stored inerrstrmust remain valid until the plugin'sclose()function is called.
NOTE: theerrstrparameter is only available starting with API version 1.15. A plugin must check the API version specified by the sudo front-end before usingerrstr. Failure to do so may result in a crash. ๐
๐ log_ttyout ๐
int (*log_ttyout)(const char *buf, unsigned int len,
const char **errstr);
The log_ttyout() function is called whenever data can be read from the command but before it's written to the user's terminal. This lets the plugin reject data if it wants to (for instance if the output contains banned content ๐). Returns 1 if the data should be passed to the user, 0 if the data is rejected (which will terminate the running command), or -1 if an error occurred.
The function arguments are as follows:
bufโ the buffer containing command output.lenโ the length ofbufin bytes.errstrโ if thelog_ttyout()function returns a value other than1, the plugin may store a message describing the failure or error inerrstr. The sudo front-end will then pass this value to any registered audit plugins. The string stored inerrstrmust remain valid until the plugin'sclose()function is called.
NOTE: theerrstrparameter is only available starting with API version 1.15. A plugin must check the API version specified by the sudo front-end before usingerrstr. Failure to do so may result in a crash. ๐
๐ log_stdin ๐
int (*log_stdin)(const char *buf, unsigned int len,
const char **errstr);
The log_stdin() function is only used if the standard input does not correspond to a tty device. It's called whenever data can be read from the standard input but before it's passed to the running command. This lets the plugin reject data if it chooses to (for instance if the input contains banned content ๐). Returns 1 if the data should be passed to the command, 0 if the data is rejected (which will terminate the running command), or -1 if an error occurred.
The function arguments are as follows:
bufโ the buffer containing user input.lenโ the length ofbufin bytes.errstrโ if thelog_stdin()function returns a value other than1, the plugin may store a message describing the failure or error inerrstr. The sudo front-end will then pass this value to any registered audit plugins. The string stored inerrstrmust remain valid until the plugin'sclose()function is called.
NOTE: theerrstrparameter is only available starting with API version 1.15. A plugin must check the API version specified by the sudo front-end before usingerrstr. Failure to do so may result in a crash. ๐
๐ log_stdout ๐
int (*log_stdout)(const char *buf, unsigned int len,
const char **errstr);
The log_stdout() function is only used if the standard output does not correspond to a tty device. It gets called whenever data can be read from the command but before it's written to standard output. Which is the whole point bestie โ it lets the plugin reject data if it wants to (say, the output contains banned content ๐). Returns 1 if the data should be passed to the user, 0 if the data is rejected (and heads up, that will terminate the running command), or -1 if an error occurred.
The function arguments are as follows:
bufโ the buffer containing command output.lenโ the length ofbufin bytes.errstrโ if thelog_stdout()function returns a value other than1, the plugin may store a message describing the failure or error inerrstr. The sudo front-end will then pass this value to any registered audit plugins. The string stored inerrstrmust remain valid until the plugin'sclose()function is called.
NOTE: theerrstrparameter is only available starting with API version1.15. A plugin must check the API version specified by the sudo front-end before usingerrstr. Failure to do so may result in a crash. ๐
๐ซถ log_stderr
int (*log_stderr)(const char *buf, unsigned int len,
const char **errstr);
The log_stderr() function is only used if the standard error does not correspond to a tty device. It gets called whenever data can be read from the command but before it's written to standard error. Same deal as above โ this is your chance to reject data if you want to (banned content in the stderr? rejected, blocked, not on my watch ๐
). Returns 1 if the data should be passed to the user, 0 if the data is rejected (which will terminate the running command), or -1 if an error occurred.
The function arguments are as follows:
bufโ the buffer containing command output.lenโ the length ofbufin bytes.errstrโ if thelog_stderr()function returns a value other than1, the plugin may store a message describing the failure or error inerrstr. The sudo front-end will then pass this value to any registered audit plugins. The string stored inerrstrmust remain valid until the plugin'sclose()function is called.
NOTE: theerrstrparameter is only available starting with API version1.15. A plugin must check the API version specified by the sudo front-end before usingerrstr. Failure to do so may result in a crash. ๐
๐ register_hooks
Go read the โPolicy plugin APIโ section, bestie โ that's where register_hooks gets described. It's the same thing over here.
๐ธ deregister_hooks
Same situation, fr fr โ see the โPolicy plugin APIโ section for the description of deregister_hooks.
๐ฆ change_winsize
int (*change_winsize)(unsigned int lines, unsigned int cols,
const char **errstr);
The change_winsize() function is called whenever the window size of the terminal changes from the initial values specified in the user_info list. Returns -1 if an error occurred, in which case no further calls to change_winsize() will be made,
The function arguments are as follows:
linesโ the number of lines (rows) in the re-sized terminal.colsโ the number of columns in the re-sized terminal.errstrโ if thechange_winsize()function returns a value other than1, the plugin may store a message describing the failure or error inerrstr. The sudo front-end will then pass this value to any registered audit plugins. The string stored inerrstrmust remain valid until the plugin'sclose()function is called.
NOTE: theerrstrparameter is only available starting with API version1.15. A plugin must check the API version specified by the sudo front-end before usingerrstr. Failure to do so may result in a crash. ๐
๐ log_suspend
int (*log_suspend)(int signo, const char **errstr);
The log_suspend() function is called whenever a command is suspended or resumed. Logging this info is lowkey iconic because it makes it possible to skip the period of time when the command was suspended during playback of a session. Returns -1 if an error occurred, in which case no further calls to log_suspend() will be made,
The function arguments are as follows:
signoโ the signal that caused the command to be suspended, orSIGCONTif the command was resumed.errstrโ if thelog_suspend()function returns a value other than1, the plugin may store a message describing the failure or error inerrstr. The sudo front-end will then pass this value to any registered audit plugins. The string stored inerrstrmust remain valid until the plugin'sclose()function is called.
NOTE: theerrstrparameter is only available starting with API version1.15. A plugin must check the API version specified by the sudo front-end before usingerrstr. Failure to do so may result in a crash. ๐
โจ event_alloc
struct sudo_plugin_event * (*event_alloc)(void);
The event_alloc() function is used to allocate a struct sudo_plugin_event which provides access to the main sudo event loop. And here's the plot twist โ unlike the other fields, the event_alloc() pointer is filled in by the sudo front-end, not by the plugin. Main character energy but make it the front-end's job ๐
See the โEvent APIโ section below for more information about events.
NOTE: theevent_alloc()function is only available starting with API version1.15. If the sudo front-end doesn't support API version1.15or higher,event_alloc()will not be set.
I/O Plugin Version Macros ๐
Same as for the โPolicy plugin APIโ.
๐ Audit plugin API
/* Audit plugin close function status types. */
#define SUDO_PLUGIN_NO_STATUS 0
#define SUDO_PLUGIN_WAIT_STATUS 1
#define SUDO_PLUGIN_EXEC_ERROR 2
#define SUDO_PLUGIN_SUDO_ERROR 3
#define SUDO_AUDIT_PLUGIN 3
struct audit_plugin {
unsigned int type; /* always SUDO_AUDIT_PLUGIN */
unsigned int version; /* always SUDO_API_VERSION */
int (*open)(unsigned int version, sudo_conv_t conversation,
sudo_printf_t sudo_printf, char * const settings[],
char * const user_info[], int submit_optind,
char * const submit_argv[], char * const submit_envp[],
char * const plugin_options[], const char **errstr);
void (*close)(int status_type, int status);
int (*accept)(const char *plugin_name,
unsigned int plugin_type, char * const command_info[],
char * const run_argv[], char * const run_envp[],
const char **errstr);
int (*reject)(const char *plugin_name, unsigned int plugin_type,
const char *audit_msg, char * const command_info[],
const char **errstr);
int (*error)(const char *plugin_name, unsigned int plugin_type,
const char *audit_msg, char * const command_info[],
const char **errstr);
int (*show_version)(int verbose);
void (*register_hooks)(int version,
int (*register_hook)(struct sudo_hook *hook));
void (*deregister_hooks)(int version,
int (*deregister_hook)(struct sudo_hook *hook));
struct sudo_plugin_event * (*event_alloc)(void);
}
An audit plugin can be used to log successful and unsuccessful attempts to run sudo, independent of the policy or any I/O plugins. And you can stack them โ multiple audit plugins may be specified in sudo.conf(5). Slay โจ
The audit_plugin struct has the following fields:
type
The type field should always be set to SUDO_AUDIT_PLUGIN.
version
The version field should be set to SUDO_API_VERSION.
This allows sudo to determine the API version the plugin was built against.
open
int (*open)(unsigned int version, sudo_conv_t conversation,
sudo_printf_t sudo_printf, char * const settings[],
char * const user_info[], int submit_optind,
char * const submit_argv[], char * const submit_envp[],
char * const plugin_options[], const char **errstr);
The audit open() function is run before any other sudo plugin API functions. Which is the whole reason it exists โ it makes it possible to audit failures in the other plugins. ๐
It returns 1 on success, 0 on failure, -1 if a general error occurred, or -2 if there was a usage error. In that last case, sudo will print a usage message before it exits. If an error occurs, the plugin may optionally call the conversation() or plugin_printf() function with SUDO_CONF_ERROR_MSG to present additional error information to the user.
The function arguments are as follows:
versionโ the version passed in by sudo allows the plugin to determine the major and minor version number of the plugin API supported by sudo.conversationโ a pointer to theconversation()function that may be used by theshow_version()function to display version information (seeshow_version()below). Theconversation()function may also be used to display additional error message to the user. Theconversation()function returns0on success, and-1on failure.plugin_printfโ a pointer to aprintf()-style function that may be used by theshow_version()function to display version information (seeshow_versionbelow). Theplugin_printf()function may also be used to display additional error message to the user. Theplugin_printf()function returns number of characters printed on success and-1on failure.settingsโ a vector of user-supplied sudo settings in the form of โname=valueโ strings. The vector is terminated by aNULLpointer. These settings correspond to options the user specified when running sudo. As such, they will only be present when the corresponding option has been specified on the command line.settingsโ bestie, when you're parsingsettings, split on the first equal sign (=) only, okay? Because the name field is never gonna contain one itself, but the value totally might. ๐
And yeah โ head over to the โPolicy plugin APIโ section for the full list of all possible settings. โจ
user_infoโ a vector of info about the user running the command, in the form of โname=valueโ strings, and the whole vector is terminated by aNULLpointer.
When you're parsing user_info, split on the first equal sign (=) since the name field will never include one itself but the value might. ๐
See the โPolicy plugin APIโ section for a list of all possible strings.
submit_optindโ the index intosubmit_argvthat corresponds to the first entry that is not a command line option. Ifsubmit_argvonly consists of options โ which may be the case with the-lor-voptions โ thensubmit_argv[submit_optind]will evaluate to theNULLpointer. ๐ซถsubmit_argvโ the argument vectorsudowas invoked with, including all command line options. Thesubmit_optindargument can be used to determine the end of the command line options. ๐ธsubmit_envpโ the invoking user's environment, in the form of aNULL-terminated vector of โname=valueโ strings.
When parsing submit_envp, split on the first equal sign (=) since the name field will never include one itself but the value might. No cap.
plugin_optionsโ any (non-comment) strings immediately after the plugin path get treated as arguments to the plugin. These arguments are split on a white space boundary and passed to the plugin in the form of aNULL-terminated array of strings. If no arguments were specified,plugin_optionswill be theNULLpointer. ๐ฅerrstrโ if theopen()function returns a value other than1, the plugin may store a message describing the failure or error inerrstr. The sudo front-end will then pass this value to any registered audit plugins. The string stored inerrstrmust remain valid until the plugin'sclose()function is called. โ ๏ธ Like, keep it alive, bestie.
๐ close ๐
void (*close)(int status_type, int status);
The close() function gets called when sudo is finished โ like, shortly before it exits. It's giving last-call energy. ๐ฆ
The function arguments are as follows:
status_typeโ the type of status being passed. One ofSUDO_PLUGIN_NO_STATUS,SUDO_PLUGIN_WAIT_STATUS,SUDO_PLUGIN_EXEC_ERRORorSUDO_PLUGIN_SUDO_ERROR.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. So basically it's a โจchoose your own adventureโจ but thestatus_typepicks for you.
๐ accept ๐
int (*accept)(const char *plugin_name, unsigned int plugin_type,
char * const command_info[], char * const run_argv[],
char * const run_envp[], const char **errstr);
The accept() function is called when a command or action is accepted by a policy or approval plugin. ๐ The function arguments are as follows:
plugin_nameโ the name of the plugin that accepted the command, or โsudoโ for the sudo front-end.plugin_typeโ the type of plugin that accepted the command, currently eitherSUDO_POLICY_PLUGIN,SUDO_POLICY_APPROVAL, orSUDO_FRONT_END. Theaccept()function is called multiple times โ once for each policy or approval plugin that succeeds, and once for the sudo front-end. When called on behalf of the sudo front-end,command_infomay include information from an I/O logging plugin as well. ๐
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 accept() and reject() functions will both be called. ๐ญ Plot twist.
command_infoโ an optional vector of information describing the command being run, in the form of โname=valueโ strings. The vector is terminated by aNULLpointer.
When parsing command_info, split on the first equal sign (=) since the name field will never include one itself but the value might. ๐
See the โPolicy plugin APIโ section for a list of all possible strings.
run_argvโ aNULL-terminated argument vector describing a command that will be run, in the same form as what would be passed to theexecve(2)system call.run_envpโ the environment the command will be run with, in the form of aNULL-terminated vector of โname=valueโ strings.
When parsing run_envp, split on the first equal sign (=) since the name field will never include one itself but the value might. ๐ธ
errstrโ if theaccept()function returns a value other than1, the plugin may store a message describing the failure or error inerrstr. The sudo front-end will then pass this value to any registered audit plugins. The string stored inerrstrmust remain valid until the plugin'sclose()function is called. ๐ซถ
๐ reject ๐
int (*reject)(const char *plugin_name, unsigned int plugin_type,
const char *audit_msg, char * const command_info[],
const char **errstr);
The reject() function is called when a command or action is rejected by a plugin. ๐ค The function arguments are as follows:
plugin_nameโ the name of the plugin that rejected the command.plugin_typeโ the type of plugin that rejected the command, currently eitherSUDO_POLICY_PLUGIN,SUDO_APPROVAL_PLUGIN, orSUDO_IO_PLUGIN.
Unlike the accept() function, the reject() function is not called on behalf of the sudo front-end. Nope, not this one. ๐
audit_msgโ an optional string describing the reason the command was rejected by the plugin. If the plugin did not provide a reason,audit_msgwill be theNULLpointer.command_infoโ an optional vector of information describing the command being run, in the form of โname=valueโ strings. The vector is terminated by aNULLpointer.
When parsing command_info, split on the first equal sign (=) since the name field will never include one itself but the value might. โจ
See the โPolicy plugin APIโ section for a list of all possible strings.
errstrโ if thereject()function returns a value other than1, the plugin may store a message describing the failure or error inerrstr. The sudo front-end will then pass this value to any registered audit plugins. The string stored inerrstrmust remain valid until the plugin'sclose()function is called. โ ๏ธ
๐ error ๐
int (*error)(const char *plugin_name, unsigned int plugin_type,
const char *audit_msg, char * const command_info[],
const char **errstr);
The error() function is called when a plugin or the sudo front-end returns an error. ๐ The function arguments are as follows:
plugin_nameโ the 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 did not provide a description,audit_msgwill be theNULLpointer.command_infoโ an optional vector of information describing the command being run, in the form of โname=valueโ strings. The vector is terminated by aNULLpointer.
When parsing command_info, split on the first equal sign (=) since the name field will never include one itself but the value might. ๐
See the โPolicy plugin APIโ section for a list of all possible strings.
errstrโ if theerror()function returns a value other than1, the plugin may store a message describing the failure or error inerrstr. The sudo front-end will then pass this value to any registered audit plugins. The string stored inerrstrmust remain valid until the plugin'sclose()function is called. ๐ฅ
๐ง show_version ๐ง
int (*show_version)(int verbose);
The show_version() function is called by sudo when the user specifies the -V option. The plugin may display its version information to the user via the conversation() or plugin_printf() function using SUDO_CONV_INFO_MSG. If the user requests detailed version information, the verbose flag will be set. ๐
Returns 1 on success, 0 on failure, -1 if a general error occurred, or -2 if there was a usage error โ although the return value is currently ignored. ๐ญ Like, it's doing all that work for nothing, honestly.
โญ register_hooks โญ
See the โPolicy plugin APIโ section for a description of register_hooks.
๐ซ deregister_hooks ๐ซ
See the โPolicy plugin APIโ section for a description of deregister_hooks.
๐ธ event_alloc ๐ธ
struct sudo_plugin_event * (*event_alloc)(void);
The event_alloc() function is used to allocate a struct sudo_plugin_event which provides access to the main sudo event loop. And here's the iconic part โ unlike the other fields, the event_alloc() pointer is filled in by the sudo front-end, not by the plugin. ๐คฏ Main character energy, honestly.
See the โEvent APIโ section below for more info about events, bestie. ๐
NOTE: theevent_alloc()function is only available starting with API version 1.17. If the sudo front-end doesn't support API version 1.17 or higher,event_alloc()will not be set. So if you're on an old sudo, that pointer's just gonna be sitting there empty, no cap. ๐ซ
๐ Approval plugin API ๐
struct approval_plugin {
#define SUDO_APPROVAL_PLUGIN 4
unsigned int type; /* always SUDO_APPROVAL_PLUGIN */
unsigned int version; /* always SUDO_API_VERSION */
int (*open)(unsigned int version, sudo_conv_t conversation,
sudo_printf_t sudo_printf, char * const settings[],
char * const user_info[], int submit_optind,
char * const submit_argv[], char * const submit_envp[],
char * const plugin_options[], const char **errstr);
void (*close)(void);
int (*check)(char * const command_info[], char * const run_argv[],
char * const run_envp[], const char **errstr);
int (*show_version)(int verbose);
};
So an approval plugin is the final boss of vibes โ it gets to apply extra constraints after the policy plugin has already accepted the command. It's the "okay but actuallyโฆ" of the plugin world. ๐
Unlike the other plugin types, it does not stay open until the command finishes. It gets opened right before a call to check() or show_version(), and then closed shortly after โ and yes, audit plugin functions have to be called before the plugin gets closed. Multiple approval plugins can be specified in sudo.conf(5). Slay, stack 'em up. ๐
The approval_plugin struct has these fields:
type
The type field should always be set to SUDO_APPROVAL_PLUGIN. Periodt. ๐
version
The version field should be set to SUDO_API_VERSION.
This is how sudo figures out which API version the plugin was built against. โจ
open
int (*open)(unsigned int version, sudo_conv_t conversation,
sudo_printf_t sudo_printf, char * const settings[],
char * const user_info[], int submit_optind,
char * const submit_argv[], char * const submit_envp[],
char * const plugin_options[], const char **errstr);
The approval open() function runs immediately before a call to the plugin's check() or show_version() functions. It only gets called if the version is being requested, or if the policy plugin's check_policy() function returned successfully. ๐
It returns 1 on success, 0 on failure, -1 if a general error happened, or -2 if there was a usage error. In that last case, sudo will print a usage message before it exits. And if an error occurs, the plugin may optionally call the conversation() or plugin_printf() function with SUDO_CONF_ERROR_MSG to present extra error info to the user. ๐ฃ๏ธ
The function arguments are as follows:
versionโ the version passed in by sudo lets the plugin figure out the major and minor version number of the plugin API supported by sudo. iykyk ๐งconversationโ a pointer to theconversation()function that the plugin can use to interact with the user (see โConversation APIโ for details). Returns0on success and-1on failure. ๐ฌplugin_printfโ a pointer to aprintf()-style function that may be used to display informational or error messages (see โConversation APIโ for details). Returns the number of characters printed on success and-1on failure. ๐จ๏ธsettingsโ a vector of user-supplied sudo settings in the form of โname=valueโ strings. The vector is terminated by aNULLpointer. These settings correspond to options the user specified when running sudo, which means they'll only be present when the corresponding option was actually given on the command line. โ๏ธ
When parsing settings, the plugin should split on the first equal sign (โ=โ) since the name field will never include one itself but the value might. Sneaky little values. ๐
See the โPolicy plugin APIโ section for a list of all possible settings.
user_infoโ a vector of info about the user running the command, in the form of โname=valueโ strings. The vector is terminated by aNULLpointer. ๐ง
When parsing user_info, the plugin should split on the first equal sign (โ=โ) since the name field will never include one itself but the value might.
See the โPolicy plugin APIโ section for a list of all possible strings.
submit_optindโ the index intosubmit_argvthat corresponds to the first entry that is not a command line option. Ifsubmit_argvonly consists of options โ which can totally happen with the-lor-voptions โ thensubmit_argv[submit_optind]will evaluate to theNULLpointer. ๐submit_argvโ the argument vector sudo was invoked with, including all command line options. Thesubmit_optindargument can be used to determine where the command line options end. ๐งพsubmit_envpโ the invoking user's environment in the form of aNULL-terminated vector of โname=valueโ strings. ๐
When parsing submit_envp, the plugin should split on the first equal sign (โ=โ) since the name field will never include one itself but the value might.
plugin_optionsโ any (non-comment) strings immediately after the plugin path get treated as arguments to the plugin. These arguments are split on a white space boundary and are passed to the plugin as aNULL-terminated array of strings. If no arguments were specified,plugin_optionswill be theNULLpointer. ๐errstrโ if theopen()function returns a value other than1, the plugin may store a message describing the failure or error inerrstr. The sudo front-end will then pass this value along to any registered audit plugins. The string stored inerrstrmust remain valid until the plugin'sclose()function is called. โณ
close
void (*close)(void);
The close() function gets called after the approval plugin's check() or show_version() functions have been called. It takes no arguments, bestie, it's just vibes. ๐ซถ
close() is typically used for plugin-specific cleanup โ like freeing memory objects the plugin allocated. If your plugin doesn't need any cleanup, close() may be set to the NULL pointer. No cleanup, no problem. โจ
check
int (*check)(char * const command_info[], char * const run_argv[],
char * const run_envp[], const char **errstr);
The approval check() function runs after the policy plugin check_policy() function and before any I/O logging plugins. If multiple approval plugins are loaded, they all have to succeed for the command to be allowed. It's giving group project where everyone has to actually pull their weight. ๐ญ
It returns 1 on success, 0 on failure, -1 if a general error occurred, or -2 if there was a usage error. In the latter case, sudo will print a usage message before it exits. If an error occurs, the plugin may optionally call the conversation() or plugin_printf() function with SUDO_CONF_ERROR_MSG to present additional error information to the user. ๐ข
The function arguments are as follows:
command_infoโ a vector of info describing the command being run in the form of โname=valueโ strings. The vector is terminated by aNULLpointer. ๐
When parsing command_info, the plugin should split on the first equal sign (โ=โ) since the name field will never include one itself but the value might.
See the โPolicy plugin APIโ section for a list of all possible strings.
run_argvโ aNULL-terminated argument vector describing a command that will be run, in the same form as what would be passed to theexecve(2)system call. ๐run_envpโ the environment the command will be run with, in the form of aNULL-terminated vector of โname=valueโ strings. ๐ฑ
When parsing run_envp, the plugin should split on the first equal sign (โ=โ) since the name field will never include one itself but the value might.
errstrโ if theopen()function returns a value other than1, the plugin may store a message describing the failure or error inerrstr. The sudo front-end will then pass this value to any registered audit plugins. The string stored inerrstrmust remain valid until the plugin'sclose()function is called. โณ
show_version
int (*show_version)(int verbose);
The show_version() function is called by sudo when the user specifies the -V option. The plugin may display its version info to the user via the conversation() or plugin_printf() function using SUDO_CONV_INFO_MSG. If the user requests detailed version information, the verbose flag will be set. ๐
Returns 1 on success, 0 on failure, -1 if a general error occurred, or -2 if there was a usage error โ although the return value is currently ignored. So like, do your best, it doesn't count. ๐
๐จ Signal handlers ๐จ
The sudo front-end installs default signal handlers to trap common signals while the plugin functions are run. The following signals are trapped by default before the command is executed:
SIGALRMSIGHUPSIGINTSIGPIPESIGQUITSIGTERMSIGTSTPSIGUSR1SIGUSR2
If a fatal signal is received before the command is executed, sudo will call the plugin's close() function with an exit status of 128 plus the value of the signal that was received. This allows for consistent logging of commands killed by a signal, for plugins that log that kind of info in their close() function. ๐
An exception to this is SIGPIPE, which is ignored until the command is executed. Rude little guy, honestly. ๐
A plugin may temporarily install its own signal handlers, but it must restore the original handler before the plugin function returns. Don't leave the kitchen messy, bestie. ๐งน
๐ช Hook function API ๐ช
Beginning with plugin API version 1.2, it is possible to install hooks for certain functions called by the sudo front-end. ๐ฃโจ
๐ช Hook API
Okay bestie, rn the only hooks that are supported are the ones about handling environment variables. Hooks let you intercept attempts to get, set, or remove environment variables so those changes can be reflected in the version of the environment that's used to execute a command. A future version of the API is gonna support hooking internal sudo front-end functions too, so stay tuned ig. โจ
๐ช Hook structure
Hooks in sudo are described by this structure right here:
typedef int (*sudo_hook_fn_t)();
struct sudo_hook {
unsigned int hook_version;
unsigned int hook_type;
sudo_hook_fn_t hook_fn;
void *closure;
};
The sudo_hook structure has these fields:
hook_versionโ thehook_versionfield should be set toSUDO_HOOK_VERSION. that's it, that's the vibe.hook_typeโ thehook_typefield may be one of the following supported hook types:SUDO_HOOK_SETENVโ the C librarysetenv(3)function. Any registered hooks will run before the C library implementation. Thehook_fnfield should be a function that matches this typedef:
typedef int (*sudo_hook_fn_setenv_t)(const char *name,
const char *value, int overwrite, void *closure);
If the registered hook does not match the typedef, the results are unspecified. ๐ like, nobody knows what happens. do not do this.
SUDO_HOOK_UNSETENVโ the C libraryunsetenv(3)function. Any registered hooks will run before the C library implementation. Thehook_fnfield should be a function that matches this typedef:
typedef int (*sudo_hook_fn_unsetenv_t)(const char *name,
void *closure);
SUDO_HOOK_GETENVโ the C librarygetenv(3)function. Any registered hooks will run before the C library implementation. Thehook_fnfield should be a function that matches this typedef:
typedef int (*sudo_hook_fn_getenv_t)(const char *name,
char **value, void *closure);
If the registered hook does not match the typedef, the results are unspecified. ๐
SUDO_HOOK_PUTENVโ the C libraryputenv(3)function. Any registered hooks will run before the C library implementation. Thehook_fnfield should be a function that matches this typedef:
typedef int (*sudo_hook_fn_putenv_t)(char *string,
void *closure);
If the registered hook does not match the typedef, the results are unspecified. fr fr.
hook_fn
sudo_hook_fn_t hook_fn;
The hook_fn field should be set to the plugin's hook implementation. The actual function arguments will vary depending on the hook_type (see hook_type above ๐). In all cases, the closure field of struct sudo_hook is passed as the last function parameter. This can be used to pass arbitrary data to the plugin's hook implementation. cute, right?
The function return value may be one of the following:
SUDO_HOOK_RET_ERRORโ the hook function encountered an error. ๐ญSUDO_HOOK_RET_NEXTโ the hook completed without error, go on to the next hook (including the system implementation if applicable). For example, agetenv(3)hook might returnSUDO_HOOK_RET_NEXTif the specified variable was not found in the private copy of the environment.SUDO_HOOK_RET_STOPโ the hook completed without error, stop processing hooks for this invocation. This can be used to replace the system implementation. For example, asetenvhook that operates on a private copy of the environment but leavesenvironunchanged. periodt.
โ ๏ธ Heads up bestie: it is very easy to create an infinite loop when hooking C library functions. Like, agetenv(3)hook that calls thesnprintf(3)function may create a loop if thesnprintf(3)implementation callsgetenv(3)to check the locale. To prevent this, you may wish to use a static variable in the hook function to guard against nested calls. For example:
static int in_progress = 0; /* avoid recursion */
if (in_progress)
return SUDO_HOOK_RET_NEXT;
in_progress = 1;
...
in_progress = 0;
return SUDO_HOOK_RET_STOP;
๐ข Hook API Version Macros
/* Hook API version major/minor */
#define SUDO_HOOK_VERSION_MAJOR 1
#define SUDO_HOOK_VERSION_MINOR 0
#define SUDO_HOOK_VERSION SUDO_API_MKVERSION(SUDO_HOOK_VERSION_MAJOR,\
SUDO_HOOK_VERSION_MINOR)
For getters and setters see the โPolicy plugin APIโ. ๐
๐ Event API
When sudo runs a command, it uses an event loop to service signals and I/O. Events may be triggered based on time, a file or socket descriptor becoming ready, or due to receipt of a signal. Starting with API version 1.15, it is possible for a plugin to participate in this event loop by calling the event_alloc() function. slay, plugins get to hang out in the event loop now ๐
๐ฆ Event structure
Events are described by this structure:
typedef void (*sudo_plugin_ev_callback_t)(int fd, int what, void *closure);
struct sudo_plugin_event {
int (*set)(struct sudo_plugin_event *pev, int fd, int events,
sudo_plugin_ev_callback_t callback, void *closure);
int (*add)(struct sudo_plugin_event *pev, struct timespec *timeout);
int (*del)(struct sudo_plugin_event *pev);
int (*pending)(struct sudo_plugin_event *pev, int events,
struct timespec *ts);
int (*fd)(struct sudo_plugin_event *pev);
void (*setbase)(struct sudo_plugin_event *pev, void *base);
void (*loopbreak)(struct sudo_plugin_event *pev);
void (*free)(struct sudo_plugin_event *pev);
};
The sudo_plugin_event struct contains these function pointers:
set()
int (*set)(struct sudo_plugin_event *pev, int fd, int events,
sudo_plugin_ev_callback_t callback, void *closure);
The set() function takes these arguments:
struct sudo_plugin_event *pevโ a pointer to thestruct sudo_plugin_eventitself. yes it's passing itself, iconic behavior honestly.fdโ the file or socket descriptor for I/O-based events, or the signal number for signal events. For time-based events,fdmust be-1.eventsโ the following values determine what will trigger the event callback:SUDO_PLUGIN_EV_TIMEOUTโcallbackis run after the specified timeout expiresSUDO_PLUGIN_EV_READโcallbackis run when the file descriptor is readableSUDO_PLUGIN_EV_WRITEโcallbackis run when the file descriptor is writableSUDO_PLUGIN_EV_PERSISTโ event is persistent and remains enabled until explicitly deletedSUDO_PLUGIN_EV_SIGNALโcallbackis run when the specified signal is received
The SUDO_PLUGIN_EV_PERSIST flag may be ORed with any of the event types. It is also possible to OR SUDO_PLUGIN_EV_READ and SUDO_PLUGIN_EV_WRITE together to run the callback when a descriptor is ready to be either read from or written to. All other event values are mutually exclusive. ๐ซ
sudo_plugin_ev_callback_t callback
typedef void (*sudo_plugin_ev_callback_t)(int fd, int what,
void *closure);
The function to call when an event is triggered. The callback() function is run with these arguments:
fdโ the file or socket descriptor for I/O-based events, or the signal number for signal events.whatโ the event type that triggered that callback. For events that have multiple event types (for exampleSUDO_PLUGIN_EV_READandSUDO_PLUGIN_EV_WRITE) or have an associated timeout,whatcan be used to determine why the callback was run. lowkey detective work ๐closureโ the generic pointer that was specified in theset()function.
closureโ a generic pointer that will be passed to the callback function.
The set() function returns 1 on success, and -1 if a error occurred.
add()
int (*add)(struct sudo_plugin_event *pev, struct timespec *timeout);
The add() function adds the event pev to sudo's event loop. The event must have previously been initialized via the set() function. If the timeout argument is not NULL, it should specify a (relative) timeout after which the event will be triggered if the main event criteria has not been met. This is often used to implement an I/O timeout where the event will fire if a descriptor is not ready within a certain time period. If the event is already present in the event loop, its timeout will be adjusted to match the new value, if any.
The add() function returns 1 on success, and -1 if a error occurred.
del()
int (*del)(struct sudo_plugin_event *pev);
The del() function deletes the event pev from sudo's event loop. Deleted events can be added back via the add() function. no hard feelings ๐
The del() function returns 1 on success, and -1 if a error occurred.
pending()
int (*pending)(struct sudo_plugin_event *pev, int events,
struct timespec *ts);
The pending() function can be used to determine whether one or more events is pending. The events argument specifies which events to check for. See the set() function for a list of valid event types. If SUDO_PLUGIN_EV_TIMEOUT is specified in events, the event has an associated timeout and the ts pointer is non-NULL, it will be filled in with the remaining time. โณ
fd()
int (*fd)(struct sudo_plugin_event *pev);
The fd() function returns the descriptor or signal number associated with the event pev.
setbase()
void (*setbase)(struct sudo_plugin_event *pev, void *base);
The setbase() function sets the underlying event base for pev to the specified value. This can be used to move an event created via event_alloc() to a new event loop allocated by sudo's event subsystem. If base is NULL, pev's event base is reset to the default value, which corresponds to sudo's main event loop. Using this function requires linking the plugin with the sudo_util library. It is unlikely to be used outside of the sudoers plugin. ngl this one is giving internal-tools-only energy ๐ซถ
loopbreak()
void (*loopbreak)(struct sudo_plugin_event *pev);
The loopbreak() function causes sudo's event loop to exit immediately and the running command to be terminated. like, immediate immediate โ no waiting around, the party's over ๐
free()
void (*free)(struct sudo_plugin_event *pev);
The free() function deletes the event pev from the event loop and frees the memory associated with it. bye bestie, you're not needed anymore ๐ซถ
๐ Remote command execution ๐
Okay so here's the tea โ the sudo front-end does not support running remote commands. Like, not at all, that's just not its thing.
However โ and this is the plot twist โ starting with sudo 1.8.8, the -h option may be used to specify a remote host that is passed to the policy plugin. A plugin may also accept a runas_user in the form of โuser@hostnameโ which will work with older versions of sudo. legacy support slay โจ
It is anticipated that remote commands will be supported by executing a โhelperโ program. The policy plugin should setup the execution environment such that the sudo front-end will run the helper which, in turn, will connect to the remote host and run the command. the helper does the actual traveling, the plugin just sets the vibe ๐ฆ
For example, the policy plugin could utilize ssh to perform remote command execution. The helper program would be responsible for running ssh with the proper options to use a private key or certificate that the remote host will accept and run a program on the remote host that would setup the execution environment accordingly.
Note that remote sudoedit functionality must be handled by the policy plugin, not sudo itself as the front-end has no knowledge that a remote command is being executed. This may be addressed in a future revision of the plugin API. i.e. don't come for the front-end, it literally doesn't know ๐
๐ฌ Conversation API ๐ฌ
If the plugin needs to interact with the user, it may do so via the conversation() function. A plugin should not attempt to read directly from the standard input or the user's tty (neither of which are guaranteed to exist). read the room โ literally, neither might be there ๐ญ The caller must include a trailing newline in msg if one is to be printed.
A printf()-style function is also available that can be used to display informational or error messages to the user, which is usually more convenient for simple messages where no use input is required. no reply needed? just printf it, easy ๐
Conversation function structures
The conversation function takes as arguments pointers to the following structures:
struct sudo_conv_message {
#define SUDO_CONV_PROMPT_ECHO_OFF 0x0001 /* do not echo user input */
#define SUDO_CONV_PROMPT_ECHO_ON 0x0002 /* echo user input */
#define SUDO_CONV_ERROR_MSG 0x0003 /* error message */
#define SUDO_CONV_INFO_MSG 0x0004 /* informational message */
#define SUDO_CONV_PROMPT_MASK 0x0005 /* mask user input */
#define SUDO_CONV_PROMPT_ECHO_OK 0x1000 /* flag: allow echo if no tty */
#define SUDO_CONV_PREFER_TTY 0x2000 /* flag: use tty if possible */
int msg_type;
int timeout;
const char *msg;
};
#define SUDO_CONV_REPL_MAX 1023
struct sudo_conv_reply {
char *reply;
};
typedef int (*sudo_conv_callback_fn_t)(int signo, void *closure);
struct sudo_conv_callback {
unsigned int version;
void *closure;
sudo_conv_callback_fn_t on_suspend;
sudo_conv_callback_fn_t on_resume;
};
Pointers to the conversation() and printf()-style functions are passed in to the plugin's open() function when the plugin is initialized. The following type definitions can be used in the declaration of the open() function:
typedef int (*sudo_conv_t)(int num_msgs,
const struct sudo_conv_message msgs[],
struct sudo_conv_reply replies[], struct sudo_conv_callback *callback);
typedef int (*sudo_printf_t)(int msg_type, const char *fmt, ...);
To use the conversation() function, the plugin must pass an array of sudo_conv_message and sudo_conv_reply structures. There must be a struct sudo_conv_message and struct sudo_conv_reply for each message in the conversation, that is, both arrays must have the same number of elements. matched set, no mismatched pairs bestie, that's a vibe check fail ๐
Each struct sudo_conv_reply must have its reply member initialized to NULL. The struct sudo_conv_callback pointer, if not NULL, should contain function pointers to be called when the sudo process is suspended and/or resumed during conversation input. The on_suspend and on_resume functions are called with the signal that caused sudo to be suspended and the closure pointer from the struct sudo_conv_callback. These functions should return 0 on success and -1 on error. On error, the conversation will end and the conversation function will return a value of -1.
The intended use is to allow the plugin to release resources, such as locks, that should not be held indefinitely while suspended and then reacquire them when the process is resumed. put your toys away while you nap, grab them back when you wake up ๐ด Note that the functions are not actually invoked from within a signal handler.
The msg_type must be set to one of the following values:
SUDO_CONV_PROMPT_ECHO_OFFโ Prompt the user for input with echo disabled; this is generally used for passwords. The reply will be stored in therepliesarray, and it will never beNULL. classic password moment, nothing to see here ๐SUDO_CONV_PROMPT_ECHO_ONโ Prompt the user for input with echo enabled. The reply will be stored in therepliesarray, and it will never beNULL.SUDO_CONV_ERROR_MSGโ Display an error message. The message is written to the standard error unless theSUDO_CONV_PREFER_TTYflag is set, in which case it is written to the user's terminal if possible. oopsie message, delivered with graceSUDO_CONV_INFO_MSGโ Display a message. The message is written to the standard output unless theSUDO_CONV_PREFER_TTYflag is set, in which case it is written to the user's terminal if possible. just a lil info drop โจSUDO_CONV_PROMPT_MASKโ Prompt the user for input but echo an asterisk character for each character read. The reply will be stored in therepliesarray, and it will never beNULL. This can be used to provide visual feedback to the user while reading sensitive information that should not be displayed.****energy fr fr ๐
In addition to the above values, the following flag bits may also be set:
SUDO_CONV_PROMPT_ECHO_OKโ Allow input to be read when echo cannot be disabled when the message type isSUDO_CONV_PROMPT_ECHO_OFForSUDO_CONV_PROMPT_MASK. By default, sudo will refuse to read input if the echo cannot be disabled for those message types. default is "no, absolutely not," this flag says "okay fine"SUDO_CONV_PREFER_TTYโ When displaying a message viaSUDO_CONV_ERROR_MSGorSUDO_CONV_INFO_MSG, try to write the message to the user's terminal. If the terminal is unavailable, the standard error or standard output will be used, depending upon whetherSUDO_CONV_ERROR_MSGorSUDO_CONV_INFO_MSGwas used. The user's terminal is always used when possible for input, this flag is only used for output. tty first, fallback second ๐ฆ
The timeout in seconds until the prompt will wait for no more input. A zero value implies an infinite timeout. zero = no clock, no rush, we wait forever apparently โณ
The plugin is responsible for freeing the reply buffer located in each struct sudo_conv_reply, if it is not NULL. SUDO_CONV_REPL_MAX represents the maximum length of the reply buffer (not including the trailing NUL character). In practical terms, this is the longest password sudo will support. so like, don't write a novel in there ๐
The printf()-style function uses the same underlying mechanism as the conversation() function but only supports SUDO_CONV_INFO_MSG and SUDO_CONV_ERROR_MSG for the msg_type parameter. It can be more convenient than using the conversation() function if no user reply is needed and supports standard printf() escape sequences.
See the sample plugin for an example of the conversation() function usage. go look at the sample, it's giving tutorial ๐
๐ Plugin invocation order ๐
As of sudo 1.9.0, the plugin open() and close() functions are called in the following order:
- audit open
- policy open
- approval open
- approval close
- I/O log open
- command runs
- command exits
- I/O log close
- policy close
- audit close
- sudo exits
look at that sequence, the way it opens in order and closes in reverse... that's symmetry bestie โจ
Prior to sudo 1.9.0, the I/O log close() function was called after the policy close() function. old lore, different order ๐ฐ๏ธ
๐ธ Sudoers group plugin API ๐ธ
The sudoers plugin supports its own plugin interface to allow non-Unix group lookups. This can be used to query a group source other than the standard Unix group database. Two sample group plugins are bundled with sudo, group_file, and system_group, are detailed in sudoers(5). Third party group plugins include a QAS AD plugin available from Quest Software. yes, third parties can play too ๐ซถ
A group plugin must declare and populate a sudoers_group_plugin struct in the global scope. This structure contains pointers to the functions that implement plugin initialization, cleanup, and group lookup.
struct sudoers_group_plugin {
unsigned int version;
int (*init)(int version, sudo_printf_t sudo_printf,
char *const argv[]);
void (*cleanup)(void);
int (*query)(const char *user, const char *group,
const struct passwd *pwd);
};
The sudoers_group_plugin struct has the following fields:
versionโ Theversionfield should be set toGROUP_API_VERSION.
This allows sudoers to determine the API version the group plugin was built against. name tag check at the door ๐
init
int (*init)(int version, sudo_printf_t plugin_printf,
char *const argv[]);
The init() function is called after sudoers has been parsed but before any policy checks. It returns 1 on success, 0 on failure (or if the plugin is not configured), and -1 if a error occurred. If an error occurs, the plugin may call the plugin_printf() function with SUDO_CONF_ERROR_MSG to present additional error information to the user.
The function arguments are as follows:
versionโ The version passed in by sudoers allows the plugin to determine the major and minor version number of the group plugin API supported by sudoers.plugin_printfโ A pointer to aprintf()-style function that may be used to display informational or error message to the user. Returns the number of characters printed on success and-1on failure.argvโ ANULL-terminated array of arguments generated from thegroup_pluginoption in sudoers. If no arguments were given,argvwill beNULL. empty argv? that's a NULL, not an empty list, noted
cleanup
void (*cleanup)();
The cleanup() function is called when sudoers has finished its group checks. The plugin should free any memory it has allocated and close open file handles. tidy up your room bestie, close those files ๐งน
query
int (*query)(const char *user, const char *group,
const struct passwd *pwd);
The query() function is used to ask the group plugin whether user is a member of group. the moment of truth: are you in the group chat or not ๐
The function arguments are as follows:
userโ the name of the user we're looking up in the external group database. ๐groupโ the name of the group being queried. ๐pwdโ the password database entry foruser, if there is one. But ifuserisn't in the password database? Thenpwdis gonna beNULL, no cap. ๐
Group API Version Macros
Okay so these are the macros that tell you which version of the group plugin API you're dealing with. Iconic lil version-tagging moment:
/* Sudoers group plugin version major/minor */
#define GROUP_API_VERSION_MAJOR 1
#define GROUP_API_VERSION_MINOR 0
#define GROUP_API_VERSION ((GROUP_API_VERSION_MAJOR << 16) | \
GROUP_API_VERSION_MINOR)
For the getters and setters, go look at the "Policy plugin API". That's where they live. ๐
โจ PLUGIN API CHANGELOG โจ
So here's the whole receipts list of every revision that's ever been made to the Sudo Plugin API. Like a glow-up timeline but for an API. ๐๐
Version 1.0
- The initial API version. Baby's first API, we love a debut. ๐
Version 1.1 (sudo 1.8.0)
- The I/O logging plugin's
open()function got modified so it takes thecommand_infolist as an argument.
Version 1.2 (sudo 1.8.5)
- The Policy and I/O logging plugins'
open()functions are now passed a list of plugin parameters, if any are specified insudo.conf(5). - A simple hooks API was introduced, so plugins can hook into the system's environment handling functions.
- The
init_sessionPolicy plugin function is now passed a pointer to the user environment, which can be updated as needed. This can be used to merge in environment variables stored in the PAM handle before a command is run.
Version 1.3 (sudo 1.8.7)
- Support for the
exec_backgroundentry got added to thecommand_infolist. - The
max_groupsandplugin_direntries were added to the settings list. - The
version()andclose()functions are now optional. And ngl, before this? A missingversion()orclose()function would literally crash you. ๐ If no policy pluginclose()function is defined, a defaultclose()function gets provided by the sudo front-end, and it displays a warning if the command could not be executed. - The sudo front-end now installs default signal handlers to trap common signals while the plugin functions are run.
Version 1.4 (sudo 1.8.8)
- The
remote_hostentry was added to the settings list.
Version 1.5 (sudo 1.8.9)
- The
preserve_fdsentry was added to thecommand_infolist.
Version 1.6 (sudo 1.8.11)
- The behavior when an I/O logging plugin returns an error (
-1) has changed. Before this, the sudo front-end took no action when thelog_ttyin(),log_ttyout(),log_stdin(),log_stdout(), orlog_stderr()function returned an error. - The behavior when an I/O logging plugin returns
0has changed too. Before this, output from the command would be displayed to the terminal even if an output logging function returned0.
Version 1.7 (sudo 1.8.12)
- The
plugin_pathentry was added to the settings list. - The
debug_flagsentry now starts with a debug file path name, and it may occur multiple times if there are multiple plugin-specificDebuglines in thesudo.conf(5)file.
Version 1.8 (sudo 1.8.15)
- The
sudoedit_checkdirandsudoedit_followentries were added to thecommand_infolist. Oh and heads up โ the default value ofsudoedit_checkdirwas changed to true in sudo 1.8.16. - The sudo conversation function now takes a pointer to a
struct sudo_conv_callbackas its fourth argument. Thesudo_conv_tdefinition has been updated to match. The plugin must specify that it supports plugin API version 1.8 or higher to receive a conversation function pointer that supports this argument.
Version 1.9 (sudo 1.8.16)
- The
execfdentry was added to thecommand_infolist.
Version 1.10 (sudo 1.8.19)
- The
umaskentry was added to theuser_infolist. And theiolog_group,iolog_mode, andiolog_userentries were added to thecommand_infolist.
Version 1.11 (sudo 1.8.20)
- The
timeoutentry was added to the settings list.
Version 1.12 (sudo 1.8.21)
- The
change_winsizefield was added to theio_pluginstruct.
Version 1.13 (sudo 1.8.26)
- The
log_suspendfield was added to theio_pluginstruct.
Version 1.14 (sudo 1.8.29)
- The
umask_overrideentry was added to thecommand_infolist.
Version 1.15 (sudo 1.9.0)
- The
cwd_optionalentry was added to thecommand_infolist. - The
event_allocfield was added to thepolicy_pluginandio_pluginstructs. - The
errstrargument was added to the policy and I/O plugin functions, which the plugin function can use to return an error string. This string may be used by the audit plugin to report failure or error conditions set by the other plugins. - The
close()function is now called regardless of whether or not a command was actually executed. This makes it possible for plugins to perform cleanup even when a command was not run. Cleanup girlies, rise. ๐งน SUDO_CONV_REPL_MAXhas increased from255to1023bytes.- Support for audit and approval plugins was added.
Version 1.16 (sudo 1.9.3)
- Initial resource limit values were added to the
user_infolist. - The
cmnd_chrootandcmnd_cwdentries were added to the settings list.
Version 1.17 (sudo 1.9.4)
- The
event_allocfield was added to theaudit_pluginandapproval_pluginstructs.
Version 1.18 (sudo 1.9.9)
- The policy may now set resource limit values in the
command_infolist.
๐ SEE ALSO ๐
๐ AUTHORS ๐
So many people have worked on sudo over the years, and honestly? Legends, every one of them. This version consists of code written primarily by:
- 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. The full roster, bestie. ๐ซถ
๐ BUGS ๐
If you feel like you've found a bug in sudo, please submit a bug report at https://bugzilla.sudo.ws/ โ tell them everything, they wanna know. ๐
๐ซถ 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. Free help is free help, take it. ๐
๐ 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 file distributed with sudo or https://www.sudo.ws/license.html for complete details. No promises, no take-backs, read the fine print bestie. ๐
And that's a wrap on the whole page, fr fr! ๐ This lil masterpiece is Sudo 1.9.9, dated January 20, 2022, and it lives at section SUDO_PLUGIN(5). Go forth and plugin, you absolute icon. ๐
โจ๐
๐ฆ where this page comes from
- ubuntu jammy: sudo 1.9.9-1ubuntu2 ยท ISC
- ubuntu jammy: sudo 1.9.9-1ubuntu2.7 ยท ISC
- ubuntu jammy: sudo-ldap 1.9.9-1ubuntu2 ยท ISC
- ubuntu jammy: sudo-ldap 1.9.9-1ubuntu2.7 ยท ISC
- ๐ the page's license: ISC
- Copyright (c) 2009-2022 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