User:SwifT/selinux-tutorials/4

How to get a process into a certain context
In the previous tutorials, we already got across the context in which a process resides, and which can be checked using utilities like ps -Z.

But how do processes get into this context?

The answer lays in transitions.

Context inheritance
First of all, know that SELinux supports inheritance of contexts. Even more, inheritance of contexts is default behavior: if there is no policy in SELinux telling otherwise, then anything created will inherit the context of its parent.
 * A process running as context foo_t and which spawns another process (forks), this new process too will run in the foo_t context (as long as SELinux has no rules telling otherwise)
 * A file or directory created in a directory with context bar_t will get the bar_t context as well (as long as SELinux has no rules telling otherwise)

This inheritance is always the case, even if the SELinux management utilities (but not SELinux policy rules) say otherwise: even if there is a context definition saying that should be auditd_log_t, if you create this  directory within  then this directory will inherit the var_log_t context from its parent directory. Only later, when you run restorecon, will the context be changed.

Since we are talking about inheritance, there probably is a root context for everything. Well, there is - of course this is defined by the policy and SELinux support, but it is safe to assume that the root context (domain) for processes is the kernel_t context (as this is the context that the kernel runs as, and it is the kernel that spawns init, which itself spawns various other processes) and the root context for the file system is root_t.

Transitioning
Of course, SELinux would be quite dull if it doesn't support changing to other contexts. And in this tutorial, we want to talk about process context transitions: the idea that a process, once created, is within a different context than its parent process.

SELinux supports context transitions when a process forks (actually upon calling execve which is implied when we talk about high-level forking and not the fork method). Forking seems like some weird programming term to some, so let's say it is when something is executed. And when you execute something, we mean that a process referred to some file (most likely a binary or a script) saying "execute this", so that the referred file is loaded and 'becomes' a process.

What a SELinux policy writer can do in these cases is to define a context transition, like so:

When an init_t process executes a file with context initrc_exec_t, then the resulting process should run in the initrc_t context.

Or, in a dumb ASCII-art alike flow:

[init_t] --{execute}--> (initrc_exec_t) > [initrc_t]