Recovering the root password is a trivial task while still logged in as an administrator or a user with full sudo access, but is slightly more involved when an administrator is not logged in. In the latter situation, the administrator could boot from a Live CD, mount the root ﬁle system from there, and edit /etc/shadow. Administrators should also be able to perform root password recovery without the use of external media.
On CentOS/RHEL 7, it is possible to have the scripts that run from the initramfs pause at certain points, provide a root shell, and then continue when that shell exits. While this is mostly meant for debugging, it can also be used to recover a lost root password:
1. Reboot the system. Interrupt the boot loader countdown by pressing any key.
2. Move the cursor to the entry that needs to be booted.
3. Press e to edit the selected entry. Move the cursor to the kernel command line (the line that starts with linux16.
4. Append rd.break (this will break just before control is handed from the initramfs to the actual system).
5. Press Ctrl+x to boot with the changes.
At this point, a root shell will be presented, with the root ﬁle system for the actual system mounted read-only on /sysroot.
To recover the root password from this point, use the following procedure:
1. Remount /sysroot as read-write.
# switch_root:/# mount -o remount,rw /sysroot
2. Switch into a chroot jail, where /sysroot is treated as the root of the ﬁle system tree.
# switch_root:/# chroot /sysroot
3. Set a new root password
# sh-4.2# passwd root
4. Make sure that all unlabeled ﬁles (including /etc/shadow at this point) get relabeled during boot.
# sh-4.2# touch /.autorelabel
5. Type exit twice. The ﬁrst will exit the chroot jail, and the second will exit the initramfs debug shell.
At this point, the system will continue booting, perform a full SELinux relabel, then reboot again.