User:SwifT/selinux-tutorials/3

Controlling file contexts yourself
Now that we understand that processes run within a certain SELinux domain, and that this domain is used by SELinux to check the permissions against files with a particular context, we now need to find out how to set the file contexts ourself and how to make this manageable.

The context of a file (or directory) in SELinux is set through its extended attribute, but having to manually set the context for every file would require a huge database of all possible file paths and their associated SELinux context. As this is not really manageable, SELinux uses file context definitions using regular expressions.

A file context definition/expression
In our example of the audit logs, it is safe to assume that every file within /var/log/audit is to be used for audit logging purposes. So expression-wise, we could say that /var/log/audit/.* is a good match for files which should have the auditd_log_t type. Although correct, it leaves /var/log/audit itself undefined.

What most SELinux policy writers do in such a case is to use a regular expression that matches both the directory as well as its content:

/var/log/audit(/.*)?

Next is to define which context to assign to it. In our example, we use the auditd_log_t type. SELinux' management tools will automatically convert this to the full context system_u:object_r:auditd_log_t (or system_u:object_r:auditd_log_t:s0 - we will discuss the context structure and their additional fields in a later part of this tutorial series). So we have

/var/log/audit(/.*)? system_u:object_r:auditd_log_t

We are still missing the class(es) for which this is applicable. As we have an expression that matches both a directory and files, we generally say that all classes (well, file related classes since we are talking about a file system) are applicable. So we have:

/var/log/audit(/.*)? all files      system_u:object_r:auditd_log_t

With semanage fcontext, we can query the existing SELinux file context definitions. To get to the definition for the audit logs:

What you need to remember
What you should remember from this tutorial is that
 * 1) the context of a file is one of the most important parts of a SELinux secured system,
 * 2) that wrong contexts are the most common source of SELinux-related denials and permission problems,
 * 3) that contexts are defined by mapping types with regular expressions through semanage fcontext, and
 * 4) that contexts are then best applied through restorecon