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.
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
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 command | su - | |
|---|---|---|
| Does | runs one command as root | starts a whole shell as root |
| Password | your own | root's |
| Rights | whatever the rules allow (can be one command) | everything |
| Logging | each command, with your name | only that someone became root |
You'll also see these combinations:
| Command | Does |
|---|---|
sudo -i | a root login shell, using your own password (when rules allow) |
sudo -s | a root shell keeping more of your environment |
sudo -u priya cmd | run as priya instead of root |
sudo -l | list what you may run |
sudo -k | forget the cached password now |
sudoedit /etc/file | edit 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:
grep -v '^#' /etc/sudoers | grep -v '^$'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| Line | Meaning |
|---|---|
Defaults env_reset | commands get a clean, minimal environment |
Defaults secure_path=... | commands are searched only in these trusted folders, not your $PATH |
Defaults use_pty | run commands in their own terminal, so they can't interfere with yours after exiting |
root ALL=(ALL:ALL) ALL | root may do anything |
%sudo ALL=(ALL:ALL) ALL | members of group sudo may do anything, with their password |
@includedir /etc/sudoers.d | read every file in this folder too |
Anatomy of a rule
%devops ALL = (appsvc) NOPASSWD: /usr/bin/systemctl restart shop
└──┬──┘ └┬┘ └──┬───┘ └───┬───┘ └──────────────┬──────────────┘
who hosts run as option which commands| Part | Values |
|---|---|
| who | a user (anita) or a group (%devops) |
| hosts | almost 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 |
| option | NOPASSWD: skips the password; useful for automation and narrow rules |
| commands | ALL, or full paths, optionally with exact arguments; separate several with commas |
Who can become root?
Find and remove the rule that gives a former intern passwordless root.
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
grep -v '^#' /etc/sudoers | grep -v '^$'Strips the comments and blank lines so only the active settings remain.
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| Line | Meaning |
|---|---|
Defaults env_reset | commands run with a clean environment, not yours |
Defaults secure_path=... | commands are looked up only in these trusted folders |
root ALL=(ALL:ALL) ALL | root may run anything as anyone |
%sudo ALL=(ALL:ALL) ALL | members of group sudo (the % means group) may run anything, with their password |
@includedir /etc/sudoers.d | also read every file in that folder |
2. Check the extra rule files
ls -l /etc/sudoers.d/
cat /etc/sudoers.d/interntotal 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: ALLNOPASSWD: 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
sudo -l -U old-intern
sudo -l -U rohan-l lists rights, -U user for another user (root only).
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.
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
rm /etc/sudoers.d/intern
sudo -l -U old-internWhat 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.
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:
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?User rohan may run the following commands on devopsshack:
(ALL : ALL) ALLsudo -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.
A new admin
Give Rohan full sudo rights, the standard Ubuntu way.
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
getent group sudo
su - rohan -c 'sudo -n whoami'sudo:x:27:
sudo: a password is requiredThe 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
usermod -aG sudo rohan
sudo -l -U rohanRemember -a (append), or Rohan loses his other groups.
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.
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
usermod -aG sudo rohanWhat each part does
usermod -aG sudo rohan: append rohan to thesudoGroup. Without-a,-Gwould replace all his other groups.- On Ubuntu, members of
sudomay run any command as root. It takes effect at his next login.
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/:
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/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-restartAnita can run exactly one program as root, and every attempt at anything else is refused and logged.
More examples of real-world rules:
# 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.logWhen you list exact arguments, the user must type them exactly. With no arguments listed, any arguments are allowed.
One command, nothing more
Let Anita run the shop restart script as root, and nothing else.
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
cat /usr/local/bin/shop-restart
su - anita -c 'sudo -n /usr/local/bin/shop-restart'#!/bin/bash
echo "[$(date +%T)] shop restarted by ${SUDO_USER:-$USER}" | tee -a /var/log/shop-restarts.log
sudo: a password is requiredThe 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
echo 'anita ALL=(root) NOPASSWD: /usr/local/bin/shop-restart' > /etc/sudoers.d/support
visudo -c| Part | Meaning |
|---|---|
anita | the 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-restart | this exact program, by full path |
/etc/sudoers.d/support: bad permissions, should be mode 0440
/etc/sudoers: parsed OK
/etc/sudoers.d/README: parsed OKvisudo -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:
chmod 440 /etc/sudoers.d/support
visudo -c
sudo -l -U anita/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-restart3. Test it, and test what she can't do
su - anita -c 'sudo /usr/local/bin/shop-restart'
su - anita -c 'sudo -n cat /etc/shadow'[10:30:14] shop restarted by anita
sudo: a password is requiredThe 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.
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
echo 'anita ALL=(root) NOPASSWD: /usr/local/bin/shop-restart' > /etc/sudoers.d/support
chmod 440 /etc/sudoers.d/support
visudo -cWhat each part does
- The rule reads: user
anita, onALLhosts, 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 printsparsed OK. A broken file can lock everyone out of sudo.
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:
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'orders=1042
appsvc
sudo: a password is requiredAs appsvc: allowed, no password. As root: refused.
Acting as a service account
Let the devops group run commands as appsvc without a password, but not as root.
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
ls -l /srv/app/data
su - priya -c 'cat /srv/app/data/stats.txt'cat: /srv/app/data/stats.txt: Permission deniedThe 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
echo '%devops ALL=(appsvc) NOPASSWD: ALL' > /etc/sudoers.d/devops
chmod 440 /etc/sudoers.d/devops
visudo -c| Part | Meaning |
|---|---|
%devops | every member of the devops group |
(appsvc) | may run commands as appsvc (not as root) |
NOPASSWD: ALL | any command, no password |
3. Use it with sudo -u
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.
orders=1042
appsvc
sudo: a password is requiredPriya 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.
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
echo '%devops ALL=(appsvc) NOPASSWD: ALL' > /etc/sudoers.d/devops
chmod 440 /etc/sudoers.d/devops
visudo -cWhat 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 likesudo -u appsvc whoami.- Then
chmod 440andvisudo -c, as before.
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:
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 itvisudo 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:
/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:
/etc/sudoers.d/support: bad permissions, should be mode 0440Two 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 allows | Escape |
|---|---|
an editor: vim, nano, less, more | run a shell from inside it (:!bash in vim) |
an interpreter: python3, perl, bash | run any code |
find, awk, tar, git, env | all have options that run commands |
cp, tee, chmod on any file | overwrite /etc/sudoers or /etc/shadow |
| a script the user can edit | edit 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
sudofor single commands. It asks for your password and logs who did what. - Rules:
who hosts=(runas) [NOPASSWD:] commands, in/etc/sudoersand/etc/sudoers.d/(mode 440, no dots in names). - Full admins: the
sudogroup (Ubuntu) orwheel(Red Hat).sudo -l -U usershows anyone's real rights. - Least privilege: exact commands by full path,
(appsvc)+sudo -ufor service accounts. - Always
visudo/visudo -c. Editors, interpreters and writable scripts in rules are root in disguise.
Quick quiz
You've practised everything in this lesson
Every task was checked on your own machine. You can end the lab, or keep experimenting in the terminal.