Security Enhanced Linux, SELinux is the discretionary access control in the Linux distribution. This extra layer of security keeps the user's data safe in the system. SELinux context contains additional information, labels attached to each process, and files to determine the SELinux policy. The extra details about user, role, type, and sensitivity help to make access control decisions. The context of the file is generally similar to the context of its parent directory.
It is essential to alter the SELinux context to grant or deny access through SELinux.
chcon, (change context) the command is used to change the SELinux context. The files and processes share the same SELinux context as their parent directory.
$ mkdir data $ ls -Zd /data drwxr-xr-x. root root unconfined_u:object_r:default_t:s0 /data
We are creating a directory called /data.
ls -Zd is the command to show the SELinux context of the directory.
$ sudo chcon -t httpd_sys_content_t /data $ ls -Zd /data drwxr-xr-x. root root unconfined_u:object_r:httpd_sys_content_t:s0 /data
chcon -t we changed selinux context of /data to httpd_sys_content_t from its default context default_t .
restorecon restores, alters the context of the files, process, and directories to its default SELinux context.
$ sudo restorecon -v /data restorecon reset /data context unconfined_u:object_r:httpd_sys_content_t:s0->unconfined_u:object_r:default_t:s0
semanage is the policy management tool for SELinux. It modifies the port type for service different from its default usage. But it does not modify or recompile the policy sources.
semanage can map the usernames to SELinux user identities and security context for objects like network ports, interfaces, and hosts. The default settings of SELinux only allow known services to bind to known ports. To modify a service for the usage of a non-default port, we use
$ sudo semanage fcontext -a -t httpd_sys_content_t '/data(./*)?'
This adds the SELinux policy for the data directory.
$ sudo semanage fcontext -l /data(./*)? all files system_u:object_r:httpd_sys_content_t:s0
Then we can add the new context by using the restorecon command.
$ sudo restorecon -v /data restorecon reset /data context unconfined_u:object_r:default_t:s0->unconfined_u:object_r:httpd_sys_content_t:s0
Difference between semanage and chcon
chcon commands, we can change the SELinux context of a file, process, or directory. But there is a significant difference between both. The changes made with
chcon are temporary in nature whereas with
semanage it is permanent. The context of the file altered with chcon goes back to default with the execution of the restorecon command.
restorecon relabels the file system and restores the selinux context set by
semanage. This makes changes made by
semanage fcontext persistent. Therefore it is not advisable to use the
chcon to change the SELinux context.