SELinux file path context not working with regex

Solution 1:

Try using

HOME_DIR/\.google_authenticator -- gen_context(system_u:object_r:radiusd_google_authenticator_t,s0)

Instead. Home directories aren't necessarily in /home and this acts as a macro when you rebuild policy.

EDIT

So I checked the source code and it provides the following text which probably indicates whats going on here.

label_file.c
680     /*
681      * Check for matching specifications in reverse order, so that
682      * the last matching specification is used.
683      */

Regex that match last, win. The SELinux library is using the following order of file lookups to match:

/etc/selinux/targeted/contexts/files/file_contexts.subs_dist
/etc/selinux/targeted/contexts/files/file_contexts.subs
/etc/selinux/targeted/contexts/files/file_contexts
/etc/selinux/targeted/contexts/files/file_contexts.homedirs
/etc/selinux/targeted/contexts/files/file_contexts.local

The matching regex that wins in your case is this one:

grep user_home_t /etc/selinux/targeted/contexts/files/file_contexts.homedirs
/home/[^/]+/.+  user_u:object_r:user_home_t:s0

By adding the entry as a local context, it is fetched from this file instead: /etc/selinux/targeted/contexts/files/file_contexts.local which appears after the file that matches at the moment.

So, in order to fix this (which is basically a little bit of a hack) you can add the entry as a local override.

Alternatively I tried adding this as a HOME_DIR override (like I originally suggested, but using audio_home_t to test the principal) doing the following:

HOME_DIR/(tcr)?/\.google_authenticator          --      gen_context(system_u:object_r:audio_home_t)

This worked for me, given it added the entry to the later files and the 'last regex won' when I did that.

It actually changed the regex to this in the file:

grep tcr /etc/selinux/targeted/contexts/files/*
/etc/selinux/targeted/contexts/files/file_contexts.homedirs:/home/[^/]+/(tcr)?/\.google_authenticator   --  user_u:object_r:audio_home_t:s0

I would suggest trying the HOME_DIR option first (which is the actual way in policy you should implement it) or alternatively use a local override.

Solution 2:

I'm not entirely sure what you're trying to to but if it's to have a wildcard * after API so that for example

/home/API/one/.google_authenticator
/home/API/two/.google_authenticator
...

all have type radiusd_google_authenticator_t then this seems to work

sudo semanage fcontext -a -t mysqld_db_t  "/home/API(/.*)?/.google_authenticator"

Note I have used mysqld_db_t as I don't have radiusd_google_authenticator_t

matchpathcon /home/API/one/.google_authenticator
/home/API/one/.google_authenticator     system_u:object_r:mysqld_db_t:s0
matchpathcon /home/API/two/.google_authenticator
/home/API/two/.google_authenticator     system_u:object_r:mysqld_db_t:s0