If you lose the password of a normal user, you can always reset it as root. But if you lost the root password it is a little more complicated. But not impossible.
Boot to recovery kernel
First we need to reboot the machine. Then once you see the Grub-menu quickly press any arrow key to break the countdown for the automatic boot.
Next we need to look at the present kernels. One of them (usually the last one) has recovery
in its name.
Use the arrow-keys to hover over it and the press e
to edit this grub-entry.
You will see a list of parameters, but no worries, you don’t have to understand what they do.
Look for the line starting with linux
and add the parameter rd.break
at the end of the line.
Lastly press ctrl + x
to boot with these parameters.
rd.break
will tell the kernel to pause the boot-process once the initial ramdisk is loaded. It will then ask you for a password to enter maintenance mode. Usually you would need your root password to this, but since we are using the recovery kernel we can just press enter
and get a shell.
Mount the Filesystem
By default the recovery kernel will mount its filesystem in read-only mode, but since we want to change the password, we need to remount it as read-write. Keep in mind that the root-fs is not mounted at /
but at /sysroot
, since /
is already occupied by the initram disk.
$ mount -o remount,rw /sysroot
Chroot into Sysroot
Next we need to change the root of the filesystem into /sysroot
. That way the kernel will behave as if /sysroot
was mounted at /
without unmounting our initram disk.
$ chroot /sysroot
Change Password
Now we can use our system as we are used to and reset our password with passwd
.
$ passwd
SELinux
Since the recovery kernel only loads needed parts of the operating system, services like selinux are not present.
With the passwd
command we changed the /etc/shadows
file, which would usually be relabeled by selinux once it is written. But since selinux is not running, the file now has the wrong context and could cause problems on the next boot.
Luckily it is easy to tell selinux to relabel the whole filesystem at the next boot.
Just create the file /.autorelabel
.
$ touch /.autorelabel
The next boot will take slightly longer since selinux will scan the entire filesystem, but there will be no errors because of wrong file-contexts.
Reboot
Lastly we can reboot our system with ctrl + d
.
Once it is rebooted we can log in with the new root-password.