RHEL6 – Using Semanage and Restorecon to Modify SELinux File Contexts

Potty TrainingOk, how to keep this simple? Lets see…

Semanage:

Ok, semanage, when used with the fcontext argument, is used to define SELinux file contexts for file. It basically adds the new definition to the file,  /etc/selinux/targeted/contexts/files/file_contexts.

For example lets say that I create a new file called /root/foobar.

Using the command below I can see the default context that is assigned to a file created in /root

# ls -lZ foobar
-rw-r–r–. root root unconfined_u:object_r:admin_home_t:s0 foobar

Now lets say that I want to change the context of this file to public_content_t.  The first step to accomplish this is to define its new context.

# semanage fcontext -a -t public_content_t /root/foobar

Restorecon:

Now that the context type is defined we need to actually modify the current context of our file. So now you run restorecon against the file to actually make the change. Note: use -v for verbose.

# restorecon -v /root/foobar

restorecon reset /root/foobar context unconfined_u:object_r:admin_home_t:s0->unconfined_u:object_r:public_content_t:s0

Chcon:

There is also a command called chcon, that can also be used to change the defined context for a file. However I advise against using it as changes made using chcon will not survive a filesystem relabel. What is a filesystem relabel? Well according to wiki.centos.org, a relabel is defined below.

“Sometimes it is necessary to relabel the complete filesystem although this should only be necessary when enabling SELinux after it has been disabled or when changing the SELinux policy from the default targeted policy to strict.”

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.