Grant one command, then watch it become root

short · 30 min · Objective 3.3

Task

Configure sudo to allow a user one specific command, then demonstrate that if that command has a shell escape you have granted full root. Learn to edit sudoers safely, and see why the file's own validation matters.

Steps

  1. Edit sudoers with visudo -- always this, never a plain editor -- and grant operator the ability to run only /usr/bin/systemctl as root, with no password.
  2. As operator, confirm sudo -l lists exactly that, and that sudo systemctl restart something works while sudo cat /etc/shadow is refused.
  3. Now grant a command with a shell escape instead: allow /usr/bin/less via sudo. As operator, run sudo less /etc/motd, then from inside less type !sh. Observe that you now have a root shell.
  4. Confirm the root shell with id, then leave it, and state the lesson: a NOPASSWD grant on any command with a shell escape is a grant of root.
  5. Block the escape with the NOEXEC tag on the sudoers line and confirm !sh no longer works.
  6. Break sudoers deliberately with a syntax error, using visudo, and observe that visudo refuses to save it. Then understand why editing the file directly would have been dangerous.
  7. Put a custom rule in /etc/sudoers.d/operator and confirm a filename containing a dot is silently ignored.

Verify

sudo -l -U operator | grep -i systemctl
su - operator -c 'sudo -n cat /etc/shadow' 2>&1 | grep -qi 'not allowed' && echo "scope holds"
visudo -c                                   # syntax OK
ls /etc/sudoers.d/                          # no dotted filenames

visudo -c validating the whole configuration is the check to run after any sudoers change. The scope test must show that a command you did not grant is refused -- if it is not, the rule is broader than you think.

Notes

The shell-escape lesson generalises well beyond less: vim, find, awk, more and almost anything with a ! or -exec gives the same result. Grant specific commands with fixed arguments, add NOEXEC where a shell escape is possible, and never assume "just this one command" is a small grant.