How to configure Sudo to run programs as a different user

From NewbieDOC


Chris Lale
chrislale AT users DOT berlios DOT de

Latest version

You can find the latest version of this document at http://newbiedoc.berlios.de.

Revision History

1.0 14th September 2004 Revised by Chris Lale
Initial Release.
1.1 15th February 2007 Revised by Chris Lale
Converted to wikitext and added an example template for the sudoers file.
1.2 17th February 2007 Revised by Chris Lale
Added the missing Abstract.
1.3 19th March 2007 Revised by Chris Lale
Modified and corrected sudoers file structure section to improve clarity. Added a Comments section with a link to the article's discussion page.

Abstract

This article explains how a normal user can use Sudo to run particular programs with root permissions. It explains how to configure Sudo using a simple table as an alternative to the Extended Backus-Naur Form used in the Sudoers man (5) page.

Contents


1 Who needs to know about Sudo?

You do not need to know anything about Sudo to run your PC normally. Being able to switch user using Su is quite sufficient. However, Sudo is a valuable tool for anyone who spends significant time administering a PC.

2 Overview

It's not Sudo so much as the Sudo manual that you have to wrestle with. It is written in a rather cryptic style. Hopefully you will find here all that you need to know about Sudo to manage your PC more efficiently. Sudo enables specific users to run specific programs as though they were another user -- normally as the Root user.

Sudo has a configuration file called /etc/sudoers. Sudo is a program that runs any other program as the Superuser or any other user specified in the /etc/sudoers file. This is especially useful for programs that can normally only be run by the root user; for example, installing or removing software.

It is unwise to try and use an ordinary text editor to compose or edit the Sudoers file. There is a customised version of Vi called Visudo which helps prevent you making dangerous changes to /etc/sudoers. Don't worry if you have not used Vi or any of its derivatives before. There instructions here should be enough to do the job.

One more thing -- you must either switch user to Root with Su, or log in as Root to be able to edit the Sudoers file.

3 The Sudoers file

3.1 Creating and modifying the Sudoers file

Sudo must be installed before you begin.

Here is the default Sudoers file which is created when you install the Sudo package.

# sudoers file.
#
# This file MUST be edited with the 'visudo' command as root.
#
# See the man page for details on how to write a sudoers file.
#
# Host alias specification
# User alias specification
# Cmnd alias specification
#
# User privilege specification
root    ALL=(ALL) ALL

It has only one specification statement:

root    ALL=(ALL)ALL

This statement allows the Root user to run any command via Sudo.

3.2 Editing Sodoers with Visudo

You can configure Sudo by modifying the Sudoers file using Visudo. Visudo is installed on your system when you install the Sudo package. Switch to the Superuser with Su or login as the Root user. Open a terminal window if you are working in X.

First make a backup copy of /etc/sudoers. You can use a file manager to do the job. Alternatively, you can use the command line as follows. Change directory (cd) to /etc and list (ls) the existing Sudoers file sudoers. (You may also find sudoers.tmp if Visudo has been modified before, but Visudo normally deletes this file after a successful editing session.)

# cd /etc
# ls sudoers*
sudoers  sudoers.tmp

Make a copy of sudoers called sudoers.old.

# cp sudoers sudoers.old

Visudo is a derivative of the Vi text editor.

Run Visudo from a terminal or a terminal window in X.

# visudo

Visudo starts in command mode. You can check by looking in the bottom right-hand corner -- you should see "Command" in a red font. Change to insert mode by pressing i.

i

Check that the bottom right-hand corner has changed from "Command" to "Input". You can now move around the document using the arrow keys. You can delete a character under the cursor using the DEL key.

Add the User alias specification below, substituting your username for "chris".

# User alias specification
User_Alias MAINTAINERS = chris

Add the Cmnd alias specification as shown below.

# Cmnd alias specification
Cmnd_Alias DEB = /usr/sbin/synaptic, /usr/bin/aptitude, 
/usr/bin/apt-get

Finally, add a second line to the User privilege specification.

# User privilege specification
root ALL=(ALL) ALL
MAINTAINERS ALL = DEB

You must return to Command mode to save the changes and exit. Press the ESC key and check that "Command" has replaced "Input" in the bottom right-hand corner. Commands begin with a colon (:). The tables show you the commands that you are likely to need.

Command Result of issuing the command
:w Write to file (sudoers.tmp) and continue in Command mode.
:q Quit. (Will not quit unless you have saved changes.)
:wq Write to file (sudoers) and quit. (Sudoers.tmp is deleted.)
:q! Quit without saving changes.

Table 1: Some Visudo (Vim) commands

Command Result of issuing the command
Ctrl-O Write to file (sudoers.tmp) and continue in Command mode.
Ctrl-X Quit. (Prompts for save unless you have saved changes.)

Table 2: Some Visudo (Nano) commands

Save the amended file and quit.

:wq

3.3 What to do if the editing goes wrong

Don't worry if you end up with a file full of mistakes that you cannot correct. You still have your saved original version (sudoers.old). Preserve the messed-up file by copying it to a new file called sudoers.new. You are unlikely to need it again, but keep it as insurance in case you decide that you were right after all. Overwrite sudoers with sudoers.old.

# cp sudoers sudoers.new
# cp sudoers.bak sudoers

You are now back to square one with no harm done.

3.4 Testing Sudo

You can test Sudo by attempting to install a package from a terminal or a terminal window in X. This example uses the Nethack package. It does not matter whether Nethack is already installed or not. You can abort the installation if Nethack is already installed by holding down the CTRL key and pressing Z.

First, attempt to install Nethack as a normal user. You should be logged in as a normal user (with a $ prompt).

$ apt-get install nethack
E: Could not open lock file /var/lib/dpkg/lock - open 
(13 Permission denied)
E: Unable to lock the administration directory (/var/lib/dpkg/), 
are you root?
$

Next, switch user to Root and attempt to install Nethack. Remember that the superuser's prompt is "#".

$ su
Password: (enter password for user root)
# apt-get install nethack

If Nethack is not installed you will get message including this line:

The following NEW packages will be installed:

Otherwise you will get this message:

Sorry, nethack is already the newest version.

Finally, exit back to your normal user and use Sudo to run Apt-get. You will get the same messages if you have configured Sudo correctly. Remember that Nethack will ask you for you normal user's password.

# exit
$
$ sudo apt-get install nethack
Password: (enter password for normal user)
The following NEW packages will be installed:

or

Sorry, nethack is already the newest version.
$

If you did not get the same messages as before, go back and check the Sodoers file.

4 The structure of the Sudoers file

Here is an example of a Sudoers file.

# User alias specification
User_Alias MAINTAINERS = chris

# Cmnd alias specification
Cmnd_Alias DEB = /usr/sbin/synaptic, /usr/bin/aptitude, 
/usr/bin/apt-get

# User privilege specification
root ALL=(ALL) ALL
MAINTAINERS ALL = DEB

All lines starting with # are comments and are ignored. The other lines are statements.

The first statement sets up a collection of one or more users called MAINTAINERS. It is not the same thing as the group used in file permissions. It only means anything to Sudo. The statement also makes one user (chris) a member of MAINTAINERS.

The second statement sets up a collection of one or more commands called DEB. The statement also adds three commands to DEB.

The last two statements specify which users can run which programs with which privileges. The penultimate statement allows the Root user on all PCs to run all commands as any user. The last statement allows all MAINTAINERS on all PCs to run the commands collected in DEB as the Root user. (The Root user is the default when "(...)" is omitted.)

Both these statements are examples of the same general form:

User_Alias Host_Alias = (Runas_Alias) Authentication Cmnd_Alias

where the contents of the variables is shown in Table 3: Contents of the Sudoers variables.

Variable Contents of the variable Default value
User_Alias a user or collection of users none -must be specified
Host_Alias is a host (a specific computer on a network) or a

collection of hosts

none -must be specified
(Runas_Alias) the user to switch to when the command is run Root user
Authentication whether or not to ask for a password before the command is run ask for the real user's password
Cmnd_Alias the command (eg a program), or commands, allowed to be run as the run-as-user by the user none -must be specified

Table 3: Contents of the Sudoers variables

User names, host names, run-as-user names and commands are in their normal case (lower case). The collections of names or commands are all in upper case.

 
Note
Note: 
You can find your PC's host name with the command hostname.
 

The simplest Sudoers file statement would contain just three variables:

ALL ALL = ALL

This allows all users on all PCs to run all commands as the Root user, authenticated with the particular user's password. The two variables missing from the statement (Runas_Alias and Authentication) assume the default values. This would be a very dangerous statement. Don't use it!

The original Sudoers file is created when Sudo is installed. It contains this one statement with four variables:

root ALL = (ALL) ALL

The statement allows the Root user on all PCs to run all commands as any user. The missing variable (Authentication) assumes the default value. (The default is for Sudo to prompt for Root's password before running the requested command.)

The second user privilege statement in the example is

MAINTAINERS ALL = DEB

This statement allows any user in the MAINTAINERS collection to run certain commands on any PC. The user is allowed to run all the commands in the DEB collection as the Root user (Runas_Alias default) after suppling the user's normal password (Authentication default).

You could use this statement if the host is a networked PC:

MAINTAINERS mypc = DEB

It allows the same users to run the same programs, but only on the PC whose hostname is mypc.

You may find it easier to identify the variables in each statement by putting them into a table (see Table 4: Combining Sudoers variables into statements)

User_Alias Host_Alias = (Runas_Alias) Authentication Cmnd_Alias Comment
ALL ALL = ALL Dangerous - do not use this one!
root ALL = (ALL) ALL You should find this statement in most Sudoers files.
MAINTAINERS ALL = DEB Any user in MAINTAINERS can run any commands specified in DEB.
MAINTAINERS mypc = DEB Equivalent to previous example for a single computer with hostname "mypc".

Table 4: Combining Sudoers variables into statements

4.1 Example

This is how you fill in the table for the statement

root ALL = (ALL) ALL

The first two variables before the equals sign are compulsory, so you put root and ALL straight into the first two columns. The last statement is also compulsory, so ALL goes into the last column. This leaves one variable - (ALL) - to be placed. A variable in brackets belongs immediately after the equals sign. A variable without brackets belongs immediately before the final variable. In this case (ALL) goes immediately after the equals sign.

You can easily identify the aliases once you have filled in the table. The User_alias is root, the Host_alias is ALL and the Run_as alias is (ALL). Authentication is not specified, so the default will be used. Finally, the Cmnd_alias is ALL.

Table 5: Contents of collections (Sudo groups) shows the "Sudo groups" or collections

Alias type Collection (Sudo group) = Contents of the collection
Cmnd_alias DEB = /usr/sbin/synaptic, /usr/bin/aptitude, /usr/bin/apt-get
User_alias MAINTAINERS = chris

Table 5: Contents of collections (Sudo groups)

The DEB Sudo-group consistes of three commands which run the programs Synaptic, Aptitude and Apt-get. MAINTAINERS contains one user (chris). You could use the username itself if only that user needed to run the three commands. However, doing it this way allows you to add other users later.

4.2 A template for the Sudoers file

You can use comments to tabulate your Sudoers file and make it more understandable. Here is an example.

# sudoers file.
# This file MUST be edited with the 'visudo' command as root.
#
# See the man page for details on how to write a sudoers file.

# Host alias specification
# ========================

# User alias specification
# ========================
User_Alias MAINTAINERS = username
 
# Command alias specification
# ========================
Cmnd_Alias DEB = /usr/local/sbin/checkinstall
 
# User privilege specification
# ============================
# Format:
#
#--------------------------------------------------------------
# User_Alias   Host_Alias = (Runas_Alias)  Authent   Cmnd_Alias
#                                          -ication
# -------------------------------------------------------------
# compulsory   run on     = run as which   PASSWD:   compulsory
#              which        user (root     (default)
#              hosts        by default)    or      
#              (PCs)                       NOPASSWD: 
#-------------------------------------------------------------- 
#
root           ALL        =   (ALL)                      ALL
MAINTAINERS    ALL        =   (root)       PASSWD:       DEB

5 Comments

If you find any mistakes or you have any other comments, please add them to this article's discussion page

6 Appendix A: Licence

Copyright (c) 2004, 2007 Chris Lale. chrislale AT users DOT berlios DOT de

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license can be found at http://www.fsf.org/copyleft/fdl.html.

Content is available under GNU Free Documentation License 1.2, unless otherwise stated.