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
/var/www(/.*)?/logs(/.*)?
or
/var/www/*
or even
/var/www/*/logs
Is there a way to work around this problem?
EDIT:
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
file_contexts
ships with the installation. Since that did not work I added the second withsemanage fcontext
with a plain absolute path and no further regex magic, so I agree, that should work. I tried on both a CentOS 6.0 as well as a CentOS 6.3 server and it works on neither. Hm.