Softpanorama
May the source be with you, but remember the KISS principle ;-)

Contents Bulletin Scripting in shell and Perl Network troubleshooting History Humor

Unix Sudo (superuser do)

Softpanorama main  >  Access Control in Operating Systems

News

Introduction to Sudo

Recommended Links The su Command Reference Wheel Group
Sudo on AIX Sudo for HPUX Solaris RBAC Group administration SUID/SGID attributes The umask
Root Account Root Security Admin Horror Stories History Humor Etc

One problem with Unix security is not that root is all-powerful, but that regular accounts are not powerful enough to be useful for many common tasks.  One way to solve this Unix problem was sudo, the utility that can grant to non-root account root access on "per-command" basis.  Essentially sudo is a rudimentarily implementation of RBAC (see, for example Solaris RBAC) in a completely portable Unix-flavor independent way.  All problem related to proper structuring of roles are present in sudo, as soon as it is used for anything else then access of root account by non-root but privileged (typically members of Wheel Group) users.

Sudo (superuser do) is an extension of the classic Unix command su (introduced in BSD). It allows a system administrator to work using his own account and switch to root or other user identity available on the system only for commands that need it. In most cases it is used to as "one command switch to root". It also protect system administrators from horrible mistakes that can happen when you work as root all the time. In case you are tired you can do a lot of damage with just one "subconscious" mistake. For example, if you accidentally type rm /etc* instead of rm etc*. See Admin Horror Stories for a overview of typical "horrors" of this time. In other words working in your own account all the time and using sudo prefix when you need to execute commands as root is much safer way of working for sysadmins. Here the value of sudo is undisputable. 

In addition sudo provides logging of commands which you submitted. That also has value when, say, two people administer the same server. Otherwise  to understand what was done by your partner is not easy, as sysadmin typically are in a hurry and seldom completely document their actions. Sometimes people lie and try to hide their mistakes. Here you have some chances to recreate the set of actions of your partner.

Sudo is useful on all version and flavors of Unix, with possible exception of Solaris 10 were native OS mechanisms (RBAC) are superior. For a brief history of Sudo see history section

Sudo is integrated in OpenBSD and Ubuntu and pre-installed on enterprise linux distributions (RHEL and Suse). It is not installed on AIX and HP-UX but it is available in "vendor-precompiled", "vendor-unsupported" form. See

The great advantage of sudo is that it can (and should) be deployed on all Unix systems under administration (it's pretty simple to deploy if via SSH).  This universal availability is a huge advantage over other similar packages.

Suse has a turbulent history with many vulnerabilities fixed at different periods of time. While sudo provide an elegant way to provide to users temporary root capabilities without communicating to the user root password, there is no easy way to prevent a user from gaining a root shell if that user is allowed to run commands with shell escape via sudo. Many programs (such as editors) allow the user to run commands via shell escapes, thus avoiding sudo's checks. Some Unix utilities such as find  and xarg, allow execution or arbitrary commands. However, on most systems it is possible to prevent shell escapes with sudo's noexec functionality.

The current version as of April 2013 is 1.8.6p8, but most linux distros provide only much older (but adequate) version 1.7.6p2 (called Maintenance release on sudo site).  It's now pretty complex product which is the major deficiency. Security vulnerabilities are periodically discovered and for open source program of such complexity its presence in the system is essentially a free backdoor to root as it is reasonable to assume that for any version there is at lease one unknown zero-day exploit.  There is a great need for simpler and more secure "sudo-light"...

In some organizations and flavors on Linux (such as Ubuntu) root account has password disabled and the only way to access root is via sudo.  This concept is called Rootsudo in Ubuntu

Sudoers file

The most difficult part of sudo is the /etc/sudoers syntax. The basic syntax is like so:

user  host = commands

But the devil is in details.

The user name can also be substituted with a group name - in this case you should start the group name with a % sign. For instance, to allow any one in the wheel group to execute emerge:

%users  localhost = /usr/bin/crontab
oracle  localhost = /usr/bin/crontab, /etc/inint.d/oracle

You can also specify a precise command and not only the tool itself.

oracle  localhost = /usr/bin/crontab -u oracle

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 pathnames as well as command line arguments in the sudoers file. Note that these are not regular expressions.

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.

You should know that sudo does not alter the ${PATH} variable: any command you place after sudo is treated from your environment.

Using Aliases

In larger environments having to enter all users over and over again (or hosts, or commands) can be a daunting task. To ease the administration of /etc/sudoers you can define aliases. The format to declare aliases is quite simple:

Host_Alias hostalias = hostname1, hostname2, ...
User_Alias useralias = user1, user2, ...
Cmnd_Alias cmndalias = command1, command2, ...

One alias that always works, for any position, is the ALL alias (to make a good distinction between aliases and non-aliases it is recommended to use capital letters for aliases). As you might undoubtedly have guessed, the ALL alias is an alias to all possible settings.

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

ALL  localhost = /sbin/shutdown

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

swift   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!

User_Alias  SOFTWAREMAINTAINERS = swift, john, danny
User_Alias  PASSWORDMAINTAINERS = swift, 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

Non-Root Execution

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).

Inside /etc/sudoers you list the user(s) in between ( and ) before the command listing:

users  hosts = (run-as) commands

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

Cmnd_Alias KILL = /bin/kill, /usr/bin/pkill

swift   ALL = (apache, gorg) KILL

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

$ sudo -u apache pkill apache

You can set an alias for the user to run an application as using the Runas_Alias directive. Its use is identical to the other _Alias directives we have seen before.

Passwords and Default Settings

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.

Of course, this behavior can be changed: you can set the Defaults: directive in /etc/sudoers to change the default behavior for a user.

For instance, to change the default 5 minutes to 0 (never remember):

Defaults:swift  timestamp_timeout=0

A setting of -1 would remember the password indefinitely (until the system reboots).

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

Another interesting feature is to keep the DISPLAY variable set so that you can execute graphical tools:

Defaults:john env_keep=DISPLAY

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

If you however want to allow a user to run a certain set of commands without providing any password whatsoever, you need to start the commands with NOPASSWD:, like so:

swift     localhost = NOPASSWD: /usr/bin/emerge

Listing Privileges

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

$ sudo -l

If you have any command in /etc/sudoers that does not require you to enter a password, it will not require a password to list the entries either. Otherwise you might be asked for your password if it isn't remembered.

Prolonging the Password Timeout

By default, if a user has entered his password to authenticate himself 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.

$ sudo -v

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

Implementing two groups of administrators

Sometimes you have two group administrators

In this case you can have two privileged groups:

For example:

%admin  ALL=(ALL) ALL
%wheel  ALL=(ALL) NOPASSWD: ALL

Grouping of commands

Here are some examples that give you idea of how to implement grouping of commands via Cmnd_Alias

# User Alias specification
User_Alias      TOMCATTERS = apps_owner1, apps_owner2
# Runas alias specification

# CMND alias specification
#The idea if a group of commands called VIEWCMD
Cmnd_Alias      VIEW_CMDS = /bin/ls, /bin/more, /bin/cat
#start and stop command for particular daemon for application owner
Cmnd_Alias      TOMCAT_CMDS = /etc/init.d/tomcat_stop, /etc/init.d/tomcat_start

%staff          ALL=(root) NOPASSWD: VIEW_CMDS
TOMCATTERS      ALL=(root) NOPASSWD: TOMCAT_CMDS
# grant a single command to user oracle
oracle ALL=(root) NOPASSWD: /usr/bin/crontab

Multiple tags on a line

There are times where you need to have both NOPASSWD and NOEXEC or other tags on the same configuration line. The man page for sudoers is less than clear, so here is an example of how this is done:

%staff ALL = (root) NOPASSWD:NOEXEC: /usr/bin/vim

This example lets the user "myuser" run as root the "vim" binary without a password, and without letting vim shell out (the :shell command).

More about Runas_Spec

A Runas_Spec determines the user and/or the group that a command may be run as. A fully-specified Runas_Spec consists of two Runas_Lists (as defined above) separated by a colon (‘:’) and enclosed in a set of parentheses. The first Runas_List indicates which users the command may be run as via sudo's ‑u option. The second defines a list of groups that can be specified via sudo's ‑g option. If both Runas_Lists are specified, the command may be run with any combination of users and groups listed in their respective Runas_Lists. If only the first is specified, the command may be run as any user in the list but no ‑g option may be specified. If the first Runas_List is empty but the second is specified, the command may be run as the invoking user with the group set to any listed in the Runas_List. If both Runas_Lists are empty, the command may only be run as the invoking user. If no Runas_Spec is specified the command may be run as root and no group may be specified.

A Runas_Spec sets the default for the 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.

We can extend this to allow dgb to run /bin/ls with either the user or group set to operator:

dgb	boulder = (operator : operator) /bin/ls, (root) /bin/kill,\
	/usr/bin/lprm

Note that while the group portion of the Runas_Spec permits the user to run as command with that group, it does not force the user to do so. If no group is specified on the command line, the command will run with the group listed in the target user's password database entry. The following would all be permitted by the sudoers entry above:

$ sudo -u operator /bin/ls
$ sudo -u operator -g operator /bin/ls
$ sudo -g operator /bin/ls

In the following example, user tcm may run commands that access a modem device file with the dialer group.

tcm	boulder = (:dialer) /usr/bin/tip, /usr/bin/cu,\
	/usr/local/bin/minicom

Note that in this example only the group will be set, the command still runs as user tcm. E.g.

$ sudo -g dialer /usr/bin/cu

Multiple users and groups may be present in a Runas_Spec, in which case the user may select any combination of users and groups via the ‑u and ‑g options. In this example:

alan	ALL = (root, bin : operator, system) ALL

user alan may run any command as either user root or bin, optionally setting the group to operator or system.

 


Top updates

Bulletin Latest Past week Past month
Google Search


NEWS CONTENTS

Old News ;-)

Take Control of your Linux sudoers file How to with Examples

Written by Guillermo Garron .
Date: 2012-05-22 14:56:30 +0000

... ... ....

In order to use sudo you first need to configure the sudoers file. The sudoers file is located at /etc/sudoers. And you should not edit it directly, you need to use the visudo command.

Once you enter visudo command, you will see something like this:

# /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

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL) ALL

Almost all lines are commented out, the one that matters in this sudoers file example is:

root ALL=(ALL) ALL

This line means: The root user can execute from ALL terminals, acting as ALL (any) users, and run ALL (any) command.

The first part is the user, the second is the terminal from where the user can use sudo command, the third part is which users he may act as, and the last one, is which commands he may run when using sudo.

sudoers examples

operator ALL= /sbin/poweroff

The above command, makes the user operator can from any terminal, run the command power off.

You can also create aliases for: users -> User_Alias, run commands as other users -> Runas_Alias, host -> Host_Alias and command -> Cmnd_Alias

User_Alias OPERATORS = joe, mike, jude 
Runas_Alias OP = root, operator 
Host_Alias OFNET = 10.1.2.0/255.255.255.0 
Cmnd_Alias PRINTING = /usr/sbin/lpc, /usr/bin/lprm

As you can see the alias OPERATORS includes the users joe, mike and jude, the alias OP includes the users root and operator, alias OFNET includes the network 10.1.2.0 (all the C class), and the command alias PRINTING includes the commands lpc and lprm.

So, a typical sudoers file may look like this:

 User_Alias     OPERATORS = joe, mike, jude
 Runas_Alias    OP = root, operator
 Host_Alias     OFNET = 10.1.2.0/255.255.255.0
 Cmnd_Alias     PRINTING = /usr/sbin/lpc, /usr/bin/lprm

OPERATORS ALL=ALL

#The users in the OPERATORS group can run any command from
 any terminal.

linus ALL=(OP) ALL

# The user linus can run any command from any terminal as any 
user in the OP group (root or operator).

user2 OFNET=(ALL) ALL

# user user2 may run any command from any machine in the 
OFNET network, as any user.

user3 ALL= PRINTING

# user user3 may run lpc and lprm from any machine.

go2linux ALL=(ALL) ALL

# user go2linux may run any command from any machine acting
 as any user. (like Ubuntu)

If you want not to be asked for a password use this form:

go2linux ALL=(ALL) NOPASSWD: ALL

[May 24, 2012]  Sudo Netmask Matching Security Bypass Vulnerability

As of May 24, 2012   the current stable release of sudo is 1.8.5p1.  
May 17, 2012

A vulnerability has been reported in Sudo, which can be exploited by malicious users to bypass certain security restrictions.

The vulnerability is caused due to an error within the network matching mechanism when processing hosts based on the IPv4 netmask. This can be exploited to execute commands from otherwise restricted hosts.

Successful exploitation requires that the user exists in the sudoers file and is granted access to commands on hosts on one or more IPv4 networks.

The vulnerability is reported in versions 1.6.9p3 through 1.8.4p4.

Solution:

Update to version 1.8.4p5 or 1.7.9p1.

Provided and/or discovered by: Jan Lieskovsky (Red Hat).

Original Advisory:

[Feb 17, 2011] Sudoers file

Jan 21, 2011 | IT Resource Center forums

ozas (Question Author )

Hi,

Please just a quick one. Does any one know how I can restrict users from being able to switch to root in sudoers file?? Presently the users are defined in the sudoers file and could switch to another user without password but I do not want them to be able to switch to root.

Note: If you are the author of this question and wish to assign points to any of the answers, please login first.For more information on assigning points ,click here

Patrick Wallek

:Use a command alias like this:

Cmnd_Alias SU=!/usr/bin/su -, !/usr/bin/su *root* 

Add this to each user and they should not be able to su to root.

ozas ( Question Author )

I have tried that before it did not work. See below my sudoers file, maybe I need to change anything.

This is the sudoers file:

# User_Alias 
User_Alias WAS = g343ahe,m017ahe,y073ahe 
User_Alias SUPPORT = d060ahe,h070ahe,s029ahe  
#User privilege specification
root ALL=(ALL) ALL SUPPORT ALL=(ALL) ALL
SUPPORT ALL=(ALL) NOPASSWD: ALL WAS 
ALL=(ALL) NOPASSWD: ALL WAS ALL=/usr/bin/su - wasdevadmin,/bin/su - wasdevadmin  

What I want is that the users in WAS should not be able to switch to root, but they should be able to switch to user "wasdevadmin". Only users in SUPPORT should be able to switch to root.

Jeff Traigle:

> WAS ALL=(ALL) NOPASSWD: ALL
> WAS ALL=/usr/bin/su - wasdevadmin,/bin/su - wasdevadmin

The first line is saying to allow the WAS users to run any command on any host as any user. The second line is redundantly saying to allow WAS users to run the su commands specified on all hosts as root. You don't have anything restricting them from running su to root as a previous post stated to do.

Patrick Wallek:

What about the following:

WAS ALL=!/usr/bin/su -, !/usr/bin/su *root*, /usr/bin/su - wasdevadmin,/bin/su - wasdevadmin

You also have 2 lines for WAS. I don't remember which will take priority, but the 2 may be conflicting.

What happens if you comment out the first WAS line?

ofure:

Thanks for your prompt reply. This has partly resolved the issue. At least users in WAS cannot su to root again but now the WAS cannot switch to wasdevadmin user.

I want a situation where they can switch to wasdevadmin without been prompted for a password.

Matti Kurkela:

> I want a situation where they [= the users in sudo group WAS] can switch to wasdevadmin without been prompted for a password.

You need this line in your sudoers file:

WAS ALL=(wasdevadmin) NOPASSWD: ALL

Then tell your users to use the sudo command like this:

sudo -H -u wasdevadmin -i (to run a shell as wasdevadmin; equivalent to "sudo su - wasdevadmin")

...or like this:

sudo -H -u wasdevadmin <command> (to run <command> as wasdevadmin and then continue the session as themselves)

MK

ofure:

Below is how my sudoers file now look:

User_Alias WAS = g343ahe,m017ahe,y073ahe,y072ahe,h234ahe,r019ahe

User_Alias SUPPORT = d060ahe,h070ahe,s029ahe #User privilege specification root ALL=(ALL) ALL SUPPORT ALL=(ALL) ALL SUPPORT ALL=(ALL) NOPASSWD: ALL WAS ALL=!/usr/bin/su -, !/usr/bin/su *root*, /usr/bin/su - wasdevadmin,/bin/su - wasdevadmin WAS ALL=(wasdevadmin) NOPASSWD: ALL

But the users in WAS still cannot switch to wasdevadmin account. I want the users in WAS to be able to do this without prompting for password. Thanks. Regards.

INH :

Remove the user name you dont wantthem to do sudo to root in sudoers file

if you have to grant specfic access you can grant in sudoers file for required users. by defining user alias, command alias and host alias for those users

ofure:

;The challenge I have now is that I want the users in WAS to be able to switch to the account wasdevadmin without prompting for password. I have tried this below but did not work.

WAS ALL=(wasdevadmin) NOPASSWD: ALL

Regards,

Matti Kurkela Jan 24, 2011 15:49:55 GMT Unassigned

> WAS ALL=(wasdevadmin) NOPASSWD: ALL

When you use this sudoers line, your user *must* use "sudo -u wasdevadmin -i" or similar sudo command to become wasdevadmin. The "-H" option is optional, but probably in line with the user's expectations.

With this sudoers line, a command like "sudo su wasdevadmin" or "sudo su - wasdevadmin" will *not* work. This is because these commands first use sudo to become root, then use su to become the target user. Sudo can do it in one step - but it requires that the user uses the correct syntax.

MK

ofure:

Hi All,

When I type this: sudo -u wasdevadmin -i it works without prompting me for password but it is a long command. I want to be able to type su - wasdevadmin and for it to call up sudo -u wasdevadmin -i

Presently, I have this configuration:

#cd /bin # ls -l su* root root 45 Feb 16 17:17 su root root 28336 Oct 30 2008 su.original

# cat su sudo su.original $@

So presently when I type su -, it call up sudo su.original, which works fine for my switching to root access. How can I also have: "sudo -u wasdevadmin -i" equal to "su - wasdevadmin"

Thanks.

ofure:

I have resolved this by creating an alias for wasdevadmin.

Thanks all.

Tags: Sudo, Sudo for HPUX

[Oct 17, 2009] Make sudo work harder

Oct 06, 2009 | developerWorks
To view what commands a user can run and what other constraints are assigned under sudo, as the user, run:
sudo -l

Using groups

Users belonging to a valid AIX group can be included in sudoers, making the sudoers file more manageable with fewer entries per user. When reorganizing the sudoers entries to include groups, you may have to create a new groups under AIX to include users that are only allowed to use sudo for certain commands. To use groups, simply prefix the entries with a '%'. Assume you have groups called devops and devuat, and with those groups you have the following users:

# lsgroup -f -a users devops

devops:
        users=joex,delta,charlie,tstgn

 # lsgroup -f -a users devuat
devuat:
        users=zebra,spsys,charlie

For the group devops to be allowed to run the /usr/local/bin/data_ext.sh command as dbdftst.

For the group devuat to be allowed to run the commands :/usr/local/bin/data_mvup.sh, /usr/local/bin/data_rep.sh as dbukuat.

We could have the following sudoers entries:

%devops rs6000 =  (dbdftst) NOPASSWD: /usr/local/bin/data_ext.sh
%devuat rs6000 =  (dbukuat) /usr/local/bin/data_mvup.sh
%devuat rs6000 =  (dbukuat) /usr/local/bin/data_rep.sh

Notice in the previous entries, the group devops users will not be prompted for their password when executing /usr/local/bin/data_ext.sh; however, the group devuat users will be prompted for their password. User "charlie" is a member of both groups (devops and devuat), so he can execute all the above commands.

[Sep 4, 2009] Linux Layer 8 Security LG #166

It's better to have sudo file standard and periodically overwritable from baseline as unauthorized (and undetected) modifications of the sudoer file is a security risk. Enrollment of users should be done via adding them to a privileged group such as wheel.
LG #166

It's often too late when we realize that our sudoers file was not configured to be limited to only a select list of users, or was not logging (e.g., if we have inherited 200 machines installed with stock sudo -- see my August 2009 Linux Gazette "Layer 8 Linux Security" column on maintaining sudo via Puppet). So, perhaps it went unnoticed that a past disgruntled developer was accessing the system from his desktop via RDP to SSH and accessing root regularly via 'sudo su'.

In startup ISPs and Web development shops in the mid-1990s, a "Nazi" Linux security administrator would often tire of being on-call 24x7 in an uncontrollable server farm, and come down with the avant-garde edict of "no shared root access", whereupon all developers just took escalated access via escaping system calls from emacs or vi, or via buffer overflows, and happily changed the access passwords for users: games, haldaemon, adm, lp, or sync. Similar shops and Linux un-professionals still exist, unfortunately.

Since any access to root via sudo can result in changes (and potential errors), a good keylogger makes a lot of sense as an easily setup secondary tracking mechanism.

PCI compliance and SOX both require controls in place for the root or administrative user. However, when mixed with corporate profit, these controls are loosely interpreted to the point of complete insecurity. If we cannot track change, we control nothing. Implementing a keylogger will take no more than fifteen to thirty minutes (and can easily be automated through Puppet), so if you suspect your systems of being accessed and the logs being wiped, or if you don't have the time to fully evaluate all binary checksums for rootkits, keyloggers can be a good immediate additional security tool.

By default, 'rootsh' logs to /var/log/rootsh/ (which can be changed during setup). Of course, 'rootsh' logs can be edited, like any logs, unless you use 'syslog-ng', or stunnel loghost or cron-based e-mail log burst, so hide them well. You will generally find that no one even notices that 'rootsh' is logging, and happily carry on as normal.

Running Complex Commands with sudo

Linux Journal

If you use sudo to run commands as root, you've probably run into “permission denied” problems when only part of a pipeline or part of a command is running with root permissions.

This fails with “permission denied” because the file is writable only by root:

$ echo 12000 > /proc/sys/vm/dirty_writeback_centisecs

But, this fails too:

$ sudo echo 12000 > /proc/sys/vm/dirty_writeback_centisecs

Why? The /bin/echo program is running as root, because of sudo, but the shell that's redirecting echo's output to the root-only file is still running as you. Your current shell does the redirection before sudo starts.

The solution is to run the whole pipeline under sudo. There are a couple ways to do it, but I prefer:

echo "echo 12000 > /proc/sys/vm/dirty_writeback_centisecs" | sudo sh

That way, I can type everything before the pipe character, and see what I'm about to run as root, then press the up arrow and add the | sudo sh  to do it for real. This is not a big deal for short, obvious pipelines, but when you're building up a more complicated command as root, it's safer to look at it first before you run it.

Secure Cooking with Linux, Part 2

O'Reilly

Recipe 5.11. Permitting Read-Only Access to a Shared File via sudo

Author's note: Sharing a file with multiple users is easy with Linux groups. But what if you want to restrict some people to have read-only access to a file, while giving others read/write access? This recipe, from Chapter 5, "Authorization Controls," explains how sudo can come to the rescue.

Problem

Two or more users want to share a file, some read/write and the others read-only.

Solution

Create two Linux groups, one for read/write and one for read-only users:

/etc/group:
readers:x:300:r1,r2,r3,r4
writers:x:301:w1,w2,w3

Permit the writers group to write the file via group permissions:

$ chmod 660 shared_file
$ chgrp writers shared_file

Permit the readers group to read the file via sudo:

/etc/sudoers:
%readers  ALL = (w1) /bin/cat /path/to/shared_file

Discussion

This situation could arise in a university setting, for example, if a file must be writable by a group of teaching assistants but read-only to a group of students.

If there were only two users -- one reader and one writer -- you could dispense with groups and simply let the reader access the file via sudo. If smith is the reader and jones the writer, and we give smith the following capability:

/etc/sudoers:
smith  ALL = (jones) NOPASSWD: /bin/cat /home/jones/private.stuff

then jones can protect her file:

jones$ chmod 600 $HOME/private.stuff

and smith can view it:

smith$ sudo -u jones cat /home/jones/private.stuff

See Also

sudo(8), sudoers(5), group(5), chmod(1), chgrp(1).

Check back here next week for recipes from Linux Security Cookbook on how to use PAM to restrict authentication on Linux systems, and how to use SMTP to securely accept connections from arbitrary clients.

[Sep 18, 2008] Gentoo Sudo(ers) Guide — Gentoo Linux Documentation

Sudoers Syntax

Basic Syntax>

The most difficult part of sudo is the /etc/sudoers syntax. The basic syntax is like so:

user  host = commands

This syntax tells sudo that the user, identified by user and logged on through the system host can execute any of the commands listed in commands as the root user. A more real-life example might make this more clear: allow the user swift to execute emerge if he is logged on from the system (not through SSH):

swift  localhost = /usr/bin/emerge

A big warning is in place though: do not allow a user to run an application that can allow people to elevate privileges. For instance, allowing users to execute emerge as root can indeed 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 rights.

The user name can also be substituted with a group name - in this case you should start the group name with a % sign. For instance, to allow any one in the wheel group to execute emerge:

%wheel  localhost = /usr/bin/emerge

You can extend the line to allow for several commands (instead of making a single entry for each command). For instance, to allow the same user to not only run emerge but also ebuild and emerge-webrsync as root:

swift  localhost = /usr/bin/emerge, /usr/bin/ebuild, /usr/sbin/emerge-webrsync

You can also specify a precise command and not only the tool itself. 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 pathnames as well as command line arguments in the sudoers file. Note that these are not regular expressions.

Let us put this to the test:

$ 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.

You should know that sudo does not alter the ${PATH} variable: any command you place after sudo is treated from your environment. If you want the user to run a tool in for instance /sbin he should provide the full path to sudo, like so:

$ sudo /usr/sbin/emerge-webrsync

Using Aliases

In larger environments having to enter all users over and over again (or hosts, or commands) can be a daunting task. To ease the administration of /etc/sudoers you can define aliases. The format to declare aliases is quite simple:

Host_Alias hostalias = hostname1, hostname2, ...
User_Alias useralias = user1, user2, ...
Cmnd_Alias cmndalias = command1, command2, ...

One alias that always works, for any position, is the ALL alias (to make a good distinction between aliases and non-aliases it is recommended to use capital letters for aliases). As you might undoubtedly have guessed, the ALL alias is an alias to all possible settings.

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

ALL  localhost = /sbin/shutdown

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

swift   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!

User_Alias  SOFTWAREMAINTAINERS = swift, john, danny
User_Alias  PASSWORDMAINTAINERS = swift, 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

Non-Root Execution

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).

Inside /etc/sudoers you list the user(s) in between ( and ) before the command listing:

users  hosts = (run-as) commands

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

Cmnd_Alias KILL = /bin/kill, /usr/bin/pkill

swift   ALL = (apache, gorg) KILL

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

$ sudo -u apache pkill apache

You can set an alias for the user to run an application as using the Runas_Alias directive. Its use is identical to the other _Alias directives we have seen before.

Passwords and Default Settings

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.

Of course, this behavior can be changed: you can set the Defaults: directive in /etc/sudoers to change the default behavior for a user.

For instance, to change the default 5 minutes to 0 (never remember):

Defaults:swift  timestamp_timeout=0

A setting of -1 would remember the password indefinitely (until the system reboots).

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

Another interesting feature is to keep the DISPLAY variable set so that you can execute graphical tools:

Defaults:john env_keep=DISPLAY

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

If you however want to allow a user to run a certain set of commands without providing any password whatsoever, you need to start the commands with NOPASSWD:, like so:

swift     localhost = NOPASSWD: /usr/bin/emerge

3. Using Sudo

Listing Privileges

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

$ sudo -l
User swift 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

If you have any command in /etc/sudoers that does not require you to enter a password, it will not require a password to list the entries either. Otherwise you might be asked for your password if it isn't remembered.

Prolonging the Password Timeout

By default, if a user has entered his password to authenticate himself 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.

$ sudo -v

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

[Feb 19, 2008] Linux.com sudo, or not sudo that is the question

The format of the sudoers file is simple: it starts with four optional sections, and it ends with the specific rights assignments. It can include empty lines, or comment lines that start with the # sign. The optional sections are:

You don't need to use aliases, but they do make future editing easier. For example, if you have to assign donald_duck the same rights that mickey_mouse has, just add the former to the latter's group, and you won't have to spend lots of time duplicating lines everywhere. A special alias called ALL exists, and you can use it anywhere; it can mean ALL users, ALL hosts, and so on.

After these sections, you must have a section for specific rights, which looks like "who where = (whoelse) what," meaning who (a user, a group, or a user alias) on the host where can run a command what as a user whoelse. (If this is too cryptic, look at the following example.) You can also include several specific options, such as NOPASSWD to allow a user to sudo without entering his password; check the manual for the other options.

This sample doesn't show every configuration possible (for that, you should do man sudoers), but here's what a sample file with some of these options might look like:

#
# Sample /etc/sudoers file, with apologies to the Disney company!
#

# User aliases
# The first line creates an alias for three specific users.
# The second one includes everybody in the "ducks" user group, but excludes "donald"
# The third one creates an alias for just one user; it can be useful in the future!
#
User_Alias	NEPHEWS = huey, dewey, louie
User_Alias	ALL_DUCKS_BUT_DONALD = %ducks, !donald
User_Alias	MICKEY = mickey_mouse

# Command aliases

Cmnd_Alias      HALT_OR_REBOOT = /sbin/halt
Cmnd_Alias      KILL = /usr/bin/killall
Cmnd_Alias      SHUTDOWN = /sbin/shutdown
Cmnd_Alias      SU = /bin/su

# The rights: who gets to run what

# A standard rule: root, and users in group "wheel", have full rights
root            ALL = (ALL) ALL
%wheel          ALL = (ALL) ALL

# Suppose mickey is an sysadmin; let him run anything without a password
MICKEY		ALL = NOPASSWD: ALL

# NEPHEWS can stop the box if they want
NEPHEWS		HALT_OR_REBOOT, SHUTDOWN
																					

You can also add some extra configuration lines at the end of the configuration file. You can specify, for example:

[Jan 30, 2008] Sudo FAQ

polishlinux.org

The syntax of /etc/sudoers.
The basic syntax of /etc/sudoers file looks like this:

user computer = command

In short, it means that the user logged into computer can run the command with administrative privileges. Here is an example:

johnny localhost = /usr/bin/du

This means that johnny will be able to use du (disk usage) command on localhost (the current computer).
Warning: if the computer name has been change, a real name (not localhost) needs to be entered..

2.b. Granting users of group XXX the right to execute the command YYY:
% XXX localhost = /the/path/to/command/YYY

2.c. Allow to execute many command in one rule:
johnny localhost = /usr/bin/du, /usr/bin/nail, /usr/bin/sane

[Jan 30, 2008] sudo-tools sudolog-usage and sudoers-lint

Here's the tarball for sudo-tools-1.2 (2003_12_15) ... basically just two Perl scripts ... VERY simple to install/configure/run ...

See also UNIX Sysadmin Tools and Alek's free personal home pages

[Jan 30, 2008] Sudo at a VERY LARGE site

[Jan 30, 2008] ONLamp.com Eliminating Root with Sudo

While proper implementation of groups can help reduce the need for the root password, at times, users must absolutely run commands as another user (usually root). As the system administrator, you're stuck between deciding to hand out the root password or doing everything for your users. sudo provides a third way, one that can help solve this dilemma. It's a tricky program, however, and needs some care in implementation. sudo is integrated into OpenBSD, and is an add-on package for just about every other Unix-like operating system out there.

sudo is a setuid root wrapper that implements fine-grained access control for commands that need to be run as root. It takes the command you want to run and compares it to its internal list of permissions. If sudo's permissions allow that particular user to run that command, sudo runs that command for you, with its privileges. As root can run commands as any user, sudo can execute commands as any arbitrary system user.

With proper setup, the system administrator can allow any user to run any command as any other user. sudo is a very powerful tool, and can be configured to allow or deny almost any set of commands. As a result of this flexibility, the documentation tends to scare off new users. We're going to do a basic sudo setup that will cover almost all uses, but you should be aware that many more combinations are possible, and are documented in sudo(8) and sudoers(5).

Other than the obvious fine-grained access control sudo provides, there are a few other benefits to using sudo. One of the biggest advantages is the command logging. Every sudo command is logged, making it very easy to track who made what changes. And once you have sudo configured correctly, you can change the root password and not give it to anyone. Nobody should need the root password if they have the correct sudo permissions, after all! Reducing the number of people who have the root password can help improve security. Finally, a single sudo configuration file can be used on all of these systems, vastly easing administrator overhead.

The most overwhelmingly common disadvantage to sudo is that users and junior administrators don't like it. If people have traditionally had root access on a system, they will perceive that they're losing something when you implement sudo. They key to overcoming this is to make sure that people have the ability to do their jobs. If users think that they need the root password to perform other tasks, then your need to settle just who is responsible for what. These users may have been taking extra duties upon themselves, rather than troubling you with jobs that you should do.

A faulty sudo setup can create security holes. A thoughtless configuration will create holes in the system that a clever user can use to actually become root. This problem is best dealt with by a combination of careful configuration and administrative policy.

[Jan 30, 2008] Linux Tips Password usage in sudo (PASSWD - NOPASSWD) MDLog-sysadmin

NOPASSWD option is useful for temporary granting a specific user access to root: you enroll him to the wheel group and submit at command that deletes him from this group at the end of the specified period. This way you do not need to communicate the password to the user at all and thus do not need change it back after the period for which the user was granted tem root access expire...

You have an entry in your sudoers file that contains something like this:

admin    ALL=(ALL) ALL

then sudo will require you to enter a password when running a command with sudo. This is the user password (and not the root password), in this case the password of the user “admin”.

targetpw

If for some reason you want to change this behavior, then you can use the sudo global flag targetpw. This is by default OFF, and if you set it like show bellow then the password you will be asked while running sudo will be the password of the target user (in our case the root password).

Defaults    targetpw

Personally, I don’t see the use of this parameter and never used it myself… But maybe someone else will find it useful.

NOPASSWD

If you don’t want to be prompted for any password while running sudo then we can use the NOPASSWD parameter on a particular entry:

admin    ALL = NOPASSWD: ALL

this parameter is the opposite of the default PASSWD and will no longer require any password for the user “admin” while running sudo. This can be of useful while running scripts that will launch sudo (in this case I would recommend to enable NOPASSWD only for the needed commands), or just if you don’t want to keep typing the password. Obviously with this commodity, you will reduce the security of sudo: if someone hacks the “admin” account then this can be easily used to gain root privileges.

authenticate

Another sudo option that can be used to control the prompt for a password is the global flag: authenticate. This is by default ON and this means that it will ask the user to authenticate with a password. This can be overwritten as seen above with the NOPASSWD on a particular entry. If we want to disable it globally, this can be done with:

Defaults    !authenticate

Once set, this will disable authentication for all users that use the defaults like our “admin” sample from above. It can be overwritten on particular definition by setting the PASSWD parameter:

admin    ALL=(ALL) PASSWD: ALL

Note: this post doesn’t recommend you to disable the passwords usage in sudo (this is not a good idea, by the way), but just to show you what options are available and how you can use them. Knowing the security implications of disabling password usage in sudo, use them wisely based on your particular needs.

[Oct 27, 2007] sudo-tools sudolog-usage and sudoers-lint

Here's the tarball for sudo-tools-1.2 (2003_12_15) ... basically just two Perl scripts ... VERY simple to install/configure/run ...

[Oct 27, 2007] RootSudo - Community Ubuntu Documentation

The password is stored by default for 15 minutes. After that time, you will need to enter your password again.
  • Your password will not be shown on the screen as you type it, not even as a row of stars (******). It is being entered with each keystroke!
  • sudo !!  will repeat the last command entered, except with sudo prepended to it.
  • You should never use sudo to start graphical applications as root. You should use gksudo  to run such programs (eg. ALT+F2 gksudo gedit).
  • To run the graphical configuration utilities, simply launch the application via the menu.
  • [Oct 27, 2007] Sudoers Manual

    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 directory /usr/oper/bin.

     joe            ALL = /usr/bin/su operator

    Sys Admin Magazine RBAC instead of sudo

    SUMMARY sudo vs RBAC

    Ximo Domenech ximo_d at yahoo.com
    Thu Nov 6 06:43:17 EST 2003

    sudo is better to set up pseudo root access in smaller environments.
    
    The size of your environment and your requirements will determine which is the better tool.

    Recommended Links

    Softpanorama Top Visited

    Softpanorama Recommended

    Sudo Main Page Sudo (superuser do) allows a system administrator to give certain users (or groups of users) the ability to run some (or all) commands as root while logging all commands and arguments.

    sudo - Wikipedia

    Sys Admin Magazine RBAC instead of sudo

    ONLamp.com -- Eliminating Root with Sudo by Michael W. Lucas

    A Brief History of Sudo

    sudo-tools - some handy utilities for sudo

    Other Sudo-like Utilities

     

    Sudo at a VERY LARGE site by Alek Komarnitsky

    Using Sudo -- article by A.P. Lawrence

    Managing Root Access with Sudo. About.com

    Installing sudo on Solaris

    ONLamp.com Eliminating Root with Sudo

    RootSudo - Community Ubuntu Documentation

    Linux Help - Sudo Setup Guide

    Sudo and other ways to avoid root!




    Etc

    Society

    Groupthink : Understanding Micromanagers and Control Freaks : Toxic Managers : BureaucraciesHarvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Two Party System as Polyarchy : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

    Quotes

    Skeptical Finance : John Kenneth Galbraith : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotes : Oscar Wilde : Talleyrand : Somerset Maugham : War and Peace : Marcus Aurelius : Eric Hoffer : Kurt Vonnegut : Otto Von Bismarck : Winston Churchill : Napoleon Bonaparte : Ambrose Bierce : Oscar Wilde : Bernard Shaw : Mark Twain Quotes

    Bulletin:

    Vol 26, No.1 (January, 2013) Object-Oriented Cult : Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks: The efficient markets hypothesis : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Vol 23, No.10 (October, 2011) An observation about corporate security departments : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

    History:

    Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

    Classic books:

    The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

    Most popular humor pages:

    Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

     

    The Last but not Least


    Copyright © 1996-2014 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Site uses AdSense so you need to be aware of Google privacy policy. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine. This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

    You can use PayPal to make a contribution, supporting hosting of this site with different providers to distribute and speed up access. Currently there are two functional mirrors: softpanorama.info (the fastest) and softpanorama.net.

    Disclaimer:

    The statements, views and opinions presented on this web page are those of the author and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

    Last modified: April 17, 2014