The chcon command helps to change the SELinux context or TYPE of what will most often be a single or perhaps sometimes a few files that can be referenced easily together with some form of a wildcard. chcon along with semanage and restorecon can be used to fix an incorrect SELinux context. You can use chcon command in 2 ways to fix or change the SELinux context.

Manually way of specifying the correct context

In this way, we can use the -t option to change the context of the file. This method of modifying the context of the file is not recommended, as errors can happen while using it.

# chcon -t httpd_sys_content_t index.html

You can see in the ‘ls -Z’ output that the command was successful.

# ls -Z
-rw-rw-r--. apacheuser apacheuser unconfined_u:object_r:httpd_sys_content_t:s0 index.html

Reference file with proper context

The other way to use chcon is to reference a file that has the proper context.

# chcon --reference some_file.html index.html

So, I used the –reference option and specified the file that I wanted to use as a reference. The file that I wanted to change is listed at the end of the command.

Examples of using chcon command

1. To change a type of a web directory

# chcon -R -t httpd_sys_content_t /web/

2. To change a security context by using the reference file:

# chcon --reference=/tmp/file2 /tmp/file2

3. To set security context on files recursively:

# chcon -R httpd_sys_content_t /web/

4. To change files user security context:

5. To change files role security context:

# chcon -u object_r /file

6. To change files type security context:

# chcon -u admin_home_t /file

7. To change files level security context: