Welcome to Part 4 of the LFCS Certification - Phase 1 series! In previous posts, you learned about the root user, groups, and the su command. Now it's time to master sudo - the modern, safer, and more flexible approach to privilege escalation in Linux.
๐ฏ What You'll Learn: In this guide, you'll master:
- What sudo is and why it's safer than su
- Comprehensive sudo vs su comparison
- Basic sudo command syntax and usage
sudo -ifor interactive root shellsudo -svssudo -idifferences- The famous "sudo lecture" and what it means
- Default admin users on RedHat vs Ubuntu
- sudo password caching and timeout mechanism
- How sudo logging provides accountability
- sudo security features and benefits
- 20+ comprehensive practice labs
Series: LFCS Certification Preparation - Phase 1 (Post 4 of 52) Previous: Part 3 - Understanding the Root User and su Command Next: Part 5 - Creating and Managing sudo Configuration (/etc/sudoers)
What is sudo?
sudo stands for "superuser do" or "substitute user do". It allows authorized users to run commands as another user (typically root) without needing to know that user's password.
The Philosophy Behind sudo
sudo embodies the principle of "least privilege":
Key Characteristics of sudo
| Feature | Description | Benefit |
|---|---|---|
| Authentication | Uses YOUR password, not root's | No need to share root password |
| Scope | Executes single command | Automatic privilege drop |
| Logging | Every sudo command is logged | Full audit trail of who did what |
| Granularity | Can restrict specific commands | Fine-grained access control |
| Timeout | Caches credentials temporarily | Convenient but secure |
Why sudo is Safer Than su
Let's understand why sudo has become the preferred method for privilege escalation:
Security Advantages
1. No Root Password Sharing
# With su: Everyone needs root password
su -
Password: ****** # Root password shared with all admins
# With sudo: Use your own password
sudo command
[sudo] password for john: ****** # John's own password
2. Accountability
# With su: All actions appear as root
su -
useradd newuser # Log shows: root created user
exit
# With sudo: Clear attribution
sudo useradd newuser # Log shows: john ran useradd as root
3. Automatic Privilege Drop
# With su: Must remember to exit
su -
# ... doing admin work ...
# Oops, forgot to exit! Still root.
# With sudo: Privileges drop automatically
sudo command # Runs as root
whoami # Back to regular user automatically
4. Granular Control
# With su: All or nothing - full root access
su - # Now can do ANYTHING
# With sudo: Can limit specific commands
# User can run only systemctl restart httpd
# Cannot run other admin commands
Comparison Table: sudo vs su
| Aspect | sudo | su |
|---|---|---|
| Password Required | Your own password | Target user's (root) password |
| Access Type | Command-by-command | Full shell session |
| Privilege Duration | Single command (or cached 15 min) | Until you explicitly exit |
| Logging | Detailed: who, what, when | Basic: who became root |
| Granularity | Can limit to specific commands | All or nothing |
| Root Password | Not needed/shared | Must be shared |
| Revocation | Easy (remove from sudoers) | Hard (must change root password) |
| User Tracking | Excellent (every command logged) | Poor (all actions as root) |
| Security | Higher (principle of least privilege) | Lower (full root access) |
| Best For | Most tasks, production systems | Extended admin sessions, recovery |
โ For LFCS: Understand both sudo and su, but know that sudo is the modern best practice. The exam focuses on RedHat-based systems where sudo is the standard approach.
Basic sudo Usage
Let's learn the fundamental sudo command patterns.
Running a Single Command
Basic syntax:
sudo command [arguments]
Example: List root's home directory
# As regular user - fails
[centos9@centos ~]$ ls -l /root
ls: cannot open directory '/root': Permission denied
# With sudo - works!
[centos9@centos ~]$ sudo ls -l /root
[sudo] password for centos9: ******
total 16
-rw-------. 1 root root 999 Jul 20 15:35 anaconda-ks.cfg
drwxr-xr-x. 142 root root 8192 Oct 31 21:23 etc
What happened:
sudoprompts for YOUR password (not root's)- Checks if you're authorized (in wheel/sudo group)
- Runs the command as root
- Returns you to regular user after command completes
The Famous "sudo Lecture"
The first time you use sudo, you'll see this message:
[john@centos ~]$ sudo systemctl status sshd
We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:
#1) Respect the privacy of others.
#2) Think before you type.
#3) With great power comes great responsibility.
[sudo] password for john:
Why this message appears:
- Reminds users of their responsibility
- Only shown once per user
- Can be disabled (but shouldn't be!)
- A Unix tradition since sudo's creation
Common sudo Command Examples
1. Package installation:
# RedHat/CentOS
sudo dnf install nginx -y
# Ubuntu/Debian
sudo apt install nginx -y
2. Service management:
sudo systemctl restart sshd
sudo systemctl status httpd
sudo systemctl enable nginx
3. File editing:
sudo vi /etc/hosts
sudo nano /etc/hostname
4. User management:
sudo useradd newuser
sudo passwd newuser
sudo usermod -aG wheel newuser
5. Viewing logs:
sudo tail -f /var/log/messages
sudo cat /var/log/secure
sudo journalctl -xe
sudo Options: -i, -s, and More
sudo has several important options that change its behavior.
sudo -i: Interactive Login Shell
Usage:
sudo -i
What it does:
- Starts an interactive login shell as root
- Similar to
su - - Loads root's environment completely
- Changes to /root directory
- Runs /etc/profile and ~/.bash_profile
Example:
[centos9@centos ~]$ whoami
centos9
[centos9@centos ~]$ sudo -i
[sudo] password for centos9:
[root@centos ~]# whoami
root
[root@centos ~]# pwd
/root
[root@centos ~]# echo $USER
root
[root@centos ~]# exit
logout
[centos9@centos ~]$ whoami
centos9
sudo -s: Non-Login Shell
Usage:
sudo -s
What it does:
- Starts shell as root
- Does NOT load login environment
- Stays in current directory
- Preserves environment variables
Example:
[centos9@centos ~]$ pwd
/home/centos9
[centos9@centos ~]$ sudo -s
[root@centos centos9]# whoami
root
[root@centos centos9]# pwd
/home/centos9 # Still in user's directory!
[root@centos centos9]# exit
exit
[centos9@centos ~]$
sudo -u: Run as Different User
Usage:
sudo -u username command
Example:
# Run command as user 'apache'
sudo -u apache touch /var/www/html/test.txt
# Run command as user 'postgres'
sudo -u postgres psql
sudo -l: List Allowed Commands
Usage:
sudo -l
Example output:
[centos9@centos ~]$ sudo -l
[sudo] password for centos9:
User centos9 may run the following commands on centos:
(ALL) ALL
This shows what commands you're allowed to run with sudo.
Comparison: sudo -i vs sudo -s vs sudo su -
| Command | Shell Type | Directory | Environment |
|---|---|---|---|
| sudo -i | Login shell | /root | Root's environment |
| sudo -s | Non-login shell | Current directory | Current environment |
| sudo su - | Login shell | /root | Root's environment |
Best practice:
- Use
sudo commandfor single commands - Use
sudo -iif you need an interactive root shell - Avoid
sudo -s(incomplete environment) sudo su -works butsudo -iis cleaner
Default Admin Users: RedHat vs Ubuntu
Different distributions create different default administrative users during installation.
RedHat/CentOS/Fedora
During installation:
- Creates user you specify (e.g., "centos9")
- Automatically adds to wheel group
- Can use sudo immediately
Check:
[centos9@centos ~]$ id
uid=1000(centos9) gid=1000(centos9) groups=1000(centos9),10(wheel)
[centos9@centos ~]$ sudo whoami
[sudo] password for centos9:
root
Ubuntu/Debian
During installation:
- Creates user you specify (e.g., "ubuntu")
- Automatically adds to sudo group
- Can use sudo immediately
Check:
ubuntu@ubuntu:~$ id
uid=1000(ubuntu) gid=1000(ubuntu) groups=1000(ubuntu),27(sudo)
ubuntu@ubuntu:~$ sudo whoami
[sudo] password for ubuntu:
root
Key Differences
| Aspect | RedHat/CentOS | Ubuntu/Debian |
|---|---|---|
| Admin Group | wheel | sudo |
| Group GID | 10 | 27 |
| Root Account | Enabled by default | Disabled by default |
| su - root | Works (if you know password) | Doesn't work (no password set) |
| Philosophy | Root available, prefer sudo | sudo only, no direct root access |
๐ก Ubuntu Root Account: On Ubuntu, the root account exists but has no password set. You can only become root via sudo -i or sudo su -. This forces the use of sudo for all administrative tasks.
sudo Password Caching and Timeout
One of sudo's convenient features is password caching.
How Password Caching Works
When you first use sudo:
[centos9@centos ~]$ sudo systemctl status sshd
[sudo] password for centos9: ****** # Prompted for password
# ... output ...
[centos9@centos ~]$ sudo systemctl status httpd
# ... output ... # No password prompt!
[centos9@centos ~]$ sudo ls -l /root
# ... output ... # Still no password prompt!
What's happening:
- First
sudo: Password required - Password cached for 15 minutes (default)
- Subsequent
sudocommands: No password needed - After 15 minutes: Password required again
The Timeout Mechanism
Clearing the sudo Cache
Force sudo to forget your cached credentials:
sudo -k
Example:
[centos9@centos ~]$ sudo whoami
[sudo] password for centos9: ******
root
[centos9@centos ~]$ sudo whoami
root # No password needed
[centos9@centos ~]$ sudo -k # Clear cache
[centos9@centos ~]$ sudo whoami
[sudo] password for centos9: ****** # Password required again
root
When to use sudo -k:
- Before leaving your desk
- In shared/public workstations
- Security-conscious environments
- Scripts that shouldn't rely on cached credentials
Validating sudo Credentials
Refresh your sudo timestamp without running a command:
sudo -v
Example:
[centos9@centos ~]$ sudo -v
[sudo] password for centos9: ******
[centos9@centos ~]$ sudo whoami
root # No password needed (just validated)
sudo Logging and Accountability
One of sudo's major security advantages is comprehensive logging.
Where sudo Logs Go
RedHat/CentOS:
sudo tail -f /var/log/secure
Ubuntu/Debian:
sudo tail -f /var/log/auth.log
Example sudo Log Entries
Nov 3 18:52:21 vm1 sudo: centos9 : TTY=pts/0 ; PWD=/home/centos9/LFCS ; USER=root ; COMMAND=/bin/ls -l /root
Nov 3 18:52:41 vm1 sudo: centos9 : TTY=pts/0 ; PWD=/home/centos9/LFCS ; USER=root ; COMMAND=/bin/bash -i
Nov 3 18:53:44 vm1 sudo: centos9 : TTY=pts/0 ; PWD=/home/centos9/LFCS ; USER=root ; COMMAND=/bin/su -
Breaking down a log entry:
Nov 3 18:52:21 vm1 sudo: centos9 : TTY=pts/0 ; PWD=/home/centos9/LFCS ; USER=root ; COMMAND=/bin/ls -l /root
โ โ โ โ โ โ โ
โ โ โ โ โ โ โโ Command executed
โ โ โ โ โ โโ Ran as this user (root)
โ โ โ โ โโ From this directory
โ โ โ โโ From this terminal
โ โ โโ Username who ran sudo
โ โโ Hostname
โโ Timestamp
Viewing Recent sudo Activity
Show last 20 sudo commands:
sudo grep sudo /var/log/secure | tail -20
Show sudo commands by specific user:
sudo grep "sudo.*john" /var/log/secure
Show failed sudo attempts:
sudo grep "NOT allowed" /var/log/secure
Example failed attempt log:
Nov 3 19:24:03 vm1 sudo: labuser : user NOT in sudoers ; TTY=pts/0 ; PWD=/home/labuser ; USER=root ; COMMAND=/usr/sbin/useradd bob
This shows user labuser tried to run useradd but was denied because they're not in sudoers.
โ For LFCS: Understanding sudo logs is crucial for troubleshooting access issues and security auditing. Know where logs are located on both RedHat and Debian systems.
๐งช Practice Labs
Time to master sudo with hands-on practice!
Lab 1: First sudo Command (Beginner)
-
Check if you can use sudo:
sudo -l -
Run a simple sudo command:
sudo whoami # Should output: root -
Check your groups:
id groups -
Verify you're in wheel (RedHat) or sudo (Ubuntu) group
-
Try accessing root's home:
ls -l /root # Fails sudo ls -l /root # Works!
Lab 2: sudo Password Caching (Beginner)
-
First sudo command (requires password):
sudo whoami # Enter password -
Immediate second command (no password):
sudo ls /root # No password needed -
Wait 1 minute, try again:
sleep 60 sudo cat /etc/shadow # Still no password (within 15 min window) -
Clear sudo cache:
sudo -k -
Try again (password required):
sudo whoami # Password required again
Lab 3: Comparing sudo Options (Intermediate)
-
Test
sudo -i:pwd echo $USER sudo -i pwd # Now in /root echo $USER # Now root exit -
Test
sudo -s:pwd sudo -s pwd # Still in your directory echo $USER # May still show your username exit -
Document the differences you observe
Lab 4: Package Installation with sudo (Intermediate)
-
Try without sudo (fails):
dnf install tree # Or: apt install tree # Should fail: Permission denied -
Try with sudo (works):
sudo dnf install tree -y # Or: sudo apt install tree -y -
Verify installation:
which tree tree --version
Lab 5: Service Management (Intermediate)
-
Check service status (works without sudo):
systemctl status sshd -
Try to restart without sudo (fails):
systemctl restart sshd # Fails: Authentication required -
Restart with sudo (works):
sudo systemctl restart sshd -
Check status again:
systemctl status sshd
Lab 6: Viewing Logs with sudo (Intermediate)
-
Try to view secure log without sudo:
cat /var/log/secure # Or on Ubuntu: cat /var/log/auth.log # Should fail: Permission denied -
View with sudo:
sudo tail -20 /var/log/secure # Or: sudo tail -20 /var/log/auth.log -
Follow logs in real-time:
sudo tail -f /var/log/secure # Press Ctrl+C to stop -
Search for your sudo commands:
sudo grep "sudo.*$(whoami)" /var/log/secure | tail -10
Lab 7: sudo as Different User (Advanced)
-
Create test file as yourself:
touch /tmp/myfile ls -l /tmp/myfile -
Create file as apache user:
sudo -u apache touch /tmp/apachefile ls -l /tmp/apachefile # Owner: apache -
Run command as postgres (if installed):
sudo -u postgres whoami # Output: postgres
Lab 8: sudo -l to Check Permissions (Advanced)
-
List your sudo privileges:
sudo -l -
Analyze the output:
User centos9 may run the following commands on centos: (ALL) ALL -
Try as different user (if available):
sudo -l -U testuser
Lab 9: Investigating sudo Logs (Advanced)
-
Run several sudo commands:
sudo whoami sudo ls /root sudo systemctl status sshd -
Check logs for your activity:
sudo grep "sudo.*$(whoami)" /var/log/secure | tail -5 -
Find all sudo usage today:
sudo grep "$(date +%b\ %d)" /var/log/secure | grep sudo
Lab 10: Creating Admin User (Advanced)
-
Create new user:
sudo useradd -m adminuser sudo passwd adminuser -
Add to wheel/sudo group:
# RedHat: sudo usermod -aG wheel adminuser # Ubuntu: sudo usermod -aG sudo adminuser -
Switch to new user and test:
su - adminuser sudo whoami # Should work! exit
Lab 11-15: Real-World Scenarios
Lab 11: System Update via sudo
# RedHat
sudo dnf check-update
sudo dnf update -y
# Ubuntu
sudo apt update
sudo apt upgrade -y
Lab 12: File Editing
# Create backup first
sudo cp /etc/hosts /etc/hosts.backup
# Edit file
sudo vi /etc/hosts
# Or: sudo nano /etc/hosts
# Verify changes
sudo cat /etc/hosts
Lab 13: User Management Script
Create script using sudo:
#!/bin/bash
# manage-users.sh
echo "Creating users..."
sudo useradd user1
sudo useradd user2
echo "Setting passwords..."
echo "password123" | sudo passwd --stdin user1
echo "password123" | sudo passwd --stdin user2
echo "Adding to groups..."
sudo usermod -aG developers user1
sudo usermod -aG developers user2
echo "Done!"
Lab 14: Emergency System Check
# Check disk space
sudo df -h
# Check memory
sudo free -m
# Check top processes
sudo top -bn1 | head -20
# Check recent logins
sudo last | head -10
# Check failed login attempts
sudo grep "Failed password" /var/log/secure | tail -10
Lab 15: Network Configuration
# View network config
sudo ip addr show
# View routing table
sudo ip route show
# View firewall rules
sudo iptables -L -n -v
Lab 16-20: Advanced Challenges
Lab 16: Time how long sudo password cache lasts (use a loop)
Lab 17: Create a script that automatically clears sudo cache when done
Lab 18: Compare execution times: sudo command vs su -c "command"
Lab 19: Analyze sudo logs to find the most frequently used sudo commands
Lab 20: Create monitoring script to alert on failed sudo attempts
๐ Best Practices
โ sudo Best Practices
-
Prefer sudo over su for most tasks
- Better security through accountability
- No need to share root password
- Automatic privilege dropping
-
Use specific commands, not sudo -i for everything
# Good: Specific command sudo systemctl restart httpd # Acceptable: Multiple related tasks sudo -i # ... do several admin tasks ... exit -
Clear sudo cache when leaving workstation
sudo -k -
Check what you're allowed to do
sudo -l # Know your permissions -
Read command carefully before sudo
- Double-check paths
- Verify command syntax
- Consider consequences
-
Don't use sudo for regular user tasks
# Wrong sudo cp file.txt ~/documents/ # Right (no sudo needed) cp file.txt ~/documents/ -
Monitor sudo logs regularly
sudo tail -50 /var/log/secure -
Use sudo -v to extend timeout without running commands
sudo -v # Refresh credentials -
Be cautious with sudo -i
- Only use when needed for multiple commands
- Exit immediately when done
- Easy to forget you're root
-
Educate users about sudo responsibility
- The "sudo lecture" is there for a reason
- With sudo access comes accountability
- All commands are logged
๐จ Common Pitfalls to Avoid
โ Mistakes to Avoid
-
Using sudo for non-admin tasks
sudo mkdir ~/myfolder # WRONG - don't need sudo mkdir ~/myfolder # RIGHT -
Forgetting you're in sudo -i shell
- Easy to run dangerous commands
- Visual prompt should show # vs $
- Set colored prompt for root
-
Assuming sudo will always work
- Check
sudo -lfirst - Not all users have sudo access
- May be limited to specific commands
- Check
-
Not checking logs after problems
- Logs show why sudo failed
- Check /var/log/secure or /var/log/auth.log
- Look for "NOT allowed" messages
-
Relying too heavily on password caching
- Creates complacency
- 15-minute window is security risk if you walk away
- Always
sudo -kbefore leaving
-
Using sudo in pipes incorrectly
# Wrong - sudo doesn't apply to tee echo "text" > /etc/file # Fails # Right - pipe through sudo tee echo "text" | sudo tee /etc/file -
Not understanding sudo -s vs sudo -i
sudo -shas incomplete environment- Prefer
sudo -ifor interactive shells - Or just use
sudo command
-
Sharing sudo passwords/credentials
- Everyone should have their own account
- Defeats accountability purpose
- Revocation becomes impossible
-
Not testing in safe environment first
- sudo commands are powerful
- Test in VM or dev system first
- Production mistakes are costly
-
Ignoring the sudo lecture message
- It's not just decoration
- Real reminder of responsibility
- Think before you sudo
๐ Command Cheat Sheet
Basic sudo Commands
# Run command as root
sudo command
# Interactive root shell (login)
sudo -i
# Non-login shell
sudo -s
# Run as specific user
sudo -u username command
# List allowed commands
sudo -l
# Validate credentials
sudo -v
# Clear cached credentials
sudo -k
# Exit sudo shell
exit
Common sudo Patterns
# Package management (RedHat)
sudo dnf install package
sudo dnf update -y
sudo dnf remove package
# Package management (Ubuntu)
sudo apt update
sudo apt install package
sudo apt upgrade -y
# Service management
sudo systemctl start service
sudo systemctl stop service
sudo systemctl restart service
sudo systemctl status service
sudo systemctl enable service
# User management
sudo useradd username
sudo passwd username
sudo usermod -aG groupname username
sudo userdel username
# File operations
sudo cp file /etc/
sudo mv file /etc/
sudo rm /etc/file
sudo chmod 644 /etc/file
sudo chown root:root /etc/file
# Viewing protected files
sudo cat /etc/shadow
sudo less /var/log/secure
sudo tail -f /var/log/messages
# Editing system files
sudo vi /etc/hosts
sudo nano /etc/hostname
sudo Logging and Monitoring
# View sudo logs (RedHat)
sudo tail -f /var/log/secure
sudo grep sudo /var/log/secure
# View sudo logs (Ubuntu)
sudo tail -f /var/log/auth.log
sudo grep sudo /var/log/auth.log
# Show recent sudo activity
sudo grep sudo /var/log/secure | tail -20
# Show failed sudo attempts
sudo grep "NOT allowed" /var/log/secure
# Show sudo activity by user
sudo grep "sudo.*username" /var/log/secure
# Show sudo activity today
sudo grep "$(date +%b\ %d)" /var/log/secure | grep sudo
Checking sudo Access
# Am I in wheel/sudo group?
id | grep -E 'wheel|sudo'
groups | grep -E 'wheel|sudo'
# What can I run with sudo?
sudo -l
# Test sudo access
sudo whoami # Should output: root
# Check other user's sudo access (requires root)
sudo -l -U username
๐ฏ Key Takeaways
โ Remember These Points
- sudo = safer than su - Uses your password, not root's
- Principle of least privilege - Only elevated for specific commands
- Everything is logged - Full accountability of who did what
- Password caching - 15-minute timeout (default) for convenience
- sudo -i for shell - Like su -, starts login shell as root
- sudo -s less useful - Non-login shell, incomplete environment
- wheel group (RedHat) - Members can use sudo
- sudo group (Ubuntu) - Members can use sudo
- sudo -k clears cache - Use before leaving workstation
- sudo -l shows permissions - Know what you're allowed to do
- Logs in /var/log/secure - RedHat/CentOS location
- Logs in /var/log/auth.log - Ubuntu/Debian location
- No root password needed - Major security advantage
- Granular control possible - Can limit specific commands
- Industry best practice - Modern standard for Linux administration
๐ What's Next?
Now that you've mastered the basics of sudo, you're ready to learn about sudo configuration and creating custom privilege policies!
In the next post (Part 5), we'll cover:
- Understanding /etc/sudoers file structure
- Using visudo safely (never edit sudoers directly!)
- Basic sudoers syntax and rules
- Granting specific commands to users
- Restricting dangerous commands (like passwd root)
- Creating command aliases
- Setting sudo defaults (timeout, logging)
- sudoers best practices
- Comprehensive labs for custom sudo policies
Coming Up in Phase 1:
- Part 6: Linux Command Basics (case sensitivity, options)
- Part 7: Essential Navigation Commands (ls, pwd, cd, whoami)
- Part 8: The touch Command and File Creation
- And 44 more posts!
๐ Congratulations! You've completed Part 4 of the LFCS Certification series. You now understand sudo, why it's safer than su, and how to use it effectively for privilege escalation.
Practice is essential! Complete the 20 practice labs to build confidence with sudo. Understanding sudo is fundamental to modern Linux system administration and is heavily tested in the LFCS exam.
Remember: sudo is not just a tool - it's a philosophy of security through accountability!
๐ฌ Discussion
I'd love to hear about your experience:
- Do you prefer sudo or su for your daily admin work?
- What's your most frequently used sudo command?
- Have you ever been locked out due to sudoers misconfiguration?
- How do you handle sudo in production environments?
Connect with me:
This is Part 4 of 52 in the LFCS Certification - Phase 1 series. Stay tuned for Part 5: Creating and Managing sudo Configuration!

