There may come a time in your day to day activities where you need access to a RHEL/CentOS server or workstation and you do not have the root password.  How do you go about changing a password, when you need root access to change passwords.  Fortunately there is a method which is fairly easy that allows you to reset the root password.  You do need physical access to the server however, so this can not be done via SSH or any other remote method.

Reset unknown root password adding rd.break to grub2 menuWe first need to reboot the server so we can get to the grub2 boot menu.  Once the menu is up just press the ‘E‘ key (for edit).  This will bring up all the boot options for you.  Move the cursor down to the end of the line starting with linux16.  At the end of the line you will want to type in rd.break.  This will break you into the boot process very early on and allow you to perform the following tasks.

 

Once you are at the prompt you will want to enter the following commands:

Reset unknown root password with mount, chroot, passwd, and selinuxTo explain the previous steps further, the mount command is to get our root partition in a Read / Write condition.  Without doing this we won’t be able to write to the /etc/shadow file and update our root password.

The chroot command changes our root path from /sysroot to /, this enables /etc/shadow to be in the correct path, instead of /sysroot/etc/shadow.  Without doing this the passwd command will not work properly.

Now we can issue the standard passwd command and change the password for root.

Our next steps deal with SELinux.  The context of the shadow file will be wrong as SELinux has not been loaded yet by using rd.break.  So we have to let SELinux know we made this change and configure it properly.  There are two ways of actually doing this.  You can create an empty file on the root with touch /.autorelable.  After the reboot SELinux will see this hidden file in the root partition and proceed to relabel every file on the system.  Depending on how large your system is and how many files there are, this could take some time.  A quicker method would be to just relabel the file we changed.  This is where load_policy -i and chcon -t shadow_t /etc/shadow come into play.

Finally we enter Control D twice.  The first to exit from our chroot, and the second to exit from the rd.break and continue the boot process.  At which point we can then login to the system with our new root password and gain access to  the system we previously did not have access to.

If you have any questions or comments, please feel free to reach out.

Cheers,

Ivan Windon

 

Leave a Reply

Your email address will not be published. Required fields are marked *

four + 11 =