Search code examples
cselinuxlibselinux

What is the format of an selinux context (security_context_t)?


The getfilecon() API call is declared to return a security_context_t as follows:

int getfilecon(const char *path, security_context_t *con);

What is the formal definition of a security_context_t?

Anecdotally a security_context_t appears to be a char* containing four pieces of information separated by colons, is this always true?

If you were only interested in the file type (third field), would the correct way to parse this would be a regex like this?

^.*:.*:(.*):.*$

Is there an API I should be using to parse the context string?


Solution

  • What is the formal definition of a security_context_t?

    From http://selinuxproject.org/page/Guide/Contexts :

    SELinux contexts are composed of 4 pieces: selinux user, role, type, and range.

    unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c255
        user    :    role    :    type    :    range
    

    Is there an API I should be using to parse the context string?

    From https://man7.org/linux/man-pages/man3/context_new.3.html :

    context_t context_new(const char *context_str);
    

    The API call to return the context_type would be :

    const char * context_type_get(context_t con);
    

    would the correct way to parse this would be a regex like this?

    Hm... Looking at https://github.com/SELinuxProject/selinux/blob/fb7f35495fbad468d6efa76c5fed727659903038/libselinux/src/context.c#L40 I think something along, where \1 \2 \3 \4 groups would be user, role, type and range.

    ^([^\n\t\r:]+):([^\n\t\r:]+):([^\n\t\r:]+)(:[^\n\t\r :]+){1,2})$
    

    is this always true?

    No, there can be from 3 up to 5 pieces. (MLS counts as "one" piece).