How can I do an SELINUX filesystem relabel without rebooting first?

Skaperen asked:

I can touch the file /.autorelabel and reboot and during the initialization coming back up it will do the SELINUX relabel for me. But I want to do this in a different situation where the system has just been copied to a hard drive image. I can chroot to the originating file tree, or chroot to the just populated device image and run it. I just can’t find anything that says what to be run.

This image is being made into an AMI on AWS EC2, and contains CentOS 6.3. But the time it takes to relabel is too long (6 minutes or more). I want to move the relabel to the image build where the extra time is not an issue (because it happens once instead of every time an AMI is launched). I can make this relabel be the very last thing just before the filesystem is unmounted for the last time until it becomes an AMI and will launch. I just need to know what to call to do it.

I have searched man pages with no luck. I have searched system init scripts but where /.autorelabel is detected, it is unclear what is happening.

Documents like only tell how to do things that still really do the work after a reboot. I need to have the work doing BEFORE the “reboot” (unmount, build AMI, and launch ready to go).

The big point is … yes there will be a reboot … but I want the relabel work to be done before that so it won’t be done every time an AMI is launched (because it takes so long).

My answer:

If you’re copying files from one filesystem to another, you can:

  • If using cp, add the -c option to copy the SELinux context.
  • If using tar, add the --selinux option to copy the SELinux context.

This may save you some time by ensuring that the destination files have the expected context, assuming that the contexts are correct to begin with.

As for fixfiles, it’s a wrapper for restorecon, which is what I generally use. When /.autorelabel is present, the init script runs restorecon -p -r /, which prints the dots for six minutes, and then reboots afterward. I prefer -v for a verbose listing of the contexts which have changed, instead of -p. Either way, you should chroot into the filesystem before you run this.

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.