分类: LINUX
2010-01-04 13:17:58
SUDO(8) MAINTENANCE COMMANDS SUDO(8) NAME sudo, sudoedit - execute a command as another user SYNOPSIS sudo -h | -K | -k | -L | -l | -V | -v sudo [-bEHPS] [-a auth_type] [-c class|-] [-p prompt] [-u username|#uid] [VAR=value] {-i | -s | command} sudoedit [-S] [-a auth_type] [-c class|-] [-p prompt] [-u username|#uid] file ... DESCRIPTION sudo allows a permitted user to execute a command as the superuser or another user, as specified in the sudoers file. The real and effective uid and gid are set to match those of the target user as specified in the passwd file and the group vector is initialized based on the group file (unless the -P option was specified). If the invoking user is root or if the target user is the same as the invoking user, no password is required. Otherwise, sudo requires that users authenticate themselves with a password by default (NOTE: in the default configuration this is the user's password, not the root password). Once a user has been authenticated, a timestamp is updated and the user may then use sudo without a password for a short period of time (15 minutes unless overridden in sudoers). When invoked as sudoedit, the -e option (described below), is implied. sudo determines who is an authorized user by consulting the file /etc/sudoers. By giving sudo the -v flag, a user can update the time stamp without running a command. The password prompt itself will also time out if the user's password is not entered within 0 minutes (unless overridden via sudoers). If a user who is not listed in the sudoers file tries to run a command via sudo, mail is sent to the proper authorities, as defined at configure time or in the sudoers file (defaults to root). Note that the mail will not be sent if an unauthorized user tries to run sudo with the -l or -v flags. This allows users to determine for themselves whether or not they are allowed to use sudo. If sudo is run by root and the SUDO_USER environment variable is set, sudo will use this value to deter- mine who the actual user is. This can be used by a user to log commands through sudo even when a root shell has been invoked. It also allows the -e flag to remain useful even when being run via a sudo-run script or program. Note however, that the sudoers lookup is still done for root, not the user specified by SUDO_USER. sudo can log both successful and unsuccessful attempts (as well as errors) to syslog(3), a log file, or both. By default sudo will log via syslog(3) but this is changeable at configure time or via the sudoers file. OPTIONS sudo accepts the following command line options: …… -b The -b (background) option tells sudo to run the given command in the background. Note that if you use the -b option you cannot use shell job control to manipulate the process. …… -E The -E (preserve environment) option will override the env_reset option in sudoers(5)). It is only available when either the matching command has the SETENV tag or the setenv option is set in sudo- ers(5). -e The -e (edit) option indicates that, instead of running a command, the user wishes to edit one or more files. In lieu of a command, the string "sudoedit" is used when consulting the sudoers file. If the user is authorized by sudoers the following steps are taken: 1. Temporary copies are made of the files to be edited with the owner set to the invoking user. 2. The editor specified by the VISUAL or EDITOR environment variables is run to edit the temporary files. If neither VISUAL nor EDITOR are set, the program listed in the editor sudoers variable is used. 3. If they have been modified, the temporary files are copied back to their original location and the temporary versions are removed. If the specified file does not exist, it will be created. Note that unlike most commands run by sudo, the editor is run with the invoking user's environment unmodified. If, for some reason, sudo is unable to update a file with its edited version, the user will receive a warning and the edited copy will remain in a temporary file. -H The -H (HOME) option sets the HOME environment variable to the homedir of the target user (root by default) as specified in passwd(5). By default, sudo does not modify HOME (see set_home and always_set_home in sudoers(5)). -h The -h (help) option causes sudo to print a usage message and exit. …… -L The -L (list defaults) option will list out the parameters that may be set in a Defaults line along with a short description for each. This option is useful in conjunction with grep(1). -l The -l (list) option will list out the allowed (and forbidden) commands for the invoking user on the current host. -P The -P (preserve group vector) option causes sudo to preserve the invoking user's group vector unal- tered. By default, sudo will initialize the group vector to the list of groups the target user is in. The real and effective group IDs, however, are still set to match the target user. -p The -p (prompt) option allows you to override the default password prompt and use a custom one. The following percent (`%') escapes are supported: %H expanded to the local hostname including the domain name (on if the machine's hostname is fully qualified or the fqdn sudoers option is set) %h expanded to the local hostname without the domain name %U expanded to the login name of the user the command will be run as (defaults to root) %u expanded to the invoking user's login name %% two consecutive % characters are collapsed into a single % character …… -S The -S (stdin) option causes sudo to read the password from the standard input instead of the termi- nal device. -s The -s (shell) option runs the shell specified by the SHELL environment variable if it is set or the shell as specified in passwd(5). ……
SUDOERS(5) MAINTENANCE COMMANDS SUDOERS(5) NAME sudoers - list of which users may execute what DESCRIPTION The sudoers file is composed of two types of entries: aliases (basically variables) and user specifica- tions (which specify who may run what). When multiple entries match for a user, they are applied in order. Where there are multiple matches, the last match is used (which is not necessarily the most specific match). The sudoers grammar will be described below in Extended Backus-Naur Form (EBNF). Don't despair if you don't know what EBNF is; it is fairly simple, and the definitions below are annotated. Quick guide to EBNF EBNF is a concise and exact way of describing the grammar of a language. Each EBNF definition is made up of production rules. E.g., symbol ::= definition | alternate1 | alternate2 ... (::=表示其左边的内容可用右边的内容来替换) Each production rule references others and thus makes up a grammar for the language. EBNF also contains the following operators, which many readers will recognize from regular expressions. Do not, however, confuse them with "wildcard" characters(通配符), which have different meanings. ? Means that the preceding symbol (or group of symbols) is optional. That is, it may appear once or not at all. * Means that the preceding symbol (or group of symbols) may appear zero or more times. + Means that the preceding symbol (or group of symbols) may appear one or more times. Parentheses may be used to group symbols together. For clarity, we will use single quotes ('') to desig- nate what is a verbatim character string (as opposed to a symbol name). Aliases There are four kinds of aliases: User_Alias, Runas_Alias(Runas stand for Run as), Host_Alias and Cmnd_Alias(Cmnd stand for Command). Alias ::= 'User_Alias' User_Alias (':' User_Alias)* | 'Runas_Alias' Runas_Alias (':' Runas_Alias)* | 'Host_Alias' Host_Alias (':' Host_Alias)* | 'Cmnd_Alias' Cmnd_Alias (':' Cmnd_Alias)* User_Alias ::= NAME '=' User_List Runas_Alias ::= NAME '=' Runas_List Host_Alias ::= NAME '=' Host_List Cmnd_Alias ::= NAME '=' Cmnd_List NAME ::= [A-Z]([A-Z][0-9]_)* Each alias definition is of the form Alias_Type NAME = item1, item2, ... where Alias_Type is one of User_Alias, Runas_Alias, Host_Alias, or Cmnd_Alias. A NAME is a string of uppercase letters, numbers, and underscore characters ('_'). A NAME must start with an uppercase letter. It is possible to put several alias definitions of the same type on a single line, joined by a colon (':'). E.g., Alias_Type NAME = item1, item2, item3 : NAME = item4, item5 The definitions of what constitutes a valid alias member follow. User_List ::= User | User ',' User_List User ::= '!'* username | '!'* '%'group | '!'* '+'netgroup | '!'* User_Alias A User_List is made up of one or more usernames, system groups (prefixed with '%'), netgroups (prefixed with '+') and other aliases. Each list item may be prefixed with one or more '!' operators. An odd num- ber of '!' operators negate the value of the item; an even number just cancel each other out. Runas_List ::= Runas_User | Runas_User ',' Runas_List Runas_User ::= '!'* username | '!'* '#'uid | '!'* '%'group | '!'* +netgroup | '!'* Runas_Alias A Runas_List is similar to a User_List except that it can also contain uids (prefixed with '#') and instead of User_Aliases it can contain Runas_Aliases. Note that usernames and groups are matched as strings. In other words, two users (groups) with the same uid (gid) are considered to be distinct. If you wish to match all usernames with the same uid (e.g. root and toor), you can use a uid instead (#0 in the example given). Host_List ::= Host | Host ',' Host_List Host ::= '!'* hostname | '!'* ip_addr | '!'* network(/netmask)? | '!'* '+'netgroup | '!'* Host_Alias A Host_List is made up of one or more hostnames, IP addresses, network numbers, netgroups (prefixed with '+') and other aliases. Again, the value of an item may be negated with the '!' operator. If you do not specify a netmask along with the network number, sudo will query each of the local host's network inter- faces and, if the network number corresponds to one of the hosts's network interfaces, the corresponding netmask will be used. The netmask may be specified either in standard IP address notation (e.g. 255.255.255.0 or ffff:ffff:ffff:ffff::), or CIDR notation (number of bits, e.g. 24 or 64). A host- name may include shell-style wildcards (see the Wildcards section below), but unless the hostname command on your machine returns the fully qualified hostname, you'll need to use the fqdn option for wildcards to be useful. Cmnd_List ::= Cmnd | Cmnd ',' Cmnd_List commandname ::= filename | filename args | filename '""' Cmnd ::= '!'* commandname | '!'* directory | '!'* "sudoedit" | '!'* Cmnd_Alias A Cmnd_List is a list of one or more commandnames, directories, and other aliases. A commandname is a fully qualified filename which may include shell-style wildcards (see the Wildcards section below). A simple filename allows the user to run the command with any arguments he/she wishes. However, you may also specify command line arguments (including wildcards). Alternately, you can specify "" to indicate that the command may only be run without command line arguments. A directory is a fully qualified path- name ending in a '/'. When you specify a directory in a Cmnd_List, the user will be able to run any file within that directory (but not in any subdirectories therein). If a Cmnd has associated command line arguments, then the arguments in the Cmnd must match exactly those given by the user on the command line (or match the wildcards if there are any). Note that the following characters must be escaped with a '' if they are used in command arguments: ',', ':', '=', ''. The special command "sudoedit" is used to permit a user to run sudo with the -e flag (or as sudoedit). It may take command line arguments just as a normal command does. Defaults(默认的配置参数,具体有哪些参数其后有说明,了解即可) Certain configuration options may be changed from their default values at runtime via one or more Default_Entry lines. These may affect all users on any host, all users on a specific host, a specific user, or commands being run as a specific user. Default_Type ::= 'Defaults' | 'Defaults' '@' Host_List | 'Defaults' ':' User_List | 'Defaults' '>' Runas_List Default_Entry ::= Default_Type Parameter_List Parameter_List ::= Parameter | Parameter ',' Parameter_List Parameter ::= Parameter '=' Value | Parameter '+=' Value | Parameter '-=' Value | '!'* Parameter Parameters may be flags, integer values, strings, or lists. Flags are implicitly boolean and can be turned off via the '!' operator. Some integer, string and list parameters may also be used in a boolean context to disable them. Values may be enclosed in double quotes (") when they contain multiple words. Special characters may be escaped with a backslash (). Lists have two additional assignment operators, += and -=. These operators are used to add to and delete from a list respectively. It is not an error to use the -= operator to remove an element that does not exist in a list. See "SUDOERS OPTIONS" for a list of supported Defaults parameters. User Specification User_Spec ::= User_List Host_List '=' Cmnd_Spec_List (':' Host_List '=' Cmnd_Spec_List)* Cmnd_Spec_List ::= Cmnd_Spec | Cmnd_Spec ',' Cmnd_Spec_List Cmnd_Spec ::= Runas_Spec? Tag_Spec* Cmnd Runas_Spec ::= '(' Runas_List ')' Tag_Spec ::= ('NOPASSWD:' | 'PASSWD:' | 'NOEXEC:' | 'EXEC:' | 'SETENV:' | 'NOSETENV:') A user specification determines which commands a user may run (and as what user) on specified hosts. By default, commands are run as root, but this can be changed on a per-command basis. Let's break that down into its constituent parts: Runas_Spec A Runas_Spec is simply a Runas_List (as defined above) enclosed(附带的) in a set of parentheses. If you do not specify a Runas_Spec in the user specification, a default Runas_Spec of root will be used. A Runas_Spec sets the default for commands that follow it. What this means is that for the entry: dgb boulder = (operator) /bin/ls, /bin/kill, /usr/bin/lprm The user dgb may run /bin/ls, /bin/kill, and /usr/bin/lprm -- but only as operator. E.g., $ sudo -u operator /bin/ls. It is also possible to override a Runas_Spec later on in an entry. If we modify the entry like so: dgb boulder = (operator) /bin/ls, (root) /bin/kill, /usr/bin/lprm Then user dgb is now allowed to run /bin/ls as operator, but /bin/kill and /usr/bin/lprm as root. Tag_Spec A command may have zero or more tags associated with it. There are six possible tag values, NOPASSWD, PASSWD, NOEXEC, EXEC, SETENV and NOSETENV. Once a tag is set on a Cmnd, subsequent Cmnds in the Cmnd_Spec_List, inherit the tag unless it is overridden by the opposite tag (i.e.: PASSWD overrides NOPASSWD and NOEXEC overrides EXEC). NOPASSWD and PASSWD By default, sudo requires that a user authenticate him or herself before running a command. This behav- ior can be modified via the NOPASSWD tag. Like a Runas_Spec, the NOPASSWD tag sets a default for the commands that follow it in the Cmnd_Spec_List. Conversely, the PASSWD tag can be used to reverse things. For example: ray rushmore = NOPASSWD: /bin/kill, /bin/ls, /usr/bin/lprm would allow the user ray to run /bin/kill, /bin/ls, and /usr/bin/lprm as root on the machine rushmore as root without authenticating himself. If we only want ray to be able to run /bin/kill without a password the entry would be: ray rushmore = NOPASSWD: /bin/kill, PASSWD: /bin/ls, /usr/bin/lprm Note, however, that the PASSWD tag has no effect on users who are in the group specified by the exempt_group option. By default, if the NOPASSWD tag is applied to any of the entries for a user on the current host, he or she will be able to run sudo -l without a password. Additionally, a user may only run sudo -v without a password if the NOPASSWD tag is present for all a user's entries that pertain to the current host. This behavior may be overridden via the verifypw and listpw options. NOEXEC and EXEC If sudo has been compiled with noexec support and the underlying operating system supports it, the NOEXEC tag can be used to prevent a dynamically-linked executable from running further commands itself. In the following example, user aaron may run /usr/bin/more and /usr/bin/vi but shell escapes will be dis- abled. aaron shanty = NOEXEC: /usr/bin/more, /usr/bin/vi See the "PREVENTING SHELL ESCAPES" section below for more details on how NOEXEC works and whether or not it will work on your system. SETENV and NOSETENV These tags override the value of the setenv option on a per-command basis. Note that if SETENV has been set for a command, any environment variables set on the command line way are not subject to the restric- tions imposed by env_check, env_delete, or env_keep. As such, only trusted users should be allowed to set variables in this manner. If the command matched is ALL, the SETENV tag is implied for that command; this default may be overridden by use of the UNSETENV tag. Wildcards(通配符) sudo allows shell-style wildcards (aka meta or glob characters) to be used in pathnames as well as com- mand line arguments in the sudoers file. Wildcard matching is done via the POSIX fnmatch(3) routine. Note that these are not regular expressions. * Matches any set of zero or more characters. ? Matches any single character. [...] Matches any character in the specified range. [!...] Matches any character not in the specified range. x For any character "x", evaluates to "x". This is used to escape special characters such as: "*", "?", "[", and "}". Note that a forward slash ('/') will not be matched by wildcards used in the pathname. When matching the command line arguments, however, a slash does get matched by wildcards. This is to make a path like: /usr/bin/* match /usr/bin/who but not /usr/bin/X11/xterm. Exceptions to wildcard rules The following exceptions apply to the above rules: "" If the empty string "" is the only command line argument in the sudoers entry it means that com- mand is not allowed to be run with any arguments. Other special characters and reserved words The pound sign ('#') is used to indicate a comment (unless it is part of a #include directive or unless it occurs in the context of a user name and is followed by one or more digits, in which case it is treated as a uid). Both the comment character and any text after it, up to the end of the line, are ignored. The reserved word ALL is a built-in alias that always causes a match to succeed. It can be used wherever one might otherwise use a Cmnd_Alias, User_Alias, Runas_Alias, or Host_Alias. You should not try to define your own alias called ALL as the built-in alias will be used in preference to your own. Please note that using ALL can be dangerous since in a command context, it allows the user to run any command on the system. An exclamation point ('!') can be used as a logical not operator both in an alias and in front of a Cmnd. This allows one to exclude certain values. Note, however, that using a ! in conjunction with the built- in ALL alias to allow a user to run "all but a few" commands rarely works as intended (see SECURITY NOTES below). Long lines can be continued with a backslash ('') as the last character on the line. Whitespace between elements in a list as well as special syntactic characters in a User Specification ('=', ':', '(', ')') is optional. The following characters must be escaped with a backslash ('') when used as part of a word (e.g. a user- name or hostname): '@', '!', '=', ':', ',', '(', ')', ''. SUDOERS OPTIONS sudo's behavior can be modified by Default_Entry lines, as explained earlier. A list of all supported Defaults parameters, grouped by type, are listed below. Flags: …… Integers: passwd_tries The number of tries a user gets to enter his/her password before sudo logs the failure and exits. The default is 3. Integers that can be used in a boolean context: …… Strings: …… Strings that can be used in a boolean context: …… Lists that can be used in a boolean context: …… FILES /etc/sudoers List of who can run what /etc/group Local groups file /etc/netgroup List of network groups
EXAMPLES Since the sudoers file is parsed in a single pass, order is important. In general, you should structure sudoers such that the Host_Alias, User_Alias, and Cmnd_Alias specifications come first, followed by any Default_Entry lines, and finally the Runas_Alias and user specifications. The basic rule of thumb is you cannot reference an Alias that has not already been defined. Below are example sudoers entries. Admittedly, some of these are a bit contrived (人造的, 勉强的, 不自然的). First, we define our aliases: # User alias specification User_Alias FULLTIMERS = millert, mikef, dowdy User_Alias PARTTIMERS = bostley, jwfox, crawl User_Alias WEBMASTERS = will, wendy, wim # Runas alias specification Runas_Alias OP = root, operator Runas_Alias DB = oracle, sybase # Host alias specification Host_Alias SPARC = bigtime, eclipse, moet, anchor : SGI = grolsch, dandelion, black : ALPHA = widget, thalamus, foobar : HPPA = boa, nag, python Host_Alias CUNETS = 128.138.0.0/255.255.0.0 Host_Alias CSNETS = 128.138.243.0, 128.138.204.0/24, 128.138.242.0 Host_Alias SERVERS = master, mail, www, ns Host_Alias CDROM = orion, perseus, hercules # Cmnd alias specification Cmnd_Alias DUMPS = /usr/bin/mt, /usr/sbin/dump, /usr/sbin/rdump, /usr/sbin/restore, /usr/sbin/rrestore Cmnd_Alias KILL = /usr/bin/kill Cmnd_Alias PRINTING = /usr/sbin/lpc, /usr/bin/lprm Cmnd_Alias SHUTDOWN = /usr/sbin/shutdown Cmnd_Alias HALT = /usr/sbin/halt Cmnd_Alias REBOOT = /usr/sbin/reboot Cmnd_Alias SHELLS = /usr/bin/sh, /usr/bin/csh, /usr/bin/ksh, /usr/local/bin/tcsh, /usr/bin/rsh, /usr/local/bin/zsh Cmnd_Alias SU = /usr/bin/su Cmnd_Alias PAGERS = /usr/bin/more, /usr/bin/pg, /usr/bin/less Here we override (废除) some of the compiled in default values. We want sudo to log via syslog(3) using the auth facility in all cases. We don't want to subject the full time staff to the sudo lecture, user millert need not give a password, and we don't want to reset the LOGNAME, USER or USERNAME environment variables when running commands as root. Additionally, on the machines in the SERVERS Host_Alias, we keep an additional local log file and make sure we log the year in each log line since the log entries will be kept around for several years. Lastly, we disable shell escapes for the commands in the PAGERS Cmnd_Alias (/usr/bin/more, /usr/bin/pg and /usr/bin/less). # Override built-in defaults Defaults syslog=auth Defaults>root !set_logname Defaults:FULLTIMERS !lecture Defaults:millert !authenticate Defaults@SERVERS log_year, logfile=/var/log/sudo.log Defaults!PAGERS noexec The User specification is the part that actually determines who may run what. root ALL = (ALL) ALL %wheel ALL = (ALL) ALL We let root and any user in group wheel run any command on any host as any user. FULLTIMERS ALL = NOPASSWD: ALL Full time sysadmins (millert, mikef, and dowdy) may run any command on any host without authenticating themselves. PARTTIMERS ALL = ALL Part time sysadmins (bostley, jwfox, and crawl) may run any command on any host but they must authenti- cate themselves first (since the entry lacks the NOPASSWD tag). jack CSNETS = ALL The user jack may run any command on the machines in the CSNETS alias (the networks 128.138.243.0, 128.138.204.0, and 128.138.242.0). Of those networks, only 128.138.204.0 has an explicit netmask (in CIDR notation) indicating it is a class C network. For the other networks in CSNETS, the local machine's netmask will be used during matching. lisa CUNETS = ALL The user lisa may run any command on any host in the CUNETS alias (the class B network 128.138.0.0). operator ALL = DUMPS, KILL, SHUTDOWN, HALT, REBOOT, PRINTING, sudoedit /etc/printcap, /usr/oper/bin/ The operator user may run commands limited to simple maintenance. Here, those are commands related to backups, killing processes, the printing system, shutting down the system, and any commands in the direc- tory /usr/oper/bin/. joe ALL = /usr/bin/su operator The user joe may only su(1) to operator. pete HPPA = /usr/bin/passwd [A-z]*, !/usr/bin/passwd root The user pete is allowed to change anyone's password except for root on the HPPA machines. Note that this assumes passwd(1) does not take multiple usernames on the command line. bob SPARC = (OP) ALL : SGI = (OP) ALL The user bob may run anything on the SPARC and SGI machines as any user listed in the OP Runas_Alias (root and operator). jim +biglab = ALL The user jim may run any command on machines in the biglab netgroup. sudo knows that "biglab" is a net- group due to the '+' prefix. +secretaries ALL = PRINTING, /usr/bin/adduser, /usr/bin/rmuser Users in the secretaries netgroup need to help manage the printers as well as add and remove users, so they are allowed to run those commands on all machines. fred ALL = (DB) NOPASSWD: ALL The user fred can run commands as any user in the DB Runas_Alias (oracle or sybase) without giving a password. john ALPHA = /usr/bin/su [!-]*, !/usr/bin/su *root* On the ALPHA machines, user john may su to anyone except root but he is not allowed to give su(1) any flags. jen ALL, !SERVERS = ALL The user jen may run any command on any machine except for those in the SERVERS Host_Alias (master, mail, www and ns). jill SERVERS = /usr/bin/, !SU, !SHELLS For any machine in the SERVERS Host_Alias, jill may run any commands in the directory /usr/bin/ except for those commands belonging to the SU and SHELLS Cmnd_Aliases. steve CSNETS = (operator) /usr/local/op_commands/ The user steve may run any command in the directory /usr/local/op_commands/ but only as user operator. matt valkyrie = KILL On his personal workstation, valkyrie, matt needs to be able to kill hung processes. WEBMASTERS www = (www) ALL, (root) /usr/bin/su www On the host www, any user in the WEBMASTERS User_Alias (will, wendy, and wim), may run any command as user www (which owns the web pages) or simply su(1) to www. ALL CDROM = NOPASSWD: /sbin/umount /CDROM, /sbin/mount -o nosuid,nodev /dev/cd0a /CDROM Any user may mount or unmount a CD-ROM on the machines in the CDROM Host_Alias (orion, perseus, hercules) without entering a password. This is a bit tedious for users to type, so it is a prime candidate for encapsulating in a shell script.
root@fhc2007-desktop:~# cat /etc/sudoers # /etc/sudoers # # This file MUST be edited with the 'visudo' command as root. # # See the man page for details on how to write a sudoers file. # Defaults env_reset # Uncomment to allow members of group sudo to not need a password # %sudo ALL=NOPASSWD: ALL # Host alias specification # User alias specification # Cmnd alias specification # User privilege specification root ALL=(ALL) ALL # Members of the admin group may gain root privileges %admin ALL=(ALL) ALL root@fhc2007-desktop:~#