SELinux reset root password
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.
Solution 1:
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 anAuthentication token manipulation error
.This is pretty obvious: If the filesystem is not mounted read-write, it is not possible to write to it.
-
The SELinux policy may not be loaded. In this case
passwd
will successfully change the password, but you will have the problem described in the original question above: no one will be able to log in.Password hashes are stored in the
/etc/shadow
file. This file normally has the SELinux typeshadow_t
. However, changing the file while no SELinux policy is loaded causes the SELinux type to be removed from the file, leaving it asunlabeled_t
. Thus, services which try to read the file to authenticate logins are no longer able to read it.
To change the root password on RHEL/CentOS 7, you therefore need to follow this process:
- Add
init=/bin/bash
to the end of the kernel command line in grub, as you previously did. - At the bash prompt, load the SELinux policy with
/usr/sbin/load_policy -i
. - Mount the root filesystem read-write with
mount -o remount,rw /
. - Now change the password, and it will succeed.
passwd root
- Remount the filesystem readonly to commit changes and have a clean filesystem on next boot with
mount -o remount,ro /
. - 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).