Starting from CentOS/RHEL 7, resetting of root password has slightly changed than its earlier versions. Let see in this post how we can recover a lost root password on a CentOS/RHEL 8 machine.
Breaking Boot Sequence
1. Reboot the system and interrupt the boot loader sequence 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 linux, it looks like the below output:
4. Append rd.break options in the end of the kernel command line. This will break just before control is handed from the initramfs to the actual system.
5. Press “Ctrl+x” and reboot the system. At this point, a root shell will be presented, with the root file system for the actual system mounted read-only on /sysroot.
Resetting root Password
To recover the root password from this point, use the following procedure.
1. Verify if the the root filesystem is mounted as read-only at the ‘/sysroot’ directory:
switch_root:/# mount | grep -i sysroot
2. Remount /sysroot as read-write:
switch_root:/# mount -o remount,rw /sysroot
3. Switch into a chroot jail, where /sysroot is treated as the root of the file system tree:
switch_root:/# chroot /sysroot sh-4.4#
4. Set a new root password here:
# passwd root
You can ignore the warning here for the less complicated password.
Rebel SELinux
SELinux is not yet enabled at this point, so any new files being created will not have an SELinux context assigned to them. Keep in mind that some tools (such as passwd) first create a new file, then move it in place of the file they are intended to edit, effectively creating a new file without an SELinux context
1. Make sure that all unlabeled files (including /etc/shadow at this point) get relabeled during boot.
sh-4.2# touch /.autorelabel
2. Type exit twice. The first 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.