Create new directory
When a new directory is created, the default SELinux context of the directory is determined by the rules of the /etc/selinux/targeted/contexts/files/file_contexts files. For example, when the /home/JohnDoe/.ssh directory is created, the directory will have ssh_home_t context.
~]# mkdir /home/JohnDoe/.ssh ~]# ls -Z /home/JohnDoe drwxrwxr-x. JohnDoe JohnDoe unconfined_u:object_r:ssh_home_t:s0 .ssh
The context of the .ssh directory is ssh_home_t because the /etc/selinux/targeted/contexts/files/file_contexts.homedirs file contain the following rule, which sets the .ssh directory to ssh_home_t.
Create new file
When a new file is created, the file will inherit the SELinux type of the parent directory. For example, if the /srv/samba/share directory has type samba_share_t, files created in the /srv/samba/share directory will also have type samba_share_t.
Copy or move file
Problems can occur when copying or moving files. For example, a file created in the /etc directory will probably have type etc_t. If the file is copied or moved to /srv/samba/share, the file may retain type etc_t. SELinux will detect that the file does not have the appropriate type for Samba. When attempting to interact with the file, some error will be displayed. There are a few ways to address this challenge.
Temporarily change SELinux context
The chcon command can be used to tempoarily change the SELinux context of a file or directory. If the system is rebooted, or if the restorecon command is used on the file or directory, the SELinux context will be returned to it's prior value.
For example, to temporarily update the context of index.html to httpd_sys_content_t.
~]# chcon -t httpd_sys_content_t index.html
To temporarily update the context of the /var/www/html directory to httpd_sys_content_t.
~]# chcon -R -t httpd_sys_content_t /var/www/html
Restore SELinux context
The restorecon command can be used to permanently restore a file or directory to it's default SELinux context.
Permanently change SELinux context
The most common way to permanently change the SELinux context of a file is to set the files parent directory to have the preferred context, and to then use the restorecon command so that the file inherits the SELinux context of the parent directory.
However, if there is a need for a file to permanently have a context that is different from the files parent directory, the semanage fcontext command can be used. For example, to permanently update myFile.txt to have type etc_t. After running this command, run the restorecon command. The absolute path to the file should be used.
~]# semanage fcontext -a -t etc_t /srv/samba/share/myFile.txt
Likewise, the SELinux context of a directory can also be changed using semanage fcontext.
~]# semanage fcontext -a -t samba_share_t /srv/samba/share
The restorecon command must be used to apply the change.
~]# restorecon -v /path/to/file or directory