Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 37 ยท Security Hardening

Mandatory Access Control: SELinux and AppArmor

Learn how SELinux and AppArmor confine Linux processes beyond file permissions: modes, contexts, booleans, profiles, reading denials, and fixing problems without turning protection off.

Ordinary Linux permissions are discretionary: the owner of a file decides who may access it, and a process runs with all the rights of its user. If an attacker takes over a web server process running as www-data, they get everything www-data can touch. Mandatory Access Control (MAC) adds a second, system-wide policy that even root-owned processes cannot bypass: "the web server may read web content and write its logs, and nothing else".

Linux has two widely used MAC systems. SELinux (Fedora, RHEL, Rocky, Alma, CentOS Stream) labels every file and process and writes policy about label interactions. AppArmor (Ubuntu, Debian, SUSE) restricts programs by path with per-program profiles. This lesson teaches the concepts and the daily commands. They need a real kernel with the module enabled, so commands are read-only here; the Python stand-ins model how the decisions are made.

Why it matters

Consider a flaw in a PHP application that lets an attacker run commands as the web user. With only DAC, they might read /etc/passwd, browse other sites' files, or connect to a database port. With MAC, the process is confined to its domain, and many of those attempts are denied and logged. MAC does not fix the bug, but it limits the damage, which is exactly "defence in depth".

flowchart LR
    P["process"] --> D{"DAC check<br/>owner, group, mode"}
    D -- denied --> X["EACCES"]
    D -- allowed --> M{"MAC check<br/>SELinux or AppArmor policy"}
    M -- denied --> X
    M -- allowed --> F["access granted"]

Both checks must pass. MAC can only deny more, never grant what DAC refuses.

SELinux basics

Every process and object has a security context with up to four parts: user:role:type:level. In practice the type matters most.

Terminal
ls -Z /var/www/html
# -rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 index.html
ps -eZ | grep httpd
# system_u:system_r:httpd_t:s0   812 ?   00:00:01 httpd
id -Z

The policy says that processes of type httpd_t may read files of type httpd_sys_content_t. If you copy a file from your home directory and it keeps a user_home_t label, Apache cannot read it even though the permissions look fine. That is the number one SELinux surprise.

Modes

  • Enforcing: policy is applied; violations are denied and logged.
  • Permissive: violations are only logged. Perfect for diagnosis.
  • Disabled: no SELinux (changing this needs a reboot and a full relabel to come back).
Terminal
getenforce                     # Enforcing / Permissive / Disabled
sestatus                       # detailed status and policy name
sudo setenforce 0              # temporary permissive until reboot
sudo setenforce 1              # back to enforcing
# permanent setting: SELINUX=enforcing in /etc/selinux/config

Switching to permissive to test a theory is fine; leaving SELinux off because something broke is how a server loses a major protection layer. Fix the label or boolean instead.

Fixing the usual problems

1. Wrong file label. Restore labels from the policy's rules, or define a rule for a custom location.

Terminal
sudo restorecon -Rv /var/www/html
sudo semanage fcontext -a -t httpd_sys_content_t "/srv/site(/.*)?"
sudo restorecon -Rv /srv/site

chcon changes a label immediately but is forgotten after a relabel; semanage fcontext plus restorecon is the permanent way.

2. A boolean. Policy ships with switches for common needs.

Terminal
getsebool -a | grep httpd
sudo setsebool -P httpd_can_network_connect on     # -P = persistent
sudo setsebool -P httpd_can_network_connect_db on

3. A non-standard port. Allow the service to bind a different port.

Terminal
sudo semanage port -l | grep http_port_t
sudo semanage port -a -t http_port_t -p tcp 8081

4. Read the denial. Denials appear as AVC records in the audit log.

Terminal
sudo ausearch -m AVC -ts recent
sudo journalctl -t setroubleshoot
sudo sealert -a /var/log/audit/audit.log      # human-readable advice (setroubleshoot)
sudo audit2why < /var/log/audit/audit.log

An AVC line looks like avc: denied { read } for pid=812 comm="httpd" name="data.csv" scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:user_home_t:s0 tclass=file. Read it as: source type httpd_t tried to read a file of target type user_home_t, and policy forbids it. The fix is usually to relabel the file so its type is httpd_sys_content_t.

Python Mini SELinux: type enforcement lookup

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 input()), it gets the next line from this box.

AppArmor basics

AppArmor identifies programs by path and attaches a profile that lists what files, capabilities and network access they may use. It is simpler to read than SELinux, and profiles are plain text under /etc/apparmor.d/.

Terminal
sudo aa-status                           # loaded profiles and their modes
sudo aa-enforce /etc/apparmor.d/usr.sbin.nginx
sudo aa-complain /etc/apparmor.d/usr.sbin.nginx   # log only
sudo apparmor_parser -r /etc/apparmor.d/usr.sbin.nginx   # reload a profile
sudo aa-logprof                          # update a profile from logged denials
sudo journalctl -k | grep -i apparmor

A tiny profile:

TEXT
/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,

  deny /home/** rwx,
}

Rules read as path plus permissions: r read, w write, a append, x execute, ix execute and inherit the profile, ** any depth. Denials show up in the kernel log as apparmor="DENIED" operation="open" profile="/usr/sbin/mydaemon" name="/home/alice/data" requested_mask="r". Modes are enforce and complain (log only), the equivalent of enforcing and permissive. When a service fails on an AppArmor system after you moved its data directory, add the new path to the profile (or a local override in /etc/apparmor.d/local/) rather than disabling AppArmor.

Python Mini AppArmor: path rules

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 input()), it gets the next line from this box.

SELinux vs AppArmor

SELinux AppArmor
Identifies objects by labels (extended attributes) file paths
Default on RHEL family, Fedora Ubuntu, Debian, SUSE
Policy size and detail Large, very fine-grained Small, per-program profiles
Learning curve Steeper Gentler
Typical fix relabel, boolean, port edit profile

Pick the one your distribution supports and leave it enabled. Containers add their own layers: Docker and Podman apply default SELinux or AppArmor profiles, which is one more reason not to turn them off.

When something works as root but fails as the service, or fails only on a distribution with SELinux or AppArmor, suspect MAC. Set permissive or complain mode, reproduce the problem, read the denial, then make the narrowest permanent change and return to enforcing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A file is readable by everyone but Apache still cannot serve it on a RHEL server. What should you check first?

    A wrong type such as user_home_t is denied to httpd_t even when DAC permissions are open.
  2. 2. What is the correct permanent way to allow Apache to connect to the network on SELinux?

    Booleans are policy switches; -P stores the change across reboots.
  3. 3. Which statement about AppArmor is true?

    AppArmor profiles list the paths, capabilities and network access a program may use.
  4. 4. Why is permissive (SELinux) or complain (AppArmor) mode useful?

    You can reproduce the problem and read the denials before writing a precise fix.

Summary

  • MAC adds a mandatory policy on top of normal permissions; it can only deny additional access.
  • SELinux uses labels and types (RHEL family); AppArmor uses path-based profiles (Ubuntu, Debian, SUSE).
  • Learn the modes: enforcing/permissive and enforce/complain; never leave protection disabled to "fix" an error.
  • SELinux fixes: restorecon/semanage fcontext for labels, setsebool -P for booleans, semanage port for ports; read AVCs with ausearch.
  • AppArmor fixes: adjust the profile, reload with apparmor_parser, use aa-logprof to learn from denials.

Next: Auditing and Integrity Checking