Tuesday, September 25, 2018

Fixing a corrupt /etc/sudoers file in Linux VM in Azure

I was editing the /etc/sudoers file with nano on a linux VM (RHEL 7.5) in Azure trying to remove or disable being prompted for a password every time I sudo.

I added the following to the file

root        ALL=(ALL:ALL) ALL
myadminuser     ALL=(ALL:ALL) ALL     NOPASSWD: ALL

Apparently that does not follow the correct syntax so immediately after I was not able to sudo. Below is the error meesage:

[myadminuser@MYSERVER ~]$ sudo reboot
>>> /etc/sudoers: syntax error near line 93 <<<
sudo: parse error in /etc/sudoers near line 93
sudo: no valid sudoers sources found, quitting
sudo: unable to initialize policy plugin


Since on the Azure VMs you don't have the root password, then you're stuck as the regular user do not have permissions to edit the sudoers file and you can't sudo to root.

You could mount the VM disk to another VM and then edit the file that way, but that is cumbersome.

Fix:

From the Azure portal start Cloud CLI, choose Powershell

Run the following command to make /etc/sudoers editable by master

az vm run-command invoke --resource-group YOUR_RESOURCE_GROUP --name YOURVM --command-id RunShellScript --scripts "chmod 446 /etc/sudoers"

This gives the regular user permission to edit the file

with nano or VI undo the changes (i just deleted the NOPASSWD: ALL): 

nano /etc/sudoers (no sudo since you have access)

after edit, run the below command to configure default access to file.

az vm run-command invoke --resource-group YOUR_RESOURCE_GROUP --name YOURVM --command-id RunShellScript --scripts "chmod 440 /etc/sudoers"

I got the fix from the following link. Note that the syntax has changed a bit.

The useful thing about this command is that you can execute any command as root on your VMs as long as you have access to the Azure portal.

How to edit /etc/sudoers:

To ensure that you don't introduce the wrong syntax in the file, use the command to edit:

visudo

This will open the file using vi editor and if you use wrong syntax you'll get a warning/error.

See this link for a quick guide using vi editor

Update: 2018.11.07: On RHEL 7.5 and with visudo, the below lines work, meaning that with the command:
# sudo su -
you're not prompted for passwd

root    ALL=(ALL)       ALL
myadminuser    ALL=(ALL)       NOPASSWD: ALL