# Linux Selinux Apparmor

> Use when enforcing mandatory access control on Linux with SELinux or AppArmor on systems you administer. Covers SELinux enforcing and permissive modes, reading AVC denials from audit logs, restoring file contexts, tuning booleans, writing and testing targeted policy modules, AppArmor profiles in complain and enforce mode, aa-genprof and aa-logprof workflows, and troubleshooting denials without permanently disabling enforcement. Defensive hardening for RHEL, Debian, Ubuntu, and SUSE hosts built around least privilege and containment.

- Skill: `mizazhaider-ceh/linux-selinux-apparmor` (Agent Skill)
- Install (CLI): `npx get-skill add mizazhaider-ceh/linux-selinux-apparmor`
- Raw SKILL.md: https://api.skillmd.com/api/skills/mizazhaider-ceh/linux-selinux-apparmor/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Security
- Author: mizazhaider-ceh (https://skillmd.com/u/mizazhaider-ceh)
- Updated: 2026-11-22
- Page: https://skillmd.com/skills/mizazhaider-ceh/linux-selinux-apparmor

---


Mandatory access control (MAC) is the layer that still says no after
discretionary permissions say yes. SELinux (RHEL, Fedora, CentOS Stream)
labels every process and file and only allows interactions the policy
permits. AppArmor (Ubuntu, Debian, SUSE) confines programs by path-based
profiles. Both exist to contain a compromised service, so a web server
exploit does not automatically become full host compromise. The cardinal
rule of this skill is that disabling enforcement is never the fix. A
denial is a signal: either the policy is wrong, the file label is wrong,
or the application is doing something it should not do. Find out which
one before you change anything.

## Quick Workflow

1. Identify which MAC system the host runs, and confirm it is enforcing,
   not disabled or merely permissive.
2. Reproduce the failing behavior, then read the denial from the audit
   log rather than guessing at a fix.
3. Classify the denial: wrong file context, missing boolean, missing
   policy rule, or genuinely suspicious behavior.
4. Apply the narrowest fix: restore a context, flip one boolean, or add
   one policy rule or profile rule.
5. Retest the application in enforcing mode and confirm the denial is
   gone and no new denial appeared.
6. Record the change (boolean, context, or module) in configuration
   management so the next rebuild inherits it.
7. Monitor: alert on new AVC denials and on any host where enforcement
   flips to permissive or disabled.

## 1. SELinux modes and status

SELinux has three modes. Enforcing blocks and logs denials. Permissive
logs denials but allows the action, which makes it the diagnostic mode.
Disabled loads no policy at all and requires a reboot plus a full
relabel to re-enable safely. Check status before doing anything else,
and treat a host that should be enforcing but is not as a finding in
itself.

```bash
getenforce
sestatus
cat /etc/selinux/config | grep -E "SELINUX=|SELINUXTYPE="
```

Expected on a hardened RHEL host: `Enforcing`, with `SELINUXTYPE=targeted`
in the config. Targeted policy confines network-facing services and
leaves most user processes unconfined; MLS and strict policies exist but
are rarely the right choice for a general server. If a host is in
permissive mode, find out why before flipping it back: a service that
only works in permissive mode has an unresolved denial waiting to break
it at the next mode change.

## 2. Reading AVC denials

Every SELinux denial lands in the audit log as an AVC message. Read it
with `ausearch` or `journalctl`, and use `audit2why` to translate the
denial into a human reason: missing allow rule, boolean, or file
context problem. Never pipe raw `audit2allow` output straight into a
production policy without reading it; it grants exactly what was
attempted, including anything malicious that happened to be denied.

```bash
ausearch -m avc -ts recent --interpret 2>/dev/null | head -30
journalctl -t setroubleshoot --since "1 hour ago" --no-pager | head -30
echo "type=AVC msg=audit(1698000000.000:123): avc: denied { read } for pid=1234 comm=\"nginx\" name=\"secret.key\" dev=\"dm-0\" ino=12345 scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:etc_t:s0 tclass=file permissive=0" | audit2why
```

Read the denial as a sentence: source context (`httpd_t`) tried an
operation (`read`) on a target context (`etc_t`) of a class (`file`).
That sentence tells you the fix. If the target file should be readable
by the web server, its label is wrong. If the operation is legitimate
but the policy lacks it, you need a rule or a boolean. If neither is
true, the application is misbehaving and the denial did its job.

## 3. File contexts and booleans

Most SELinux problems on a working system are labeling problems. Files
created by moving (not copying) keep their old context, and files
created in the wrong directory inherit the wrong one. `restorecon`
fixes labels from the policy database, and `semanage fcontext` makes a
label change permanent so the next relabel does not undo it. Booleans
are policy toggles for common, vetted behaviors such as letting a web
server make network connections or read user home directories.

```bash
ls -Z /var/www/html/index.html
restorecon -Rv /var/www/html/
semanage fcontext -a -t httpd_sys_content_t "/srv/www(/.*)?"
restorecon -Rv /srv/www/
getsebool httpd_can_network_connect
setsebool -P httpd_can_network_connect on
```

The `-P` flag on `setsebool` makes the change persistent across reboot;
without it, the boolean reverts and the denial returns after the next
maintenance window, which is a classic source of "it worked yesterday"
incidents. Document every persistent boolean per host role, and review
the list when the role changes: a boolean that made sense for a web
server is a needless exposure on a database host.

## 4. AppArmor profiles and modes

AppArmor profiles list what a program may read, write, execute, and
which capabilities it may use, keyed by executable path. A profile in
enforce mode blocks violations; in complain mode it only logs them,
which makes complain the diagnostic equivalent of SELinux permissive.
Check the loaded profile state, then read the log before editing.

```bash
aa-status
cat /sys/kernel/security/apparmor/profiles | head -20
grep -i apparmor /var/log/kern.log 2>/dev/null | grep DENIED | tail -20
aa-complain /usr/sbin/nginx
aa-enforce /usr/sbin/nginx
```

A minimal AppArmor profile for a static file service shows the shape of
the language: includes for shared abstractions, read access to its own
content, and explicit denial of everything else by omission.

```
#include <tunables/global>

/usr/sbin/nginx {
  #include <abstractions/base>
  #include <abstractions/nameservice>

  /usr/sbin/nginx mr,
  /var/www/html/** r,
  /var/log/nginx/* w,
  /run/nginx.pid rw,
  capability net_bind_service,
  deny /etc/shadow r,
}
```

Generate profiles from real behavior with `aa-genprof` (run the program
through its normal workload, then scan the log) and refine with
`aa-logprof`. A generated profile is a starting draft, not a finished
product: review every rule it proposes, remove access to paths the
program touched only during your test, and re-run the workload after
each edit.

## 5. Custom SELinux policy modules

When a denial is legitimate and no boolean covers it, write a small
targeted policy module. Generate a draft from the denial, read every
rule, trim anything overbroad, compile it, and test in enforcing mode.
Full module authoring, including hand-written type enforcement and file
contexts, lives in the linux-selinux-policy-writing sub-skill.

```bash
ausearch -m avc -ts today --raw | audit2allow -M myapp-fix
cat myapp-fix.te
semodule -i myapp-fix.pp
semodule -l | grep myapp-fix
```

Keep modules small and named per service, one module per problem, so a
bad module can be removed with `semodule -r` without touching unrelated
policy. A module that grants broad access (for example, allowing a web
domain to read all of `etc_t`) is worse than the denial it replaces;
rewrite it to a dedicated type for the exact files involved.

## 6. Troubleshooting without disabling enforcement

The forbidden shortcut is `setenforce 0` left in place, or
`SELINUX=disabled` in the config. The legitimate diagnostic sequence
is: reproduce in enforcing mode, read the denial, test the candidate
fix in permissive mode only long enough to confirm the denial
disappears, then return to enforcing and retest. If a vendor tells you
to disable SELinux permanently, treat that as a vendor defect to be
worked around with a scoped module, not as guidance to follow.

```bash
setenforce 0
# reproduce the workload, collect AVC denials, then immediately restore
setenforce 1
getenforce
ausearch -m avc -ts recent --raw | audit2allow -R
```

The `audit2allow -R` flag suggests reference policy interfaces instead
of raw allow rules, which produces cleaner modules. If the denial
persists after the fix, you fixed the wrong layer: check for a second
denial (a service often hits several in sequence), a mislabeled
directory above the file, or a boolean that needs the persistent flag.

## Edge cases

- Moving files with `mv` preserves the old context while `cp` applies
  the destination context, so a web page moved from a home directory
  stays labeled `user_home_t` and gets denied; `restorecon` is the fix,
  not a policy change.
- SELinux and AppArmor are mutually exclusive at runtime on most
  distributions: enabling one typically means the other is not active,
  so check which system your distribution actually loads before
  debugging the wrong one.
- Containers run under a container SELinux type (commonly
  `container_t`) on SELinux hosts, and a volume mount without the `:z`
  or `:Z` relabel option produces denials that look like application
  bugs; label the mount, not the container.
- `audit2allow` output from a compromised or misbehaving process can
  encode attacker intent as policy, so review generated rules against
  the application's documented behavior before installing a module.
- Permissive domains (`semanage permissive -a httpd_t`) confine the
  diagnostic blast radius to one domain instead of the whole system,
  which is strictly better than global permissive mode during testing.
- AppArmor profiles are path-based, so replacing a binary (or a
  symlink target) can silently change which profile applies; audit
  profiles after package upgrades that replace confined binaries.
- A full filesystem relabel (`touch /.autorelabel` then reboot) is
  slow on large disks and can break a host that was mislabeled for
  months, so schedule it in maintenance and snapshot first.
- Booleans set without `-P` revert on reboot, which turns a fixed
  service into a recurring outage; always verify persistence after a
  boolean change.

## Key references

- Red Hat SELinux guide: https://www.redhat.com/en/topics/linux/what-is-selinux
- SELinux Project wiki: https://selinuxproject.org/
- AppArmor documentation: https://apparmor.net/
- Ubuntu AppArmor guide: https://ubuntu.com/server/docs/security-apparmor
- MITRE ATT&CK T1562 Impair Defenses: https://attack.mitre.org/techniques/T1562/
- MITRE ATT&CK M1026 Privileged Account Management (least privilege): https://attack.mitre.org/mitigations/M1026/

