Which method to use for granting sudo

What is the difference between adding a user to /etc/sudoers and usermod -a -G sudo? Which method should be used for granting sudo?


Solution 1:

If you can avoid it, never grant sudo privileges to individual users. Always grant privilegs to a group and then add users to that group.

For ubuntu-based servers, instead of adding lines to /etc/sudoers, add config file fragments into /etc/sudoers.d. This is more flexible, easier to understand, more resilient in the face of upgrades, and works better with systems managed by configuration management systems.

NOTE: never edit /etc/sudoers directly. Instead, use visudo, which will perform syntax checking on your edits, preventing you from breaking your sudo config with invalid syntax.

Solution 2:

I just found this little tidbit out there... seems you need to be particularly careful with using the -G option in Ubuntu, in particular in combination -g option. So:

  1. Use usermod -aG to add the user(s) to a group.
  2. Then as @EEAA suggested, add the group to the /etc/sudoers file using the $ sudovisudo command (automatically invokes a privileged editor with syntax checking).

Here's the info about the -aG option on Ubuntu, taken from here http://ubuntuforums.org/showthread.php?t=1240477:

'I'm reading the Wiley "Linux Command Line and Scripting Bible" - and they said that usermod -G "appends" a group to whatever user account you are modifying. I found this to be false in Ubuntu, don't know if it's just different in other distro's, or a typo in the book. It removes you from EVERY other group you belong to, except your default user group (modified by the -g option). I managed to remove myself from the admin group and could no longer sudo anything. Thank goodness for recovery mode...'

The correct option is usermod -aG. Lesson learned...

Solution 3:

You don't tell us how big your environment is, but if it's more than one machine you may also want to consider configuring sudo using LDAP s an alternative to editing sudoers locally (either through visudo or using the /etc/sudoers.d fragments method).

LDAP configuration is a well-tested way of making sure that multiple machines have the same sudo configuration, and presents a nice unified environment (with central management of an important authorization mechanism). As a bonus if you already use LDAP (or AD) for authentication/authorization in your environment you can take advantage of the existing infrastructure (and if you don't you should seriously consider it - centralization has many benefits).

Everything folks have already said in the other answers about creating authorized groups still stands - it's easier as you scale up to grant privileges to a group and manage group membership than it is to deal with managing rights for individual users.