CentOS / RHEL: Change / Copy File SELinux Security Context Command

In CentOS and Red Hat Enterprise Linux (RHEL), you can change or copy the SELinux security context of a file using the chcon or semanage command.

The chcon command is used to change the SELinux security context of a file, and it has the following syntax:

chcon <context> <file>

For example, to change the SELinux security context of a file /var/www/html/index.html to httpd_sys_content_t, you can use the following command:

chcon -t httpd_sys_content_t /var/www/html/index.html

The semanage command is used to manage the SELinux policy, including changing the SELinux security context of files. To copy the SELinux security context of a file to another file, you can use the semanage fcontext command with the -a option, which adds a new entry to the SELinux policy:

semanage fcontext -a -t <context> <file>

For example, to copy the SELinux security context of the file /var/www/html/index.html to the file /var/www/html/example.html, you can use the following command:

semanage fcontext -a -t $(ls -Z /var/www/html/index.html | awk '{print $3}') /var/www/html/example.html

Then, you can use the restorecon command to apply the new policy:

restorecon /var/www/html/example.html

Note that the chcon and semanage commands should be used with care, as incorrect usage can result in unexpected behavior or security problems. It is recommended to consult the manual pages (man chcon and man semanage) or the official SELinux documentation before using these commands.

Leave a Comment