You can hardly mention the sudo command without recalling the hilarious XKCD strip about making sandwiches. It does seem like sudo is the magic power to make a Linux system do what you want. The only problem is that those superpowers are not something to be taken lightly.
CC-BY-NC-2.5 by [XKCD]If you are surfing the web, for example, you really don’t want to be root, because if someone naughty takes over your computer they could do a lot more harm with your root password. But still, there are times when you want to run certain commands that are normally root-only and don’t want to bother with a password. Luckily, sudo can handle that use case very easily.
As a simple example, suppose you like to shut your computer down at the end of the day. You run the shutdown command from the terminal but it doesn’t work because you aren’t root. You then have to do it again with sudo and if you haven’t logged in lately, provide your password. Ugh.
In my case, I got to thinking about this when I needed to manipulate the dbus service in a startup script. I wanted the script to manipulate just that service as a normal user and not prompt for a password, especially since some users don’t have sudo powers anyway. Either way, you would like a way to let normal users run very specific commands without additional permission.
A Simple But Bad Way
Your first thought might be to wrap the code in a shell script owned by root and set the suid bit so that when you execute it, the script elevates to having root access. That will work, but it seems like a potential security problem. After all, a script could do anything. Are you sure there is no way for a user to force it to do something else? Are you really sure?
Granted, you always have to think about this. If you, say, allowed someone to run emacs as root, that person could then open a shell and have full access to the system even if they didn’t otherwise have root access. That’s not good. But it is usually easier to reason about programs that have specific functions instead of a general-purpose shell script.
That’s where sudo comes in. There’s really only one place to set up sudo, although most modern distributions have that one place read files from a second place that you can also use. The primary place is /etc/sudoers and, as you would guess, you need to be root to change that file. In fact, you shouldn’t open it with a regular editor at all. Use visudo which verifies you…