SELinux – canonical way of automatically applying a context on file creation

Adrian Frühwirth asked:

My current understanding is that you have to manually use restorecon to apply the desired context to a newly created file or directory unless you are happy with the context that it inherits from its parent directory.

I am wondering if it is possible to automatically apply a context on creation based on its path without having to run restorecon.

I googled a bit and found this post by Dan Walsh where he mentions restorecond which uses inotify to change context on creation. He also points out the obvious problem with it (race condition). Is this the only way to automatically solve the issue of re-context-ing in case a child should not inherit its context from the parent directory?

One problem is that restorecond does not seem to handle entries the same way as /etc/selinux/targeted/contexts/files/file_contexts, that is, no regexes and it does not work recursively, so /etc/selinux/restorecond.conf cannot contain something like




or even


Is there a way to work around this problem?


As per @Michael’s answer this should work OOTB if a respective rule exists, but it doesn’t:

# rm -rf /var/www/foo
# semanage fcontext -a -t httpd_log_t '/var/www/foo/logs'
# grep '/var/www.*logs' /etc/selinux/targeted/contexts/files/file_contexts*
/etc/selinux/targeted/contexts/files/file_contexts:/var/www(/.*)?/logs(/.*)?    system_u:object_r:httpd_log_t:s0
/etc/selinux/targeted/contexts/files/file_contexts.local:/var/www/foo/logs    system_u:object_r:httpd_log_t:s0
# matchpathcon /var/www/foo/logs
/var/www/foo/logs       system_u:object_r:httpd_log_t:s0
# mkdir -p /var/www/foo/logs
# touch /var/www/foo/logs/quux
# ls -alZ /var/www/foo/logs*
drwxr-xr-x. root root unconfined_u:object_r:httpd_sys_content_t:s0 .
drwxr-xr-x. root root unconfined_u:object_r:httpd_sys_content_t:s0 ..
-rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 quux
# restorecon -vR /var/www/foo
restorecon reset /var/www/foo/logs context unconfined_u:object_r:httpd_sys_content_t:s0->unconfined_u:object_r:httpd_log_t:s0
restorecon reset /var/www/foo/logs/quux context unconfined_u:object_r:httpd_sys_content_t:s0->unconfined_u:object_r:httpd_log_t:s0

My answer:

This is not a problem, you’re just approaching it from the wrong direction.

If you want your own file contexts, just create your own using semanage fcontext. This does accept regular expressions.

Here is a common example, used to relocate the directory from which Apache serves files:

semanage fcontext -a -t httpd_sys_content_t "/volume1/web(/.*)?"

Feel free to adapt this to your own needs.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.