CYBER MONDAY OFFER! 50% OFF on All Paid Plans - Limited Time! ๐Ÿ”ฅ

Use CYBER50 Claim Offer โ†’

sudo and Linux Privilege Management: Safe Delegation of Admin Access

By LinuxCert.Guru Teamยท

Objective

Almost every administrative task on Linux needs elevated privileges, and the question is how to grant them without handing out the root password. sudo is the standard answer: it lets specific users run specific commands as root or another user, with every use logged. This guide covers how sudo makes its decisions, how to write and validate policies, and how to avoid the mistakes that quietly turn a restricted rule into full root access. By the end, you will know how to:

  • Grant full sudo access to users and groups, on both Red Hat and Debian family systems
  • Read and write the sudoers syntax, including aliases
  • Use drop-in files in /etc/sudoers.d/ instead of editing the main file
  • Validate every change with visudo so you never break sudo
  • Create restricted rules for specific commands, and understand where restrictions fail
  • Configure passwordless access for automation with appropriate limits
  • Run commands as other users, and view and audit sudo activity
  • Apply these skills to LFCS exam tasks and real multi-user systems

Why sudo Instead of Logging In as root

Sharing the root password is convenient until something goes wrong. Nobody can tell which person ran a command, you cannot give one person less access than another, and removing someone's access means changing a password that everyone else also uses. sudo solves each of these:

Problem with Shared root How sudo Fixes It
No accountability: every action looks like root Every sudo command is logged with the real user who ran it
Everyone has full power Rules can grant only the commands a person actually needs (least privilege)
Revoking access means changing a shared password Remove a user from a group or delete a rule, and nobody else is affected
The root password is a single point of failure Users authenticate with their own password, so the root password is not shared
Long root sessions are easy to forget and abuse Privileges apply to one command at a time, and the authentication cache expires

How sudo Decides

When a user runs sudo command, sudo works through a simple sequence:

  1. Reads the policy from /etc/sudoers and every file in /etc/sudoers.d/
  2. Checks whether the user, host, target user, and command match a rule. If nothing matches, the request is denied and logged.
  3. Authenticates the user by asking for the user's own password, unless the rule says NOPASSWD or a recent authentication is still cached
    • The cache typically lasts between 5 and 15 minutes depending on the distribution, controlled by timestamp_timeout
  4. Runs the command as the target user, which is root unless you ask for another user
  5. Logs the event with the user, terminal, working directory, target user, and command

Granting Full sudo Access

The usual way to give someone administrative access is group membership, because the default configuration already grants sudo to one specific group. The group name depends on the distribution family:

Distribution Family Admin Group Default Rule in sudoers
RHEL, Rocky Linux, AlmaLinux, Fedora wheel %wheel ALL=(ALL) ALL
Debian, Ubuntu sudo %sudo ALL=(ALL:ALL) ALL
# Red Hat family: add a user to the wheel group
usermod -aG wheel alice

# Debian family: add a user to the sudo group
usermod -aG sudo alice

# Always use -aG. Without -a, the user is REMOVED from every other supplementary group
# and a mistake here can remove their existing sudo access.

# Verify the membership
id alice
getent group wheel
getent group sudo

Group changes do not apply to sessions that are already open. After adding a user to the group, they must log out and back in before sudo recognizes it.

Checking What You Can Do

# List your own sudo privileges
sudo -l

# Sample output:
# User alice may run the following commands on server1:
#     (ALL) ALL

# Root can list another user's privileges
sudo -l -U alice

# Test that sudo works at all
sudo whoami
# root

The sudoers Syntax

Every rule in sudoers follows one pattern: who may run what, as whom, and where.

#  who   where = (as_whom : as_group)  tags:   commands
alice   ALL   = (ALL      : ALL)       ALL
Field Meaning Examples
who The user, or a group written with a leading % alice, %webadmins
where The host the rule applies to. Almost always ALL on a single system. ALL, server1
(as_whom : as_group) The user and group the command may be run as (ALL), (root), (postgres)
tags Optional modifiers that change behaviour NOPASSWD:, PASSWD:, NOEXEC:
commands The commands the rule allows, as full paths ALL, /usr/bin/systemctl restart nginx

Two behaviours catch people out and are worth learning early:

  • The last matching rule wins. If a user matches several rules, sudo applies the final one, not the most specific. A broad rule placed after a narrow one overrides it.
  • Lines starting with # are comments, with one exception: #include and #includedir are directives. Newer sudo versions (1.9.1 and later) also accept the clearer spellings @include and @includedir.

Aliases Keep Rules Readable

Aliases give names to lists of users, hosts, target users, or commands, so that rules stay short and a command list is defined in one place.

User_Alias   ADMINS    = alice, bob
Host_Alias   WEBHOSTS  = web01, web02
Runas_Alias  DBUSERS   = postgres, mysql
Cmnd_Alias   WEB_CTL   = /usr/bin/systemctl start nginx, \
                         /usr/bin/systemctl stop nginx, \
                         /usr/bin/systemctl restart nginx, \
                         /usr/bin/systemctl status nginx

# Use the aliases in rules
ADMINS  ALL=(ALL) ALL
%web    WEBHOSTS=(root) WEB_CTL

Editing Safely with visudo

This is the most important habit in this guide. A syntax error in the sudoers policy can make sudo refuse to run at all, and if sudo is your only route to root, you are locked out of administration. visudo exists to prevent that: it locks the file against simultaneous edits, checks the syntax when you save, and refuses to install a broken file.

# Edit the main policy file safely
sudo visudo

# Edit a drop-in file safely
sudo visudo -f /etc/sudoers.d/10-webadmins

# Check the syntax of the main file and every included file
sudo visudo -c
# /etc/sudoers: parsed OK
# /etc/sudoers.d/10-webadmins: parsed OK

# Check a specific file without installing it
visudo -cf /tmp/candidate-rule

Never open /etc/sudoers with a normal editor. Keep a second root or sudo session open while you test changes, so that if something does break, you still have a way back in.

Drop-In Files in /etc/sudoers.d/

Rather than editing the main /etc/sudoers, which the distribution manages, put your own rules in separate files under /etc/sudoers.d/. Package upgrades will not overwrite them, each team or purpose gets its own file, and removing a rule is deleting one file.

# The main file pulls the directory in with this line (already present by default)
grep -E "^[#@]includedir" /etc/sudoers

# Create a drop-in the safe way: write to a temporary file, validate, then install
cat > /tmp/10-webadmins << 'EOF'
%webadmins ALL=(root) /usr/bin/systemctl restart nginx, /usr/bin/systemctl status nginx
EOF

visudo -cf /tmp/10-webadmins
sudo install -m 0440 -o root -g root /tmp/10-webadmins /etc/sudoers.d/10-webadmins
rm /tmp/10-webadmins

# Confirm the whole policy still parses
sudo visudo -c

Several rules about drop-in files cause silent failures when ignored:

  • A file name containing a dot is skipped. webadmins.conf is ignored, and webadmins works. Files ending in ~ are skipped too.
  • Permissions should be 0440, owned by root. sudo may refuse or warn about files that are writable by others.
  • Files are read in alphabetical order, and the last match wins. Numeric prefixes such as 10- and 20- make the order explicit.
  • Writing a rule with echo straight into the directory skips validation. A one-line example such as echo 'user ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/user works, but a typo in the same pattern leaves sudo unable to parse its policy. Validate with visudo -c immediately afterward, or use the temporary-file method above.

Restricted Rules: Allowing Only Specific Commands

Instead of ALL, a rule can list exactly the commands a user may run. This is least privilege in practice, for example letting a team restart one service without giving them the whole system.

# Find the real path of a command, and use that path in the rule
command -v systemctl

# Allow one user to restart nginx and nothing else
alice ALL=(root) /usr/bin/systemctl restart nginx

# Allow a group several specific commands
%webadmins ALL=(root) /usr/bin/systemctl start nginx, \
                      /usr/bin/systemctl stop nginx, \
                      /usr/bin/systemctl restart nginx

# Allow running one command as a different, non-root user
alice ALL=(postgres) /usr/bin/psql

# Allow everything EXCEPT certain commands (weak, see the warning below)
bob ALL=(ALL) ALL, !/usr/bin/passwd root, !/usr/sbin/visudo

# Test the rule as the user it applies to
sudo -l -U alice
sudo -u alice sudo systemctl restart nginx

Where Restrictions Fail

Restricted sudo rules are easy to write and surprisingly easy to defeat. Treat them as a way to reduce accidents and limit scope, and be cautious about treating them as a hard security boundary.

Risk Why It Is Dangerous Safer Approach
Allowing editors or pagers such as vim, less, or man They can run a shell from inside the program, giving a full root shell Use sudoedit for file editing. The NOEXEC: tag can help where supported, but is not a complete guarantee
Allowing interpreters or tools that run commands such as find, awk, python, or tar They can execute arbitrary programs, so the restriction is meaningless Do not grant them. Give a wrapper script with fixed behaviour instead.
Wildcards in arguments such as /usr/bin/cat /var/log/* A wildcard can match more than intended, including paths like /var/log/../../etc/shadow List exact commands and arguments, with no wildcards
Open-ended subcommands such as /usr/bin/systemctl alone The user can run any subcommand, including ones that change units or run commands Name each allowed subcommand and unit explicitly
Exclusion lists such as ALL, !/bin/su Easy to bypass by copying or renaming a binary, or using another route to a shell Allow a short list of what is needed, not everything minus a few things
Allowing a script the user can edit The user changes the script, then runs it as root Root-owned scripts in a directory users cannot write to

sudoedit: The Safe Way to Edit Files

If someone only needs to edit particular files, give them sudoedit instead of an editor. sudo copies the file to a temporary location, opens it in the user's own editor as that user, and copies it back when they finish, so the editor never runs as root and cannot spawn a root shell.

# In sudoers: allow editing one specific file
alice ALL=(root) sudoedit /etc/nginx/nginx.conf

# As alice
sudoedit /etc/nginx/nginx.conf

Passwordless sudo with NOPASSWD

Normally sudo asks for the user's password. The NOPASSWD: tag skips that, which is genuinely needed for scripts, deployment tools, and automation that run unattended. It is also a common way to turn a stolen session or account into instant root access, so keep it as narrow as the task allows.

# Too broad: any compromise of this account is a compromise of root
deploy ALL=(ALL) NOPASSWD: ALL

# Better: only the exact command automation needs
deploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart myapp

# Mixed: a password for general use, none for one harmless command
alice ALL=(ALL) ALL
alice ALL=(root) NOPASSWD: /usr/bin/systemctl status nginx

# Remember: the LAST matching rule wins, so order matters
# If a broader PASSWD rule came after a NOPASSWD rule for the same command,
# the password would be required again.
  • Use NOPASSWD: ALL only where you accept that the account is effectively root, such as a throwaway lab machine
  • For automation, prefer a dedicated service account with a narrow rule, and key-based authentication
  • Cloud images often ship with passwordless sudo for the default user. That is a deliberate convenience trade-off for a first login and worth tightening on production systems.

Running Commands as Other Users and Getting Root Shells

sudo is not only for becoming root. You can run a command as any user the rules allow, and there are several ways to get an interactive shell.

# Run a single command as another user
sudo -u postgres psql
sudo -u alice whoami
# alice

# Run a command with a specific group
sudo -g developers touch /srv/project/notes.txt

# Run a command as root (the default)
sudo systemctl restart nginx

# Get a root login shell with root's environment
sudo -i

# Get a root shell that keeps more of your current environment
sudo -s

# Clear your cached authentication so the next sudo asks again
sudo -k

# Refresh the cache without running a command
sudo -v
Command What You Get Notes
sudo command One command as root The most auditable form. Each command is logged individually.
sudo -u user command One command as another user Needs a rule that allows that target user
sudo -i A root login shell with root's environment and home Closest to logging in as root. Prefer it over sudo su -.
sudo -s A root shell using your shell and mostly your environment Handy for a quick session
su - A root login shell Needs the root password, so it defeats the point of sudo if the password is shared

A practical audit point: sudo logs that a shell was started, but the individual commands typed inside sudo -i or sudo -s are not each logged by sudo. If you need a full record of what was done in those sessions, use the Linux audit system (auditd) or sudo's input and output logging.

Useful sudo Defaults

The Defaults lines in sudoers change how sudo behaves, either globally or for a specific user. Put them in a drop-in file with a name like 00-defaults.

# Ask for the password again after 5 minutes (the default is 5 or 15 depending on the distribution)
Defaults timestamp_timeout=5

# Always ask for a password for one particular user (0 means never cache)
Defaults:alice timestamp_timeout=0

# Limit password attempts
Defaults passwd_tries=3

# Write sudo activity to its own log file
Defaults logfile="/var/log/sudo.log"

# Record full terminal input and output of sudo sessions, for audit
Defaults log_input, log_output

Two defaults you will meet without setting them: env_reset clears most of the user's environment so that a hostile variable cannot influence a privileged command, and secure_path forces a safe PATH for sudo commands. These explain why a command that works in your shell is sometimes "not found" under sudo, or why a variable you exported is missing. The fix is to use the full path, or to allow that variable deliberately with env_keep, not to disable the protections.

Viewing and Auditing sudo Activity

Because every use is logged, sudo doubles as an audit trail. The place the logs end up depends on the distribution.

Where What It Holds
/var/log/secure sudo events on Red Hat family systems
/var/log/auth.log sudo events on Debian and Ubuntu
journalctl -t sudo sudo events from the systemd journal on any systemd distribution
A logfile set with Defaults A dedicated sudo log, if you configured one
# Today's sudo activity from the journal
journalctl -t sudo --since today

# Search the traditional log files
sudo grep sudo /var/log/secure        # Red Hat family
sudo grep sudo /var/log/auth.log      # Debian family

# A typical entry shows who, where, as whom, and what:
# sudo: alice : TTY=pts/0 ; PWD=/home/alice ; USER=root ; COMMAND=/usr/bin/systemctl restart nginx

# Failed attempts are logged too
journalctl -t sudo | grep -i -E "incorrect password|not in the sudoers"

Practical Example: A Small Team Policy

This brings the pieces together. The scenario: administrators get full access, a web team may manage nginx only, and a deployment account may restart one application without a password.

# 1. Groups and users
groupadd webadmins
useradd -m -G webadmins carol
useradd -m deploy
usermod -aG wheel alice            # use "sudo" instead of "wheel" on Debian or Ubuntu

# 2. Web team: manage nginx only (written safely via a temp file)
cat > /tmp/10-webadmins << 'EOF'
Cmnd_Alias WEB_CTL = /usr/bin/systemctl start nginx, \
                     /usr/bin/systemctl stop nginx, \
                     /usr/bin/systemctl restart nginx, \
                     /usr/bin/systemctl status nginx
%webadmins ALL=(root) WEB_CTL
EOF

# 3. Deployment account: one command, no password
cat > /tmp/20-deploy << 'EOF'
deploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart myapp
EOF

# 4. Validate each file, then install with correct ownership and mode
for f in 10-webadmins 20-deploy; do
    visudo -cf /tmp/$f
    install -m 0440 -o root -g root /tmp/$f /etc/sudoers.d/$f
    rm /tmp/$f
done

# 5. Validate the whole policy
visudo -c

# 6. Verify what each account can actually do
sudo -l -U carol
sudo -l -U deploy
# carol is asked for her own password in these two tests
sudo -u carol sudo systemctl restart nginx    # should work
sudo -u carol sudo cat /etc/shadow            # should be refused

Troubleshooting

Symptom Likely Cause Fix
alice is not in the sudoers file No rule matches the user, or group membership has not taken effect Check id alice. Add the user to wheel or sudo, then have them log out and in.
syntax error near line N and sudo stops working A bad edit left the policy unparseable Get a root shell another way (su -, a second session, or recovery mode), run visudo -c, and fix the named file
A drop-in rule has no effect File name contains a dot, the directory is not included, or permissions are wrong Rename without a dot, confirm the @includedir line exists, and set chmod 0440
A narrow rule is overridden by a broader one The last matching rule wins Reorder files or rules so the intended one comes last
Command not found under sudo secure_path replaces your PATH Use the full path from command -v
An exported variable is missing under sudo env_reset cleared it Pass it inline, such as sudo VAR=value command, or allow it with env_keep if appropriate
User still asked for a password despite NOPASSWD A later rule matches without NOPASSWD, or the command in the rule does not match exactly Check rule order, and compare the rule's command path to what you ran
sudo: unable to resolve host warning Hostname missing from /etc/hosts Add the hostname to /etc/hosts

Best Practices

  • Grant to groups, not individuals. Adding or removing a person is then a one-line group change, and the rules stay stable.
  • Prefer drop-ins to editing the main file. One file per team or purpose, with numeric prefixes for order.
  • Always use visudo, and run visudo -c after any change.
  • Apply least privilege. Give the specific commands needed, with exact arguments, as the minimum viable rule.
  • Avoid shell-capable commands in restricted rules. Editors, pagers, interpreters, and tools like find are root shells in disguise.
  • Use sudoedit for file editing instead of allowing an editor.
  • Keep NOPASSWD narrow, and prefer service accounts and keys for automation.
  • Review regularly. Run sudo -l -U user for each account and remove access that is no longer needed.
  • Audit. Know where sudo logs, and use auditd or I/O logging where you need full session records.
  • Do not lean on the root password. If sudo works, root can be reserved for emergencies, and direct root SSH login can be disabled separately.

Common Mistakes

  • Editing /etc/sudoers with a regular editor. One typo and sudo may refuse to run. Use visudo.
  • Writing a drop-in with echo and not validating it. The same shortcut that works can also silently break the whole policy.
  • Naming a drop-in with a dot, such as team.conf. It is ignored, and nothing tells you why.
  • Forgetting that the last matching rule wins. Rule order silently changes who can do what.
  • Using usermod -G instead of -aG. It replaces all supplementary groups, which can strip someone's sudo access.
  • Expecting group changes to apply immediately. The user must log in again.
  • Granting NOPASSWD: ALL casually. It converts any compromise of that account into root.
  • Allowing vim, less, find, or a bare systemctl. Each one can escape the restriction.
  • Using wildcards in command arguments. They match more than you think.
  • Making changes without a spare root session open. If sudo breaks, you need another way in.

Quick Reference

Task Command or Rule
View your sudo privileges sudo -l
View another user's privileges (as root) sudo -l -U username
Give full access on Red Hat family systems usermod -aG wheel username
Give full access on Debian family systems usermod -aG sudo username
Edit the main policy safely sudo visudo
Edit a drop-in safely sudo visudo -f /etc/sudoers.d/name
Validate all sudoers files sudo visudo -c
Validate one file before installing visudo -cf /path/to/file
Full access for a user user ALL=(ALL) ALL
Full access for a group %group ALL=(ALL) ALL
One command only user ALL=(root) /full/path/to/command args
Passwordless for one command user ALL=(root) NOPASSWD: /full/path/to/command
Allow editing one file safely user ALL=(root) sudoedit /path/to/file
Run a command as another user sudo -u username command
Get a root login shell sudo -i
Forget cached authentication sudo -k
View sudo activity journalctl -t sudo

sudo and the LFCS Exam

Delegating administrative access is a standard part of Linux user administration and appears in the LFCS skill areas. Tasks typically ask you to:

  • Give a user or group full or restricted sudo access, often through a file in /etc/sudoers.d/
  • Allow a user to run one specific command as root or as another user
  • Configure passwordless sudo for a given user or command
  • Validate the configuration with visudo and confirm it with sudo -l

The habits that earn the marks are the safe ones: use visudo or visudo -cf, set mode 0440, avoid dots in drop-in file names, and verify with sudo -l -U before you finish. Confirm the exact objectives against the current LFCS curriculum for your exam version.

Conclusion

sudo lets you delegate exactly the access people need, with a log of every use, and without sharing the root password. Most of the skill is in a small set of disciplined habits:

  • Grant full access through the wheel or sudo group, and use -aG when adding members
  • Put custom rules in drop-in files under /etc/sudoers.d/, with no dots in the name and mode 0440
  • Always edit and validate with visudo, and keep a spare root session open while you work
  • Remember that the last matching rule wins
  • Restrict to exact commands and arguments, and avoid editors, interpreters, wildcards, and exclusion lists, because they quietly reopen root access
  • Use sudoedit for file editing, and keep NOPASSWD as narrow as the task allows
  • Verify every change with sudo -l -U username, and know where sudo logs so you can audit what happened

Used carefully, sudo is one of the most effective security controls on a Linux system. Used carelessly, a single wildcard or a permissive editor rule makes a restricted account into root. Test every rule as the user it is meant for, and treat the restrictions as something you have to prove, not something you can assume.

Start the sudo and Privilege Management lab at LinuxCert.Guru → https://linuxcert.guru/lfcs/?name=lfcs-sudo-privilege-management

$_
Ready to go beyond reading? Manage Local Users and Groupsfree ยท auto-graded RHCSA lab, nothing to install Not sure where you stand? Take the 10-min RHCSA skill check โ†’
Open lab โ†’