Sudo

From Gentoo Wiki
Jump to: navigation, search
This page is a translated version of the page Sudo and the translation is 56% complete.

Other languages:
English • ‎español • ‎français • ‎italiano • ‎日本語 • ‎한국어 • ‎русский • ‎中文(中国大陆)‎


Resources

The sudo command provides a simple and secure way to configure privilege escalation — i.e., letting normal users execute certain (or even all) commands as root or another user, either with or without giving a password.

When you want some people to perform certain administrative steps on your system without granting them total root access, using sudo is your best option. With sudo you can control who can do what. This guide offers you a small introduction to this powerful tool.

This article is meant as a quick introduction. The app-admin/sudo package is a lot more powerful than what is described here. It has special features for editing files as a different user (sudoedit), running from within a script (so it can background, read the password from standard in instead of the keyboard, ...), etc.

Please read the sudo and sudoers manual pages for more information.

설치

USE 플래그

USE flags for app-admin/sudo Allows users or groups to run commands as other users

gcrypt Use SHA2 from dev-libs/libgcrypt instead of sudo's internal SHA2. local
ldap Add LDAP support (Lightweight Directory Access Protocol) global
nls Add Native Language Support (using gettext - GNU locale utilities) global
offensive Let sudo print insults when the user types the wrong password. local
openssl Use SHA2 from dev-libs/openssl instead of sudo's internal SHA2. local
pam Add support for PAM (Pluggable Authentication Modules) - DANGEROUS to arbitrarily flip global
sasl Add support for the Simple Authentication and Security Layer global
selinux !!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur global
sendmail Allow sudo to send emails with sendmail. local
skey Enable S/Key (Single use password) authentication support global

Emerge

root #emerge --ask app-admin/sudo

설정

활동 기록

One additional advantage of sudo is that it can log any attempt (successful or not) to run an application. This is very useful if you want to track who made that one fatal mistake that took you 10 hours to fix :)

권한 부여

The app-admin/sudo package allows the system administrator to grant permission to other users to execute one or more applications they would normally have no right to. Unlike using the setuid bit on these applications sudo gives a more fine-grained control on who can execute a certain command and when.

With sudo you can make a clear list of who can execute a certain application. If you set the setuid bit on an executable, any user would be able to run the application (or any user of a certain group, depending on the permissions used). With sudo you can (and probably should) require the user to provide a password in order to execute the application.

The sudo configuration is managed by the /etc/sudoers file. This file should never be edited through nano /etc/sudoers or vim /etc/sudoers, or any other editor you would normally use. When you want to alter the /etc/sudoers file, you should always use visudo. This tool makes sure that no two system administrators are editing this file at the same time, preserves the permissions on the file, and performs some syntax checking to make sure you make no fatal mistakes in the file.

기본 문법

The most difficult part of sudo is the /etc/sudoers syntax. The basic syntax is as follows:

코드 Basic /etc/sudoers syntax
user  host = command

This line tells sudo that the user, identified by user and logged in on the system host, can execute the command command (which can also be a comma-separated list of allowed commands).

A more real-life example might make this more clear: To allow the user larry to execute emerge when he is logged in on localhost:

코드 Real /etc/sudoers example
larry  localhost = /usr/bin/emerge
참고
The hostname must match the name that the hostname command returns.
참고
In the simplest case, commands must be fully qualified paths to executables: hence /usr/bin/emerge not just emerge. Paths can also contain wildcards and may refer to entire directories. See the manpage for details.
경고
Do not allow a normal user to run an application that can enable them to elevate privileges. For instance, allowing users to execute emerge as root can grant them full root access to the system because emerge can be manipulated to change the live file system to the user's advantage. If you do not trust your sudo users, don't grant them any additional rights.

The user name can also be substituted with a group name, in which case the name is prefaced by a % sign. For instance, to allow any one in the wheel group to execute emerge:

코드 Allowing any wheel group member to execute emerge
%wheel  localhost = /usr/bin/emerge

To enable more than one command for a given user on a given machine, multiple commands can be listed on the same line. For instance, to allow larry to not only run emerge but also ebuild and emerge-webrsync as root:

코드 다중 명령
larry  localhost = /usr/bin/emerge, /usr/bin/ebuild, /usr/sbin/emerge-webrsync

You can also specify a precise command line (including parameters and arguments) not just the name of the executable. This is useful to restrict the use of a certain tool to a specified set of command options. The sudo tool allows shell-style wildcards (AKA meta or glob characters) to be used in path names as well as command-line arguments in the sudoers file. Note that these are not regular expressions.

Here is an example of sudo from the perspective of a first-time user of the tool who has been granted access to the full power of emerge:

user $sudo emerge -uDN world
We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:
 
    #1) Respect the privacy of others.
    #2) Think before you type.
    #3) With great power comes great responsibility.
 
Password: ## (Enter the user password, not root!)

The password that sudo requires is the user's own password. This is to make sure that no terminal that you accidentally left open to others is abused for malicious purposes.

중요
sudo does not alter the ${PATH} variable: any command placed after sudo is executed within the user's own environment. Thus if a user wants to run a tool in /sbin, for instance, the user must provide sudo with the full path of the command, like so:
user $sudo /usr/sbin/emerge-webrsync

LDAP 기본 문법

The ldap and pam USE flags are needed for the LDAP support.

LDAP에 sudo를 사용하면 마찬가지로 LDAP 서버의 설정을 읽습니다. 따라서 다음 두개의 파일을 편집해야합니다.

파일 /etc/ldap.conf.sudoPlease chmod 400 when done
# See ldap.conf(5) and README.LDAP for details
# This file should only be readable by root
 
# supported directives: host, port, ssl, ldap_version
# uri, binddn, bindpw, sudoers_base, sudoers_debug
# tls_{checkpeer,cacertfile,cacertdir,randfile,ciphers,cert,key
 
host ldap.example.com
port 389
 
base dc=example,dc=com
 
uri ldap://ldap.example.com/
#uri ldapi://%2fvar%2frun%2fopenldap%2fslapd.sock
 
ldap_version 3
#ssl start_tls
 
sudoers_base ou=SUDOers,dc=example,dc=com
#sudoers_debug 2
 
bind_policy soft
파일 /etc/nsswitch.confsudoers에 다음 줄을 추가하십시오
sudoers:     ldap files

또한 sudo 에 다음 LDAP 항목을 추가해야 합니다.

참고
보안 문제로 sudoers 브랜치를 트리 상단에 놓도록 설계했습니다. 따라서 이 LDAP 브랜치에 읽기/쓰기 접근 권한을 다르게 줄 수 있습니다
코드 Ldap Entry for Sudo
version: 1
DN: ou=SUDOers,dc=example,dc=com
objectClass: organizationalUnit
objectClass: top
objectClass: domainRelatedObject
associatedDomain: example.com
ou: SUDOers
 
DN: cn=defaults,ou=SUDOers,dc=example,dc=com
objectClass: top
objectClass: sudoRole
cn: defaults
description: Default sudoOption's go here
sudoOption: env_reset
 
DN: cn=root,ou=SUDOers,dc=example,dc=com
objectClass: top
objectClass: sudoRole
cn: root
sudoCommand: ALL
sudoHost: ALL
sudoUser: root
 
DN: cn=%wheel,ou=SUDOers,dc=example,dc=com
objectClass: top
objectClass: sudoRole
cn: %wheel
sudoCommand: ALL
sudoHost: ALL
sudoOption: !authenticate
sudoUser: %wheel
코드 wheel 그룹의 LDAP 항목
version: 1
DN: cn=wheel,ou=Group,dc=example,dc=com
objectClass: top
objectClass: posixGroup
cn: wheel
description: Wheel Group
gidNumber: 10
memberUid: useradmin1
memberUid: root

sudoer LDAP 설정은 다른 설정을 하는 파일과 비슷합니다. 아래 링크에 있는 sudo LDAP 글을 더 읽어보십시오[1].

  1. [1] Sudoers 맨 페이지

별칭 사용

좀 더 거대한 환경에서는 모든 사용자(또는 호스트, 명령)를 계속해서 적어넣어야 하는데 그걸 다 하기엔 벅찹니다. /etc/sudoers 관리를 쉽게 하기 위해 aliases를 정의할 수 있습니다. aliases를 선언하는 형식은 약간 단순합니다:

코드 /etc/sudoers에 별칭 선언
Host_Alias hostalias = hostname1, hostname2, ...
User_Alias useralias = user1, user2, ...
Cmnd_Alias cmndalias = command1, command2, ...

어디에 있든, 항상 동작하는 별칭은 ALL 입니다(별칭인 것과 아닌 것을 쉽게 구분하기 위해 대문자 사용을 추천합니다). 확실히 짐작한 바와 같이 ALL 별칭은 모든 설정에서 쓸 수 있는 별칭입니다.

A sample use of the ALL alias to allow any user to execute the shutdown command if he is logged on locally is:

코드 일부 사용자에게 shutdown 실행 허가
ALL  localhost = /sbin/shutdown

Another example is to allow the user larry to execute the emerge command as root, regardless of where he is logged in from:

코드 위치에 상관 없이 사용자에게 프로그램 실행 허가
larry   ALL = /usr/bin/emerge

More interesting is to define a set of users who can run software administrative applications (such as emerge and ebuild) on the system and a group of administrators who can change the password of any user, except root!

코드 Using aliases for users and commands
User_Alias  SOFTWAREMAINTAINERS = larry, john, danny
User_Alias  PASSWORDMAINTAINERS = larry, sysop
Cmnd_Alias  SOFTWARECOMMANDS    = /usr/bin/emerge, /usr/bin/ebuild
Cmnd_Alias  PASSWORDCOMMANDS    = /usr/bin/passwd [a-zA-Z0-9_-]*, !/usr/bin/passwd root
 
SOFTWAREMAINTAINERS  localhost = SOFTWARECOMMANDS
PASSWORDMAINTAINERS  localhost = PASSWORDCOMMANDS

비 루트 실행

It is also possible to have a user run an application as a different, non-root user. This can be very interesting if you run applications as a different user (for instance apache for the web server) and want to allow certain users to perform administrative steps as that user (like killing zombie processes).

/etc/sudoers에는 명령을 나열하기 전에 () 사이에 사용자를 나열하십시오:

코드 비 루트 실행 문법
users  hosts = (run-as) commands

For instance, to allow larry to run the kill tool as the apache or gorg user:

코드 Non-root execution example
Cmnd_Alias KILL = /bin/kill, /usr/bin/pkill
 
larry   ALL = (apache, gorg) KILL

With this set, the user can run sudo -u to select the user he wants to run the application as:

user $sudo -u apache pkill apache

Runas_Alias 지시어를 활용하면 프로그램을 실행할 사용자의 별칭을 설정할 수 있습니다. 앞서보았던 _Alias 지시자에게도 이러한 활용법은 완전히 같습니다.

암호 및 기본 설정

By default, sudo asks the user to identify himself using his own password. Once a password is entered, sudo remembers it for 5 minutes, allowing the user to focus on his tasks and not repeatedly re-entering his password.

물론 이 동작을 바꿀 수 있습니다: /etc/sudoers에서 Defaults: 지시어로 사용자에 대한 기본 동작 설정을 바꿀 수 있습니다.

기본 5분값을 0(기억하지 않음)으로 바꾸려면:

코드 제한 시간 값 바꾸기
Defaults:larry  timestamp_timeout=0

-1로 설정하면 (시스템을 다시 부팅하기 전까지) 암호를 무한대 시간동안 기억합니다.

A different setting would be to require the password of the user that the command should be run as and not the users' personal password. This is accomplished using runaspw. In the following example we also set the number of retries (how many times the user can re-enter a password before sudo fails) to 2 instead of the default 3:

코드 사용자 명령 대신 루트 암호 요구
Defaults:john   runaspw, passwd_tries=2

그래픽 도구를 실행할 수 있게 DISPLAY 변수 설정을 유지하는 또 다른 재밌는 기능도 있습니다:

코드 DISPLAY 변수 값 유지
Defaults:john env_keep=DISPLAY

You can change dozens of default settings using the Defaults: directive. Fire up the sudoers manual page and search for Defaults.

허나 어쨌든간에 암호를 제공하지 않고 명령 세트를 실행할 수 있게 하려면, 다음과 같이 NOPASSWD: 지시자를 붙여 명령 기입을 시작해야합니다:

코드 암호를 묻지 않고 루트 권한으로 emerge 를 실행하도록 허용
larry     localhost = NOPASSWD: /usr/bin/emerge

배시 자동 완성

sudo에 bash 명령 완성 기능을 사용하려는 사용자는 다음 명령을 한번 실행하십시오.

user $sudo echo "complete -cf sudo" >> $HOME/.bashrc

Z쉘 명령 완성

sudo에 zsh 명령 완성 기능을 사용하려는 사용자는 .zprofile.zshrc에 각각 다음 내용을 설정할 수 있습니다

파일 .zprofileAdding zshell completion
if [[ $EUID != 0 ]]; then
    typeset -xT SUDO_PATH sudo_path
    typeset -U sudo_path
    sudo_path=({,/usr/local,/usr}/sbin(N-/))
    alias sudo="sudo env PATH=\"SUDO_PATH:$PATH\""
fi
파일 .zshrczshell 명령 완성 추가
zstyle ':completion:*:sudo:*' environ PATH="$SUDO_PATH:$PATH"

위 내용으로 바꾸면, /sbin, /usr/sbin, /usr/local/sbin 위치에 있는 값은 'sudo' 다음에 놓은 명령에 대한 명령 완성 기능을 쉘에서 사용할 수 있습니다.

사용법

권한 확인

To inform yourself what your capabilities are, run sudo -l :

user $sudo -l
User larry may run the following commands on this host:
    (root)   /usr/libexec/xfsm-shutdown-helper
    (root)   /usr/bin/emerge
    (root)   /usr/bin/passwd [a-zA-Z0-9_-]*
    (root)   !/usr/bin/passwd root
    (apache) /usr/bin/pkill
    (apache) /bin/kill

/etc/sudoers 에 암호를 입력할 필요가 없는 명령이 있다면, 항목에 있는 명령에 암호를 요구하지 않습니다. 그렇지 않아 항목에 없어 기억하지 않으면 암호를 물어봅니다.

암호 입력 제한 시간 미리 연장

By default, if a user has entered their password to authenticate their self to sudo, it is remembered for 5 minutes. If the user wants to prolong this period, he can run sudo -v to reset the time stamp so that it will take another 5 minutes before sudo asks for the password again.

user $sudo -v

The inverse is to kill the time stamp using sudo -k.