May 18, 2015

Sudo and Sudoers Configuration

We can configure who can use the sudo command and how. You may have noticed that the Vagrant user on your development server can use sudo without a password. Similarly, AWS servers allow the same thing. Find out how that's done, and much more!

We can configure who can use the sudo command and how. You may have noticed that the Vagrant user on your development server can use sudo without a password. Similarly, AWS servers allow the same thing. Find out how that's done, and much more!We'll configure who can use "sudo" and how.

Visudo

We can configure who can use sudo commands by editing the /etc/sudoers file, or by adding configuration to the /etc/sudoers.d directory.

To edit the sudoers file, we should always use the visudo command.

This uses your default editor to edit the sudoers configuration.

You can decide which editor to use to edit sudoers in a quick one liner:

sudo EDITOR=vim visudo

In general, you can set your editor via the EDITOR and/or VISUAL environment variables.

sudo export VISUAL=nano
sudo export EDITOR=nano
sudo update-alternatives --set editor /usr/bin/nano

# Try this to set a new editor globally
sudo update-alternatives --set editor /usr/bin/nano

Sudoers File

Let's check out the root user in the sudoers configuration. The root user can do anything: ALL(ALL:ALL) ALL.

What's this mean?

host(user:group) cmds

  • root ALL=(ALL:ALL) ALL - This applies to user root
  • root ALL=(ALL:ALL) ALL - This rule applies to all user root logged in from all hosts
  • root ALL=(ALL:ALL) ALL - User root can run commands as all users
  • root ALL=(ALL:ALL) ALL - User root can run commands as all groups
  • root ALL=(ALL:ALL) ALL - These rules apply to all commands

NOPASSWD & Vagrant

vagrant ALL(ALL:ALL) NOPASSWD:ALL

This allows user vagrant to run all commands using sudo without a password.

%group

We can try editing a group. The following will allow group www-data to run sudo service php5-fpm * commands without a password, great for deployment!

%www-data ALL(ALL:ALL) NOPASSWD:/usr/sbin/service php5-fpm *

Here's the same configuration as a comma-separated list of multiple commands. This let's us get more specific on which service commands we can use with php5-fpm:

%www-data ALL(ALL:ALL) NOPASSWD:/usr/sbin/service php5-fpm reload,/usr/sbin/service php5-fpm restart,

We can enforce the use of a password with some commands, but no password for others:

%admin ALL NOPASSWD:/bin/mkdir, PASSWD:/bin/rm

/etc/sudoers.d

We cam add configuration files into /etc/sudoers.d. These are loaded automatically. These should be owned by root, with permissions 0440 (so user root can read it but not write it!).

!!! Be sure to log in / sudo su up to the root user BEFORE making any file, as any issues will result in lack of ability to use sudo!

All Topics