sudo,
sudoedit ¬

execute a command as another user

sudo -l[l] [-AknS] [-g groupname|#gid] [-p prompt] [-U uname] [-u uname|#uid] [command]
sudo [-AbEHnPS] [-C fd] [-g groupname|#gid] [-p prompt] [-r role] [-t type] [-u uname|#uid] [VAR=value] [-i | -s] [command]
sudoedit[-AnS] [-C fd] [-g groupname|#gid] [-p prompt] [-u uname|#uid] file
visudo
sudo -h | -K | -k | -V
sudo -v [-AknS] [-g group name|#gid] [-p prompt ] [-u uname|#uid]

Execute a command as the superuser or another user,
The real and effective uid and gid are set to match those of the target user.

As usual, this document is a tersified version of the man page, different systems have different versions, check man sudo for exact operations

Frequently used by admins to perform an administrative function.

Redirections are started before user ID is changed.
This will fail:
 /etc > sudo ls -l > listOfiles
Instead redirect output to the $HOME directory using:
 /etc > sudo ls -l > ~/listOfiles
-v validate , update the user's cached credentials.
-K Kill credentials. Default expires after 5 minutes. See / For example leaving a station logged on after issuing a sudo command.
-k [command] kill cached credentials.
Does not require a password if used without command
Allows revoking sudo permissions from .logout .
-u user
      \#uid
Run as user
Allows uids that are not in the password database as long as the targetpw is not set.
Other security policies may not support this.
-g group
      \#gid
Run with the primary group . Default: run with the primary group of the target user ( default: root).
-P Preserve the invoking user's group vector .
By default, the group vector to the list of groups the target user .
The real and effective group IDs, match the target user.
‑l[l] [command]
    [
-U uname]
lists commands for the invoking user or the user specified by -U .
If a command is specified and is permitted, the fullyqualified path to the command is displayed along with any command line arguments.
If command is specified but not allowed, exit with a status 1.
-ll, or if -l is specified multiple times, a longer list format is used.

ed: Reformatted. Notice strings with embedded spaces are in quotes

sudo -ll
Matching Defaults entries for userxxx on this host:
    env_reset,   
    env_keep+=BLOCKSIZE,        env_keep+="COLORFGBG COLORTERM",  
    env_keep+="LINES COLUMNS",  env_keep+=LSCOLORS
    env_keep+=SSH_AUTH_SOCK,    env_keep+=TZ,                     
    env_keep+="EDITOR VISUAL",  env_keep+="HOME MAIL"
    env_keep+="DISPLAY XAUTHORIZATION XAUTHORITY"
    env_keep+=__CF_USER_TEXT_ENCODING
    env_keep+="CHARSET LANG LANGUAGE LC_ALL LC_COLLATE LC_CTYPE"
    env_keep+="LC_MESSAGES LC_MONETARY LC_NUMERIC LC_TIME"

User suerxx may run the following commands on this host: 
Sudoers entry:
    RunAsUsers: ALL
    Commands: ALL
Only root or a user with ALL privilege can specify -U
-E Environment, preserve existing variables.
-A askpass, a (possibly graphical) helper program to interagate the user and output the password to stdout.
Useful with sudo -S
$SUDO_ASKPASS is the path to the helper program.
/etc/sudo.conf may specify the askpass program. For example:
 # Path to askpass helper program
          Path askpass /usr/X11R6/bin/ssh-askpass
Normally, if sudo requires a password, it is read from the user's terminal.
-S Read password,followed by a newline character, from the stdin.
Useful in a script But provides password visability unless script is not readable.
-b background command
-C fd close file descriptors fd >= 4.
This permits file descriptors between 4 and fd to be left open.
Normally, all open file descriptors > stderr are closed.
The security policy only permits the use of -C when the administrator has enabled closefrom_override .
-e file [] edit files.
  • Temporary copies are made of the files with the owner set to the invoking user.
  • edit copies. The editor specified by the policy is run to edit the temporary files with the invoking user's environment. $SUDO_EDITOR, $VISUAL and $EDITOR or the first program listed in the editor sudoers option.
  • Temporary files are copied back and removed. If file does not exist, it will be created.
    If file cannot be updated the temporary copy will remain.
    "sudoedit" is used when consulting the security policy.
  • -H $HOME is set to that of the target user. Default root
    -i [command] Simulate initial login. Run the shell of the target user as a login shell.
    .profile or .login will be read.
    With command it is passed to the via the shell's -c .
    Without command an interactive shell is executed with $HOME of the target user.
    The environment is set to a minimal set of variables similar to when a user logs in.
    -n non-interactive prevents prompting the user for a password.
    If a password is required , sudo displays an error message and exits.
    -p prompt use prompt default Password: Override password prompt on systems that support PAM unless passprompt_override is disabled in sudoers.
    %h local host name without the domain name
    %H host name including the domain name (on if the machine's host name is fully qualified or the fqdn option is set in sudoers
    %p name of the user whose password is being requested (respects the rootpw, targetpw and runaspw flags in sudoers
    %U login name of the user the command will be run as (defaults to root unless the -u is also specified)
    %u invoking user's login name
    %% a single % character
    -s [command] runs the shell specified by $SHELL or the shell from the password database.
    With a command, it is passed to the shell via the shell's -c .
    Without an interactive shell is executed.
    -r role SELinux security context to have role
    -t type SELinux security context to have type
    -V output Versions including security policy plugin and any I/O plugins.
     mac os 10.13 :
    Sudo version 1.8.17p1
    Sudoers policy plugin version 1.9.5p2  file grammar version 48  I/O plugin version 1.9.5p2 
    If the invoking user is root displays arguments passed to configure when sudo was built and plugins
    -- stop processing command line arguments.
    -h help

    Environment variables

    To be set for the command may be passed on the command line in the form of VAR=value, for example: LD_LIBRARY_PATH=/usr/local/pkg/lib.
    Variables passed on the command line are subject to the same restrictions as normal environment variables with one exception:
    If setenv is set in sudoers, the command to be run has the SETENV tag set or
    the command matched is ALL, the user may set variables that would otherwise be forbidden. See sudoers(5)

    PLUGINS

    Plugins are dynamically loaded based on the contents of the /etc/sudo.conf file. If no /etc/sudo.conf file is present, or it contains no Plugin lines, sudo will use the traditional sudoers security policy and I/O logging, which corresponds to the following /etc/sudo.conf file.
     
            # Default /etc/sudo.conf file
            #
            # Format:
            #   Plugin plugin_name plugin_path plugin_options ...
            #   Path askpass /path/to/askpass
            #   Path noexec /path/to/sudo_noexec.so
            #   Debug sudo /var/log/sudo_debug all@warn
            #   Set disable_coredump true
            #
            # The plugin_path is relative to /usr/libexec unless
            #   fully qualified.
            # The plugin_name corresponds to a global symbol in the plugin
            #   that contains the plugin interface structure.
            # The plugin_options are optional.
            #
            Plugin policy_plugin sudoers.so
            Plugin io_plugin sudoers.so
    
    A Plugin line consists Plugin followed by the symbol_name and the path to the shared object containing the plugin. The symbol_name is the name of the struct policy_plugin or struct io_plugin in the plugin shared object. The path may be fully qualified or relative. If not fully qualified it is relative to the /usr/libexec directory. Any additional parameters after the path are passed as arguments to the plugin's open function. Lines that don't begin with Plugin, Path, Debug or Set are silently ignored. see sudo_plugin.

    PATHS

    A Path line consists of the Path keyword, followed by the name of the path to set and its value. example:
    Path noexec /usr/lib/sudo/sudo_noexec.so
    Path askpass /usr/X11R6/bin/ssh-askpass
    plugin-agnostic paths may be set in /etc/sudo.conf.
    askpass fully qualified path to a helper program to read the password when no terminal is available as when sudo is executed from a graphical (as opposed to text-based) application. The program should display the argument passed to it as the prompt and write the password to standard output.
    Overridden by $SUDO_ASKPASS.
    noexec fully-qualified path to a shared library containing dummy versions of execv(), execve() and fexecve() library functions that return an error on systems that support LD_PRELOAD or its equivalent.
    Default :/usr/lib/sudo/oputputing.

    DEBUG FLAGS

    Help track down what sudo is doing internally

    A Debug line consists of Debug followed by the name of the program to debug (sudo, visudo, sudoreplay), the debug file name and a comma-separated list of debug flags. The debug flag syntax used by sudo and the sudoers plugin is subsystem@priority but the plugin is free to use a different format so long as it does not include a command ,. For instance:

    Debug sudo /var/log/sudo_debug all@warn,plugin@info
    would log all debugging statements at the warn level and higher in addition to those at the info level for the plugin subsystem.

    One Debug entry per program is shared by the sudo front end, sudoedit and the plugins.

    The priorities in order of decreasing severity, are: crit, err, warn, notice, diag, info, trace and debug/code>. Each priority, when specified, also includes all priorities higher than it.
    For example, a priority of notice would include debug messages logged at notice and higher.

    The following subsystems are used by sudo:

    all matches every subsystem
    args command line argument processing
    conv user conversation
    edit sudoedit
    exec command execution
    main sudo main function
    netif network interface handling
    pcomm communication with the plugin
    plugin plugin configuration
    pty pseudo-tty related code
    selinux SELinux-specific handling
    util utility functions
    utmp utmp handling

    RETURN VALUES

    exit status will be the exit status of the program executed.

    sudo exits with a value of 1 if there is a configuration/permission problem.
    1 if sudo cannot execute the given command the error string is printed to the standard error.
    If sudo cannot stat one or more entries in the user's PATH, an error is printed on stderr.
    If the directory does not exist or if it is not a directory, the entry is ignored and no error is printed.) This should not happen under normal circumstances.
    The most common reason for stat(2) to return "permission denied" is if you are running an automounter and one of the directories in your PATH is on a machine that is currently unreachable.

    SECURITY NOTES

    sudo tries to be safe when executing external commands.

    Logs commands via syslog notice similar to:

    2022-12-07 11:43:59 dapi2 127.0.0.1 authpriv.notice sudo: uuname : TTY=pts/0 ; PWD=/home/myhime ; USER=root ; 
                        COMMAND=/usr/bin/apt-get update
    or
    2022-12-07 11:43:59 dapi2 127.0.0.1  sudo[9115]:  uunnamme : TTY=ttys000 ; PWD=/private/var/log ; USER=root ; 
                        COMMAND=/bin/kill -hup 51

    Errors

    sudo: a terminal is required to read the password; either 
    use the -S option to read from standard input or configure an askpass helper
    To prevent command spoofing, sudo checks "." and "" (both denoting current directory) last when searching for a command in the user's PATH (if one or both are in the PATH).
    $PATH is not modified and is passed unchanged to the program that sudo executes.

    Logs only the command it explicitly runs. If a user runs a command such as sudo su or sudo sh, subsequent commands run from that shell are not subject to sudo's security policy.
    Commands that offer shell escapes (including most editors, ftp) do not log the shelkl escape activity.
    Giving users access to commands inadvertently give the user an effective root shell.

    see the PREVENTING SHELL ESCAPES section in sudoers(5).

    Dumps are disabled by default while it is executingm to re-enable core dumps set "disable_coredump" to false in the /etc/sudo.conf file.
    If I/O logging is enabled, subsequent commands will have their input and/or output logged, but there will not be traditional logs for those commands. <>Br>

    Set disable_coredump false
    systems disable core dumps from setuid programs, including sudo. To get a sudo core file enable core dumps for setuid processes. On BSD and Linux systems this is accomplished via the sysctl command, on Solaris the coreadm command can be used.

    ENVIRONMENT

    The following environment variables. The security policy has control over the content of the command's environment.
    EDITOR Default editor to use in -e (sudoedit) mode if neither SUDO_EDITOR nor VISUAL is set
    MAIL In -i mode or when env_reset is enabled in sudoers, set to the mail spool of the target user
    HOME Set to the home directory of the target user if -i or -H are specified, env_reset or always_set_home are set in sudoers, or when the -s option is specified and set_home is set in sudoers
    PATH May be overridden by the security policy.
    SHELL Used to determine shell to run with -s option
    SUDO_ASKPASS Specifies the path to a helper program used to read the password if no terminal is available or if the -A option is specified.
    SUDO_COMMAND Set to the command run by sudo
    SUDO_EDITOR Default editor to use in -e (sudoedit) mode
    SUDO_GID Set to the group ID of the user who invoked sudo
    SUDO_PROMPT Used as the default password prompt
    SUDO_PS1 If set, PS1 will be set to its value for the program being run
    SUDO_UID Set to the user ID of the user who invoked sudo
    SUDO_USER Set to the login of the user who invoked sudo
    USER Set to the target user (root unless the -u option is specified)
    VISUAL Default editor to use in -e (sudoedit) mode if SUDO_EDITOR is not set

    FILES

    /etc/sudo.conf sudo front end configuration

    EXAMPLES

    Following examples assume a properly configured security policy. Get a file listing of an unreadable directory:
    $ sudo ls /usr/local/protected
    List the home directory of user yaz on a machine where the file system holding ~yaz is not exported as root:
    $ sudo -u yaz ls ~yaz
    Edit index.html file as user www:
    $ sudo -u www vi ~www/htdocs/index.html
    View system logs only accessible to root and users in the adm group:
    $ sudo -g adm view /var/log/syslog
    Run an editor as jim with a different primary group:
    $ sudo -u jim -g audio vi ~jim/sound.txt
    Shutdown a machine:
    $ sudo shutdown -r +15 "quick reboot"
    Make a usage listing of the directories in the /home partition, runs the commands in a sub-shell to make the cd and file redirection work.
    $ sudo sh -c "cd /home ; du -s * | sort -rn > USAGE"

    SEE ALSO

    grep(1), su(1), stat(2), passwd(5), sudoers(5), sudo_plugin(8), sudoreplay(8), visudo(8) See the HISTORY file in the sudo distribution (sudo.ws for a brief history of sudo.

    CAVEATS

    There is no easy way to prevent a user from gaining a root shell if that user is allowed to run arbitrary commands via sudo.
    Many programs (such as editors) allow the user to run commands via shell escapes, thus avoiding sudo's checks. However, on most systems it is possible to prevent shell escapes with the sudoers(5) module's noexec functionality.

    It is not meaningful to run cd directly via sudo, e.g.,

     $ sudo cd /usr/local/protected
    since when the command exits the parent process (your shell) will still be the same.

    1.8.5 March 15, 2012

    from smackerpro 5/8/13

    # This file MUST be edited with the 'visudo' command as root.
    # Otherwise syntax or file permission errors may prevent sudo from running.
    
    # Host alias specification
    
    # User alias specification
    
    # Cmnd alias specification
    
    # Defaults specification
    Defaults    env_reset
    Defaults    env_keep += "BLOCKSIZE"
    Defaults    env_keep += "COLORFGBG COLORTERM"
    Defaults    env_keep += "__CF_USER_TEXT_ENCODING"
    Defaults    env_keep += "CHARSET LANG LANGUAGE LC_ALL LC_COLLATE LC_CTYPE"
    Defaults    env_keep += "LC_MESSAGES LC_MONETARY LC_NUMERIC LC_TIME"
    Defaults    env_keep += "LINES COLUMNS"
    Defaults    env_keep += "LSCOLORS"
    Defaults    env_keep += "SSH_AUTH_SOCK"
    Defaults    env_keep += "TZ"
    Defaults    env_keep += "DISPLAY XAUTHORIZATION XAUTHORITY"
    Defaults    env_keep += "EDITOR VISUAL"
    Defaults    env_keep += "HOME MAIL"
    
    # Runas alias specification
    
    # User privilege specification
    root    ALL=(ALL) ALL
    %admin  ALL=(ALL) ALL
    
    # Uncomment to allow people in group wheel to run all commands
    # %wheel    ALL=(ALL) ALL
    
    # Same thing without a password
    # %wheel    ALL=(ALL) NOPASSWD: ALL
    
    # Samples
    # %users  ALL=/sbin/mount /cdrom,/sbin/umount /cdrom
    # %users  localhost=/sbin/shutdown -h now

    As of 5/8/13 this is taken from man of March 15, 2012 on a system with Sudo version1.8.5p2

    See

    visudo

    See Sudo.ws for 1.8.6p8, released on April 11, 2013.


    sudo.conf

    configuration for sudo

    Specifies the security policy and I/O logging plugins, debug flags as well as plugin-agnostic path names and settings.

    Directives

    Plugin security policy or I/O logging plugin
    Path plugin-agnostic path
    Set front end setting, such as disable_coredump or group_source
    Debug debug flags to aid in debugging sudo, sudoreplay, visudo, and the sudoers plugin.

    The pound sign ('#') a comment to the end of the line.
    Continued with a backslash ('\') as the last character on the line.
    Leading white space is removed from the beginning of lines.
    Lines that don't begin with a directive are silently ignored.
    The sudo.conf file is always parsed in the ``C'' locale.

    Plugin configuration

    sudo supports a plugin architecture for security policies and input/output logging. Third parties can develop and distribute their own policy and I/O logging plugins to work seamlessly with the sudo front end. Plugins are dynamically loaded.

    A Plugin line consists of Plugin, the symbol_name and the path to the dynamic shared object that contains the plugin.
    The symbol_name is the name of the struct policy_plugin or struct io_plugin symbol contained in the plugin.
    The path may be fully qualified or relative to the directory specified by the plugin_dir Path setting, which defaults to /usr/lib/sudo.. In other words:
    Plugin sudoers_policy sudoers.so is equivalent to: Plugin sudoers_policy /usr/lib/sudo/sudoers.so If the plugin was compiled statically into sudo the path should be specified without a leading directory. For example:
    Plugin sudoers_policy sudoers.so parameters after the path are passed as arguments to the plugin's open function. For example, to override the compile-time default sudoers file mode:
    Plugin sudoers_policy sudoers.so sudoers_mode=0440

    See sudoers(5) for a list of supported arguments.

    One dynamic shared object may contain multiple plugins, each with a different symbol name.
    The file must be owned by uid 0 and only writable by its owner.
    Only a single policy plugin may be specified.

    If no sudo.conf is present, or if it contains no Plugin lines, the sudoers plugin will be used as the default security policy and for I/O logging (if enabled by the policy). This is equivalent to the following:
    Plugin sudoers_policy sudoers.so
    Plugin sudoers_io sudoers.so

    see sudo_plugin(8)

    Path settings

    A Path line consists of Path , followed by the name of the path to set and its value. For example:
    Path noexec /usr/lib/sudo/sudo_noexec.so
    Path askpass /usr/X11R6/bin/ssh-askpass

    If no path name is specified, features relying on the specified setting will be disabled.

    plugin-agnostic paths may be set in /etc/sudo.conf:

    askpass The fully qualified path to a helper program used to read the user's password when no terminal is available. This may be the case when sudo is executed from a graphical (as opposed to text-based) application.
    The helper should display the argument passed to it as the prompt and write the user's password to the standard output.
    The value of askpass may be overridden by $SUDO_ASKPASS.
    noexec The fully-qualified path to a shared library containing wrappers for execl(), execle(), execlp(), exect(), execv(), execve(), execvP(), execvp(), execvpe(), fexecve(), popen(), posix_spawn(), posix_spawnp(), system(), and wordexp() library functions that prevent the execution of further commands used to implement the noexec functionality on systems that support LD_PRELOAD or its equivalent. The default value is: /usr/lib/sudo/sudo_noexec.so.
    plugin_dir directory to use when searching for plugins without a fully qualified path name. default /usr/lib/sudo.
    sesh The fully-qualified path to sesh binary. only used when sudo is built with SELinux support.
    default /usr/lib/sudo/sesh.

    Other settings

    disable_coredump Core dumps of sudo itself are disabled by default. To debug sudo crashes, re-enable core dumps by
    Set disable_coredump false
    Restrictions on core dumps from setuid processes can be enabled without compromising security. To actually get a sudo core file you will likely need to enable core dumps for setuid processes.
    group_source     static |
       dynamic |
      adaptive
    change behavior of determining user group list.
    sudo passes the invoking user's group list to the policy and I/O plugins. There maybe a limit to the number of groups that a user may belong to (typically 16 ). With a member of a larger number of groups they won't be included in the list returned .
    If the user's kernel group list has the maximum number of entries, sudo will consult the group database directly

    static Use the group list the kernel returns. fast but may be subject to a limit. it does not reflect changes to the group database made after the user logs in.

    dynamic query the group database directly. Can be time consuming especially when querying a network-based group database.

    adaptive Only query the group database if the static group list returned by the kernel has the maximum number of entries.

    max_groups n
    probe_interfaces By default, sudo probes network interfaces and passes the IP address of enabled interface to the policy plugin.

    A Debug line consists of Debug, the name of the program (or plugin) to debug (sudo, visudo, sudoreplay, sudoers), the debug file name and a comma-separated list of debug flags. The debug flag syntax used by sudo and the sudoers plugin is subsystem@priority but a plugin is free to use a different format so long as it does not include a comma (',').

    For example: Debug sudo /var/log/sudo_debug all@warn,plugin@info

    would log all debugging statements at the warn level and higher in addition to those at the info level for the plugin subsystem.

    Multiple Debug entries may be specified per program. the plugin that was loaded (for example sudoers.so) or by the plugin's fully-qualified path name.
    The priorities are , in order of decreasing severity: crit, err, warn, notice, diag, info, trace and debug. Each priority, includes all priorities higher than it. For example, a priority of notice would include debug messages logged at notice and higher.

    The priorities trace and debug include function call tracing which logs when a function is entered and when it returns. For example, the following trace is for the get_user_groups() function located in src/sudo.c:
    sudo[123] -> get_user_groups @ src/sudo.c:385
    sudo[123] <- get_user_groups @ src/sudo.c:429 := groups=10,0,5

    When the function is entered, indicated by a right arrow '->', the program, process ID, function, source file and line number are logged. When the function returns, indicated by a left arrow '<-', the same information is logged along with the return value. In this case, the return value is a string.

    These subsystems are used

         all         matches every subsystem 
         args        command line argument processing 
         conv        user conversation 
         edit        sudoedit 
         event       event subsystem 
         exec        command execution 
         main        sudo main function 
         netif       network interface handling 
         pcomm       communication with the plugin 
         plugin      plugin configuration 
         pty         pseudo-tty related code 
         selinux     SELinux-specific handling 
         util        utility functions 
         utmp        utmp handling 
    The sudoers(5) plugin includes support for additional subsystems.

    FILES

    /etc/sudo.conf sudo front end configuration

    Examples

         # Default /etc/sudo.conf file
         #
         # Format:
         #   Plugin plugin_name plugin_path                 plugin_options ...
         #   Path   askpass     /path/to/askpass
         #   Path   noexec      /path/to/sudo_noexec.so
         #   Debug  sudo        /var/log/sudo_debug         all@warn
         #   Set disable_coredump true
         
         # plugin_path is relative to /usr/lib/sudo unless fully qualified.
         # plugin_name corresponds to a global symbol in the plugin
         #   that contains the plugin interface structure.
         # plugin_options are optional.
         
         # sudoers plugin is used by default if no Plugin lines are present.
         Plugin sudoers_policy  sudoers.so
         Plugin sudoers_io      sudoers.so
    
         # Sudo askpass:
         #
         # askpass helper program may be specified to provide a graphical
         # password prompt for "sudo -A" support.  
         # No askpass program is included with sudo but see OpenSSH askpass.
         #
         # Use the OpenSSH askpass
         #Path askpass /usr/X11R6/bin/ssh-askpass
         #
         # Use the Gnome OpenSSH askpass
         #Path askpass /usr/libexec/openssh/gnome-ssh-askpass
    
         # Sudo noexec:
         #
         # Path to a shared library containing dummy versions of the execv(),
         # execve() and fexecve() library functions that just return an error.
         # Used to implement the "noexec" functionality on systems that
         # support C<LD_PRELOAD> or its equivalent.
         # Compiled-in value is usually sufficient and 
         # should only be changed if you rename or move the sudo_noexec.so file.
         #
         #Path noexec /usr/lib/sudo/sudo_noexec.so
    
         # Core dumps:
         #
         # Default: core dumps are disabled while it is executing
         # They are re-enabled for the command
         # To debug sudo problems, set "disable_coredump" to false.
         #
         #Set disable_coredump false
    
         # User groups:
         #
         # Sudo passes the user's group list to the policy plugin.
         # If the user is a member of the maximum number of groups (usually 16),
         # sudo will query the group database directly to be sure to include
         # the full list of groups.
         #
         # On some systems, this can be expensive so the behavior is configurable.
         # The "group_source" setting has three possible values:
         #   static   - use the user's list of groups returned by the kernel.
         #   dynamic  - query the group database to find the list of groups.
         #   adaptive - if user is in less than the maximum number of groups.
         #              use the kernel list, else query the group database.
         #
         #Set group_source static
    #Defaults env_reset, timestamp_timeout=minutes SEE sudoers(5), sudo(8), sudo_plugin(8)

    sudoers policy