Skip to content
Tutorials Center
My learning

Topics

Lesson 83 of 95 ยท System Administration

SELinux and AppArmor

Learn mandatory access control on Linux: SELinux contexts, modes, booleans and restorecon, AppArmor profiles, and how to read denial logs without disabling them.

Ordinary Linux permissions are discretionary: the owner of a file decides who may touch it, and a process runs with all the rights of the user who started it. That is a weak spot. If a web server running as www-data has a bug and an attacker takes it over, the attacker inherits everything www-data may read, which on a badly configured machine can include far more than the website. The permission bits cannot say "this program may only ever read its own folder", because they know nothing about programs, only about users.

Mandatory access control (MAC) adds a second, independent set of rules that the administrator writes and that even the file's owner or root cannot override. On Linux, MAC is implemented by Linux Security Modules (LSMs) in the kernel. The two big ones are SELinux (Red Hat, Fedora, Rocky, Alma, Android) and AppArmor (Ubuntu, Debian, openSUSE). This lesson explains the ideas behind both, the commands for everyday administration, and how to read a denial instead of disabling the protection. It builds on File Permissions and Ownership and Users, Groups and sudo. The sandbox has neither module loaded, so the system commands are read-only; the runnable examples rebuild the decision logic and parse real log lines.

Two checks, not one

When a process tries to open a file, the kernel runs the usual permission check first. If that check passes, the LSM gets a veto. Access happens only if both agree:

flowchart LR
    A["Process calls open(file)"] --> B{"DAC check<br/>owner, group, mode, ACL"}
    B -- denied --> X["EACCES: permission denied"]
    B -- allowed --> C{"MAC check<br/>SELinux or AppArmor policy"}
    C -- denied --> Y["EACCES, plus a log entry"]
    C -- allowed --> Z["Access granted"]

Discretionary permissions come first; the security module can only take rights away, never add them.

That last point is important: MAC never grants more than the normal permissions, it only restricts. A denial from SELinux or AppArmor looks like an ordinary "Permission denied", even to root, which is why administrators who do not know about it lose hours chasing file modes that are perfectly fine.

SELinux: labels on everything

SELinux (developed with the US National Security Agency) gives every process and every object (file, directory, socket, port) a label called a security context. Policy rules then say which labels may do what to which labels. The context has four colon-separated fields:

TEXT
unconfined_u : object_r : user_home_t : s0
    user         role        type       level

In the default targeted policy, the part that matters in daily work is the third field, the type. A process type is also called its domain. The web server runs in the domain httpd_t; the files it may serve carry the type httpd_sys_content_t. The policy contains rules like "domain httpd_t may read and getattr files of type httpd_sys_content_t", written in policy language as allow httpd_t httpd_sys_content_t:file { read getattr open };. Anything not explicitly allowed is denied. This is called type enforcement.

See the labels with the -Z option that many tools understand (read-only; output from a Fedora-style system):

CONSOLE
$ ls -Z /var/www/html/index.html /home/maria/notes.txt
system_u:object_r:httpd_sys_content_t:s0 /var/www/html/index.html
unconfined_u:object_r:user_home_t:s0     /home/maria/notes.txt
$ ps -eZ | grep nginx
system_u:system_r:httpd_t:s0     1204 ?  00:00:00 nginx
$ id -Z
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

Even if the compromised web server runs as a user that can read /home/maria/notes.txt according to the mode bits, SELinux blocks it, because there is no rule allowing httpd_t to read user_home_t.

The type-enforcement idea in code

The simulation below keeps a few allow-rules in an array, parses the contexts the way the kernel sees them, and answers access requests. Notice how the check ignores users and file modes and looks only at type pairs:

Bash A tiny SELinux type-enforcement checker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The web server may read the site content but not write it (a common hardening rule: a hacked server cannot rewrite its own pages), it may not read home directories or shadow_t, while sshd_t may read home files. All of that holds even if the file modes were 777.

Modes and the everyday commands

SELinux runs in one of three modes:

Mode Behaviour
Enforcing the policy is applied; violations are blocked and logged
Permissive violations are only logged; nothing is blocked (for debugging)
Disabled SELinux is off (changing this needs a reboot and a full relabel when turned back on)
CONSOLE
$ getenforce                         # Enforcing, Permissive or Disabled
$ sestatus                           # mode, policy name, config file
$ sudo setenforce 0                  # permissive until reboot (temporary, for testing only)
$ sudo setenforce 1                  # enforcing again
# permanent setting: SELINUX=enforcing in /etc/selinux/config

The two things that go wrong most often are wrong file labels and booleans that are off. Files get their label from the directory they are created in; a file moved with mv keeps its old label, which is the classic cause of "my web server returns 403 but the permissions are fine". The fix is to restore the label the policy expects for that path:

CONSOLE
$ ls -Z /srv/site/index.html
unconfined_u:object_r:user_home_t:s0 /srv/site/index.html
$ sudo semanage fcontext -a -t httpd_sys_content_t "/srv/site(/.*)?"   # define the rule
$ sudo restorecon -Rv /srv/site                                         # apply it
Relabeled /srv/site/index.html from unconfined_u:object_r:user_home_t:s0 to unconfined_u:object_r:httpd_sys_content_t:s0

semanage fcontext records the rule permanently (it survives a full relabel), and restorecon applies the current rules to existing files. The quick alternative chcon -t httpd_sys_content_t file changes the label immediately but is forgotten at the next relabel; use it only for experiments.

Booleans are on/off switches for common policy variations, for example "may the web server connect to the network?":

CONSOLE
$ getsebool -a | grep httpd_can_network     # list switches
httpd_can_network_connect --> off
$ sudo setsebool -P httpd_can_network_connect on    # -P makes it permanent

Other fixes include semanage port -a -t http_port_t -p tcp 8081 to let a web server listen on a non-standard port, and custom policy modules built with audit2allow as a last resort.

Reading a denial

Every block is written to the audit log (/var/log/audit/audit.log) as an AVC (access vector cache) message. Find them with sudo ausearch -m avc -ts recent, or read the helpful summary from sudo sealert -a /var/log/audit/audit.log or audit2why. A raw line looks like this:

TEXT
type=AVC msg=audit(1699999999.123:456): avc:  denied  { read } for  pid=1204 comm="nginx" name="index.html" dev="sda1" ino=5678 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:user_home_t:s0 tclass=file permissive=0

Read it as a sentence: denied the read permission, process nginx running in httpd_t, target a file labelled user_home_t. The source and target types are all you need. Here is a small parser that turns such a line into that sentence and suggests the next step:

Bash Explain an AVC denial

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The first line shows the classic mislabel. The second is a different class of problem: the web application wants to connect to the database port, which a boolean (httpd_can_network_connect_db) controls, and the name field is absent because the target is a socket, so the output shows it empty. Always read tclass before you pick a fix.

AppArmor: profiles for paths

AppArmor reaches the same goal with a different design. Instead of labelling every file, it attaches a profile to a program, identified by its path, and the profile lists the file paths, capabilities and network access that program may use. Programs without a profile are unconfined. Profiles are plain text files in /etc/apparmor.d/, named after the program path with slashes turned into dots:

TEXT
# /etc/apparmor.d/usr.sbin.mydaemon
#include <tunables/global>

/usr/sbin/mydaemon {
  #include <abstractions/base>

  capability net_bind_service,
  network inet stream,

  /etc/mydaemon/**        r,
  /var/lib/mydaemon/**    rw,
  /var/log/mydaemon.log   w,
  /tmp/*                  rw,
  deny /etc/shadow        r,
}

Each rule is path permissions,. Permission letters include r read, w write, a append, x execute, k file locking, m memory-map as executable and l link. In globs, * matches any characters except /, ** matches anything including /, and ? is one character. A deny rule always wins over an allow rule, and everything not allowed is refused and logged.

Tools (package apparmor-utils):

CONSOLE
$ sudo aa-status                              # loaded profiles, enforce vs complain, confined processes
$ sudo aa-complain /usr/sbin/mydaemon         # log violations only (learning mode)
$ sudo aa-enforce  /usr/sbin/mydaemon         # enforce again
$ sudo apparmor_parser -r /etc/apparmor.d/usr.sbin.mydaemon   # reload after editing
$ sudo aa-genprof /usr/sbin/mydaemon          # create a profile by running the program
$ sudo aa-logprof                             # update profiles from logged denials
$ sudo journalctl -k | grep 'apparmor="DENIED"'   # see denials

A denial in the kernel log looks like apparmor="DENIED" operation="open" profile="/usr/sbin/mydaemon" name="/etc/hosts" requested_mask="r" denied_mask="r". The profile, name and requested_mask fields tell you what to add to the profile. This script reproduces the rule evaluation:

Bash Evaluating an AppArmor profile

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Look at the pairs: /etc/mydaemon/conf.d/site/a.conf is allowed because ** crosses directory boundaries, while /tmp/sub/cache.bin is refused because /tmp/* stops at the next slash. The write to /etc/mydaemon/app.conf fails because the rule grants only r, and the explicit deny for /etc/shadow wins. That kind of path-glob detail causes most AppArmor bugs.

SELinux or AppArmor?

SELinux AppArmor
Basis labels (contexts) stored on files and given to processes file paths in per-program profiles
Default on RHEL, Fedora, Rocky, Alma, Android Ubuntu, Debian (optional), openSUSE
Strength very fine-grained, covers files, ports, users, even IPC; survives renames and hard links readable, quick to write, easy to learn
Cost steep learning curve; labels can go wrong path-based, so bind mounts and links need care; less expressive
Debug mode permissive complain

Both are valuable and neither is a replacement for patching and good permissions. They limit the blast radius when something goes wrong. Containers use them too: Docker applies an AppArmor or SELinux profile to each container by default.

The rule of thumb for administrators

  • Never turn the module off to "fix" an error. Switch to permissive or complain mode, reproduce the problem, read the log, then fix the label, the boolean or the profile, and go back to enforcing.
  • Suspect MAC when you see Permission denied although ls -l, ACLs and lsattr (see ACLs, chattr and Extended Attributes) all look right, especially after moving files or changing a service's port or directory.
  • Keep custom data in locations the policy already knows, or teach the policy with semanage fcontext.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does mandatory access control add to normal Linux permissions?

    MAC is a second layer. The normal DAC check runs first; then the SELinux or AppArmor policy can still deny access. It can only restrict, never grant more than the normal permissions.
  2. 2. After mv ~/site /srv/site, nginx on a RHEL system returns 403 although the file modes are 755. What is the most likely cause and fix?

    mv keeps the old SELinux label. The web server domain has no rule for user_home_t. semanage fcontext plus restorecon sets the correct httpd_sys_content_t label; disabling SELinux or chmod 777 would just hide the problem.
  3. 3. How does AppArmor identify which rules apply to a process?

    AppArmor is path-based: a profile is attached to a program path and lists the paths, capabilities and network access that program may use.
  4. 4. Which command switches a single AppArmor profile to log-only mode while you debug it?

    aa-complain puts one profile into complain mode, where violations are logged but not blocked. setenforce 0 is the SELinux equivalent, and it affects the whole system.
  5. 5. In the SELinux context system_u:system_r:httpd_t:s0, which field matters most for type enforcement in the targeted policy?

    The targeted policy decides access mostly from the type of the process (its domain) and the type of the object. The user, role and level fields play a smaller part.

Summary

  • Normal permissions are discretionary; MAC adds administrator-defined rules, enforced by a Linux Security Module, that apply after the normal check and can only deny.
  • SELinux labels everything with a context user:role:type:level; policy allows specific type pairs (httpd_t reading httpd_sys_content_t). See labels with ls -Z, ps -Z, id -Z.
  • Modes: enforcing, permissive (log only, setenforce 0), disabled. Fix wrong labels with semanage fcontext and restorecon, switch behaviour with booleans (setsebool -P).
  • Denials are AVC messages in the audit log: read the source type, target type and class with ausearch -m avc or sealert.
  • AppArmor attaches a path-based profile to each program in /etc/apparmor.d/; * stops at /, ** does not, deny beats allow. Use aa-status, aa-complain, aa-enforce, aa-logprof.
  • Debug in permissive or complain mode and fix the cause; do not disable the module.

Next: PAM, sudoers and Account Policies