SELinux reset root password

Jorge Heleno asked:

Disclaimer: This question is not to solve the problem of changing root password while SELinux is active because there are a lot of guides to solve that already. This is more of how SELinux does that internally.

I’m a recent user of SELinux but lately I’ve been more in touch with it. There was a moment when someone asked me how I could reset root password in case of forgetting it.
So I booted my CentOS, edited grub entry to something like

linux16 <kernel_location> root=/dev/mapper/centos-root rw init=/bin/bash

I ran passwd and afterwards ran sync and forced reboot.
After reboot, logging in with the new password was rejected as well as with the old of course.
Rebooted again and passed the kernel the parameter to disable SELinux (selinux=0). Tried logging in with the new password and it worked.
Afterwards I forced a fs auto relabel (via the file .autorelabel) and with SELinux active it was now possible to log in.

My question is: why does happen? Why does relabeling affect log in when there was merely a change of password and not of users or objects?

Thank you for your attention.

TL;DR: Usual root password reset doesn’t work in SELinux. Why?

Edit: This was tested on a virtual machine running CentOS7 with KVM as hypervisor.

My answer:

I was able to duplicate this issue in a freshly installed CentOS 7.5 system.

Here is what is happening:

When you boot with init=/bin/bash there are two issues you may run into:

  • The root filesystem may be mounted readonly. In this case passwd will complain of an Authentication token manipulation error.
  • The SELinux policy may not be loaded. In this case passwd will appear to succeed, but nothing will happen, and you will have the problem described in the original question above.

To change the root password on RHEL/CentOS 7, you therefore need to follow this process:

  1. Add init=/bin/bash to the end of the kernel command line in grub, as you previously did.
  2. At the bash prompt, load the SELinux policy with /usr/sbin/load_policy -i.
  3. Mount the root filesystem read-write with mount -o remount,rw /.
  4. Now change the password, and it will succeed. passwd root
  5. Remount the filesystem readonly to commit changes and have a clean filesystem on next boot with mount -o remount,ro /.
  6. Exit the shell or restart the system with exec /sbin/init 6.

Now you can log in with the changed root password.

A longer explanation of this procedure is available from Red Hat (subscription required).

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.