Grant one command, then watch it become root
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
- Edit sudoers with
visudo-- always this, never a plain editor -- and grant operator the ability to run only/usr/bin/systemctlas root, with no password. - As operator, confirm
sudo -llists exactly that, and thatsudo systemctl restart somethingworks whilesudo cat /etc/shadowis refused. - Now grant a command with a shell escape instead: allow
/usr/bin/lessvia sudo. As operator, runsudo less /etc/motd, then from inside less type!sh. Observe that you now have a root shell. - 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. - Block the escape with the
NOEXECtag on the sudoers line and confirm!shno longer works. - 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. - Put a custom rule in
/etc/sudoers.d/operatorand 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.