Sudo and privilege escalation on Linux

Topic: Servers linux

Summary

Grant and revoke sudo access: add users to the sudo or wheel group, or add rules in /etc/sudoers and /etc/sudoers.d. Use visudo to avoid syntax errors. Restrict commands or require a password so only authorized users run as root.

Intent: How-to

Quick answer

  • Add user to sudo group: usermod -aG sudo user (Debian) or usermod -aG wheel user (RHEL); user must log out and back in for group to apply.
  • Custom rule: visudo or add file in /etc/sudoers.d/ (no extension .bak); syntax: user ALL=(ALL) ALL or user ALL=(ALL) NOPASSWD: /path/to/cmd.
  • Revoke: remove user from sudo/wheel group or remove/comment the line in sudoers; verify with sudo -l -U user.

Prerequisites

Steps

  1. Grant sudo via group

    usermod -aG sudo alice (Debian/Ubuntu) or usermod -aG wheel alice (RHEL); groups alice; have alice log out and back in; alice runs sudo whoami to test.

  2. Add a sudoers rule

    sudo visudo or create /etc/sudoers.d/alice with: alice ALL=(ALL) ALL; or alice ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx; visudo -c to check syntax.

  3. Restrict to specific commands

    Rule: user ALL=(ALL) NOPASSWD: /path/cmd1, /path/cmd2; avoid wildcards that allow shell escape; use full paths.

  4. Revoke sudo

    gpasswd -d user sudo (or wheel); or remove the file in sudoers.d or comment the line; sudo -l -U user should show no sudo permission.

Summary

You will grant sudo by adding users to the sudo/wheel group or by adding sudoers rules, optionally restrict to specific commands, and revoke by removing the user from the group or the rule. Use this to give operators root access without sharing the root password.

Prerequisites

  • Root access; the username to grant or revoke.

Steps

Step 1: Grant sudo via group

sudo usermod -aG sudo alice
groups alice

User must start a new login session (log out and back in, or su - alice).

Step 2: Add a sudoers rule

sudo visudo
# Add: alice ALL=(ALL) ALL
# Or:
echo 'alice ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx' | sudo tee /etc/sudoers.d/alice
sudo visudo -c

Step 3: Restrict to specific commands

Use full paths and avoid broad wildcards. Example: alice ALL=(ALL) NOPASSWD: /usr/bin/systemctl status nginx, /usr/bin/systemctl restart nginx

Step 4: Revoke sudo

sudo gpasswd -d alice sudo
# or
sudo rm /etc/sudoers.d/alice
sudo -l -U alice

Verification

  • User can run allowed sudo commands; after revoke, sudo prompts for password and is denied or not available.

Troubleshooting

visudo: syntax error — Fix the line (no duplicate, correct format); restore from backup if you broke sudoers; use root shell if everyone is locked out.

User still has sudo after removing from group — Check /etc/sudoers and /etc/sudoers.d for a rule with that user; remove it.

Next steps

Continue to