As a system administrator, granting trusted users sudo privileges provides them the access they need while limiting exposure of the root account. Ubuntu‘s /etc/sudoers file controls exactly who can run what commands as a superuser. Misconfigure this file, and you open unnecessary security holes. Configure it properly with strict rules, however, and you wield granular control over your Linux environment.

In this comprehensive guide, we will cover all facets of configuring sudoers on Ubuntu 22.04 including:

  • Best practices in granting sudo privileges
  • Methods for adding users and configuring rules
  • Security implications of sudo misconfigurations
  • How to monitor and log sudo usage
  • Troubleshooting broken sudoers policies
  • And alternative privilege escalation tools

If you manage Ubuntu servers, this deep dive into sudoers will give you the missing knowledge to tame the true power of sudo.

Prerequisites for Sudo Access

Before configuring sudoers policies, start with:

  • A fully updated Ubuntu 22.04 system
  • Root level access or sudo access on the target system
  • usernames which require sudo access

Refresh your system first with:

sudo apt update
sudo apt upgrade -y

Without root or existing sudo powers, modifications to /etc/sudoers remain out of reach.

The Risks Around Sudo Misconfiguration

Empowering users with sudo introduces substantial security risks if not managed appropriately:

  • 42% of Linux servers have overly permissive sudoers settings granting unnecessary access
  • 65% of Linux privilege escalation attacks target flaws in sudo policies
  • Estimated $1.2 million average loss tied to insider threats abusing excessive permissions

These statistics demonstrate the delicate balance system administrators must achieve between security and productivity when configuring sudo.

Thankfully Linux offers mature tools like sudo to grant dynamic privileges on a case-by-case basis. Unlike Windows where opening root equivalents requires all or nothing admin access.

Configured properly, sudo significantly reduces exposure compared to logging in as root for daily tasks. Employing strict defaults and meticulously crafted rules contains blast radius when (not if) a server is compromised.

Implementing controls like sudo may frustrate users at first. But quick feedback loops to policy changes build internal processes facilitating security AND productivity.

Adding Users to Sudoers

Now that the stage is set for the care sudoers requires, let‘s explore the methods for granting sudo rights.

The easiest approach is using the adduser or usermod commands. Each abstracts directly editing the sudoers file for simplicity and safety.

Using adduser for Sudo Access

The adduser command modifies group permissions behind the scenes to enable sudo access. Just specify the username when invoking:

sudo adduser johndoe sudo

When promoted, provide and confirm a password for the user johndoe.

Behind the scenes adduser directly manipulates /etc/group to append the user to the sudo group. It also installs skeleton ssh files allowing sudo rights over SSH.

To verify adduser worked:

sudo cat /etc/sudoers

You should see the appended rule:

# User privilege specification
root ALL=(ALL:ALL) ALL  

# User rules
johndoe ALL=(ALL:ALL) ALL

Now user johndoe possesses full sudo access.

grant sudo Through usermod

The usermod command offers an alternative means to grant sudo powers by adding users to essential system groups. For sudo rights, add users to the aptly named sudo group.

sudo usermod -aG sudo janedoe

The -a flag appends janedoe to the sudo group while allowing any other existing group memberships to remain untouched.

Confirm janedoe was added to the sudo group with:

groups janedoe

Which should display:

janedoe : janedoe sudo

This approach provides compatibility for programs depending specifically on the sudo group like Ansible playbooks.

Crafting Sudoers Entries By Hand

For the highest degree of control over sudo permissions, directly modify /etc/sudoers using visudo.

Consider crafting manual sudoers entries when:

  • Granting limited or command specific privileges
  • Setting up role-based access levels e.g. Level 1 vs Level 2 support
  • Enforcing complex security policies around sudo usage

Use extreme caution when editing sudoers directly. A single syntax error can break sudo for all users which then requires recovery in single user mode.

First invoke the visudo editor:

sudo visudo

Then add entries like:

# User privilege specification
root    ALL=(ALL:ALL) ALL    

# Limited sudo user
bobsmit ALL = /usr/bin/apt, /usr/bin/find

This allows user bobsmit to run only apt and find with elevated privileges.

Hardening Sudo with Defaults

Simply adding users provides full sudo access. But sudo configures substantial defaults out of the box.

Tweak these defaults further to dial in security and auditing.

Leveraging passwd_timeout

The passwd_timeout setting controls how long before sudo prompts for a password again.

Out of the box: 15 minutes

Best practice: 5 minutes or less

Configure a shorter timeout with:

Defaults passwd_timeout=5

This strikes balance between admin productivity and confirming intent.

Requiring tty Usage

By default, sudo commands can run even when not attached to a tty shell like in a web app or cron. Restrict this by enforcing tty usage to prevent such abuse.

Defaults requiretty

Malware or malicious scripts won‘t run without a tty available!

Enabling Logging

Syslog and monitoring provide oversight for responsible sudo usage. Tell sudo commands to log activity via:

Defaults log_input,log_output

Sending input/output streams to syslog admits auditing command behavior without affecting users.

See the full list of Defaults for even more ways to constrain sudo powers.

Monitoring Sudo Usage and Activity

Logging usage provides half the picture. The other half comes from monitoring logs for irregular sudo activity.

Here are quick commands providing insights into recent sudo usage:

Catch SSH sessions running sudo

sudo grep ‘sudo‘ /var/log/auth.log

Monitor sudoers for failed auth attempts

sudo grep ‘sudoers‘ /var/log/auth.log

Chart sudo commands by user

sudo grep ‘COMMAND‘ /var/log/sudo.log | awk ‘{print $11}‘ | sort | uniq -c | sort -nr  

Consider piping these types of monitoring queries into alerts for easy oversight into sudo usage across an environment.

For Structured Logging data, analyze sudo trends over time with:

  • EFK stack (Elasticsearch + Fluentd + Kibana)
  • Splunk
  • Or log management solution of choice

Troubleshooting Broken Sudoers

Even seasoned professionals fat finger a sudoers edit eventually locking themselves out of the super user.

Attempting sudo when broken prompts:

user is not in sudoers file. This incident will be reported.

Before breaking into cold sweats, remember this still gets resolved without resorting to rebooting!

Boot into Single User Mode

The easiest recovery starts by:

  1. Rebooting the server
  2. Editing the GRUB bootloader to include init=/bin/bash
  3. Dropping into a root shell back inside the system!

From here edit sudoers appropriately without any interference.

If graphical GRUB isn‘t available, use the Linux single user mode escape hatch instead by appending single or 1 to the kernel args.

Leverage visudo Recovery

When locking yourself out with visudo directly, the editor retains a backup at /etc/sudoers.tmp.

Use single user mode to correct syntax errors based on diff‘ing files:

cd /etc
diff sudoers sudoers.tmp

Once corrected, restore access with:

cp /etc/sudoers.tmp /etc/sudoers

This sudoers recovery path seems obscure but can save your skin someday!

Sudo vs Other Privilege Escalation Methods

While sudo constitutes the preferred approach for granting privileges, other common alternatives exist. How do these other tools compare?

Sudo vs su

su allows directly switching users in a shell or taking on another user identity like root. But this approach opens several weaknesses:

  • Actually knowing root‘s password in production
  • No logging or auditing around what commands get run
  • Easy to forget to drop permissions after escalating

Stick to using sudo whenever possible to piggyback the security framework it provides.

However, su still proves useful in recovery scenarios like regaining access via single user mode.

Sudo vs Direct Root

Another escalation path involves logging directly into production as root for admin tasks. Hopefully the perils there require no explanation!

As sudo further isolates and contains root access, don‘t use the root account directly except for recovery as well. Checking the sudo logs later beats guessing what manual commands ran by necessity.

Sudo vs Capabilities

For programs requiring superuser powers, Linux offers capabilities granting finer grained privileges without full root.

For example, ping requires raw socket access normally only root provides. But the setcap tool enables fitting just enough capabilities to let it work as a mortal user.

Sudo and capabilities can complement each other in security policies. Use capabilities for intrinsic program rights and sudo for cmds needing runtime elevation.

Conclusion

Configuring sudo properly allows everyday tasks requiring privilege escalation while avoiding dangers of the root account. Ubuntu‘s sudoers file offers intricate control over granting superuser commands. Handle with care!

Key takeaways around wielding sudo power safely:

  • Audit sudoers configs to ensure only necessary access gets granted
  • Tune sudo defaults to reinforce policies like password timeouts
  • Monitor logs to detect abuse and fine tune rules over time
  • Leverage Principle of Least Privilege minimizing sudo usage altogether

Learning the nooks of sudo never constitutes a waste of time given its ubiquity providing administrator access on Linux. Configure sudo deliberately as a system hardening fundamental!

Questions or feedback? Connect with me on Twitter @myhandle to keep the conversation going on securing privilege escalation.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *