Report issue Add example

semanage

Query and modify the security context of default directories.

Description

The semanage command is used to query and modify the security context of default directories in SELinux. Related commands for managing SELinux policies and rules include seinfo, sesearch, getsebool, setsebool, and semanage.

Syntax

semanage {login|user|port|interface|fcontext|translation} -l
semanage fcontext -{a|d|m} [-frst] file_spec

Options

-l: Query.
fcontext: Primarily used for file security contexts.
-a: Add; you can add default security context type settings for certain directories.
-m: Modify.
-d: Delete.

Examples

Query the default security context settings for /var/www/html:

semanage fcontext -l
SELinux fcontext    type          Context
....(omitted)....
/var/www(/.*)?      all files     system_u:object_r:httpd_sys_content_t:s0
....(omitted)....

As shown in the example above, we can query the security context of each directory. Regular expressions can be used to specify a range for directory settings. So, what if we want to add security contexts for some custom directories? For example, if I want to set /srv/samba to the public_content_t type, how should I do it?

Use the semanage command to set the default security context of the /srv/samba directory to public_content_t:

mkdir /srv/samba
ll -Zd /srv/samba
drwxr-xr-x  root root root:object_r:var_t    /srv/samba

As shown above, the default type is var_t.

semanage fcontext -l | grep '/srv'
/srv/.*                     all files   system_u:object_r:var_t:s0
/srv/([^/]*/)?ftp(/.*)?     all files   system_u:object_r:public_content_t:s0
/srv/([^/]*/)?www(/.*)?     all files   system_u:object_r:httpd_sys_content_t:s0
/srv/([^/]*/)?rsync(/.*)?   all files   system_u:object_r:public_content_t:s0
/srv/gallery2(/.*)?         all files   system_u:object_r:httpd_sys_content_t:s0
/srv                        directory   system_u:object_r:var_t:s0   // Look here!

The above shows the default security context data under /srv, but it does not specify /srv/samba.

semanage fcontext -a -t public_content_t "/srv/samba(/.*)?"
semanage fcontext -l | grep '/srv/samba'
/srv/samba(/.*)?            all files   system_u:object_r:public_content_t:s0
cat /etc/selinux/targeted/contexts/files/file_contexts.local
# This file is auto-generated by libsemanage
# Please use the semanage command to make changes
/srv/samba(/.*)?    system_u:object_r:public_content_t:s0  # Written to this file
restorecon -Rv /srv/samba* # Attempt to restore default values
ll -Zd /srv/samba
drwxr-xr-x  root root system_u:object_r:public_content_t /srv/samba/  # Now has a default value, making it easier to modify with restorecon in the future!

The semanage command has many functions; here we mainly focused on the usage of the fcontext option. As shown above, you can use semanage to query all directory defaults and also use it to add default settings!