Understanding sudo vs su - Safe Privilege Escalation in Linux
What you'll be able to do
- Choose between sudo and su according to the task
- Explain in security terms why sudo is recommended
- Edit sudoers safely with visudo
Prerequisites (read these first)
What You'll Learn
- You will be able to choose between
sudoandsuaccording to the task at hand. - You will be able to explain, in security terms, why
sudois the recommended approach. - You will be able to write basic
sudoersconfiguration safely yourself. - You will know the common accident patterns and how to avoid them.
Who this is for: anyone starting out on an Ubuntu server who currently types sudo as a magic incantation.
Terms defined up front
Each term below is defined once, here.
- Privilege escalation means performing an operation your current user is not allowed to do, using stronger privileges.
- root is the name of the administrator user who can do anything on the system. It is also called the superuser.
- A login shell is a shell that has loaded the login-time configuration (
.profile,.bashrc). For the same user, environment variables such asPATHdiffer depending on whether the shell is a login shell. - An environment variable is a setting the shell carries.
PATH(the list of places commands are searched for) andHOME(the home directory) are the typical examples. - sudoers is the configuration file
/etc/sudoersthat records who may run which commands. - visudo is the dedicated command for editing
sudoerswith a syntax check. - NOPASSWD is a sudoers setting that allows a command to run without entering a password.
Quick Summary
- Run one command as root →
sudo command - Start an extended root session (use sparingly) →
sudo -i - Run as another user →
sudo -u username command su -requires the root password — disabled by default on Ubuntu. Usesudo -iinstead.
Prerequisites
- OS: Ubuntu (or other Debian-based distros)
- Your user account is a member of the
sudogroup
What Is the Difference Between sudo and su?
Both sudo (substitute user do) and su (switch user) elevate privileges, but they work differently.
| Aspect | sudo | su |
|---|---|---|
| Authentication | Your own password | Target user's password |
| Root password needed | No | Yes (for su -) |
| Audit logging | /var/log/auth.log |
Minimal |
| Permission control | Per-command via /etc/sudoers |
Full root access |
| Ubuntu default | Available | Blocked (root pw disabled) |
sudo is the preferred tool because it enforces least-privilege access per user without sharing the root password.
How to Use sudo
2-1. Basic Usage — One Command at a Time
$ sudo command
Examples:
$ sudo apt update $ sudo systemctl restart nginx
2-2. Start a Root Login Shell
$ sudo -i
sudo -i launches a root shell that loads root's environment variables and .profile. Use this only when you need to run multiple commands as root.
Always exit the root shell when done. Running as root unnecessarily increases the risk of accidental damage.
2-3. Run as Another User
$ sudo -u username command
Example — run a command as www-data:
$ sudo -u www-data php /var/www/html/artisan cache:clear
2-4. How Long Does sudo Stay Active?
After successful authentication, sudo caches credentials for 15 minutes by default. To invalidate the cache manually:
$ sudo -k
To list your current sudo permissions:
$ sudo -l
User alice may run the following commands on hostname:
(ALL : ALL) ALL
(ALL : ALL) ALL means "as any user, any command". When only specific commands are permitted, their paths are listed instead.
How to Use su
3-1. su - for a Login Shell
$ su - [username]
The - flag (equivalent to -l or --login) recreates the target user's full login environment — home directory, environment variables, and PATH.
$ su - deploy # Start a login shell as the deploy user
3-2. su vs su - — What Changes?
$ su username # Warning: inherits YOUR current environment $ su - username # Correct: reproduces the target user's login environment
Using su username without - carries over your current environment variables into the new shell. This often causes PATH confusion and command not found errors in the target user's context.
3-3. Why su Doesn't Work on Ubuntu by Default
Ubuntu disables the root account password by default. Attempting su - to switch to root fails at authentication:
$ su - Password: su: Authentication failure # root password is disabled
Use sudo -i instead for an interactive root shell on Ubuntu.
Why Is sudo Recommended?
The core advantage of sudo over su is its security model.
Every action is logged. Each sudo invocation records who ran what command and when in /var/log/auth.log:
# Systems with rsyslog (Ubuntu 22.04 and similar) $ sudo grep sudo /var/log/auth.log | tail -3 # Systems with journald only (the Ubuntu 24.04 default install and similar) $ sudo journalctl -t sudo -n 3
May 31 10:30:01 host sudo: alice : TTY=pts/0 ; PWD=/home/alice ; USER=root ; COMMAND=/usr/bin/apt update
The Ubuntu 24.04 default install does not include rsyslog, so /var/log/auth.log may not exist. In that case the logs are collected by journald, so use the journalctl form.
Who ran it, from which directory, and which command — all on one line. Incident investigation is possible precisely because this record exists.
Least-privilege enforcement. sudoers lets you grant only the commands a user actually needs. An operator can restart a specific service without getting full root access.
No shared root password. Team members authenticate with their own passwords, keeping credentials individual and revocable.
Configuring sudoers with visudo
5-1. Always Use visudo
/etc/sudoers must be edited with visudo. It validates syntax before saving, preventing lockout scenarios where a broken sudoers file makes sudo unusable.
$ sudo visudo
Never edit /etc/sudoers directly
Do not open /etc/sudoers with vi or nano. What happens when it goes wrong is the following.
- A single character of bad syntax disables
sudoentirely. - On Ubuntu the root password is disabled, so
su -cannot rescue you either. You need to boot into recovery mode from a physical console. - If this happens while you are working over SSH, you can no longer get administrative access to that server.
How to stay safe takes three habits.
- Always edit with
sudo visudo. It runs a syntax check on save and refuses to write a broken file. - Practise on a local virtual machine or container, never on a production server.
- Before you start, keep a second terminal open with a session where
sudo -valready succeeds. If you do break sudoers, you can repair it from that session.
5-2. Basic Syntax
# user host=(run-as) command alice ALL=(ALL) ALL # NOPASSWD: skip password prompt for a specific command deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx
5-3. Grant Permissions to a Group
# Prefix group names with % %admin ALL=(ALL) ALL %deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl
5-4. Use Drop-In Files (Recommended)
For production environments, avoid editing sudoers directly. Place per-role files under /etc/sudoers.d/ instead:
$ sudo visudo -f /etc/sudoers.d/deploy
Content:
deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx
Common Mistakes
Setting NOPASSWD for ALL Commands
# Dangerous in production: alice ALL=(ALL) NOPASSWD: ALL
This eliminates all password friction. Acceptable on local dev boxes, but copying this config to a production server is a critical security risk. The moment this user's session is hijacked, the attacker gets root-equivalent power without knowing any password. Restrict to specific commands.
Editing sudoers without visudo
Running vi /etc/sudoers directly and introducing a syntax error disables sudo. Always use visudo — it performs a syntax check before writing the file.
Using su without the - Flag
# Inherits your PATH — likely causes command-not-found errors: $ su deploy # Correct — reproduce deploy's login environment: $ su - deploy
Quick Reference
| Task | Command |
|---|---|
| Run one command as root | sudo command |
| Start a root login shell | sudo -i |
| Run one command as another user | sudo -u user command |
| Open an interactive shell as a user | sudo -u user -i |
| Invalidate sudo credential cache | sudo -k |
| List your current sudo permissions | sudo -l |
| Safely edit sudoers | sudo visudo |
Copy-Paste Templates
# Check what sudo allows you to run sudo -l # Run one command as root sudo apt update # Start a root shell — exit when done sudo -i exit
Troubleshooting
Symptom: alice is not in the sudoers file. This incident will be reported.
Cause: the user does not belong to the sudo group (wheel on RHEL-based systems).
Check:
id -nG
alice
If sudo is not listed, the privilege is absent.
Fix: have another user with administrative rights add the account.
sudo usermod -aG sudo alice # run by the administrator
The change takes effect only after the target user logs out and back in. If no administrator is available, boot into recovery mode from a physical console and fix it there.
Symptom: sudo: unable to resolve host <hostname>
Cause: the name in /etc/hostname is not registered in /etc/hosts. sudo still works, but the warning appears every time.
Check:
hostname grep "$(hostname)" /etc/hosts
Fix: add the current hostname to the 127.0.0.1 line in /etc/hosts. Take a copy first so you can roll back.
sudo cp /etc/hosts /etc/hosts.bak sudo nano /etc/hosts
127.0.0.1 localhost myhost
Symptom: sudo: no tty present and no askpass program specified
Cause: a sudo command that asks for a password was run in an environment with no terminal, such as cron or a script.
Check: confirm whether the caller is a non-interactive context — cron, systemd, CI.
Fix: grant NOPASSWD in sudoers for that command alone, restricted by absolute path.
sudo visudo -f /etc/sudoers.d/deploy
deploy ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx
Symptom: 3 incorrect password attempts
Cause: the password was mistyped three times. sudo gives up after three failures.
Check: confirm you are typing your own password, not the root password. sudo asks for yours.
Fix: run sudo again and enter your own password. If you have forgotten it, ask another administrator to reset it with sudo passwd alice.
Completion Checklist
- [ ] Chose
sudo commandfor a single command,sudo -ifor extended work - [ ] Left the root shell with
exitonce the work was done - [ ] Edited
sudoersthroughvisudo - [ ] Restricted any
NOPASSWDentry to specific commands by absolute path - [ ] Checked what you are allowed to run with
sudo -l