3

The selabel_lookup(3) library function gives a way to obtain the SELinux security context information for a file - or rather what security label a file is expected to have [1].

Is there a command line utility which looks up security context information for a file from the policy definitions - possibly one that even uses selabel_lookup(3) under the covers?

I can sort of use a reverse grep(1) to search /etc/selinux/targeted/contexts/files/file_contexts. It looks like entries use extended regular expressions (so egrep rather than grep). So I'd have to search the keys in file_contexts by iterating over them and applying the key to a regex search against my file name. That could get time consuming. For instance, Fedora 23 has 5935 lines in file_contexts, so that could mean 5935 invocations of grep. I was hoping for a more efficient solution than that.

[1] ls -Z or secon gives current security context for a file, but that may not be the correct context for that file (as outlined in the SELinux policy definition for the system).

2

It looks like matchpathcon(8) (from the libselinux-utils package) does the trick:

% matchpathcon /tmp
/tmp    system_u:object_r:tmp_t:s0
% matchpathcon /tmp/foobar
/tmp/foobar     <<none>>

I think that should satisfy my needs [1].

You can use matchpathcon to verify existing files' labels:

% matchpathcon -V /tmp
/tmp verified

Although -V is a little confusing for files that have no policy defined:

% matchpathcon -V /tmp/foobar; echo $?
/tmp/foobar has context unconfined_u:object_r:user_tmp_t:s0, should be <<none>>
1

I would think a context value of <<none>> would match any context successfully instead of being flagged as an error. The current implementation that I tested (libselinux-utils 2.4.4) flags those cases with a non-zero exit code (as shown above).

[1] My actual need is to look up the proper security context of a file in a mounted chroot image of a removable disk and set it to the proper context based on system defined policy - this will ensure the disk gets the proper security labels before being deployed. I specifically wanted to look up the security context for /tmp in order to apply that context to a custom directory that has /tmp-like semantics. The custom directory is not (yet) defined in a file_contexts list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.