Change the SELinux Context of a File using chcon Command
Initial SELinux Context
Typically, the SELinux context of a file's parent directory determines its initial SELinux context.
The context of the parent directory is assigned to the newly created file. This works for commands like vim, cp, and touch. However, if a file is created elsewhere and the permissions are preserved, the original SELinux context will be unchanged.
The context of the parent directory is assigned to the newly created file. This works for commands like vim, cp, and touch. However, if a file is created elsewhere and the permissions are preserved, the original SELinux context will be unchanged.
Following command is used to check SELinux Context of a file.
ls -Zd /var/www/html
Changing the SELinux context of a file
There are two commands that are used to change the SELinux context of files: chcon and restorecon. The chcon command changes the context of the file to the context specified as an argument to the command. Often the -t option is used to specify only the type component of the context.
Now we will see the example:
[root@serverX]# mkdir /example
[root@serverX]# ls -Zd /example
drwxr -xr-x, root root unconfirned_u:object_r:default_t:s0 /example
[root@serverX]# chcon -t httpd_sys_context_t /example
[root@serverX]# ls -Zd /example
drwxr -xr-x. root root unconfined_u:object_r:httpd_sys_content_t:s0 /example
[root@serverX]# restorecon -v /example
restorecon reset /example context unconfined_u:object_r:httpd_sys_content_t:s0 -> unconfined_u:object_r:default_t:s0
[root@serverX]# ls -Zd /example
drwxr -xr-x. root root unconfined_u:object_r:default_t:s0 /example
restorecon applies the context defined by the SELinux policy to files and directories.
chcon command can change the SELinux context files, it shouldn't be used because the change my not persist.