Learn / Linux / Users & Permissions
Lesson 21 of 74

sudo: Admin Rights, Safely

Why you shouldn't log in as root, how sudo works, the sudo vs su difference, every part of a sudoers rule, the sudo and wheel groups, least-privilege rules in /etc/sudoers.d, NOPASSWD, running as other users with sudo -u, visudo and how not to lock yourself out, and the sudo rules that secretly give away root.

25 min read Report a problem Hands-on lab included 6-question quiz

Why not just log in as root?

root can do anything, which is exactly why working as root all day is a bad idea:

  • Mistakes are unlimited. A typo like rm -rf / tmp/build (one stray space) runs without a single permission check.
  • No accountability. If five admins share root's password, the logs only ever say "root did it".
  • Sharing a password is fragile. When someone leaves, root's password has to change on every server.
  • Attackers love it. SSH logins as root are the first thing bots try.

sudo ("substitute user do") fixes all four. Each person logs in as themselves, and runs individual commands as root when needed. sudo checks a rules file, asks for their own password, and logs who ran what.

What happens when you run sudo

rohan$ sudo systemctl restart nginxa normal user asks
Check the rules/etc/sudoers + /etc/sudoers.d/
allowed
Ask rohan's passwordremembered ~15 min
Run as rootand log "rohan ran ..."

If no rule matches, sudo refuses and logs the attempt as a security incident.

Most cloud servers ship this way: Ubuntu on AWS gives you the ubuntu user with sudo rights, and direct root login is disabled.

sudo vs su

sudo commandsu -
Doesruns one command as rootstarts a whole shell as root
Passwordyour ownroot's
Rightswhatever the rules allow (can be one command)everything
Loggingeach command, with your nameonly that someone became root

You'll also see these combinations:

CommandDoes
sudo -ia root login shell, using your own password (when rules allow)
sudo -sa root shell keeping more of your environment
sudo -u priya cmdrun as priya instead of root
sudo -llist what you may run
sudo -kforget the cached password now
sudoedit /etc/fileedit a file safely as root (in your own editor, as you)

The rules file

The rules live in /etc/sudoers, plus every file in /etc/sudoers.d/. Here is Ubuntu's main file with comments removed:

bash
grep -v '^#' /etc/sudoers | grep -v '^$'
text
Defaults	env_reset
Defaults	mail_badpass
Defaults	secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"
Defaults	use_pty
root	ALL=(ALL:ALL) ALL
%admin ALL=(ALL) ALL
%sudo	ALL=(ALL:ALL) ALL
@includedir /etc/sudoers.d
LineMeaning
Defaults env_resetcommands get a clean, minimal environment
Defaults secure_path=...commands are searched only in these trusted folders, not your $PATH
Defaults use_ptyrun commands in their own terminal, so they can't interfere with yours after exiting
root ALL=(ALL:ALL) ALLroot may do anything
%sudo ALL=(ALL:ALL) ALLmembers of group sudo may do anything, with their password
@includedir /etc/sudoers.dread every file in this folder too

Anatomy of a rule

text
  %devops   ALL   =   (appsvc)   NOPASSWD:   /usr/bin/systemctl restart shop
  └──┬──┘   └┬┘       └──┬───┘   └───┬───┘   └──────────────┬──────────────┘
    who    hosts      run as      option          which commands
PartValues
whoa user (anita) or a group (%devops)
hostsalmost always ALL; lets one file be shared across many servers
run as(root), (appsvc), (ALL), or (ALL:ALL) for any user and group; omitted = root
optionNOPASSWD: skips the password; useful for automation and narrow rules
commandsALL, or full paths, optionally with exact arguments; separate several with commas
Try it · Task 1 of 4

Who can become root?

Find and remove the rule that gives a former intern passwordless root.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

The first question in any access review: who can become root? Two places grant it: the rules in /etc/sudoers and /etc/sudoers.d/, and membership of the groups those rules name.

1. Read the main rules file

bash
grep -v '^#' /etc/sudoers | grep -v '^$'

Strips the comments and blank lines so only the active settings remain.

text
Defaults	env_reset
Defaults	mail_badpass
Defaults	secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin"
Defaults	use_pty
root	ALL=(ALL:ALL) ALL
%admin ALL=(ALL) ALL
%sudo	ALL=(ALL:ALL) ALL
@includedir /etc/sudoers.d
LineMeaning
Defaults env_resetcommands run with a clean environment, not yours
Defaults secure_path=...commands are looked up only in these trusted folders
root ALL=(ALL:ALL) ALLroot may run anything as anyone
%sudo ALL=(ALL:ALL) ALLmembers of group sudo (the % means group) may run anything, with their password
@includedir /etc/sudoers.dalso read every file in that folder

2. Check the extra rule files

bash
ls -l /etc/sudoers.d/
cat /etc/sudoers.d/intern
text
total 8
-r--r----- 1 root root 1068 Jan 29  2024 README
-r--r----- 1 root root   35 Nov 24 15:59 intern
old-intern ALL=(ALL) NOPASSWD: ALL

NOPASSWD: ALL means any command as root without even a password. Anyone who gets into this old account, by guessing its password or finding an SSH key, owns the server.

3. Ask sudo directly

bash
sudo -l -U old-intern
sudo -l -U rohan

-l lists rights, -U user for another user (root only).

text
Matching Defaults entries for old-intern on devopsshack:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin, use_pty

User old-intern may run the following commands on devopsshack:
    (ALL) NOPASSWD: ALL
User rohan is not allowed to run sudo on devopsshack.

sudo -l -U is the reliable check: it combines every file and every group membership into the user's real rights.

2 · Your task

Remove old-intern's sudo rights by deleting the rule file /etc/sudoers.d/intern.

Expected result: sudo -l -U old-intern says the user is not allowed to run sudo, and visudo -c reports everything parsed OK.

Hint: the commands, explained
text
rm /etc/sudoers.d/intern
sudo -l -U old-intern

What each part does

  • rm /etc/sudoers.d/intern: delete the rule file that gave the old intern sudo rights.
  • sudo -l -U old-intern: list what sudo allows for that User. It now says they may not run sudo.
First start the lab machine in the terminal panel on the right.

Granting full admin: the sudo group

On Ubuntu and Debian, full admins are the members of the sudo group; on RHEL, Rocky, Amazon Linux and Fedora it's wheel. Granting and revoking admin is just group membership:

bash
usermod -aG sudo rohan       # make an admin (wheel on Red Hat systems)
gpasswd -d rohan sudo        # remove admin rights
getent group sudo            # who are the admins?
sudo -l -U rohan             # what can rohan actually do?
text
User rohan may run the following commands on devopsshack:
    (ALL : ALL) ALL

sudo -l -U is the check to trust: it combines every rule file and every group into the user's real rights. Like every group change, the new membership applies at the user's next login.

Try it · Task 2 of 4

A new admin

Give Rohan full sudo rights, the standard Ubuntu way.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

On Ubuntu, full admins are simply members of the sudo group (on Red Hat-family systems it's called wheel). The rule %sudo ALL=(ALL:ALL) ALL is already there, so granting or revoking admin rights is just group membership: no sudoers editing, and easy to audit with getent group sudo.

1. Rohan has no rights yet

bash
getent group sudo
su - rohan -c 'sudo -n whoami'
text
sudo:x:27:
sudo: a password is required

The group has no members. "A password is required" with -n means sudo would have asked for one; without a matching rule, after the password it would refuse anyway.

2. Add him to the group

bash
usermod -aG sudo rohan
sudo -l -U rohan

Remember -a (append), or Rohan loses his other groups.

text
Matching Defaults entries for rohan on devopsshack:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin, use_pty

User rohan may run the following commands on devopsshack:
    (ALL : ALL) ALL

(ALL : ALL) ALL: any command, as any user and group. Without NOPASSWD, he must type his own password (it's DevOps@2026 in this lab if you want to try su - rohan, then sudo whoami).

Group changes apply at the user's next login. If Rohan was already logged in, he needs to log out and back in before sudo works for him.

2 · Your task

Make rohan a full admin by adding him to the sudo group, without removing his other groups.

Expected result: sudo -l -U rohan shows (ALL : ALL) ALL, and id rohan still includes devops.

Hint: the commands, explained
text
usermod -aG sudo rohan

What each part does

  • usermod -aG sudo rohan: append rohan to the sudo Group. Without -a, -G would replace all his other groups.
  • On Ubuntu, members of sudo may run any command as root. It takes effect at his next login.
First start the lab machine in the terminal panel on the right.

Least privilege: narrow rules

Most people don't need full root. Give each role exactly the commands its job requires, one file per purpose in /etc/sudoers.d/:

bash
echo 'anita ALL=(root) NOPASSWD: /usr/local/bin/shop-restart' > /etc/sudoers.d/support
chmod 440 /etc/sudoers.d/support
visudo -c
sudo -l -U anita
text
/etc/sudoers: parsed OK
/etc/sudoers.d/README: parsed OK
/etc/sudoers.d/support: parsed OK
Matching Defaults entries for anita on devopsshack:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin, use_pty

User anita may run the following commands on devopsshack:
    (root) NOPASSWD: /usr/local/bin/shop-restart

Anita can run exactly one program as root, and every attempt at anything else is refused and logged.

More examples of real-world rules:

text
# CI deploy user may restart one service, nothing else
deploy  ALL=(root) NOPASSWD: /usr/bin/systemctl restart shop, /usr/bin/systemctl status shop

# DBAs may run any command as the postgres account
%dba    ALL=(postgres) ALL

# Monitoring agent may read one log
nagios  ALL=(root) NOPASSWD: /usr/bin/tail -n 100 /var/log/shop/app.log

When you list exact arguments, the user must type them exactly. With no arguments listed, any arguments are allowed.

Try it · Task 3 of 4

One command, nothing more

Let Anita run the shop restart script as root, and nothing else.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

Least privilege: give people exactly what their job needs. The support team only needs to restart the shop, so instead of full root they get one command. Put each rule set in its own file under /etc/sudoers.d/, so it's easy to find, review and delete.

1. Anita has nothing yet

bash
cat /usr/local/bin/shop-restart
su - anita -c 'sudo -n /usr/local/bin/shop-restart'
text
#!/bin/bash
echo "[$(date +%T)] shop restarted by ${SUDO_USER:-$USER}" | tee -a /var/log/shop-restarts.log
sudo: a password is required

The script logs a line saying who restarted the shop. Anita can't run it as root yet: there's no rule for her.

2. Write the rule

bash
echo 'anita ALL=(root) NOPASSWD: /usr/local/bin/shop-restart' > /etc/sudoers.d/support
visudo -c
PartMeaning
anitathe user (%support would mean the whole group)
ALL=on any host (the same file can be shared across servers)
(root)may run it as root only
NOPASSWD:without typing her password
/usr/local/bin/shop-restartthis exact program, by full path
text
/etc/sudoers.d/support: bad permissions, should be mode 0440
/etc/sudoers: parsed OK
/etc/sudoers.d/README: parsed OK

visudo -c checks every file. The syntax is fine, but sudo insists rule files are readable by root only and writable by nobody. Fix the mode and check again:

bash
chmod 440 /etc/sudoers.d/support
visudo -c
sudo -l -U anita
text
/etc/sudoers: parsed OK
/etc/sudoers.d/README: parsed OK
/etc/sudoers.d/support: parsed OK
Matching Defaults entries for anita on devopsshack:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin, use_pty

User anita may run the following commands on devopsshack:
    (root) NOPASSWD: /usr/local/bin/shop-restart

3. Test it, and test what she can't do

bash
su - anita -c 'sudo /usr/local/bin/shop-restart'
su - anita -c 'sudo -n cat /etc/shadow'
text
[10:30:14] shop restarted by anita
sudo: a password is required

The script ran as root, and logged that anita did it (sudo sets $SUDO_USER). Anything else is refused. (Anita has no password, so sudo can never let her through for other commands.)

The safest way to edit sudo rules interactively is visudo -f /etc/sudoers.d/support: it opens an editor, checks the syntax when you save, and sets the right permissions. Writing with echo is fine in scripts as long as you chmod 440 and run visudo -c afterwards.

2 · Your task

Create /etc/sudoers.d/support so that anita can run /usr/local/bin/shop-restart as root without a password, and nothing else. Give the file mode 440.

Expected result: visudo -c passes, su - anita -c 'sudo -n /usr/local/bin/shop-restart' works, and su - anita -c 'sudo -n whoami' is refused.

Hint: the commands, explained
text
echo 'anita ALL=(root) NOPASSWD: /usr/local/bin/shop-restart' > /etc/sudoers.d/support
chmod 440 /etc/sudoers.d/support
visudo -c

What each part does

  • The rule reads: user anita, on ALL hosts, may run as (root), without a password (NOPASSWD:), only /usr/local/bin/shop-restart. Always use the full path.
  • chmod 440: sudo requires its files to be read-only.
  • visudo -c: check all sudoers files for syntax errors. It prints parsed OK. A broken file can lock everyone out of sudo.
First start the lab machine in the terminal panel on the right.

Running as another user

The (user) part isn't only root. Letting a team act as a service account is a clean way to give access to an app's files without loosening their permissions or giving root:

bash
echo '%devops ALL=(appsvc) NOPASSWD: ALL' > /etc/sudoers.d/devops
chmod 440 /etc/sudoers.d/devops
su - priya -c 'sudo -u appsvc cat /srv/app/data/stats.txt; sudo -u appsvc whoami'
su - priya -c 'sudo -n whoami'
text
orders=1042
appsvc
sudo: a password is required

As appsvc: allowed, no password. As root: refused.

Try it · Task 4 of 4

Acting as a service account

Let the devops group run commands as appsvc without a password, but not as root.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

sudo isn't only for root. The (user) part of a rule says who you may become. A common real setup: developers may act as the application's service account, to read its data or run its maintenance commands, without getting root and without anyone knowing that account's password (service accounts don't have one).

1. The developers are locked out of the app's data

bash
ls -l /srv/app/data
su - priya -c 'cat /srv/app/data/stats.txt'
text
cat: /srv/app/data/stats.txt: Permission denied

The data belongs to appsvc with mode 640 inside a 750 folder, so other users can't get in. That's correct, and we don't want to loosen it.

2. A rule for the whole group, as appsvc only

bash
echo '%devops ALL=(appsvc) NOPASSWD: ALL' > /etc/sudoers.d/devops
chmod 440 /etc/sudoers.d/devops
visudo -c
PartMeaning
%devopsevery member of the devops group
(appsvc)may run commands as appsvc (not as root)
NOPASSWD: ALLany command, no password

3. Use it with sudo -u

bash
su - priya -c 'sudo -u appsvc cat /srv/app/data/stats.txt; sudo -u appsvc whoami'
su - priya -c 'sudo -n whoami'

sudo -u appsvc = run as appsvc instead of root.

text
orders=1042
appsvc
sudo: a password is required

Priya reads the data as appsvc, but plain sudo (as root) is still refused. Files she creates this way belong to appsvc, so the app can keep using them.

2 · Your task

Create /etc/sudoers.d/devops (mode 440) so that members of the devops group can run any command as appsvc without a password, but not as root.

Expected result: su - priya -c 'sudo -n -u appsvc whoami' prints appsvc, and su - priya -c 'sudo -n whoami' is refused.

Hint: the commands, explained
text
echo '%devops ALL=(appsvc) NOPASSWD: ALL' > /etc/sudoers.d/devops
chmod 440 /etc/sudoers.d/devops
visudo -c

What each part does

  • %devops: % means a group, so this applies to every member of devops.
  • ALL=(appsvc) NOPASSWD: ALL: they may run any command, but only as appsvc, not as root. Use it like sudo -u appsvc whoami.
  • Then chmod 440 and visudo -c, as before.
First start the lab machine in the terminal panel on the right.

visudo: don't lock yourself out

sudo refuses to run at all if any rule file has a syntax error. One bad character and no admin can use sudo, including to fix the file. On a cloud server where root login is disabled, that can mean rebuilding the machine.

So always:

bash
visudo                              # edit /etc/sudoers safely
visudo -f /etc/sudoers.d/support    # edit (or create) one rule file safely
visudo -c                           # check every file
visudo -c -f /tmp/newrule           # check a file before installing it

visudo opens the file in an editor and checks it when you save. If there's an error, it asks what to do instead of saving a broken file:

text
/tmp/bad:1:10: syntax error
bad line here
         ^~~~

That's visudo -c -f on a file containing a nonsense line. It shows the line and points at the problem.

Rule files must also be owned by root and not writable by others. visudo -c catches that too:

text
/etc/sudoers.d/support: bad permissions, should be mode 0440

Two more safety habits: keep a second root session open while changing sudo rules on a remote server, and remember that files in /etc/sudoers.d/ whose names contain a . or end in ~ are ignored (so support.conf silently does nothing).

Rules that secretly give away root

A narrow rule is only narrow if the command can't do more than it looks like. These all hand out a root shell:

Rule allowsEscape
an editor: vim, nano, less, morerun a shell from inside it (:!bash in vim)
an interpreter: python3, perl, bashrun any code
find, awk, tar, git, envall have options that run commands
cp, tee, chmod on any fileoverwrite /etc/sudoers or /etc/shadow
a script the user can editedit it to do anything
a command with wildcards: /bin/cat /var/log/*/bin/cat /var/log/../../etc/shadow

Rules of thumb: allow specific, fixed commands; make allowed scripts owned by root and not writable by the user; for editing files use sudoedit; and treat NOPASSWD: ALL as "this account is root".

Editing /etc/sudoers with a normal editor. One typo and nobody can use sudo. Always visudo.

Forgetting -a in usermod -aG sudo. The user becomes an admin and loses every other group.

Relative paths in rules. Write /usr/local/bin/shop-restart, not shop-restart; sudo needs full paths.

NOPASSWD: ALL for convenience. Anyone who gets into that account gets root, with no password standing in the way. Keep it for tightly controlled automation accounts.

Forgotten rules. People leave and their files in /etc/sudoers.d/ stay. Review them and sudo -l -U for every account regularly.

"What's the difference between sudo and su?" sudo runs one command as another user (root by default), with your own password, under rules that can be narrow, and logs each command. su starts a shell as another user and needs that user's password.

"How do you give a user admin rights on Ubuntu?" usermod -aG sudo user (on RHEL-family: wheel), effective at next login.

"How would you let a CI user restart one service?" A file in /etc/sudoers.d/ with ci ALL=(root) NOPASSWD: /usr/bin/systemctl restart app, mode 440, checked with visudo -c.

"Why use visudo?" It validates syntax before saving; a broken sudoers file breaks sudo for everyone.

"Can sudo access to vim be a problem?" Yes, vim can spawn a shell, which would be a root shell. Use sudoedit.

Summary

  • Log in as yourself; use sudo for single commands. It asks for your password and logs who did what.
  • Rules: who hosts=(runas) [NOPASSWD:] commands, in /etc/sudoers and /etc/sudoers.d/ (mode 440, no dots in names).
  • Full admins: the sudo group (Ubuntu) or wheel (Red Hat). sudo -l -U user shows anyone's real rights.
  • Least privilege: exact commands by full path, (appsvc) + sudo -u for service accounts.
  • Always visudo / visudo -c. Editors, interpreters and writable scripts in rules are root in disguise.
Check your understanding

Quick quiz

Feedback