How can I permit a user to run some commands with passwordless sudo – without breaking all other commands?

bellackn asked:

I am on a CIS-hardened RHEL 8 host on an AWS EC2 instance. My goal is to permit my user to run some commands with sudo passwordless (e.g. ls, cat, …), while other commands (like vi) should stay password-protected.

I have added the following line to /etc/sudoers.d/99-foo, which is being included by /etc/sudoers:

myuser ALL=(ALL) NOPASSWD: /usr/sbin/visudo,/usr/bin/ls

(I have just locked myself out, hence the visudo…)

This works just fine for the specified commands:

[[email protected] ~]$ sudo ls -l /var/log/httpd/access_log | wc -l

However, all other commands – which I still want to work with password protection! – fail now:

[[email protected] ~]$ sudo echo "hello stackexchange!"
[sudo] password for myuser:
Sorry, user myuser is not allowed to execute '/bin/echo hello stackexchange!' as root on myhost.

My answer:

In addition to the rule that allows passwordless sudo for specific commands, you also need some other sudo rule which allows your user to run ALL commands with sudo.

The default sudo config allows users in the wheel group to run ALL commands with sudo (after supplying a password) and users who should have such access should be placed in this group.

# usermod -aG wheel myuser

If the user is logged in when added to a group, they must log out and log back in before this change takes effect.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.