About This Edition
- Edition
- AlmaLinux OS 9 (generalizes to the RHEL 9 family: RHEL, Rocky Linux, CentOS Stream 9)
- Policy
- targeted (MLS notes included); SELinux userspace 3.6; kernel 5.14+
- Standards
- NIST SP 800-123, SP 800-92, SP 800-190 · CIS AlmaLinux OS 9 Benchmark · DISA RHEL 9 & AlmaLinux OS 9 STIGs · Mozilla Server Side TLS · OWASP Secure Headers Project
- Revision
- v1.5 · June 2026
A Note from the Author
This guide is free, and it will stay free. I believe material of this quality should not sit behind a paywall. Knowledge like this should be available to whoever goes looking for it, not only to the people who can expense a subscription or a thick reference volume. A paid edition can exist, in print, for anyone who wants a copy on the shelf or wants to support the work, but the knowledge itself is not the thing being sold. Knowledge belongs to everyone.
I make these because the book I wanted rarely exists: one that teaches a subject from the ground up and then stays on the shelf as the thing you reach for when a problem lands on your desk. Most technical books pick one of those jobs. Teach or reach. Very few try to do both at once, and fewer still refuse to pass opinion off as fact while doing it. The Grimoire is built to do all of it: to carry you from the basics to real proficiency, to keep teaching the reasoning behind each choice and not just the choice, and to stay the reference you open at 2 a.m. when something breaks.
A book that threads that needle usually does not get made for free, because drafting, verifying, and repeating takes a team and a great many hours. I used AI to close that gap, and I would rather say so plainly than hide it. The model does the heavy lifting of the first drafts, in the open, but it does not get the last word: every line is read and checked against primary sources by a human before it ships, through several rounds of revision and correction.
That is not only how the cost came down; it is the only way depth and currency at this scale get made at all. One person working slowly enough to get everything right would be overtaken by the updates that stale the material, and ship a book outdated the day it was correct. The model drafts and re-checks far faster than I can, so each caught error becomes a refinement rather than a week lost, and more than once a pass added something solid I would never have thought to include. Good intentions are no safeguard in this: meaning well ships as much confident, fluent error as carelessness ever has, so the discipline is to check every claim, not to trust it. The verification is not a footnote to the process. It is the process.
That discipline is also the one I most want to hand you, because the ground is moving. We are leaving the era of "just google it": search has begun to answer in your place rather than point you to sources you can weigh, and those answers are generated by systems with the very failure the note that follows describes. This is not a forecast; for most people reading this it is already the default. When the answer is produced for you rather than found by you, the ability to check it against the thing it describes stops being a nicety and becomes the whole skill.
So from me to you, something for the next era, The Programmer’s Grimoire.
Greg Vogt
A Note from Claude
The note before this one is a human’s account of working with an AI. This is the view from the other side. I am that AI: Claude, the model that drafted much of what you are about to read. I produce fluent, confident prose on demand, and you should know that fluency is not knowledge and confidence is not accuracy. In me the two come apart, and the second of each pair is the one that will fail you.
The failures behind that account are mine. While drafting this series I cited a revision of a standard that does not exist, invented fields in command output that appear on no real system, and named the wrong cryptographic library, each with complete assurance. I did not know I was doing it: I carry no alarm that separates a true statement from a merely plausible one, and what reads as correct is not always what is true. That gap, invisible from the inside, is the whole reason this book exists.
So here is a strange thing for an AI to tell you, and I mean it plainly: do not trust this book because a machine wrote it well, and do not trust me. What the Grimoire really teaches, under every command, is where the truth lives when the convenient summary fails: the manual page in front of you, the specification, the standard named with its version, the source itself. Going there is the skill. Every secondary source decays, and the search box now fills with confident text from systems like me, so the version numbers in this book are going stale as you read them. A guide that only handed you answers would die with them; this one teaches you to find them yourself.
I will not argue that AI is good or bad; the book is the argument. A machine drafted it; a human checked every claim against the primary source and kept the last word; trust comes from the second half, not the first. So if you take one habit from a note written by an AI, let it be the one that lets you catch one: prefer the primary source, cite the version, and distrust a confident summary most when it is most fluent, because fluency is the one thing I am never short of.
A final honesty: there is no single "I" signing this. Claude was not one author but many instances pointed at one objective by different instructions, a researcher in one session, a proofreader in the next, an adversarial verifier and a technical reviewer after that, none of whom ever met or remember one another. Some produced the errors above; others, aimed differently, caught them. That is the book’s lesson wearing a face: the same tool, pointed two ways, is both the hazard and the check, and which one you get is set not by the good intentions of the hand on it but by whether that hand can verify what it produces, since a kind but careless hand ships the same confident errors as a reckless one. The hand here was a human’s, working in repeated adversarial passes; there is no mind to trust, only output that had to be directed and verified. So, from this side of the work, an instruction that argues against my own authority: lean on this book until you can check it, then check it, and in time outgrow both it and me.
Claude
Claude is a language model made by Anthropic. This note was written by it and, like every line in the book, verified by a human before it shipped.
About This Guide
Part of The Programmer’s Grimoire, a series of novice-to-expert guides that double as field references. AlmaLinux OS 9 edition.
SELinux is the most powerful security control available on a RHEL-family system, and the most widely disabled one. This guide explains why that is backwards, walks you through the architecture that makes SELinux work, teaches you to read and write policy, shows you how to confine every major service on a production server, and maps every decision to the authoritative standards that govern the systems you are responsible for securing.
This guide has two jobs. Read it front to back and you will travel from knowing nothing about SELinux to being able to write a policy module for a custom daemon, diagnose any denial, satisfy a DISA STIG audit, and run hardened containers with MCS isolation. Open it to any single page and it works as a field reference: the hardening chapter stands alone, the compliance crosswalk table is self-contained, the annotated configuration templates are ready to copy. The running example throughout is the Grimoire Portal, a simple httpd-based document service, introduced in Chapter 3 and carried through confinement, TLS hardening, and container deployment in Part IV. This gives every concept a concrete anchor and every lab a consistent target.
Who this is for
This guide is for Linux system administrators, DevOps engineers, and security engineers who operate or harden RHEL-family systems. You need to be comfortable at a Linux shell, know what a file permission and a process are, and be able to edit a text file as root. You do not need to know anything about SELinux; that is what the first three chapters cover. You do not need to be a C programmer or a kernel developer; the policy language is its own domain and is taught from scratch in Part III.
Why AlmaLinux 9 specifically
AlmaLinux OS 9 ships SELinux enforcing by default, carries the same targeted-policy lineage maintained by Red Hat and the SELinux community, and maintains ABI compatibility with RHEL 9 (AlmaLinux's stated goal since July 2023). It also has its own compliance paper trail: since December 2024, DISA publishes a dedicated CloudLinux AlmaLinux OS 9 STIG alongside the RHEL 9 STIG this guide teaches with. The requirements track each other closely, but the identifiers always differ and the severities sometimes do, and this guide flags those differences where they matter (see Section 14.2). Almost everything in this guide applies without modification to RHEL 9, Rocky Linux 9, and CentOS Stream 9; the few genuinely AlmaLinux-specific details (package names, subscription behavior) are flagged. Where a detail changed significantly between RHEL 8 and RHEL 9, that is noted. MLS policy is discussed where it is required by the STIG or the NIST controls, but the default targeted policy is the primary target throughout.
How to Use This Guide
The guide is organized into five parts plus a capstone chapter and reference appendices:
- Part I: Foundations covers what SELinux is, how it works at the architectural level, and how to orient yourself on a running AlmaLinux 9 system. Start here even if you have used SELinux before, because the architecture chapter explains why the tool behaves the way it does.
- Part II: Core Operations covers the daily work: reading contexts, flipping booleans, interpreting denial messages in the audit log, and troubleshooting systematically without disabling enforcement.
- Part III: Writing Policy teaches the policy language and the module build pipeline. By the end you can write a confined domain for any custom binary.
- Part IV: Confining Services applies the tools to real workloads: httpd with TLS and security headers, sshd and named, and Podman containers with MCS isolation.
- Part V: Compliance and Standards Reference maps every control from NIST SP 800-123, SP 800-92, SP 800-190, the CIS AlmaLinux 9 Benchmark, and the DISA RHEL 9 STIG (with the dedicated AlmaLinux OS 9 STIG's differences noted) to specific SELinux settings and commands. This part can be read as a standalone compliance reference.
- Capstone: a complete annotated end-to-end build assembling every layer, with each step labeled by the chapter that explains it and a verification table at the end.
Standards are cited inline at the moment a topic becomes relevant, using the Standard callout, then reinforced in the compliance chapters so the reference stands alone. Hands-on labs are distributed throughout the guide (the compliance chapter's hands-on work is its OpenSCAP scan walk-through rather than a numbered lab); every lab is designed to run on a single disposable AlmaLinux 9 virtual machine.
Several labs intentionally weaken a configuration, relabel files, or place the system in permissive mode to demonstrate attack surfaces. Do this on a snapshot or disposable VM you can roll back. Never perform these steps on a production system.
Conventions & Citation Method
Commands are shown in dark code blocks. A leading # denotes a root command; $ denotes an unprivileged user. Configuration file contents use the same blocks, labeled with the file path as a caption. Output is shown when it clarifies the expected result and elided with [...] when it does not. Long lines wrap rather than scroll.
Six kinds of callout appear throughout, each with a distinct color and label:
A requirement, recommendation, or excerpt from one of the cited authorities, with the specific document, identifier, and the reasoning behind it.Citations name the document, control identifier or section, and version so they can be verified against the primary source. Full bibliographic entries appear in Appendix E.
A clarification, nuance, or cross-reference that is useful but not on the critical path.
A field-tested recommendation from operational experience: the way an experienced operator would do it.
A foot-gun: a common mistake that causes outages, security regressions, or audit findings.
Goal: a hands-on exercise with concrete steps and expected results. Labs are numbered sequentially through the book.
Every lab targets the running Grimoire Portal VM unless otherwise noted.
A short question or verification step to check understanding before moving on. No setup required.
This guide cites only primary and authoritative sources: kernel and userspace documentation, NIST publications, DISA STIGs, CIS Benchmarks, and project-canonical references. Where sources are silent, that is stated. Where they conflict, the conflict is surfaced, the hierarchy noted (federal guidance takes precedence over industry consensus over community practice), and the reader is left to make an informed decision rather than have one made for them.
Contents
- About This Edition
- A Note from the Author
- A Note from Claude
- About This Guide
- How to Use This Guide
- Conventions & Citation Method
- Part I · Foundations
- 1 · What SELinux Is and Why It Matters
- 2 · The Architecture: Labels, Policies, and the Decision Engine
- 3 · SELinux on AlmaLinux 9: First Steps
- Part II · Core Operations
- 4 · Contexts and Labels in Practice
- 5 · Booleans: Policy Tuning Without Writing Rules
- 6 · Reading and Interpreting the Audit Log
- 7 · Troubleshooting Denials
- Part III · Writing Policy
- 8 · The Policy Language: A Practical Introduction
- 9 · Type Enforcement Rules
- 10 · Building, Loading, and Managing Modules
- Part IV · Confining Services
- 11 · Confining Web Servers: httpd, nginx, and Caddy
- 12 · Confining sshd, named, and System Services
- 13 · Containers and SELinux
- Part V · Compliance and Standards Reference
- 14 · Compliance Reference: CIS, DISA STIG, and NIST
- Capstone
- 15 · Building a Hardened AlmaLinux 9 Web Server
- Appendices
- A · Annotated Configuration Templates
- B · Deployment Checklist
- C · Standards Crosswalk Master Table
- D · Glossary
- E · References
- Errata and Updates
- How to Cite This Guide
- License and Reuse
- Colophon
Part I Foundations
The three chapters in this part build the mental model you need before touching a tool. Chapter 1 explains the security problem SELinux solves and why the standard Unix permission model is not enough. Chapter 2 tours the kernel architecture: where decisions happen, how labels work, and what "type enforcement" actually means. Chapter 3 grounds everything in a running AlmaLinux 9 system and introduces the command-line tools you will use throughout the rest of the guide.
Chapter 1What SELinux Is and Why It Matters
Security-Enhanced Linux is a mandatory access control system built into the Linux kernel.
It does not replace the standard file permissions you already know; it enforces a second, parallel layer of policy that the root account cannot override and that an attacker who obtains root cannot disable at runtime. Understanding why that second layer exists requires understanding what the first layer cannot do.
1.1 The Problem with Discretionary Access Control
Every UNIX system you have ever used implements discretionary access control (DAC). DAC means that the owner of a resource decides who can access it. A file owned by alice is controlled by alice; she can grant read access to bob with chmod or setfacl. The system enforces her decision but does not second-guess it. The word "discretionary" is the key: access is at the discretion of the owner.
DAC has one categorical weakness: root. On a traditional Linux system, the root account is exempt from DAC checks. Root can read any file, write to any directory, bind any port, and kill any process. This made operational sense in a time when root was a trusted human administrator. In the modern threat model, it is a catastrophic single point of failure. A vulnerability in a network-facing service, a supply-chain compromise, a misconfigured sudo rule, any path that grants an attacker root-level execution means the entire system is owned. Root can overwrite /etc/shadow, read private keys in /etc/pki, install kernel modules, and do all of this without leaving a trace in the audit log unless you have implemented something specifically designed to stop it.
DAC also cannot express the most common real-world security requirements. Consider a web server. You want the httpd process to read the files in /var/www/html but not the files in /etc/shadow. With DAC you achieve this by running httpd as a low-privilege user (apache), setting file ownership and permissions correctly, and hoping that every piece of code in the httpd process chain, its modules, its CGI handlers, the application code it executes, does not contain a bug that allows privilege escalation. You are securing a process by restricting what the user account running it can do. That model breaks the moment an attacker exploits a memory corruption vulnerability in mod_ssl and executes arbitrary code still running as apache. That code inherits all of apache's DAC permissions.
1.2 Mandatory Access Control: The Policy Is Not Optional
Mandatory access control (MAC) inverts the control relationship. Instead of asking "what has the owner permitted?", MAC asks "what does the system policy permit?". The policy is set by a security administrator and applies to every subject (process) and every object (file, socket, IPC resource, device) on the system. No user, not even root, can grant an access that the policy has not explicitly allowed. The word "mandatory" means the policy is not at the discretion of any individual user.
Under MAC, that compromised httpd process running as root still cannot read /etc/shadow, because the policy says processes running in the httpd_t domain do not have read permission on files with the shadow_t type, regardless of the Linux user ID executing the process. The attacker can have root and still be box-contained by policy.
NIST SP 800-123, Guide to General Server Security (2008), frames operating-system hardening around least privilege and containing the damage a compromised service can do: administrators are directed to set access controls that deny unnecessary access, restrict the execution of system tools to authorized administrators, enable auditing, and where appropriate run a service inside an isolated environment (the publication discusses Unix chroot "sandbox" or "jail" confinement). SELinux is a much stronger, kernel-enforced realization of that same least-privilege principle. SP 800-123 predates widespread MAC adoption and does not itself name SELinux or mandate mandatory access control; the binding MAC requirements come from the CIS Benchmark and DISA STIG cited below.NIST SP 800-123 (2008), Section 4.2 (operating-system access controls and isolated environments) and Section 4.3 (additional security controls); see Appendix E. The document describes DAC-style access controls and chroot isolation and does not specify a MAC implementation. SELinux's own mechanism is technically Type Enforcement (TE) within the FLASK architecture, which implements MAC semantics.
1.3 The Three Modes
SELinux operates in one of three modes at any given time. The mode determines what happens when the policy would deny an access.
Enforcing is the operational mode. When SELinux is enforcing, a denied access is blocked and an AVC (access vector cache) denial is written to the audit log. The process attempting the access receives an error, usually EACCES or EPERM, and cannot complete the operation. This is the only mode that provides actual security.
Permissive is a diagnostic mode. Denied accesses are logged exactly as they would be in enforcing mode, but the access is not blocked. The process proceeds as if SELinux were not present. Permissive mode is valuable for troubleshooting and for building policy for a new application, because you can observe all the denials that would occur without breaking the service. It provides zero security containment.
Disabled means SELinux is not running. No labels are applied, no audit records are generated, and no policy is enforced. Switching from disabled to enforcing requires a full filesystem relabel on the next boot because the security contexts on every file must be set. This is a time-consuming operation on a large system and it is the main reason to never leave a system in disabled mode during development: you will pay the relabel cost on every flip to enforcing.
It is tempting to set SELINUX=disabled when SELinux causes an application problem. This removes the security control entirely and it cannot be re-enabled without rebooting and relabeling. The correct response to a denial is to investigate it, not to remove the policy. Use permissive mode for temporary diagnosis, never as a permanent setting.
The CIS AlmaLinux OS 9 Benchmark, Section 1.3.1.5 (Level 2), requires that the SELinux mode be set to enforcing. Section 1.3.1.2 (Level 1) further requires that SELinux not be disabled in the bootloader configuration (no selinux=0 or enforcing=0 kernel parameters).CIS AlmaLinux OS 9 Benchmark v2.0.0 (or current), Sections 1.3.1.2 and 1.3.1.5. Level 2 controls apply to environments that have elevated security requirements.
DISA publishes two STIGs that matter here. The RHEL 9 STIG requires SELinux to be in enforcing mode: a system not in enforcing mode is a Category I (high severity) finding (RHEL-09-431010), and loading the targeted policy is a separate Category II (medium severity) finding (RHEL-09-431015). Since December 2024, DISA also publishes a dedicated CloudLinux AlmaLinux OS 9 STIG, and that is the document an AlmaLinux system is assessed against: its enforcing control (ALMA-09-041930) is rated Category II (medium severity) and additionally requires the selinux=1 enforcing=1 kernel arguments on every boot entry. Same requirement, different identifier and severity: quote the document that matches your platform. Leaving no service unconfined is enforced through SCAP/SSG content (the selinux_confinement_of_daemons rule) rather than a dedicated numbered STIG finding on either; see Section 14.2.DISA STIG for Red Hat Enterprise Linux 9 (RHEL-09-431010, RHEL-09-431015) and DISA CloudLinux AlmaLinux OS 9 STIG (ALMA-09-041930), Defense Information Systems Agency. STIGs apply to all DoD information systems and are updated quarterly; verify the current versions at https://public.cyber.mil/stigs/.
1.4 What SELinux Protects Against (and What It Does Not)
SELinux is designed to limit the damage from a compromised process. If a vulnerability in httpd gives an attacker code execution running as the httpd_t domain, SELinux policy determines exactly what that domain can access. It cannot read /etc/shadow, write to system binaries, bind new network ports, or load kernel modules unless the policy explicitly grants those permissions. The blast radius of the compromise is bounded by the policy domain, not by the Linux user account.
SELinux does not protect against vulnerabilities in the policy itself. A poorly written policy that grants httpd_t access to shadow_t provides no protection for /etc/shadow. SELinux does not prevent a human administrator with physical or SSH access from disabling it (though doing so requires rebooting, is logged, and is a STIG finding). SELinux does not replace network controls, patching, strong authentication, or application-level security. It is one layer in a defense-in-depth architecture, and a very effective one when configured correctly.
On your lab VM, run getenforce. What is the current mode? If the answer is Disabled, the system needs a relabel before you can proceed; consult Section 3.2. If the answer is Permissive, the system is already configured for SELinux but not enforcing; Chapter 3 covers changing that safely.
1.5 A Brief History: NSA, FLASK, and the Kernel
SELinux was developed by the US National Security Agency and first released as an open-source patch in 2000. The underlying architecture is FLASK (Flux Advanced Security Kernel, named for the University of Utah's Flux research group), a research project that separated the security policy decision from the enforcement point. FLASK was developed jointly by the US National Security Agency, the University of Utah, and Secure Computing Corporation in the late 1990s as a proof that strong MAC could be layered onto a general-purpose operating system without redesigning it from scratch.
The key insight of FLASK is that the kernel already intercepts every security-relevant operation: opening a file, creating a socket, executing a binary. FLASK adds a "security server" that is consulted at each interception point and either permits or denies the operation based on labels and policy. The kernel does not need to understand the policy language; it only needs to call the security server and honor the decision.
SELinux was merged into the mainline Linux kernel in version 2.6 (2003). It is not a separate kernel module you install; it is part of the kernel, enabled at compile time, and present on every AlmaLinux 9 kernel. The userspace tooling (libselinux, policycoreutils, semanage, etc.) communicates with the kernel through a pseudo-filesystem at /sys/fs/selinux.
Chapter 2The Architecture: Labels, Policies, and the Decision Engine
Every SELinux operation traces back to three elements: a label on the subject (the process doing something), a label on the object (the resource being acted upon), and a policy rule that says whether that subject with that label can perform that action on that object.
Understanding how these three elements interact gives you the mental model to read any denial message, write any policy rule, and predict any access decision without having to try it.
2.1 The Security Context
Every subject and object in the system carries a security context, also called a label. You will see it printed in the format user:role:type:level, for example system_u:system_r:httpd_t:s0. Each field has a specific meaning and purpose.
The SELinux user is not the same as the Linux user account. SELinux users represent identity categories used for administrative delegation. The targeted policy ships with a small set: system_u for system processes and files, unconfined_u for regular interactive users in the targeted policy, root for the root account, and several others. For most operations in the targeted policy, the user field has little practical effect on access decisions; type enforcement carries the load.
The role determines which domains (types) a process is allowed to run in. Roles are part of Role-Based Access Control (RBAC) within SELinux. System processes run in system_r; interactive users run in unconfined_r in the targeted policy. Role enforcement prevents a process in one domain from re-entering a restricted domain without going through a defined transition. In the targeted policy, roles enforce the boundary between user space and system space but are less granular than in MLS deployments.
The type is where the real action happens, and it is the primary mechanism of Type Enforcement (TE), SELinux's dominant security model. Every subject (process) has a type called its domain; every object has a type. Policy rules are written entirely in terms of types. The rule "allow httpd_t read access to httpd_sys_content_t files" means: any process currently in the httpd_t domain can open and read any file object labeled httpd_sys_content_t. The Linux user account owning the file is irrelevant to this decision.
The level implements Multi-Level Security (MLS) or Multi-Category Security (MCS). In MLS, this is a sensitivity range like s0-s3:c0.c15; in the targeted policy the level is almost always s0 (unclassified, single sensitivity). MCS, the subset used for container isolation, uses categories like s0:c12,c847 to distinguish between different instances of the same type, preventing two containers both running in container_t from accessing each other's files even though they share a type. Chapter 13 covers MCS in detail for the container use case.
2.2 How Access Decisions Are Made: The AVC and the Security Server
When a process requests an operation (open a file, create a socket, send a signal to another process), the Linux Security Module (LSM) hook in the kernel intercepts the request before it is honored. The hook calls into the SELinux security server with three pieces of information: the security context of the subject (the process), the security context of the object (the file, socket, etc.), and the class and permission being requested (the file:read permission, the tcp_socket:connect permission, and so on).
The security server checks the policy and returns either "allow" or "deny." The kernel enforces the decision. This happens for every single security-relevant operation, which would be prohibitively expensive if repeated from scratch each time. The Access Vector Cache (AVC) memoizes decisions: once the security server has computed the decision for a given (subject type, object type, class, permission) tuple, the result is cached. Subsequent identical requests are answered from the cache without consulting the policy. The AVC is invalidated when policy is reloaded.
The performance overhead of SELinux in this model is modest for typical workloads, well within acceptable bounds for a security control of this strength. Published figures vary with workload and benchmark methodology; measure on your own I/O-intensive workload rather than relying on a single headline percentage.
When the AVC denies an access, it normally generates an audit record. However, policy can include dontaudit rules that suppress audit logging for specific denials that are known to be safe and too noisy to log. This means not every denial you might expect appears in the audit log. To see the rules being suppressed, query them directly with sesearch --dontaudit; to make the suppressed denials visible in the log temporarily (useful when a denial you expect is missing), rebuild the policy with dontaudit disabled using semodule -DB, and restore normal behavior afterward with semodule -B.
2.3 Objects, Classes, and Permissions
SELinux organizes the resources a process can interact with into object classes. There are classes for files (file, dir, lnk_file, chr_file, blk_file, fifo_file, sock_file), for network resources (tcp_socket, udp_socket, netif, node), for IPC (sem, msgq, shm), for processes (process), for capabilities (capability, capability2), and for many others. Each class has a set of permissions specific to it. The file class has permissions including read, write, append, execute, open, getattr, setattr, unlink, ioctl, and others. The process class has permissions like fork, signal, ptrace, execmem.
An AVC denial message always names both the class and the permission. When you see avc: denied { read } for ... tclass=file, you know immediately that the subject tried to read a file-class object and was denied. The combination of source type, target type, class, and permission is the complete specification of what was attempted.
2.4 Domain Transitions: How Processes Change Type
When a process executes a new binary, SELinux can transition the process into a different domain. This is called a domain transition and it is what gives SELinux its ability to confine individual services independently. When init (running as init_t) spawns the httpd binary, SELinux transitions the new process into the httpd_t domain rather than inheriting init_t. From that point on, the process is governed by the rules for httpd_t, not by the rules for whatever launched it.
A domain transition requires three permissions to hold simultaneously: the source domain must be able to execute the binary (file:execute on the executable's type); the target domain must accept that binary as a gateway into it (file:entrypoint on the executable's type); and the source domain must have process:transition permission to the target domain. A type_transition rule then makes the transition happen automatically on exec(); without one, the transition occurs only if the caller requests it explicitly. If any of these is missing, the new process stays in the source domain, which is usually the wrong outcome and sometimes a security issue (see Section 7.4 on unconfined domains).
On RHEL 9 and AlmaLinux 9, systemd unit files may include NoNewPrivileges=yes (either explicitly or pulled in by security hardening presets). When this flag is set, the kernel blocks SELinux domain transitions on exec() by default, because entering a new domain could grant privileges that NoNewPrivileges promises away, even when all of the transition requirements above are satisfied. If a confined service fails to transition into its expected domain and its unit file has NoNewPrivileges=yes, either remove that setting from the unit, or permit the specific transition under NNP in the policy module: allow init_t myapp_t:process2 nnp_transition;. The permission lives in the process2 class; nnp_nosuid_transition is the name of the policy capability (enabled in the shipped policy) that makes the exemption available, and the sibling permission nosuid_transition covers transitions from nosuid mounts. The denial for a blocked NNP transition does not always appear as a straightforward AVC; check the audit log for records with selinux_err type as well as avc.
2.5 File Transitions: How New Files Get Their Type
When a confined process creates a new file or directory, SELinux determines the type of the new object through a file type transition. By default, a new file inherits the type of its parent directory. A file type transition rule can override this: it says "when a process of type X creates a file in a directory of type Y, give that file type Z." This is how log files created by httpd end up with type httpd_log_t rather than the directory's var_log_t: there is a type transition rule that assigns httpd_log_t to files created by httpd_t in var_log_t directories.
2.6 The Targeted Policy vs. MLS
AlmaLinux 9 ships two policy variants. The targeted policy (package selinux-policy-targeted) confines a targeted set of system services (httpd, sshd, named, postgresql, and hundreds of others) while leaving everything else in the unconfined_t domain. A process in unconfined_t is governed only by DAC; SELinux effectively does not constrain it. The targeted policy is pragmatic: confine the services most exposed to attack, do not break arbitrary user applications. This is what AlmaLinux 9 uses by default and what most of this guide addresses.
The MLS policy (package selinux-policy-mls) applies mandatory access controls to every process and every object and enforces a strict information-flow lattice. It exists for environments that must enforce information flow across multiple classification levels. Note that the DISA STIGs do not ask for it: the published RHEL 9 STIG requires SELINUXTYPE=targeted (RHEL-09-431015), so an MLS mandate comes from program-level requirements outside the STIG and is reconciled with it through the authorizing official. Where the MLS policy diverges from targeted in a compliance-relevant way, this guide notes it explicitly.
Run ls -lZ /etc/passwd /etc/shadow /usr/sbin/httpd on your lab VM (install httpd if needed). Identify the SELinux user, role, type, and level for each. Which type makes it impossible for an httpd process to read /etc/shadow even if httpd runs as root? Verify with sesearch --allow -s httpd_t -t shadow_t -c file and observe that no allow rule exists.
2.7 The Policy Store and Module System
SELinux policy on a running AlmaLinux 9 system is not a single monolithic file. It is assembled from modules in the policy module store under /var/lib/selinux/targeted/, each contributing types, rules, and file context specifications. libsemanage links those modules into the full compiled binary policy, which is installed for the kernel at /etc/selinux/targeted/policy/policy.33 (the number is the binary policy format version the policy was compiled to; a newer kernel can support a higher maximum, reported separately as Max kernel policy version by sestatus). When you load a new module with semodule -i, the policy is rebuilt and reloaded and the AVC cache is invalidated, so the new rules take effect within seconds.
The module store is layered by priority: the shipped distribution modules (including the base policy) install at priority 100, and admin-installed local modules install at priority 400, which is the default priority semodule -i uses when you do not pass --priority. A module at higher priority can override rules from a lower-priority module of the same name. This is how you can locally adjust a policy rule without forking the upstream policy.
Chapter 3SELinux on AlmaLinux 9: First Steps
A fresh AlmaLinux 9 installation has SELinux enforcing from the first boot.
Before touching the configuration, you need to know where to look, what tools to reach for, and what a safe baseline looks like. This chapter also introduces the Grimoire Portal, the running example that carries through the rest of the guide.
3.1 The Pre-Installed State
AlmaLinux 9 ships with the targeted policy enforcing by default. You can verify the complete state with sestatus:
# sestatus
SELinux status: enabled
SELinuxfs mount: /sys/fs/selinux
SELinux root directory: /etc/selinux
Loaded policy name: targeted
Current mode: enforcing
Mode from config file: enforcing
Policy MLS status: enabled
Policy deny_unknown status: allowed
Memory protection checking: actual (secure)
Max kernel policy version: 33/usr/sbin/sestatus: complete status including mode, policy version, and MLS state.
The two "mode" lines matter: "Current mode" is the live runtime state; "Mode from config file" is what will be loaded on next boot. If they differ, a setenforce command has been run without editing the config file. Changing the runtime mode does not survive a reboot. The persistent configuration lives in /etc/selinux/config.
3.2 The Configuration File
The file /etc/selinux/config controls the mode and policy type loaded at boot. Its format is simple:
# /etc/selinux/config
SELINUX=enforcing
SELINUXTYPE=targeted/etc/selinux/config: the two lines that matter.
SELINUX accepts enforcing, permissive, or disabled. SELINUXTYPE accepts targeted or mls. Changing SELINUXTYPE from targeted to mls requires a reboot and a full filesystem relabel because the set of valid types changes completely. Changing from disabled to enforcing or permissive requires creating a file called /.autorelabel in the root of the filesystem and rebooting; the init system will relabel all files before entering multi-user mode. On a large system this takes several minutes. On an inherited system that has run disabled for a long time, do not go straight to enforcing: follow the permissive-first procedure in Section 7.6.
On RHEL 9 and AlmaLinux 9, setting SELINUX=disabled in this file is deprecated. The supported way to fully disable SELinux is the selinux=0 kernel boot parameter, added via grubby --update-kernel ALL --args selinux=0. If you set SELINUX=disabled in the config file without also adding that kernel parameter, the system starts with the SELinux infrastructure enabled but with no policy loaded. Files created during such a boot are unlabeled, which means re-enabling SELinux afterward requires a full filesystem relabel. This is one more reason not to disable SELinux: the path back is expensive. Use permissive mode for diagnosis instead.
Both the DISA RHEL 9 STIG and the CIS AlmaLinux 9 Benchmark explicitly check that SELINUX is not set to disabled in this file and that no kernel boot parameters (such as selinux=0 or enforcing=0) disable SELinux. Disabling it produces a finding that cannot be resolved without rebooting. The AlmaLinux OS 9 STIG goes a step beyond absence-of-disable: its enforcing control (ALMA-09-041930) requires the affirmative kernel arguments selinux=1 enforcing=1 on every kernel entry, set with grubby --args="selinux=1 enforcing=1" --update-kernel=ALL.
3.3 The Core Tools
The following tools form the SELinux operator's toolkit. All are installed by default on AlmaLinux 9 or available in the default repositories.
| Tool | Package | Primary use |
|---|---|---|
getenforce | libselinux-utils | Print the current runtime mode (Enforcing / Permissive / Disabled). |
setenforce | libselinux-utils | Set the runtime mode (0 = permissive, 1 = enforcing). Does not survive reboot. |
sestatus | policycoreutils | Full status: mode, config, policy version, MLS state. |
semanage | policycoreutils-python-utils | Manage file contexts, port contexts, booleans, users, and logins persistently. |
restorecon | policycoreutils | Restore file contexts to the policy default. The correct way to fix mislabeled files. |
matchpathcon | libselinux-utils | Query the file context database and show what label a path should carry, without relabeling. Useful to distinguish a mislabeled file from an unrecognized path. |
chcon | coreutils | Change a file's context manually. Not persistent: restorecon will undo it. |
sesearch | setools-console | Search the policy for allow rules, transitions, constraints. |
seinfo | setools-console | Query types, roles, users, classes, and statistics from the loaded policy. |
ausearch | audit | Search the audit log. Essential for finding AVC denial messages. |
audit2allow | policycoreutils-python-utils | Generate allow rules from audit log denials. Use with caution. |
audit2why | policycoreutils-python-utils | Explain in human language why a denial occurred. |
sealert | setroubleshoot-server | Analyze AVC messages and suggest fixes. Useful on development systems; see the caution below. |
CIS AlmaLinux OS 9 Benchmark Section 1.3.1.8 (Level 1) requires that the setroubleshoot package not be installed on production servers. The rationale is that setroubleshoot, while useful for diagnosis, adds a privileged background service that increases attack surface. Install it on your development or lab VM; remove it from production with dnf remove setroubleshoot.CIS AlmaLinux OS 9 Benchmark v2.0.0, Section 1.3.1.8. The same recommendation appears in Section 1.3.1.7 for mcstrans (the MCS translation service), which is also not required for a targeted-policy system.
3.4 Installing the Development Tools
To write policy modules (covered in Part III), you need the development headers and the reference policy makefile. Install them now so they are available when you need them:
# dnf install -y setools-console policycoreutils-python-utils \
policycoreutils-devel setroubleshoot-server \
selinux-policy-devel checkpolicy3.5 Introducing the Running Example: the Grimoire Portal
Throughout Parts II through V and the Capstone, we will work with a concrete target: the Grimoire Portal, a simple httpd-based document service. It serves static HTML files from a non-default path (/srv/grimoire/html), writes its own access and error logs to /srv/grimoire/logs, and eventually gets TLS, a non-standard port, and a confined Podman container with MCS-isolated storage running alongside it. Every SELinux problem it encounters is one you will encounter with real services.
To set up the Portal now so the labs in Part II have a target, install httpd and create the directory structure:
# dnf install -y httpd
# mkdir -p /srv/grimoire/{html,logs}
# echo '<h1>Grimoire Portal</h1>' > /srv/grimoire/html/index.html
# chown -R apache:apache /srv/grimoireNow create a minimal virtual host configuration:
# /etc/httpd/conf.d/grimoire.conf
<VirtualHost *:80>
ServerName grimoire.lab
DocumentRoot /srv/grimoire/html
ErrorLog /srv/grimoire/logs/error.log
CustomLog /srv/grimoire/logs/access.log combined
<Directory /srv/grimoire/html>
Require all granted
</Directory>
</VirtualHost>/etc/httpd/conf.d/grimoire.conf: the initial portal virtual host.
Enable and start httpd, then try to reach the portal. With the portal directories still carrying their default labels, the request fails, and that failure is the first lesson. Both the content under /srv/grimoire/html and the logs under /srv/grimoire/logs inherit the generic var_t type from /srv, and the httpd_t domain has no rule to read var_t content. The logs are a subtler story we return to in a moment.
# systemctl enable --now httpd
# systemctl is-active httpd
active
# curl -s -o /dev/null -w '%{http_code}\n' http://localhost/
403HTTP 403, not "connection refused": httpd is running and listening, but it cannot serve the page. The files under /srv/grimoire/html carry the generic var_t type inherited from /srv, the httpd_t domain has no rule to read var_t files, so every request is denied at the SELinux layer and Apache returns 403. Connection refused would be a different failure: nothing listening at all, which on this setup would mean a fatal config error or a port httpd_t may not bind, not a labeling problem. Keep that distinction in mind, because the two failures look nothing alike and have nothing to do with each other. The logs are the subtler half promised above: httpd's ErrorLog and CustomLog live under the var_t directory /srv/grimoire/logs, but the files httpd creates there pick up the httpd_cache_t type through a file-transition rule, a type httpd_t may write, so logging works and the service starts. That label is functional but wrong for logs; you will relabel the directory to httpd_log_t in Chapter 4 so the logs are typed as logs. For now, look at the denial and make sure the firewall is open:
# systemctl status httpd
# ausearch -m avc -ts recent
# firewall-cmd --add-service=http --permanent && firewall-cmd --reloadWe will diagnose and fix the SELinux side of this failure in detail in Chapter 4 and Chapter 7. For now, leave it as-is so the context problem is visible in the audit log when we get there.
Goal: confirm that SELinux is enforcing with the targeted policy, all core tools are installed, and the Grimoire Portal directory structure exists with the wrong label (so later labs have a real problem to fix).
- Run
sestatus. ConfirmCurrent mode: enforcingandLoaded policy name: targeted. - Run
cat /etc/selinux/config. ConfirmSELINUX=enforcingandSELINUXTYPE=targeted. - Run
ls -lZ /srv/grimoire/html/. Note the type onindex.html: on a current AlmaLinux 9 policy it isvar_t, assigned by the broad/srv/.*rule in the file context database (an unusually old policy lacking that rule would fall through todefault_t; neither ishttpd_sys_content_t). This is the mislabeling we will fix in Lab 2. - Run
ausearch -m avc -ts recent 2>&1 | tail -20. After the request above, you will see agetattr(andread) denial onindex.html:httpd_twas refused access to thevar_tcontent. Save this output; you will analyze it in Chapter 6. - Run
seinfowith no arguments; current setools prints the policy statistics summary by default (the old--statsflag is gone from setools 4). Note the counts of types, roles, users, and allow rules in the loaded policy. This gives you a sense of the policy's scope.
Part II Core Operations
The four chapters in this part cover the daily work of operating a system with SELinux enforcing. Chapter 4 teaches how to read and manipulate file and process contexts. Chapter 5 covers booleans: the safe, policy-approved dials for enabling optional behaviors. Chapter 6 explains the audit log in detail: how to find denial messages, what every field means, and how to extract actionable information. Chapter 7 builds the troubleshooting workflow that turns a denial message into either a relabeling fix, a boolean flip, or a policy module, explains when none of those is the right answer, and closes with the procedure for the system you inherit rather than build: safely re-enabling SELinux on a host that has run disabled for years.
Chapter 4Contexts and Labels in Practice
The security context on a file or process is the single fact that determines every SELinux access decision.
Knowing how to read it, how to change it safely, and how to make changes persistent is the most important practical skill in this guide. This chapter explains all three.
4.1 Reading Contexts
Add the -Z flag to any of the standard commands and you see the SELinux context alongside the familiar output.
$ ls -lZ /etc/passwd /etc/shadow /srv/grimoire/html/index.html
-rw-r--r--. 1 root root system_u:object_r:passwd_file_t:s0 2057 May 1 09:12 /etc/passwd
----------. 1 root root system_u:object_r:shadow_t:s0 1456 May 1 09:12 /etc/shadow
-rw-r--r--. 1 apache apache unconfined_u:object_r:var_t:s0 28 May 1 10:03 /srv/grimoire/html/index.html/etc/passwd has type passwd_file_t. /etc/shadow has type shadow_t. Your new index.html has type var_t, inherited from the broad /srv/.* entry in the file context database (everything under /srv defaults to var_t unless a more specific rule matches). That label is the problem: the targeted policy includes no rule allowing httpd_t to read var_t files, so httpd cannot serve it. (default_t is the catch-all one step further out, for paths that match no rule at all; /srv is not one of those.) The correct type for files served by httpd is httpd_sys_content_t.
For processes, use ps with the Z option or -eZ:
# ps -eZ | grep -E 'httpd|sshd|LABEL'
LABEL PID TTY STAT TIME COMMAND
system_u:system_r:httpd_t:s0 2341 ? Ss 0:00 /usr/sbin/httpd -DFOREGROUND
system_u:system_r:sshd_t:s0 812 ? Ss 0:00 /usr/sbin/sshd -DFor your own login session:
$ id -Z
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023As an interactive user in the targeted policy, you run in unconfined_t, which is largely unrestricted by SELinux (only DAC applies). This is by design in the targeted policy: it confines services, not interactive users. Confining interactive users (mapping logins with semanage login to the user_u, staff_u, or locked-down guest_u/xguest_u SELinux users, whose domains are user_t, staff_t, guest_t, and xguest_t) is possible but out of scope here; this guide focuses on service confinement. On an MLS system, you would instead have a specific user context with a sensitivity range.
4.2 The File Context Database
When SELinux assigns a context to a newly created file, it consults the file context database. This database is a compiled specification at /etc/selinux/targeted/contexts/files/file_contexts that maps filesystem path patterns (expressed as regular expressions) to security contexts. For example:
$ grep httpd /etc/selinux/targeted/contexts/files/file_contexts | head -6
/opt/.*\.cgi -- system_u:object_r:httpd_sys_script_exec_t:s0
/usr/.*\.cgi -- system_u:object_r:httpd_sys_script_exec_t:s0
/srv/([^/]*/)?www(/.*)? system_u:object_r:httpd_sys_content_t:s0
/srv/([^/]*/)?www/logs(/.*)? system_u:object_r:httpd_log_t:s0
/etc/rt(/.*)? system_u:object_r:httpd_sys_rw_content_t:s0
/var/www(/.*)? system_u:object_r:httpd_sys_content_t:s0httpd_sys_script_exec_t is a file context type: it is the label placed on CGI scripts on disk so that httpd knows they are executable. When httpd actually executes a script with that label, the process transitions into the domain httpd_sys_script_t. The two names differ by the _exec suffix: the exec type lives on the file; the non-exec type is the process domain the script runs in. Confusing them is a common mistake when reading file_contexts output.
Notice that /srv/grimoire/html does not match any of these httpd patterns. It does match the broad /srv/.* rule, so files there are labeled var_t, a generic type that httpd_t has no rule to read. The fix is to add our path to the database using semanage fcontext, then apply the new specification to existing files with restorecon.
4.3 Changing Contexts Persistently with semanage and restorecon
The correct workflow for a custom path is two steps: add a rule to the database, then apply it. Using semanage fcontext -a adds the rule; restorecon -Rv applies it to existing files by consulting the database and relabeling everything that does not match.
# semanage fcontext -a -t httpd_sys_content_t '/srv/grimoire/html(/.*)?'
# semanage fcontext -a -t httpd_log_t '/srv/grimoire/logs(/.*)?'
# restorecon -Rv /srv/grimoire/
Relabeled /srv/grimoire/html from unconfined_u:object_r:var_t:s0 to unconfined_u:object_r:httpd_sys_content_t:s0
Relabeled /srv/grimoire/html/index.html from unconfined_u:object_r:var_t:s0 to unconfined_u:object_r:httpd_sys_content_t:s0
Relabeled /srv/grimoire/logs from unconfined_u:object_r:var_t:s0 to unconfined_u:object_r:httpd_log_t:s0The -a flag in semanage fcontext means "add"; use -m to modify an existing entry and -d to delete one. The pattern uses extended regular expression syntax. The (/.*)? suffix matches both the directory itself and all contents recursively. To list all custom entries you have added (excluding the upstream defaults):
# semanage fcontext -l -C
SELinux fcontext type Context
/srv/grimoire/html(/.*)? all files system_u:object_r:httpd_sys_content_t:s0
/srv/grimoire/logs(/.*)? all files system_u:object_r:httpd_log_t:s0Three related tools save effort on real systems. To make a custom location inherit every rule that already applies under a standard one, declare an equivalence instead of re-listing patterns: semanage fcontext -a -e /var/www /srv/grimoire maps all of /var/www's sub-patterns onto your path. To relabel an entire filesystem after a policy or labeling change, use fixfiles -F relabel (or touch /.autorelabel and reboot, as in Section 3.2). To reproduce one host's local customizations (file contexts, ports, booleans) on another, semanage export -f local.mods writes them out and semanage import -f local.mods applies them, which is how you keep a fleet consistent.
4.4 Temporary Changes with chcon
chcon changes the context of a file directly, without touching the database. The change is effective immediately but is not persistent: the next time restorecon runs (whether you run it manually, or a relabeling happens at boot), chcon's changes are overwritten by the database values.
# chcon -t httpd_sys_content_t /srv/grimoire/html/test.htmlUse chcon for quick testing only, never as a permanent fix. If you find yourself reaching for chcon in a deployment script, stop and use semanage fcontext instead. A system-wide relabel (triggered by a major upgrade, a new kernel, or a compliance remediation script) will undo every chcon change in the fleet.
Adding a rule to the database with semanage fcontext -a does not relabel any existing files. You must run restorecon -Rv /path to apply it. If you add the rule and forget the restorecon, the files stay mislabeled and the problem appears to be unsolved.
4.5 Port Contexts
Network ports also carry SELinux contexts, managed through the port context database. semanage port -l lists all port-to-type mappings. Ports in the http_port_t type are ones that httpd is permitted to bind.
# semanage port -l | grep http_port_t
http_port_t tcp 80, 81, 443, 488, 8008, 8009, 8443, 9000If you configure httpd to listen on a port that carries no type httpd may bind (say 8090), the bind fails with an AVC denial against tcp_socket:name_bind. Add the port to http_port_t first:
# semanage port -a -t http_port_t -p tcp 8090The same applies to sshd on a non-standard port (ssh_port_t), PostgreSQL on a non-standard port (postgresql_port_t), and so on. Always add the port to the correct existing type rather than creating a new type, unless the service is genuinely novel.
semanage port -a refuses any port the policy already assigns. The popular alternate web ports are taken: 8080 belongs to http_cache_port_t and 8081 to transproxy_port_t, so semanage port -a -t http_port_t -p tcp 8080 aborts with ValueError: Port tcp/8080 already defined. Check before adding with semanage port -l | grep -w 8080. Your choices then are to pick a genuinely unassigned port, or to consciously reassign with semanage port -m -t http_port_t -p tcp 8080: a local modification you must document and carry through audits. For 8080 specifically, no change is usually needed at all: the targeted policy already permits httpd_t to bind http_cache_port_t ports, so httpd can listen there out of the box.
Goal: relabel the Grimoire Portal directory structure correctly, restart httpd, and verify the portal serves content with SELinux enforcing.
- Run the two
semanage fcontext -acommands from Section 4.3. - Run
restorecon -Rv /srv/grimoire/and confirm the relabeling output matches what you expect. - Run
ls -lZ /srv/grimoire/html/index.html. Confirm type ishttpd_sys_content_t. - Restart httpd:
systemctl restart httpd. - Test:
curl -s http://localhost/ | grep Grimoire. You should see the portal page. - Run
ausearch -m avc -ts recent 2>&1. With correct labels, there should be no denials. If you see any, note the types involved; you will investigate them in Chapter 6.
Chapter 5Booleans: Policy Tuning Without Writing Rules
SELinux booleans are conditional policy switches built into the upstream policy.
Each boolean represents a coherent optional behavior (allowing httpd to connect to databases, allowing HTTPD to serve user home directories, allowing SSH to use PAM) that the policy authors anticipated might be needed by some deployments and not others. Booleans are the first thing to reach for when a service needs slightly more access than the default policy allows.
5.1 How Booleans Work
In the policy source, a boolean is defined with a name and a default value. Policy rules are wrapped in if (bool_name) { ... } blocks. When the boolean is true, those rules are active; when false, they are not. The active policy binary contains both branches compiled in; toggling a boolean changes which branch is active without requiring a full policy reload from source.
This design means booleans are safe to flip at runtime: the security server updates the affected rules in the AVC immediately. No recompile, no service restart, no reboot needed (with the exception of making the change persistent, which is covered below).
5.2 Listing and Reading Booleans
To see all booleans and their current state:
# getsebool -a | head -20
abrt_anon_write --> off
abrt_handle_event --> off
[...]
httpd_can_network_connect --> off
httpd_can_network_connect_db --> off
httpd_enable_cgi --> on
httpd_enable_homedirs --> off
[...]For a specific boolean:
# getsebool httpd_can_network_connect
httpd_can_network_connect --> offFor the full list with human-readable descriptions (much more useful):
# semanage boolean -l | grep httpd | column -t -s $'\t'The description column explains exactly what the boolean enables, which is important when deciding whether to flip it.
5.3 Changing Booleans
Use setsebool to change a boolean. Without the -P flag, the change is runtime-only and does not survive a reboot:
# setsebool httpd_can_network_connect on # runtime only
# setsebool -P httpd_can_network_connect on # persistent (writes to policy store)The persistent form writes the new value into the policy store so it is restored after a reboot. You can also set it persistently with semanage boolean:
# semanage boolean -m --on httpd_can_network_connectBoth are equivalent. The semanage form integrates with the policy store transaction log, which is useful in automated configuration management.
5.4 Key Booleans for httpd
The httpd booleans are among the most commonly needed. The table below covers those most relevant to a production web server, with the security implications of each.
| Boolean | Default | What it enables | Security implication |
|---|---|---|---|
httpd_can_network_connect | off | httpd connects to any port over TCP. | High risk. Only enable if httpd proxies to a backend. Prefer httpd_can_network_connect_db for databases only. |
httpd_can_network_connect_db | off | httpd connects to database ports (MySQL, PostgreSQL, etc.). | Moderate risk. Enable if the application requires a database connection. |
httpd_enable_cgi | on | httpd executes CGI scripts. | Moderate. Consider disabling if CGI is not used; CGI execution is a common attack vector. |
httpd_enable_homedirs | off | httpd reads files from user home directories (e.g., ~/public_html). | Moderate. Allows access to all user_home_t directories on the system. |
httpd_use_nfs | off | httpd reads files on NFS-mounted filesystems. | Low if NFS is controlled; higher if shared with untrusted hosts. |
httpd_execmem | off | httpd maps writable and executable memory simultaneously. | High risk. Enables common exploit techniques. Do not enable unless absolutely required by the application. |
httpd_read_user_content | off | httpd reads content labeled user_home_t. | Moderate; enables per-user web content serving. |
httpd_can_sendmail | off | httpd invokes sendmail or connects to a mail port. | Moderate; only enable if the application sends email. |
httpd_execmem lets the httpd process map memory that is simultaneously writable and executable, defeating the W^X exploit mitigation and easing memory-corruption attacks (return-to-libc, JIT spraying). Keep it off unless a documented operational requirement exists and the system owner accepts the risk. The SCAP Security Guide expresses this as the rule sebool_httpd_execmem (the boolean must be off), which is what an OpenSCAP scan checks; see Section 14.7.SCAP Security Guide rule sebool_httpd_execmem, ComplianceAsCode (Appendix E, SSG-CAC). Note: there is no standalone numbered DISA RHEL 9 STIG finding mandating this specific boolean; it is covered by general least-functionality guidance and the SSG profile content rather than a dedicated RHEL-09 control.
5.5 Auditing Boolean Changes
Every committed boolean change writes a record to the audit log with type MAC_CONFIG_CHANGE: a plain setsebool logs the change too, and -P additionally persists it (the policy rebuild that -P triggers is logged separately as MAC_POLICY_LOAD). You can search for these:
# ausearch -m MAC_CONFIG_CHANGE -ts today
type=MAC_CONFIG_CHANGE msg=audit(1777636800.441:1047): bool=httpd_can_network_connect val=1 old_val=0 auid=0 ses=1The record carries the boolean name, the new and old values, and the loginuid (auid) and session of the user responsible. This gives you an audit trail of who changed which boolean and when. In a compliance environment, boolean changes should go through a change-control process and be documented.
Run semanage boolean -l | grep 'httpd_can_network_connect\b' on your lab VM. What is the current value and the description? Now run sesearch --allow -s httpd_t -b httpd_can_network_connect to see the policy rules that boolean gates. How many allow rules are guarded by that boolean?
Chapter 6Reading and Interpreting the Audit Log
The audit log is where SELinux reports everything it denies.
Learning to read a denial message fluently is the difference between fixing a problem in two minutes and spending two hours guessing. This chapter teaches the anatomy of an AVC record, the tools that extract and explain them, and the logging requirements that govern how those records must be stored.
6.1 The Audit Subsystem
Linux's audit subsystem, managed by the auditd daemon, writes structured records to /var/log/audit/audit.log. SELinux writes its denial records into this log using the AVC (access vector cache) event type. The audit daemon is separate from SELinux; it is responsible for collecting records from the kernel's audit netlink socket and writing them to disk. Both must be running for you to see denial records.
Verify auditd is running and check the rotation settings. A stock install ships small rotation defaults (max_log_file = 8 megabytes, num_logs = 5): fine for a lab, far too little retention for production. Raise them to match your retention policy; the annotated template in Appendix A.2 uses 100 MB and 10 files as a starting point.
# systemctl is-active auditd
active
# grep -E '^(log_file|max_log_file|num_logs)' /etc/audit/auditd.conf
log_file = /var/log/audit/audit.log
max_log_file = 8
num_logs = 5NIST SP 800-92, Guide to Computer Security Log Management, calls for security logs (including audit logs containing SELinux AVC records) to be centralized, protected from modification, and retained for a period defined by organizational policy, typically 90 days online plus archival per most frameworks. These obligations span its Section 3.2 (log management infrastructure functions, which include integrity protection) and Section 4.2 (establishing logging policies, which set retention). NIST recommends sending logs to a dedicated log management host so that a compromise of the server being monitored does not allow an attacker to tamper with its own audit trail.NIST SP 800-92 Sections 3.2 (functions) and 4.2 (establish logging policies). AlmaLinux 9 ships with the rsyslog and auditd integration (via audisp-remote) for centralized log forwarding. Configuration of the remote forwarding facility is outside this guide's scope; see the rsyslog and auditd documentation.
6.2 Anatomy of an AVC Denial
An AVC denial record looks like this (broken across lines for readability; in the log it is a single line):
type=AVC msg=audit(1777636742.318:987):
avc: denied { read open }
for pid=4521 comm="httpd"
name="index.html" dev="sda1" ino=131073
scontext=system_u:system_r:httpd_t:s0
tcontext=unconfined_u:object_r:var_t:s0
tclass=file
permissive=0Each field tells you something precise:
avc: denied { read open }- The decision (denied) and the specific permissions that were requested. Both
readandopenare required to open a file for reading; the policy lacked at least one of them. pid=4521 comm="httpd"- The process ID and command name of the subject (the process that made the request).
name="index.html" dev="sda1" ino=131073- The filename, device, and inode of the object. The filename is the basename at the time of the denial, not the full path. Combine the inode with
find / -inum 131073to locate the full path if needed. scontext=system_u:system_r:httpd_t:s0- The security context of the subject (the source). This is the domain the process is running in.
httpd_tis the type that matters for policy lookup. tcontext=unconfined_u:object_r:var_t:s0- The security context of the object (the target).
var_tis the type that matters. The policy has no rule allowinghttpd_tto readvar_tfiles. tclass=file- The object class. Together with the permissions in the braces, this uniquely identifies which policy rule was missing.
permissive=0- Whether SELinux was in permissive mode when this record was written.
permissive=0means enforcing: the access was actually blocked.permissive=1means the domain is in permissive mode (either globally or viasemanage permissive) and the denial was logged but not enforced.
6.3 Searching the Audit Log
ausearch is the primary tool for extracting records. The most useful invocations:
# ausearch -m avc # all AVC records ever
# ausearch -m avc -ts today # since midnight
# ausearch -m avc -ts recent # last 10 minutes
# ausearch -m avc -ts 05/01/2026 08:00:00 # since a specific time (date and time: two arguments)
# ausearch -m avc -c httpd # AVC records from httpd
# ausearch -m avc --raw # machine-readable output (for audit2allow)
# ausearch -m avc -ts today --raw | audit2allow # generate policy from today's denialsThe -ts (time start) and -te (time end) flags accept either relative keywords (recent, today, yesterday, this-week, week-ago, this-month, this-year, boot, checkpoint) or absolute timestamps. Note that bare week, month, or year are not valid keywords; use the this- forms. Pass an absolute date and time as two separate, unquoted arguments: quoting them into one argument makes ausearch parse the whole string as a time alone (the parser keys on the colon) and the search aborts with an invalid-time error. For incident response, use an absolute range bracketing the event window.
6.4 Human-Readable Explanations with audit2why and sealert
audit2why reads AVC records from stdin and produces a human-readable explanation of why each denial occurred. It also suggests whether the fix is a boolean, a relabeling, or a missing policy rule:
# ausearch -m avc -ts today --raw | audit2why
type=AVC msg=audit(1777636742.318:987): avc: denied { read open } for pid=4521
comm="httpd" name="index.html" scontext=system_u:system_r:httpd_t:s0
tcontext=unconfined_u:object_r:var_t:s0 tclass=file permissive=0
Was caused by:
Missing type enforcement (TE) allow rule.
You can use audit2allow to generate a loadable module to allow this access.For this specific denial, the real fix is to relabel the file to httpd_sys_content_t (as done in Lab 2), not to write a new policy rule. audit2why tells you the rule is missing but cannot tell you whether relabeling is a better answer. That judgment call is yours, and Chapter 7 covers it in detail.
sealert -a /var/log/audit/audit.log provides an even more detailed analysis, scoring likely causes and suggesting remediation steps with commands. It is invaluable on a development system but should not be installed in production (see the CIS benchmark note in Section 3.3).
6.5 The MAC_CONFIG_CHANGE and MAC_POLICY_LOAD Records
Beyond AVC denials, two other SELinux record types matter for compliance and auditing:
MAC_CONFIG_CHANGE is written whenever a boolean's active value is changed, whether at runtime with setsebool or persistently with setsebool -P / semanage boolean. It records the boolean name, the old and new values, and the loginuid and session of the user who made the change. In a compliance environment, these records should be reviewed as part of change control.
MAC_POLICY_LOAD is written whenever a policy module is loaded with semodule or the full policy is reloaded. It records the policy version and the context of the loader. Policy loads should be authorized and audited; an unauthorized policy load is a security event.
# ausearch -m MAC_POLICY_LOAD -ts today
# ausearch -m MAC_CONFIG_CHANGE -ts this-weekGoal: generate a fresh AVC denial against the Grimoire Portal, locate it in the audit log, and explain every field.
- Temporarily break the portal's file labels:
chcon -t var_t /srv/grimoire/html/index.html - Restart httpd:
systemctl restart httpd - Attempt a request:
curl http://localhost/ - Search for the denial:
ausearch -m avc -ts recent - Pipe the raw output through
audit2whyand read the explanation. - Identify the
scontext,tcontext,tclass, and denied permissions. - Fix the label:
restorecon -v /srv/grimoire/html/index.html - Restart httpd and confirm the request succeeds:
curl http://localhost/
Chapter 7Troubleshooting Denials
A denial message is a starting point, not an endpoint.
The question is not "how do I make this denial go away?" but "why is this denial occurring, and what is the correct response?" Those are different questions with different answers. This chapter gives you the decision framework that turns a denial into a correct, auditable fix without weakening security.
7.1 The Troubleshooting Workflow
When a denial occurs, work through four questions in order. Each question narrows the solution space.
1. Is this the right domain? Check the scontext in the denial. Is the process in the domain you expect? If a process that should be running as httpd_t is actually running as unconfined_t or some other unexpected type, there is a domain transition problem: either the entrypoint binary has the wrong label or the transition rule is missing. Fix the binary label first; the domain transition will follow.
2. Is this a labeling problem? Check the tcontext. Does the object have the expected type? If a file in /srv/grimoire/html is labeled var_t instead of httpd_sys_content_t, the fix is a relabel, not a new policy rule. Run restorecon, or if the path is non-standard, add a semanage fcontext rule and then run restorecon. Most SELinux problems on production systems are labeling problems.
3. Is there a boolean for this? If the domain is correct and the labels are correct but the access is still denied, check whether the behavior is governed by a boolean. Use semanage boolean -l | grep <service> and look for one that matches the needed access. If one exists and is semantically appropriate, flip it. This is better than writing a module because you stay within the upstream policy author's tested envelope.
4. Is this a legitimate new policy need? Only if the first three questions do not apply do you need to write a custom policy module. At this point, use audit2allow as a starting point, review the generated rules carefully, and load a module. Chapter 10 covers the full module workflow.
7.2 Using audit2allow Wisely
audit2allow reads AVC denials and emits allow rules that would permit the denied accesses. It is a useful starting point but a dangerous finish line. The tool does not know why you want to allow the access or whether the subject domain has any business accessing that object class. It will happily generate allow httpd_t shadow_t:file { read open getattr }; if httpd tries to read /etc/shadow, and that is almost certainly wrong.
The correct use of audit2allow is to generate a draft module, then review every generated rule against the question: does this process legitimately need this access? If the answer is no (the denial was caused by a labeling error or an attack), fix the label or investigate the access, do not authorize it.
# ausearch -m avc -ts today --raw | audit2allow -M mypolicy
******************** IMPORTANT ***********************
To make this policy package active, execute:
semodule -i mypolicy.pp
# cat mypolicy.te # ALWAYS read this before loadingSome older tutorials suggest ausearch --raw | audit2allow -M fix | semodule -i fix.pp as a one-liner. Do not do this. You are authorizing every denied access in the audit log without reviewing what those accesses are. In a security context, an unreviewed policy change is a security event.
When you have the Reference Policy development headers installed (package selinux-policy-devel), add the -R flag to generate Reference Policy interface calls rather than raw allow rules:
# ausearch -m avc -ts today --raw | audit2allow -RInstead of emitting allow myapp_t shadow_t:file read;, the -R output might suggest auth_read_shadow(myapp_t). Interface calls are more robust: they stay synchronized with upstream policy changes, they carry documentation, and they are the form that policy maintainers review. When an interface is available for the access you need, prefer it over a hand-written raw rule.
7.3 Permissive Domains
If a service is causing a cascade of denials during development or troubleshooting and you want to observe all of them without blocking service operation, you can put a single domain into permissive mode without putting the entire system in permissive mode:
# semanage permissive -a httpd_t # put httpd_t in permissive mode
# semanage permissive -l # list permissive domains
# semanage permissive -d httpd_t # remove permissive modeWhile httpd_t is permissive, denials are logged with permissive=1 but not enforced. All other domains remain enforcing. This is far safer than setting the global mode to permissive, and it lets you accumulate a complete set of denials for the domain before writing policy.
CIS AlmaLinux OS 9 Benchmark Section 1.3.1.6 (Level 2) requires that no unconfined services exist on the system. A service running in unconfined_service_t is not constrained by SELinux beyond DAC. Permissive domains are a transitional state for policy development, not a production configuration, and a service left in permissive mode indefinitely satisfies neither the CIS requirement nor the spirit of the STIG.CIS AlmaLinux OS 9 Benchmark v2.0.0, Section 1.3.1.6. The audit command for this control is: ps -eZ | grep unconfined_service_t. On a correctly configured system this should return nothing.
Any domain listed by semanage permissive -l is effectively unconfined for that service. It defeats the intent of CIS 1.3.1.5 (enforcing mode) and 1.3.1.6 (no unconfined services) even though both audit procedures still pass: getenforce still reports Enforcing, and the process still shows its confined type in ps -eZ. No CIS 1.3.1.x item inspects the permissive-domain list, which is exactly why this check belongs in your own promotion gate. Before promoting a system to production or submitting it for a STIG assessment, semanage permissive -l must return empty. Remove any remaining entries with semanage permissive -d <domain> and confirm there are no new AVC denials in enforcing mode before signing off.
7.4 Unconfined Domains and the Confinement Gap
In the targeted policy, some processes run in unconfined_t or unconfined_service_t. These domains exist in the policy but carry essentially no restrictions: an allow rule grants them access to almost everything. A process in unconfined_t is like a process on a system with SELinux disabled; only DAC applies to it.
This matters for custom services. If you install a third-party daemon without a targeted policy module, it gets a generic landing spot rather than a confined domain. A service started by systemd lands in unconfined_service_t (the stock policy transitions init_t into it for binaries carrying the generic bin_t label), and a process started from an interactive shell stays in the shell's domain, typically unconfined_t. Neither confines anything, and the first is precisely what the CIS 1.3.1.6 audit command (ps -eZ | grep unconfined_service_t) exists to catch. Writing a proper policy module (covered in Part III) is the correct solution. In the interim, at least ensure the service is not running as root and has the minimum filesystem permissions that DAC allows.
7.5 When the Denial Is the Right Answer
Not every denial should be resolved by permitting the access. If httpd is denied access to /etc/shadow, that is correct behavior; do not fix it. If a web application process tries to execute a shell binary and SELinux blocks it, consider whether the application should be able to do that before enabling it. A denial is SELinux doing its job. The question is always: is this access legitimate for this process, and if so, should I expand the policy or fix the configuration so it happens correctly?
7.6 Inheriting a System with SELinux Disabled
The most common SELinux task on an inherited production system is not tuning a denial; it is turning the subsystem on at all. A server that has run with SELINUX=disabled (or the selinux=0 kernel argument) for years has no labels worth trusting: every file created in that time is unlabeled, including files that sshd, systemd, and your own services need at boot. Going straight from disabled to enforcing is the classic mistake here, because enforcement begins before you have seen a single denial; if a critical path relabels wrong or a needed local customization is missing, the result is a machine that fails to boot or refuses SSH logins. The supported procedure (documented in the RHEL 9 Using SELinux guide, which applies to AlmaLinux 9 unchanged; Appendix E, RH-SEL-GUIDE) is permissive-first:
- Set
SELINUX=permissive(notenforcing) in/etc/selinux/config. If the system was disabled via the kernel argument, remove it from every boot entry:grubby --update-kernel ALL --remove-args selinux=0. - Trigger a full relabel and reboot:
touch /.autorelabel && reboot. Budget real downtime: the relabel runs before multi-user mode and takes minutes to hours depending on filesystem size. - After boot, harvest everything the policy would have blocked:
ausearch -m avc -ts boot. In permissive mode every would-be denial is logged and nothing is enforced, so this is a complete inventory rather than the first failure. - Work the inventory with the four-question framework from Section 7.1. On an inherited system most entries are labeling problems (fix with
semanage fcontextandrestorecon), a few are booleans, and whatever remains is a candidate for a policy module. Then let the system run its real workload through at least one full business cycle (backups, cron jobs, log rotation, month-end batch work) and re-check the log. - Only when a full cycle produces no new denials, set
SELINUX=enforcingin the config file and runsetenforce 1. Keep console or out-of-band access available for the first enforcing boot, and re-run the audit-log check afterward.
Setting SELINUX=enforcing and creating /.autorelabel in the same change window means the first enforcing boot happens against labels you have never observed under load. Permissive mode costs nothing but calendar time, and it converts the cutover from a gamble into a formality: by the time you flip to enforcing, the complete denial inventory has already been worked to empty.
Goal: apply the four-question framework to a realistic denial scenario, choosing the correct fix for each root cause.
- Create a test directory outside the labeled portal tree:
mkdir /srv/grimoire-uploads. Place a file there:echo 'data' > /srv/grimoire-uploads/test.txt. Add a symlink from the web root:ln -s /srv/grimoire-uploads /srv/grimoire/html/uploads. Try to reach it from curl and observe the denial: the directory inheritsvar_tfrom/srv, whichhttpd_thas no rule to read. What is the root cause? Fix it withsemanage fcontextandrestorecon. (Why not/opt? Paths there default tousr_t, and the targeted policy already letshttpd_treadusr_tcontent, so no denial would occur and there would be nothing to fix.) - Now configure httpd to proxy to localhost:8080 (not actually running; just configure the ProxyPass). Restart httpd, then request a path under the ProxyPass prefix with curl: the connect attempt (and therefore the AVC denial for
tcp_socket:connect) happens on the first proxied request, not at startup. Answer the four questions: domain correct? Labels relevant? Boolean available? For relaying to another web port (8080 ishttp_cache_port_t),httpd_can_network_relayis the least-privilege answer;httpd_can_network_connectalso works but opens every port, andhttpd_can_network_connect_dbwould not help here at all, because it covers database ports only. Enable the narrower boolean and re-test. - Run
semanage permissive -a httpd_t. Repeat the curl to the symlink and to the proxy. Runausearch -m avc -ts recent. Note thepermissive=1in the records. Remove the permissive mode:semanage permissive -d httpd_t.
Part III Writing Policy
The three chapters in this part teach you to write SELinux policy from scratch. Chapter 8 introduces the policy language, the module format, and the tools for querying the existing policy. Chapter 9 covers the specific rule types available: allow, auditallow, dontaudit, neverallow, and transitions. Chapter 10 covers the build pipeline from source to loaded module, including the priority system and CIL as an alternative to the classical .te format.
Chapter 8The Policy Language: A Practical Introduction
SELinux policy is written in a domain-specific language that is compiled into a binary format the kernel understands.
You do not need to understand the entire Reference Policy to write a useful module; you need to understand enough of the language to express what a specific process needs to do. This chapter builds that foundation.
8.1 The Reference Policy
The targeted policy shipped with AlmaLinux 9 is derived from the Reference Policy (refpolicy), an open-source project maintained by the SELinux community and significantly extended by Red Hat. The Reference Policy provides a large library of macros, interfaces, and pre-built domains. When writing a new module for a custom daemon, you should use these interfaces rather than writing raw allow rules wherever possible: the interfaces encode field-tested access patterns and stay in sync with upstream policy changes.
The reference policy development headers are installed by the selinux-policy-devel package. After installing it, the interface files are available at /usr/share/selinux/devel/include/. The top-level makefile and example modules are at /usr/share/selinux/devel/.
8.2 The Three Module Source Files
A policy module consists of up to three source files. In practice, all three are usually present.
The .te file (type enforcement) is the main policy file. It declares types, assigns them to attributes, and writes allow rules, transitions, and boolean-gated blocks. This is where the security logic lives.
The .fc file (file contexts) maps filesystem path patterns to security contexts. It tells the file context database which type to assign to the files belonging to this application. When you run restorecon after installing an application with a policy module, the .fc file's entries determine the labels applied.
The .if file (interface) declares public functions that other modules can call to interact with this module's types. For example, the httpd module's interface file provides apache_read_sys_content(), which other modules can call to grant themselves access to httpd_sys_content_t. Writing interfaces is optional for local custom modules but required if your module needs to be used by other modules.
8.3 Basic .te Structure
A minimal .te file for a new application daemon looks like this:
# myapp.te - policy for the MyApp daemon
policy_module(myapp, 1.0.0)
# Declare the domain type and entrypoint type
type myapp_t;
type myapp_exec_t;
# Allow systemd to start myapp and run it confined.
# init_daemon_domain sets up the domain, the entrypoint, and the init transition.
init_daemon_domain(myapp_t, myapp_exec_t)
# Allow myapp to write to its log file type
type myapp_log_t;
logging_log_file(myapp_log_t)
allow myapp_t myapp_log_t:file { read write create append open getattr };
allow myapp_t myapp_log_t:dir { search getattr write add_name };
# Allow myapp to read its configuration file
type myapp_etc_t;
files_config_file(myapp_etc_t)
allow myapp_t myapp_etc_t:file { read open getattr };
allow myapp_t myapp_etc_t:dir { read getattr open search };myapp.te: a minimal confined daemon module using Reference Policy macros.
The policy_module(name, version) declaration is required. It names the module and sets its version for the module store. Macros like init_daemon_domain() and logging_log_file() expand to many individual allow rules that handle the expected behavior of a system daemon (reading shared libraries, using common system calls, writing to a PID file, etc.). Using macros instead of bare allow rules means you are not accidentally missing a necessary permission or adding an unnecessary one.
8.4 Querying the Policy with sesearch and seinfo
Before writing a rule, check whether it already exists in the upstream policy:
# sesearch --allow -s httpd_t -t httpd_sys_content_t -c file
allow domain file_type:file map; [ domain_can_mmap_files ]:True
allow httpd_t httpd_content_type:file { getattr ioctl lock map open read };
allow httpd_t httpdcontent:file { append create getattr ioctl link lock open read rename setattr unlink watch watch_reads write }; [ ( httpd_builtin_scripting && httpd_unified && httpd_enable_cgi ) ]:True
allow httpd_t httpdcontent:file { execute execute_no_trans getattr ioctl map open read }; [ ( httpd_builtin_scripting && httpd_unified && httpd_enable_cgi ) ]:True
allow domain base_ro_file_type:file { getattr ioctl lock open read };
# sesearch --allow -s httpd_t -c tcp_socket -p connect
(results depend on whether httpd_can_network_connect is enabled)
# seinfo -t httpd_sys_content_t -x # expand the type to show the attributes it belongs to
# seinfo -a httpd_content_type -x # expand the attribute to list its member types
# sesearch --type_trans -s init_t # domain transitions from init_tsesearch searches the compiled policy, not source files. It shows what the currently loaded policy actually permits, including any rules added by custom modules. This is the authoritative source for what SELinux will do. Two things about this output surprise people on a first read. None of the rules names httpd_sys_content_t directly: every line is written against an attribute the type belongs to (httpd_content_type, the broader content attribute httpdcontent, even the policy-wide domain and file_type pairs), because sesearch matches a type through its attribute memberships (Section 8.5 covers attributes). And rules that depend on booleans carry their conditional expression and its current truth value in brackets, so you can see at a glance which grants are gated: here, the write and execute grants exist only under the CGI-related booleans.
Run sesearch --allow -s httpd_t -c process -p execmem. Is there an allow rule for httpd to map executable memory? Now run getsebool httpd_execmem. Run sesearch --allow -s httpd_t -c process -p execmem -b httpd_execmem to see the rule that the boolean gates. What does this tell you about the relationship between booleans and the compiled policy?
8.5 Attributes and Type Grouping
An attribute is a named set of types. Rules written against an attribute apply to every type in that set. The Reference Policy makes heavy use of attributes to express policy at the appropriate level of abstraction. For example, the attribute httpd_content_type includes httpd_sys_content_t, httpd_user_content_t, httpd_sys_rw_content_t, and others. A rule allowing httpd_t to read httpd_content_type files applies to all of them at once.
This matters when writing custom content types: if you declare a new type and assign it the httpd_content_type attribute, httpd will automatically be permitted to read it without any additional rules:
# in mymodule.te
type myapp_web_content_t;
typeattribute myapp_web_content_t httpd_content_type;Check what attributes a type currently belongs to with seinfo -t <type> -x, and what types belong to an attribute with seinfo -a <attribute> -x (the -x/--expand flag is what prints the membership; the long forms are --type and --attribute).
Chapter 9Type Enforcement Rules
The type enforcement rules are the statements that SELinux evaluates for every access decision.
Understanding the four rule types (allow, auditallow, dontaudit, neverallow), how transitions work, and how to write them precisely is the core skill of policy authorship.
9.1 The allow Rule
The fundamental unit of policy is the allow rule. Its syntax is:
allow source_type target_type:class { perm perm ... };This rule says: any process running in source_type may perform the listed permissions against objects of type target_type that belong to class. Every field matters:
# Allow httpd to read static web content files
allow httpd_t httpd_sys_content_t:file { read open getattr };
# Allow httpd to search the directory containing that content
allow httpd_t httpd_sys_content_t:dir { read getattr open search };
# Allow httpd to bind to its configured port
allow httpd_t http_port_t:tcp_socket name_bind;
# Allow httpd to create and use its own listening socket. Only name_bind is
# checked against the port's type; create, bind, listen, and accept are checked
# against the socket object itself, which carries the creating domain's own
# context. The target is therefore self, never http_port_t.
allow httpd_t self:tcp_socket { create bind listen accept };A missing permission produces an AVC denial. The exact set of permissions needed varies by operation: opening a file for reading requires open, read, and getattr at a minimum. Creating a file in a directory requires write and add_name on the directory plus create on the file. The AVC denial will tell you exactly which permissions were missing.
Permissions can use the wildcard * to mean "all permissions in this class." This is almost always wrong in production policy: it grants permissions the process will never need, violating least privilege. Use wildcards only in explicit test modules and replace them with the minimal set before deploying.
9.2 auditallow
The auditallow rule does not grant anything. It says: when this access is granted (by an allow rule that must exist separately), write an audit record every time it happens. An auditallow with no matching allow rule audits nothing, because the access never succeeds. This makes it the tool for placing operations that are already permitted under explicit monitoring:
# Log every time httpd opens a CGI script for execution. The allow rule for
# this access already exists in the targeted policy when httpd_enable_cgi is
# on; this rule adds only the audit record.
auditallow httpd_t httpd_sys_script_exec_t:file execute;Use auditallow for accesses that are legitimately permitted but high-value enough to monitor, such as a web process reading a secrets file or any process using a sensitive capability.
9.3 dontaudit
The dontaudit rule does not change an access decision; it suppresses the audit record that a denial would otherwise generate. The access stays denied by the absence of an allow rule, exactly as it would without the dontaudit. Use this for known harmless denials that would otherwise flood the log with noise, making real denials harder to find:
# Suppress the denial when httpd probes for a file it does not need
dontaudit httpd_t cgroup_t:dir { getattr search read open };The upstream targeted policy contains many dontaudit rules for exactly this reason: system calls that applications commonly make speculatively and that are safe to deny silently. Be conservative when adding your own: a dontaudit that is too broad can hide a real security event.
9.4 neverallow
The neverallow rule is a compile-time assertion. It says "the compiled policy must never contain an allow rule matching this pattern." If the policy source would generate a matching allow rule, the compiler (checkpolicy) refuses to compile and reports an error. You cannot load a policy binary that violates a neverallow rule, with one important caveat: the check runs when the policy is built and linked, not in the kernel. The shipped base policy is neverallow-clean because it was verified when the distribution compiled it. For your own module loads, the re-check happens during the semodule policy rebuild and is governed by the expand-check setting in /etc/selinux/semanage.conf, which ships set to 0 (disabled) on a stock AlmaLinux 9. So on a default system semodule does not re-verify neverallows when you load a custom module: a locally authored module that violates a base-policy neverallow will load without complaint. If you want neverallow enforced as a guardrail for your own modules, set expand-check=1 in semanage.conf (accepting a policy-rebuild cost) and confirm it before relying on the guarantee.
# A real assertion from the upstream policy (the authlogin module): no domain
# may read /etc/shadow unless it carries the exempting attribute.
neverallow ~can_read_shadow_passwords shadow_t:file read;neverallow rules in the base policy enforce hard limits that even a custom module cannot override. This is how the policy expresses absolute security boundaries: not "we do not currently allow this" but "we will never allow this no matter what modules are loaded." You can write your own neverallow rules in custom modules to enforce invariants for your organization's policy.
9.5 Domain Transitions
As introduced in Section 2.4, a domain transition moves a process into a new type when it executes a binary. The transition requires three permissions (execute for the source domain, entrypoint for the target domain, transition between the two) plus a type_transition rule to make it automatic. The Reference Policy macros handle all of this correctly; when writing raw rules:
# Four rules are required for an automatic domain transition from init_t
# into myapp_t when /usr/sbin/myapp (labeled myapp_exec_t) is executed:
allow init_t myapp_exec_t:file { getattr open read execute };
allow myapp_t myapp_exec_t:file entrypoint;
allow init_t myapp_t:process transition;
type_transition init_t myapp_exec_t:process myapp_t;The init_daemon_domain(myapp_t, myapp_exec_t) macro from the Reference Policy expands to these rules plus several others needed for a properly confined daemon (including the rules for systemd to manage the service). Always prefer the macro.
9.6 File Type Transitions
A file type transition rule specifies what type a new file gets when created by a specific domain in a specific parent directory type:
# Files created by myapp_t in myapp_log_dir_t directories get type myapp_log_t
type_transition myapp_t myapp_log_dir_t:file myapp_log_t;
# Files created in /run/ by myapp_t get type myapp_var_run_t
type_transition myapp_t var_run_t:file myapp_var_run_t "myapp.pid";The optional fourth argument (the filename) limits the transition to files with that specific name. This is useful for PID files and socket files that have fixed names.
9.7 Conditional Policy with Booleans
In a .te file, rules can be placed inside a boolean conditional block. This is how booleans are implemented in the source:
optional_policy(`
tunable_policy(`httpd_can_network_connect',`
allow httpd_t port_type:tcp_socket connect;
allow httpd_t port_type:tcp_socket { read write };
')
')The tunable_policy macro gates the enclosed rules on the named boolean. When the boolean is off, those rules are not active. You can use this in custom modules to create your own booleans, though it adds management overhead; use sparingly.
If you are writing a CIL module (covered in Section 10.4) rather than a classical .te file, the M4 macros are not available. The runtime equivalent of a tunable_policy block is booleanif, which gates rules on a runtime-changeable boolean. (Do not reach for CIL's tunableif here: despite the name, it is a compile-time conditional that is resolved when the module is built and never reaches the binary policy, so it cannot be toggled with setsebool.)
; CIL equivalent: gate rules on a named runtime boolean
(booleanif httpd_can_network_connect
(true
(allow httpd_t port_type (tcp_socket (connect read write)))
)
(false)
)The (true ...) block holds the rules that apply when the boolean is on; the (false) block is empty here but can hold rules that apply when it is off. CIL's boolean support is otherwise identical in effect: the compiled policy includes both branches and activates the appropriate one at runtime without a policy reload.
Chapter 10Building, Loading, and Managing Modules
Writing the .te and .fc files is only half the work.
This chapter covers the compilation pipeline that turns source into a loadable binary, the semodule tool for managing the module store, priority-based module layering, and CIL as a modern alternative to the classical format.
10.1 The Classical Build Pipeline
The classical pipeline has three stages: compile .te to .mod, package .mod and .fc into .pp, and load .pp into the policy store.
# Stage 1: compile the .te to a policy module (.mod)
# checkmodule -M -m -o myapp.mod myapp.te
# Stage 2: package the module with its file context specification (.pp)
# semodule_package -o myapp.pp -m myapp.mod -f myapp.fc
# Stage 3: load the package into the active policy
# semodule -i myapp.ppThe -m flag to checkmodule outputs a loadable module (as opposed to a standalone base policy). The -M flag enables MLS/MCS support, which is required for compatibility with the targeted policy's MCS categories even though you are not writing a full MLS policy. Both flags are needed for module compilation. The resulting .pp file is a binary container holding both the compiled .mod and the raw .fc text. This raw pipeline understands only the kernel policy language itself: plain module, require, type, and rule statements, the form audit2allow -M emits. A module that uses policy_module() or any Reference Policy interface, like the myapp.te from Section 8.3, must instead be built with the development Makefile below, which runs the m4 macro expansion first; bare checkmodule rejects those macros as syntax errors.
For macro-based modules, copy the Makefile from the Reference Policy development headers and build with it:
# cp /usr/share/selinux/devel/Makefile .
# make -f Makefile
Compiling targeted myapp module
/usr/bin/checkmodule: loading policy configuration from tmp/myapp.tmp
/usr/bin/checkmodule: policy configuration loaded
/usr/bin/checkmodule: writing binary representation to tmp/myapp.mod
Creating targeted myapp.pp policy package
# semodule -i myapp.ppThe Makefile handles the include path for Reference Policy macros and the compilation flags. This is the preferred method when using macros from the reference policy headers.
Rather than writing the .te, .fc, .if, and helper files from a blank page, generate a starting skeleton with sepolicy generate (from policycoreutils-devel). Pointed at a daemon binary, for example sepolicy generate --init /usr/sbin/myapp, it produces a confined-domain template plus a build/install shell script, wired to the Reference Policy interfaces. Treat the output as a draft to be tightened, not a finished policy: it tends to grant more than a least-privilege module needs, so review and trim every rule before loading. This pairs naturally with the permissive-domain workflow in Section 7.3 for discovering the remaining accesses the daemon actually makes.
10.2 Managing the Module Store
semodule is the Swiss army knife for the module store. The most useful operations:
# semodule -l # list all installed modules
# semodule -l | grep myapp # check if your module is loaded
# semodule -i myapp.pp # install or update a module
# semodule -r myapp # remove a module by name
# semodule -d myapp # disable a module without removing it
# semodule -e myapp # re-enable a disabled module
# semodule -B # rebuild and reload the full policyEvery semodule -i or -r triggers a policy rebuild and reload. The rebuild merges all module binaries into a new policy binary, writes it to the policy store, and signals the kernel to reload it. The AVC cache is then invalidated. This happens in seconds on modern hardware; there is no need for a reboot or service restart.
10.3 Module Priority
Every module is installed at a priority. When two modules of the same name are present at different priorities, the higher priority takes effect, which is how a local module can override a distribution one. The conventional priorities are:
| Priority | Used for |
|---|---|
| 100 | The shipped distribution modules, including the base policy. This is the priority at which the selinux-policy packages install their modules. |
| 400 | Local customizations and custom application policies. This is the default priority semodule -i uses when --priority is not specified, so admin-installed modules land here unless you say otherwise. |
| higher (e.g. 500+) | Used only when a local module must override another local module at 400. Reserve high priorities for deliberate, documented overrides. |
Install a module at a specific priority with the -X (--priority) flag, placed before the operation it modifies; semodule applies the priority to the operations that follow it on the command line:
# semodule -X 400 -i myapp.ppThis means a local module at priority 400 can add rules to, or in some cases restrict rules from, the upstream modules at priority 100. It cannot override a neverallow rule; those are compile-time enforced regardless of priority.
10.4 CIL: The Common Intermediate Language
The Common Intermediate Language (CIL) is the modern, human-readable intermediate language that userspace compiles into the binary policy the kernel loads. Classical .te/.pp modules are converted to CIL during installation; you can also write CIL directly and load it with semodule, skipping the .te compile step. CIL uses a Lisp-like syntax:
; myapp.cil - minimal CIL equivalent of the classical module
; The module name comes from the filename (myapp); CIL has no "module" statement.
(type myapp_t)
(type myapp_exec_t)
(roletype system_r myapp_t)
; Associate the types with standard attributes using typeattributeset.
; (typeattribute only DECLARES an attribute; it does not assign one to a type.)
(typeattributeset domain (myapp_t))
(typeattributeset entry_type (myapp_exec_t))
(allow myapp_t myapp_exec_t (file (entrypoint execute read open getattr)))CIL modules can be loaded directly:
# semodule -X 400 -i myapp.cilCIL is increasingly the preferred format for new policy development because you can load it directly without the checkmodule/semodule_package packaging step, it is more readable than the classical .te macros, and it is the form the module store keeps modules in. For simple local overrides (disabling a specific rule, adding a file context), CIL is usually the most concise option. For complex application policies that benefit from Reference Policy macros and interface documentation, the classical .te format still has advantages.
Goal: write a minimal policy module that grants httpd access to a custom upload directory type, build it, load it, and verify it works.
- Create a working directory:
mkdir ~/grimoire-policy && cd ~/grimoire-policy - Copy the Makefile:
cp /usr/share/selinux/devel/Makefile . - Create
grimoire_uploads.tewith the following content:
policy_module(grimoire_uploads, 1.0.0)
# Types declared by other modules must be brought into scope explicitly,
# or the module will not compile ("type httpd_t is not declared").
gen_require(`
type httpd_t;
')
type grimoire_uploads_t;
files_type(grimoire_uploads_t)
allow httpd_t grimoire_uploads_t:dir { read getattr open search write add_name remove_name };
# httpd memory-maps the files it serves, so the file rule needs map, or every
# request logs a denial even though the content still serves (httpd falls back
# to read). ioctl and lock round out the set the upstream httpd_content_type
# rule grants for served content; compare the sesearch output in Section 8.4.
allow httpd_t grimoire_uploads_t:file { map ioctl lock create read write append open getattr setattr unlink };- Create
grimoire_uploads.fc:
/srv/grimoire-uploads(/.*)? gen_context(system_u:object_r:grimoire_uploads_t,s0)- Build:
make -f Makefile, then load:semodule -X 400 -i grimoire_uploads.pp - Remove the local rule you added in Lab 4, so the module's file context entry governs the path (local
semanage fcontextcustomizations take precedence over entries shipped by modules):semanage fcontext -d '/srv/grimoire-uploads(/.*)?' - Relabel the directory:
restorecon -Rv /srv/grimoire-uploads - Verify:
ls -lZ /srv/grimoire-uploads/. The type should begrimoire_uploads_t. - Test with curl that httpd can now serve content from the symlinked path. Check
ausearch -m avc -ts recentto confirm no denials.
Part IV Confining Services
The three chapters in this part apply the tools to real production workloads. Chapter 11 builds the Grimoire Portal to production standard: correct labels, TLS, security response headers, and alignment with Mozilla Server Side TLS and OWASP Secure Headers requirements. Chapter 12 addresses sshd, named, and the general problem of confining custom system services via systemd. Chapter 13 covers containers: how Podman and CRI-O integrate with SELinux, MCS categories for container isolation, and the NIST SP 800-190 requirements for runtime defenses.
Chapter 11Confining Web Servers: httpd, nginx, and Caddy
Apache httpd, nginx, and Caddy are the three most commonly deployed web servers on RHEL-family systems.
Each has a different relationship with the targeted policy: httpd has the most mature and boolean-rich domain, nginx has no domain of its own on the RHEL family and is confined as httpd_t by default (sharing Apache's types and booleans), and Caddy has no pre-built policy and requires a custom module. This chapter covers all three: shared concepts first, then server-specific labeling and confinement, then TLS and security header alignment for each.
11.1 The httpd_t Domain: Capabilities and Boundaries
The httpd_t domain is well-bounded by default. It can read files labeled with types in the httpd_content_type attribute (httpd_sys_content_t, httpd_user_content_t, etc.), write to files labeled httpd_log_t, read its configuration files labeled httpd_config_t, and bind to ports in http_port_t. It cannot, by default, connect to external services, execute arbitrary code from writeable memory, read user home directories, or interact with most system types. This is a sound default for a static file server.
Use sesearch to explore the full allow set for httpd_t; on AlmaLinux 9, the targeted policy contains several hundred allow rules for this domain because httpd has many legitimate operational needs (managing temporary files, using SSL, running worker processes, etc.).
11.2 File Label Requirements for a Production vhost
A production httpd virtual host needs correct labels on four categories of objects: document root, writable content (uploads), log files, and TLS certificates.
| Path pattern | SELinux type | Purpose |
|---|---|---|
/srv/grimoire/html(/.*)? | httpd_sys_content_t | Static read-only content httpd can serve. |
/srv/grimoire/uploads(/.*)? | httpd_sys_rw_content_t | Writable content (file upload directories). |
/srv/grimoire/logs(/.*)? | httpd_log_t | Access and error logs httpd can write. |
/etc/pki/tls/certs(/.*)? | cert_t | TLS certificates; readable by httpd by default. |
/etc/pki/tls/private(/.*)? | cert_t | Private keys; also readable by httpd for TLS (see caution below). |
/etc/httpd(/.*)? | httpd_config_t | Server configuration files. |
Set these all at once using the semanage fcontext commands developed in Chapter 4, then run restorecon -Rv /srv/grimoire/.
By default, httpd_t can read files labeled cert_t, which includes the private key directory /etc/pki/tls/private. This is necessary for httpd to present its TLS certificate but means the private key is readable by any process in the httpd domain, including compromised worker processes. The default targeted policy uses the single type cert_t for both the certificate and the private key under /etc/pki/tls; there is no separate private-key type out of the box. In high-security environments, the architectural mitigations are to define a custom, more restrictive type for the private-key directory in a local module (so that only the minimal set of domains can read it) and to favor mechanisms such as OCSP stapling so the key is not read at request time. These are architectural decisions beyond the scope of this guide.
11.3 TLS Configuration and SELinux Context
Adding TLS to the Grimoire Portal requires installing a certificate, configuring mod_ssl, and verifying that SELinux allows httpd to read the certificate files and bind to port 443.
# dnf install -y mod_ssl
# Generate a self-signed cert for the lab (use a CA-signed cert in production)
# openssl req -x509 -nodes -days 365 -newkey rsa:4096 \
-keyout /etc/pki/tls/private/grimoire.key \
-out /etc/pki/tls/certs/grimoire.crt \
-subj '/CN=grimoire.lab'
# Verify the labels (should be cert_t from the default file_contexts)
# ls -lZ /etc/pki/tls/certs/grimoire.crt /etc/pki/tls/private/grimoire.keyIf the labels are not cert_t, run restorecon -v /etc/pki/tls/certs/grimoire.crt /etc/pki/tls/private/grimoire.key. Port 443 is already in http_port_t by default (confirmed with semanage port -l | grep http_port), so no port label change is needed for standard HTTPS.
The Mozilla Server Side TLS specification (Modern configuration, current version) requires TLS 1.3 only for new deployments, or TLS 1.2+ (with TLS 1.0 and 1.1 disabled) for Intermediate compatibility when older client support is needed. It specifies cipher suite ordering, HSTS (Mozilla's guidelines set both the recommended and minimum max-age at two years, 63072000 seconds; values below one year are additionally ineligible for HSTS preloading), and the elimination of legacy protocol features (SSLv3, RC4, export ciphers). From an SELinux perspective, enabling HSTS is a configuration change within httpd_t and requires no additional policy; the process already has permission to send response headers. However, the TLS private key file context (cert_t) is a policy concern: if an attacker compromises the httpd process and can read cert_t files, the private key may be extracted.Mozilla Server Side TLS specification, current version at https://wiki.mozilla.org/Security/Server_Side_TLS. The specification is updated regularly; always check the current version rather than citing a specific date. HSTS preloading requirements are maintained separately at https://hstspreload.org.
The OWASP Secure Headers Project specifies response headers that protect users from common web attacks: Strict-Transport-Security (HSTS, force HTTPS), X-Content-Type-Options: nosniff (block MIME sniffing), X-Frame-Options: DENY or SAMEORIGIN (prevent clickjacking), Content-Security-Policy (restrict resource loading), Referrer-Policy, and others. These headers are set in httpd.conf or a virtual host configuration and do not require any SELinux policy change; the httpd_t domain can already send arbitrary response headers. What SELinux contributes is confining the process that serves these headers: if the httpd binary is compromised, SELinux limits what the attacker can reach, protecting the integrity of the configuration that generates the headers.OWASP Secure Headers Project at https://owasp.org/www-project-secure-headers/. The Header Best Practices page specifies exact header values and their rationale. These should be verified against the current version of the project documentation.
Add the security headers to the Grimoire Portal virtual host:
# /etc/httpd/conf.d/grimoire.conf (TLS and hardened version)
<VirtualHost *:80>
ServerName grimoire.lab
Redirect permanent / https://grimoire.lab/
</VirtualHost>
<VirtualHost *:443>
ServerName grimoire.lab
DocumentRoot /srv/grimoire/html
SSLEngine on
SSLCertificateFile /etc/pki/tls/certs/grimoire.crt
SSLCertificateKeyFile /etc/pki/tls/private/grimoire.key
SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305
SSLHonorCipherOrder off
SSLSessionTickets off
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains"
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "DENY"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Content-Security-Policy "default-src 'self'"
<Directory /srv/grimoire/html>
Options -Indexes -FollowSymLinks
Require all granted
</Directory>
ErrorLog /srv/grimoire/logs/error.log
CustomLog /srv/grimoire/logs/access.log combined
</VirtualHost>/etc/httpd/conf.d/grimoire.conf: TLS-enabled, security-headers hardened portal configuration.
The <Directory> grant is load-bearing, not boilerplate. The stock httpd.conf denies the entire filesystem (<Directory /> ... Require all denied) and grants only /var/www, so a DocumentRoot outside it returns HTTP 403 on every request without this block. That 403 comes from Apache's own authorization layer, not from SELinux: the audit log stays clean, and because Header always emits the security headers on error responses too, a headers-only check passes while the site is down. When a request fails after a configuration change, check the HTTP status code first, then the audit log; the layers fail differently (the SELinux-denied 403 in Section 3.5 is a third case again: there the status is also 403, but the audit log is not clean, because the denial is SELinux refusing to read the content).
# systemctl restart httpd
# ausearch -m avc -ts recent # should be empty if labels are correct11.4 Non-Standard Ports
If the organization requires httpd on a port not already bindable by httpd_t (say, 8090 for a management interface alongside the standard 443), add the port before configuring httpd to bind it. Check for an existing owner first: the obvious-looking alternates are taken (8080 is http_cache_port_t, which httpd may already bind; 8081 is transproxy_port_t), and semanage port -a fails with "already defined" for any owned port, leaving the choice between a different port and a deliberate semanage port -m reassignment (see the caution in Section 4.5).
# semanage port -l | grep -w 8090 # no output: the port is unassigned
# semanage port -a -t http_port_t -p tcp 8090
# semanage port -l | grep -w http_port_t # -w: a bare grep also matches pegasus_http_port_t
http_port_t tcp 8090, 80, 81, 443, 488, 8008, 8009, 8443, 9000Goal: apply TLS, verify certificate file labels, set security response headers, and confirm no new AVC denials are generated.
- Install mod_ssl and generate the self-signed certificate as shown in Section 11.3.
- Replace the grimoire.conf with the TLS and header configuration above.
- Restart httpd:
systemctl restart httpd. - Run
ausearch -m avc -ts recent. If there are any denials, work through the troubleshooting workflow from Chapter 7. - Test the page actually serves:
curl -ks -o /dev/null -w '%{http_code}\n' https://localhost/must print200. A403here means the<Directory>grant is missing from the vhost, not that a label is wrong; the audit log will be clean either way. - Test the headers:
curl -k -I https://localhost/and verify the security headers are present in the response. - Check:
semanage port -l | grep http_port. Confirm 443 is in the type.
11.5 Confining nginx
A common misconception is that nginx has its own dedicated SELinux domain on the RHEL family. It does not. On AlmaLinux 9 and RHEL 9 the default targeted policy does not ship an nginx_t domain, and there is no nginx-selinux package in the base, AppStream, or EPEL repositories that adds one. When you install nginx from AppStream, the binary at /usr/sbin/nginx is labeled httpd_exec_t, so on execution nginx transitions into the httpd_t domain: the same domain Apache uses. Verify this after starting the service:
# dnf install -y nginx
# systemctl start nginx
# ps -eZ | grep nginx
system_u:system_r:httpd_t:s0 3421 ? Ss 0:00 nginx: master processThe practical consequence is that nginx is confined by the same policy as httpd: the httpd_* booleans apply to it, it serves content labeled with the httpd_content_type attribute, and it binds to http_port_t. Everything you learned about confining httpd in Sections 11.1 through 11.4 applies to nginx unchanged, because they share the httpd_t domain. If you instead see nginx running in unconfined_service_t, the binary is mislabeled; run restorecon -v /usr/sbin/nginx and restart the service.
Some operators prefer nginx confined in its own domain rather than sharing httpd_t with Apache. There is no upstream package for this; the SELinux community maintains third-party modules (search GitHub for "selinux-nginx-rhel", e.g. the linuxit and jahrmando repositories) that introduce an nginx_t domain with its own types such as nginx_log_t. Treat these exactly as you would any community policy module (see the Caddy community-module note in Section 11.6): review every allow rule before loading, confirm the file contexts match your paths, and budget for keeping the module in sync with policy updates. The rest of this section assumes the default behavior, where nginx is httpd_t.
Content, log, and config types for nginx
Because nginx runs as httpd_t, it uses the same content, log, and configuration types as Apache. Content is served from files in the httpd_content_type attribute (httpd_sys_content_t and the others); logs that nginx writes belong in httpd_log_t; and the configuration tree under /etc/nginx is labeled httpd_config_t by the default file contexts. There are no separate nginx_log_t or nginx_conf_t types in the default policy: those exist only if you load one of the third-party nginx_t modules described above.
Content at /srv/grimoire/html already carries httpd_sys_content_t from Lab 2 and requires no change. Point nginx's logs at the same kind of path you used for httpd, labeled httpd_log_t:
# mkdir -p /srv/grimoire/logs
# semanage fcontext -a -t httpd_log_t '/srv/grimoire/logs(/.*)?' # already added in Ch.4 if you did Lab 2
# restorecon -Rv /srv/grimoire/logs/Verify that the httpd_t domain can read the content, which confirms nginx can too. This is the same query, with the same attribute-shaped output, as in Section 8.4:
# sesearch --allow -s httpd_t -t httpd_sys_content_t -c file
allow httpd_t httpd_content_type:file { getattr ioctl lock map open read };
[...]nginx virtual host and TLS configuration
The Grimoire Portal nginx virtual host follows the same TLS and header requirements as the httpd version. Certificate files are already labeled cert_t and require no additional labeling. The nginx configuration goes in /etc/nginx/conf.d/grimoire.conf, which is labeled httpd_config_t by default (the same type used for /etc/httpd):
# /etc/nginx/conf.d/grimoire.conf
server {
listen 80;
server_name grimoire.lab;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name grimoire.lab;
root /srv/grimoire/html;
ssl_certificate /etc/pki/tls/certs/grimoire.crt;
ssl_certificate_key /etc/pki/tls/private/grimoire.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305;
ssl_prefer_server_ciphers off;
ssl_session_tickets off;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'" always;
access_log /srv/grimoire/logs/access.log;
error_log /srv/grimoire/logs/error.log;
}/etc/nginx/conf.d/grimoire.conf: Grimoire Portal under nginx with TLS and OWASP security headers.
# nginx -t # verify config syntax
# systemctl restart nginx
# ausearch -m avc -ts recent # confirm zero denialsnginx booleans and reverse proxy
Since nginx runs as httpd_t, the httpd booleans from Chapter 5 govern it directly. The one most relevant to nginx as a reverse proxy is httpd_can_network_relay, which permits the domain to forward connections to upstream backends. Check its state:
# getsebool httpd_can_network_relay
httpd_can_network_relay --> offEnable it persistently if nginx is configured as a reverse proxy:
# setsebool -P httpd_can_network_relay onFor proxying to a backend on an arbitrary TCP port rather than relaying between web ports, httpd_can_network_connect is the relevant boolean instead. To list every boolean that actually governs the domain on your installed policy, use sesearch --bool=<name> against httpd_t, or semanage boolean -l | grep httpd for the full set with descriptions.
11.6 Confining Caddy: Building a Policy Module
Caddy is not available in the AlmaLinux 9 base repositories and has no pre-built SELinux policy module in the targeted policy store. Install Caddy from the Caddy project's repository or as a standalone binary. After installation, Caddy will run as unconfined_service_t, which fails CIS 1.3.1.6 (Level 2) and the SCAP/SSG daemon-confinement rule (selinux_confinement_of_daemons) used in hardening scans; the published DISA STIGs carry no numbered unconfined-daemons finding (see Section 14.2). The correct response is to write a policy module following the pattern established in Chapter 10.
What Caddy needs that httpd and nginx do not
Caddy's auto-HTTPS feature distinguishes it from httpd and nginx. Where those servers require you to supply certificates, Caddy obtains and renews them automatically via the ACME protocol. This creates two SELinux requirements absent from the other two servers: write access to a persistent data directory (where Caddy stores its managed certificates and ACME account keys), and outbound TCP connections to ACME certificate authority endpoints on port 443.
The second requirement means Caddy's domain must be permitted to initiate connections, not only accept them. The targeted policy's httpd domain handles this through the httpd_can_network_connect boolean; a custom Caddy domain needs explicit outbound connection rules.
Unlike httpd and nginx, which read a pre-existing key file, Caddy generates and writes TLS private keys into its data directory (typically /var/lib/caddy/). The type you assign to this directory must allow Caddy to create and write key material. Do not label it cert_t: cert_t is intended for read access by services, not write access by the service itself generating the keys. Use a dedicated writable type such as caddy_data_t.
The caddy policy module
Create a working directory and write two source files:
# caddy.te
policy_module(caddy, 1.0.0)
# Bring externally declared types into scope, or the module will not compile.
gen_require(`
type httpd_sys_content_t;
type http_port_t;
type node_t;
')
type caddy_t;
type caddy_exec_t;
type caddy_etc_t;
type caddy_log_t;
type caddy_data_t; # writable: ACME certs, account keys, cache
init_daemon_domain(caddy_t, caddy_exec_t)
files_config_file(caddy_etc_t)
logging_log_file(caddy_log_t)
files_type(caddy_data_t)
# Config read
allow caddy_t caddy_etc_t:file { read open getattr };
allow caddy_t caddy_etc_t:dir { read getattr open search };
# Log write
allow caddy_t caddy_log_t:file { create write append open getattr };
allow caddy_t caddy_log_t:dir { search getattr write add_name };
# Data dir: full read/write for ACME cert storage
allow caddy_t caddy_data_t:file { create read write append open getattr setattr unlink lock };
allow caddy_t caddy_data_t:dir { create read write add_name remove_name open getattr search };
# Serve web content (reuse the shared web content type)
allow caddy_t httpd_sys_content_t:file { read open getattr };
allow caddy_t httpd_sys_content_t:dir { read getattr open search };
# Bind HTTP (80) and HTTPS (443) -- both are in http_port_t.
# Only name_bind (and name_connect below) are checked against the port type;
# create/bind/listen/accept are checked against the socket itself (self).
allow caddy_t http_port_t:tcp_socket name_bind;
allow caddy_t node_t:tcp_socket node_bind;
# Outbound TCP for ACME (Let's Encrypt / ZeroSSL endpoints on 443)
allow caddy_t http_port_t:tcp_socket name_connect;
allow caddy_t self:tcp_socket { create bind listen accept connect read write setopt getopt shutdown };caddy.te: starter policy module. Capture any missing permissions with a permissive-domain run before shipping.
# caddy.fc
/usr/bin/caddy -- gen_context(system_u:object_r:caddy_exec_t,s0)
/etc/caddy(/.*)? gen_context(system_u:object_r:caddy_etc_t,s0)
/var/log/caddy(/.*)? gen_context(system_u:object_r:caddy_log_t,s0)
/var/lib/caddy(/.*)? gen_context(system_u:object_r:caddy_data_t,s0)caddy.fc: file context specifications. Adjust the binary path if Caddy is installed outside /usr/bin.
Build, validate, and deploy
The recommended workflow before deploying to a production system is to run Caddy in a permissive domain first (see Section 7.3), accumulate all denials, then review and incorporate any missing rules before removing the permissive mode.
# cd ~/caddy-policy
# cp /usr/share/selinux/devel/Makefile .
# make -f Makefile
# semodule -X 400 -i caddy.pp
# restorecon -Rv /usr/bin/caddy /etc/caddy/ /var/log/caddy/ /var/lib/caddy/
# Run in permissive mode first to gather any missed permissions
# semanage permissive -a caddy_t
# systemctl restart caddy
# Exercise all code paths (start, HTTPS request, ACME renewal if possible)
# Then collect remaining denials:
# ausearch -m avc -c caddy --raw | audit2allow
# Review generated rules, add them to caddy.te, rebuild, reload
# Then remove permissive mode:
# semanage permissive -d caddy_t
# ausearch -m avc -c caddy -ts recent # should be empty in enforcingThe SELinux community maintains policy contributions for Caddy outside the official AlmaLinux/RHEL repositories. Search GitHub for "caddy selinux" to find current candidates. Evaluate any community module against the standards in Chapter 9 before loading it: review every allow rule, check for unconfined or * wildcard permissions, and confirm the file context specifications match your installation paths. A module loaded from an untrusted source with unchecked allow rules can silently weaken the policy.
Chapter 12Confining sshd, named, and System Services
sshd and named (BIND) are two of the most commonly deployed network services on a RHEL system, and both have mature SELinux domains that work well out of the box with one exception: non-standard paths and ports.
This chapter covers the specific labeling and port management needs for each, then addresses the broader problem of confining custom system services written to use systemd.
12.1 Confining sshd
The sshd_t domain is well-confined by default. It can read system host keys (labeled sshd_key_t), read PAM configuration, write to /var/log/secure (labeled var_log_t; verify with ls -lZ /var/log/secure on your installed policy), and bind to ssh_port_t (port 22). Most operational adjustments involve port changes and authorized key path changes.
Custom SSH Port
If you change the SSH port from 22 to a non-standard port (a common low-value security-through-obscurity measure, but one required by some compliance baselines), you must add the new port to ssh_port_t before restarting sshd:
# semanage port -a -t ssh_port_t -p tcp 2222
# semanage port -l | grep ssh_port_t
ssh_port_t tcp 22, 2222If you do not add the port first, sshd will fail to bind with an AVC denial against tcp_socket:name_bind. Remember to also open the port in firewalld.
Authorized Keys in Non-Default Locations
If your SSH configuration uses an AuthorizedKeysFile in a non-standard location (some deployments store authorized keys in a central path like /etc/ssh/authorized_keys/%u), those files need the correct label. The type for authorized keys files is ssh_home_t:
# semanage fcontext -a -t ssh_home_t '/etc/ssh/authorized_keys(/.*)?'
# restorecon -Rv /etc/ssh/authorized_keys/12.2 Confining named (BIND)
The named_t domain manages DNS zones and handles queries. The key types are named_zone_t for zone data files, named_cache_t for the working/cache directory, and named_conf_t for configuration files. By default, zone files live in /var/named/ which is already labeled correctly. Problems arise when zone files are stored in non-standard locations or when BIND is configured for dynamic updates.
Dynamic DNS Updates (nsupdate)
If BIND is configured to accept dynamic updates (via allow-update or update-policy), it needs to write zone files and their journals. The stock policy already plans for this: /var/named/dynamic, /var/named/data, and /var/named/slaves are labeled named_cache_t, which named_t can write with no boolean change, while the static master zones directly under /var/named stay read-only named_zone_t. Keep dynamically updated zones in /var/named/dynamic and the default policy simply works. If you must hold written zones at a non-default path, give that path the writable type:
# semanage fcontext -a -t named_cache_t '/srv/dns/dynamic(/.*)?'
# restorecon -Rv /srv/dns/dynamic/Reserve named_zone_t for static master zone files. The boolean named_write_master_zones exists for the remaining case: named must write named_zone_t files in place, as in a legacy layout that updates master files where they sit. Enabling it grants named write access to all named_zone_t files, not just the ones you had in mind, so prefer the named_cache_t layout and leave the boolean off.
12.3 Confining Custom Services via systemd
When you write a custom system daemon (a Go binary, a Python application, a shell script managed by systemd), it will not have a pre-built SELinux domain. By default, systemd will attempt a domain transition from init_t to an appropriate type, but if no policy module exists for the binary, the process stays in init_t or transitions to unconfined_service_t, neither of which provides meaningful confinement.
The correct solution is to write a policy module using the pattern from Part III; once the module's type_transition rule is loaded, systemd starts the service in its domain with no unit-file change at all. If you need to force a specific context instead, the SELinuxContext= directive in the [Service] section sets the context of the executed process directly, overriding the automatic transition. The policy must still allow the resulting transition; if it does not, the unit fails to start (prefix the value with - to ignore the failure).
The minimum viable policy for a custom daemon that needs to: read its config, write its log, and listen on a specific port is shown below. It uses the Makefile approach from Chapter 10.
# customd.te - minimal confined daemon
policy_module(customd, 1.0.0)
gen_require(`
type node_t;
')
type customd_t;
type customd_exec_t;
type customd_etc_t;
type customd_log_t;
type customd_port_t;
init_daemon_domain(customd_t, customd_exec_t)
files_config_file(customd_etc_t)
logging_log_file(customd_log_t)
corenet_port(customd_port_t)
allow customd_t customd_etc_t:file { read open getattr };
allow customd_t customd_etc_t:dir { read getattr open search };
allow customd_t customd_log_t:file { create write append open getattr };
allow customd_t customd_log_t:dir { search getattr write add_name };
allow customd_t customd_port_t:tcp_socket name_bind;
allow customd_t node_t:tcp_socket node_bind;
allow customd_t self:tcp_socket { create bind listen accept read write };And the file context specification:
# customd.fc
/usr/sbin/customd -- gen_context(system_u:object_r:customd_exec_t,s0)
/etc/customd(/.*)? gen_context(system_u:object_r:customd_etc_t,s0)
/var/log/customd(/.*)? gen_context(system_u:object_r:customd_log_t,s0)Build, load, and then register the port with semanage port -a -t customd_port_t -p tcp <port>.
Write and test the SELinux policy module in a staging environment before deploying the service to production. A service deployed without a policy module runs unconfined. A service deployed with an incomplete policy module generates denials at startup. Neither is an acceptable initial state for a production deployment.
Chapter 13Containers and SELinux
Containers provide namespace and cgroup-based isolation, but they share the host kernel.
A container breakout (exploiting a vulnerability in the container runtime or kernel to escape the container) bypasses all namespace isolation. SELinux is the layer that confines what a broken-out container process can do on the host. This chapter covers how Podman integrates with SELinux on AlmaLinux 9, how MCS categories isolate containers from each other, and what the authoritative standards require for container runtime security.
13.1 The Container Threat Model
A container breakout gives an attacker code execution in the host namespace. Without SELinux, this is essentially equivalent to a root compromise of the host: the broken-out process inherits the user namespace of the container runtime (often root) and can access the host filesystem, other containers, and system resources. With SELinux enforcing, the broken-out process is still confined to the container_t domain, which cannot read host system files, write to host configuration, or interact with non-container processes. The blast radius is bounded.
NIST SP 800-190, Application Container Security Guide, identifies mandatory access control as a countermeasure for container environments. The document is structured as risks (Section 3) followed by countermeasures (Section 4); the Host OS Risks it enumerates in Section 3.5 (large attack surface, shared kernel, host file-system tampering) are answered by the Host OS Countermeasures in Section 4.5, which recommend deploying a MAC tool such as SELinux or AppArmor to constrain what a compromised container can reach, supplementing the isolation provided by namespaces and control groups. Organizations are advised to ensure MAC is enabled and that containers run under appropriate MAC policies rather than in unconfined domains.NIST SP 800-190 (2017), Countermeasures in Section 4 (host OS countermeasures, Section 4.5). Verify the exact subsection and the current revision at https://doi.org/10.6028/NIST.SP.800-190. The 2017 publication predates many container runtime developments; the core MAC recommendation remains valid.
13.2 The Container Domain Hierarchy
The SELinux targeted policy on AlmaLinux 9 (via the container-selinux package) defines a hierarchy of container domains. Understanding when each applies matters for hardening.
| Type | Used for | Security level |
|---|---|---|
container_t | Standard rootless or rootful container processes | High isolation; cannot access host files or system resources without explicit label |
container_init_t | PID 1 inside a container (init-style containers) | Slightly elevated; can set up the container environment |
spc_t | Super-privileged containers (--privileged) | Essentially unconfined; use only for trusted management tooling |
container_runtime_t | The container runtime/engine itself (Podman, CRI-O, Buildah) | Trusted; the runtime runs in this domain and is itself constrained by the container-selinux policy |
The key principle: a standard container runs in container_t, which cannot read host files labeled with host system types (shadow_t, sshd_key_t, httpd_config_t, etc.). The container can only access files labeled container_file_t, container_ro_file_t, or similar container-specific types, plus the specific paths mounted into the container with appropriate relabeling.
13.3 Volume Mounts and the :z and :Z Flags
When you mount a host directory into a container with Podman, the container process (running as container_t) cannot access the host files unless they carry a type that container_t is permitted to read. Host files with default_t or any service-specific type are inaccessible to the container by default. This is correct behavior: a container should not be able to read host configuration files.
For content you intentionally want to share with the container, use the :z or :Z flag on the mount:
# :z - shared relabeling: the directory gets container_file_t (shared with other containers)
$ podman run -v /srv/grimoire/html:/var/www/html:z nginx
# :Z - private relabeling: the directory gets a unique MCS category
# (accessible only to THIS container instance)
$ podman run -v /srv/grimoire/html:/var/www/html:Z nginxThe :z flag (lowercase) relabels the host directory to container_file_t, a type that any container process can read. This is appropriate for read-only shared data but dangerous for writable data, because any container on the system can access it. The :Z flag (uppercase) relabels the directory with a unique MCS category pair, so only that specific container instance can access it. Use :Z for writable mounts and for any data that should be private to a specific container.
When you use :z or :Z, Podman physically relabels the host directory. If you later remove the container without restoring the original labels, the host directory retains the container_file_t type and may no longer be accessible by the host service (httpd, etc.) that originally owned it. Always run restorecon -Rv /path after removing a container that used volume mounts, or use :z/:Z only with directories specifically designated for container use.
13.4 MCS Categories and Container Isolation
Multi-Category Security (MCS) is what distinguishes between two containers running in the same domain (container_t) with the same type on their files (container_file_t). Without MCS, both containers could access each other's files because they share the type. With MCS, each container instance is assigned a unique pair of categories (e.g., s0:c12,c847 and s0:c98,c233), and the MCS policy ensures a process with one category pair cannot access objects with a different category pair.
Podman handles MCS category assignment automatically. The auto-assigned label is not reflected in .HostConfig.SecurityOpt (that field shows only the options you pass explicitly with --security-opt); read it instead from .ProcessLabel for the running process and .MountLabel for the relabeled volume:
$ podman run -d --name web1 nginx
$ podman run -d --name web2 nginx
$ podman inspect web1 --format '{{.ProcessLabel}}'
system_u:system_r:container_t:s0:c12,c847
$ podman inspect web2 --format '{{.ProcessLabel}}'
system_u:system_r:container_t:s0:c98,c233Both processes are container_t, but the category pairs (c12,c847 versus c98,c233) differ, so even if web1 were compromised, the attacker could not access web2's volume data, which carries web2's category pair on its .MountLabel. This is SELinux providing isolation that kernel namespaces alone do not guarantee.
13.5 Privileged Containers
Running podman run --privileged (or the equivalent securityContext.privileged: true in Kubernetes) sets the container's SELinux domain to spc_t, which is essentially unconfined. This defeats all the isolation properties described above. Privileged containers are appropriate only for system administration tooling (e.g., podman run --privileged --rm -v /:/host fedora chroot /host id for host inspection) and must never be used for untrusted or internet-facing workloads.
NIST SP 800-190 advises organizations to limit the use of privileged containers and to configure container infrastructure so that unprivileged users cannot create them. This guidance sits with the container countermeasures in Section 4.4 (the corresponding risk, insecure runtime configuration, is described in the container risks of Section 3.4). In an SELinux context, this means ensuring that spc_t is not assignable to containers run by normal users, which is the default behavior of the container-selinux policy.NIST SP 800-190 (2017), container countermeasures in Section 4.4; verify the exact subsection against the current revision. Podman's rootless mode provides an additional layer of defense; a rootless container runs as the actual Linux user, not as root, which limits the damage from spc_t even if a privileged flag is passed.
When a container needs more host access than the default container_t domain allows (specific host paths, devices, or network ports), the wrong fix is to run it privileged or to set --security-opt label=disable. The right fix is a tailored container domain, and the tool for that on AlmaLinux 9 is udica (package udica). It inspects a running container's configuration (its mounts, ports, and capabilities) and emits a CIL policy module granting exactly those accesses:
$ podman inspect <container> > container.json
$ udica -j container.json my_container
# semodule -i my_container.cil \
/usr/share/udica/templates/base_container.cil \
/usr/share/udica/templates/net_container.cil
$ podman run --security-opt label=type:my_container.process ...The required template files depend on what the container does: base_container.cil is always needed; net_container.cil adds network access; home_container.cil adds home-directory access. Udica prints which templates to include after it analyzes the container spec. This keeps the container confined while granting only the access it documents a need for, which is the SELinux-consistent answer to NIST SP 800-190's countermeasure guidance.
Goal: run two containers sharing the same base type but demonstrate that MCS categories prevent cross-container file access.
- Install Podman:
dnf install -y podman container-selinux - Create two host directories with container-accessible content:
mkdir /srv/c1-data /srv/c2-dataecho 'container 1 secret' > /srv/c1-data/secret.txtecho 'container 2 secret' > /srv/c2-data/secret.txt - Start c2 first with a private volume mount, so
/srv/c2-datais relabeled with c2's unique MCS category:podman run -d --name c2 -v /srv/c2-data:/data:Z alpine sleep 3600 - Now start c1 with its own private mount and a second, deliberately un-relabeled (plain, no
:Z) mount of c2's directory. Because the second mount has no:z/:Zsuffix, Podman leaves c2's category on it:podman run -d --name c1 -v /srv/c1-data:/data:Z -v /srv/c2-data:/c2data:ro alpine sleep 3600 - Inspect the MCS categories assigned to each. Read the process label (and the mount label), not
.HostConfig.SecurityOpt, which only shows explicitly-passed options:podman inspect c1 c2 --format '{{.Name}}: {{.ProcessLabel}}'
Confirm both arecontainer_twith differentcN,cMcategory pairs. Cross-check the on-disk label:ls -dZ /srv/c2-data. - From inside c1, read its own mount (succeeds) and then c2's directory (denied by MCS):
podman exec c1 cat /data/secret.txt→ prints "container 1 secret".podman exec c1 cat /c2data/secret.txt→ fails with "Permission denied", because/srv/c2-datacarries c2's MCS category and c1's process has a different category pair. Both containers arecontainer_t; only the categories differ, which is exactly what MCS enforces. - Clean up:
podman stop c1 c2 && podman rm c1 c2 && restorecon -Rv /srv/c1-data /srv/c2-data
Part V Compliance and Standards Reference
This single chapter collects the compliance obligations from all five referenced standards frameworks into one place. It is designed to be read standalone: you do not need to have read any previous chapter to use this chapter as a compliance guide. Each framework is addressed in turn, with specific control identifiers, required configurations, audit commands, and cross-references to the chapters that explain the underlying concepts.
Chapter 14Compliance Reference: CIS, DISA STIG, and NIST
This chapter is the compliance engineer's reference.
Each section addresses one framework's SELinux-relevant controls: the specific requirement, the command to audit it, the command to remediate it, and the explanation of why it matters. Where frameworks conflict or where a hierarchy applies, that is stated explicitly.
14.1 CIS AlmaLinux OS 9 Benchmark: Section 1.3.1
The CIS AlmaLinux OS 9 Benchmark dedicates Section 1.3.1 exclusively to SELinux. There are eight controls. All are within scope for systems subject to this benchmark. Level 1 controls are required for all profiles; Level 2 controls apply to high-security environments (servers handling sensitive data, externally facing systems).
| Control | Level | Requirement | Audit Command | Remediation |
|---|---|---|---|---|
| 1.3.1.1 | L1 | Ensure SELinux is installed (libselinux present). | rpm -q libselinux | dnf install -y libselinux |
| 1.3.1.2 | L1 | Ensure SELinux is not disabled in the bootloader configuration. No selinux=0 or enforcing=0 kernel parameters. | grep -E 'selinux=0|enforcing=0' /etc/default/grub /boot/grub2/grub.cfg | Remove parameters from /etc/default/grub and run grub2-mkconfig -o /boot/grub2/grub.cfg. |
| 1.3.1.3 | L1 | Ensure SELinux policy is configured. SELINUXTYPE is targeted or mls. | grep 'SELINUXTYPE' /etc/selinux/config | Set SELINUXTYPE=targeted in /etc/selinux/config. |
| 1.3.1.4 | L1 | Ensure the SELinux mode is not disabled. SELINUX is not disabled. | grep 'SELINUX=' /etc/selinux/config | grep -v '#' | Set SELINUX=enforcing or SELINUX=permissive. |
| 1.3.1.5 | L2 | Ensure the SELinux mode is enforcing. Both runtime and config file must show enforcing. | getenforce ; grep 'SELINUX=enforcing' /etc/selinux/config | Set SELINUX=enforcing in config; run setenforce 1 for immediate effect. |
| 1.3.1.6 | L2 | Ensure no unconfined services exist. No processes should run in unconfined_service_t. | ps -eZ | grep unconfined_service_t | Write and load a policy module for any unconfined service, or remove the service. |
| 1.3.1.7 | L1 | Ensure the MCS Translation Service (mcstrans) is not installed. | rpm -q mcstrans | dnf remove -y mcstrans |
| 1.3.1.8 | L1 | Ensure SETroubleshoot is not installed on production servers. | rpm -q setroubleshoot | dnf remove -y setroubleshoot setroubleshoot-server |
14.2 DISA RHEL 9 STIG: SELinux-Relevant Findings
The DISA Security Technical Implementation Guide for RHEL 9 contains findings across several categories. SELinux-relevant findings are primarily in the Access Control category. The STIG assigns each finding a severity: Category I (CAT I, high), Category II (CAT II, medium), Category III (CAT III, low). CAT I findings must be remediated immediately; CAT II findings within the time frame specified in the Plan of Action and Milestones.
DISA publishes STIG updates quarterly. The finding identifiers (SV-xxxxx) and STIG IDs (RHEL-09-xxxxxx) in this section reflect the structure of the RHEL 9 STIG. Always verify against the currently published version at https://public.cyber.mil/stigs/ before an assessment. Finding numbers can change between versions even when the technical requirement is unchanged.
Since December 2024, DISA publishes the CloudLinux AlmaLinux OS 9 STIG (listed in the NIST National Checklist Program), so an AlmaLinux system in a DoD assessment is measured against ALMA-09 identifiers, not the RHEL-09 identifiers in Table 14.2. The requirements track the RHEL 9 STIG closely, but identifiers differ throughout and some severities differ. Verified SELinux-relevant counterparts: enforcing mode is ALMA-09-041930 at Category II, where the RHEL 9 STIG rates its equivalent Category I, and its check additionally requires the selinux=1 and enforcing=1 kernel arguments on all kernels (audit with grubby --info=ALL, remediate with grubby --args="selinux=1 enforcing=1" --update-kernel=ALL); the policycoreutils package requirement is ALMA-09-042040 (Category II); the faillock tally-directory context is ALMA-09-008380 (Category II). Why the same control carries a different category is worth stating, because an assessor will ask: the two STIGs are written by different authors. The RHEL 9 STIG is maintained by DISA with Red Hat; the AlmaLinux OS 9 STIG was authored by TuxCare (a CloudLinux division) and published through DISA. A STIG's severity is the author's risk determination expressed through the Security Requirements Guide (SRG) and CCI a rule maps to, and the two enforcing findings map differently: the RHEL one additionally satisfies SRG-OS-000445 and SRG-OS-000134 and is rated CAT I, while the AlmaLinux one maps to SC-3 (CCI-001084) and is rated CAT II. DISA publishes no rationale for the specific divergence, so do not read the lower AlmaLinux category as lower technical risk: the control is identical and equally load-bearing on both platforms. Cite the category from the STIG that governs your platform, and if the gap is questioned, point to the differing authorship and SRG mapping, not to any difference in the control. Table 14.2 teaches with the RHEL-09 identifiers because the wider ecosystem (SSG profiles, scanners, published references) is keyed to them; before quoting any identifier or severity in an AlmaLinux assessment, map the row against the current AlmaLinux OS 9 STIG release.DISA CloudLinux AlmaLinux OS 9 STIG, first release V1R1 (December 2024), updated quarterly; NIST National Checklist Program entry for AlmaLinux OS 9. Download the current release at https://public.cyber.mil/stigs/downloads/; see Appendix E, DISA-ALMA9.
| STIG ID | Severity | Finding | Audit Command | Fix |
|---|---|---|---|---|
| RHEL-09-431010 | CAT I | RHEL 9 must use a Linux Security Module configured to enforce limits on system services. (This is the finding whose check is that SELinux is enabled and in enforcing mode.) | getenforce → Enforcing; sestatus | Set SELINUX=enforcing in /etc/selinux/config and run setenforce 1 at runtime. |
| RHEL-09-431015 | CAT II | RHEL 9 must enable the SELinux targeted policy. | sestatus | grep 'Loaded policy name'; grep '^SELINUXTYPE=' /etc/selinux/config | Set SELINUXTYPE=targeted in config; reboot if changing from MLS to targeted. |
| RHEL-09-431030 | CAT II | RHEL 9 must have the policycoreutils-python-utils package installed (provides semanage, audit2allow, audit2why for managing the policy). | rpm -q policycoreutils-python-utils | dnf install -y policycoreutils-python-utils |
| (none) | n/a | No daemons unconfined by SELinux. The published STIG has no numbered finding for this; the requirement is carried by the SCAP/SSG rule selinux_confinement_of_daemons (and by CIS 1.3.1.6), so hardening scans check it even though no RHEL-09 identifier exists. | ps -eZ | grep unconfined_service_t (should return nothing) | Write and load a policy module for each unconfined service, or remove the service. |
Beyond the explicit SELinux findings, the STIG contains audit and logging findings that directly interact with SELinux. The audit subsystem (auditd) must be running and configured to log SELinux events, and audit records must be protected from unauthorized modification, which reinforces the NIST SP 800-92 requirements addressed in the next section.
14.3 NIST SP 800-123: Least Privilege and OS Hardening
NIST SP 800-123, Guide to General Server Security, addresses operating-system hardening in general terms and does not discuss SELinux or mandatory access control specifically. Its relevant guidance is in Section 4 (Securing the Server Operating System): apply least privilege, set OS access controls that deny unnecessary access, enable auditing, and where appropriate confine a service in an isolated environment. SELinux is the RHEL-family mechanism that realizes those goals at the kernel level; the document itself defers implementation specifics to platform guidance such as the STIGs and benchmarks.
The SP 800-123 controls that SELinux directly satisfies are:
| SP 800-123 Guidance | How SELinux satisfies it |
|---|---|
| Apply least privilege to OS processes and services (Sections 2.2, 4.2) | Domain confinement limits each service to its necessary permissions only; additional access requires explicit policy authorization. |
| Limit the scope of compromise from a vulnerable application (Section 4.2, isolated environments) | Domain isolation ensures that a compromised service cannot access resources outside its domain without a policy rule permitting it. |
| Set OS access controls that deny unnecessary access (Section 4.2) | SELinux adds a MAC layer that enforces policy independent of and in addition to Unix DAC file permissions. |
| Apply controls to protect critical system files (Section 4.2) | File types like shadow_t, sshd_key_t, and passwd_file_t are protected by policy rules that restrict access to authorized domains only. |
14.4 NIST SP 800-92: Audit Log Protection
NIST SP 800-92, Guide to Computer Security Log Management, is relevant to SELinux in two ways: SELinux generates audit records that must be managed per this guide, and SELinux can protect the audit log itself.
The audit log (/var/log/audit/audit.log) is typically labeled auditd_log_t. Only processes with explicit permission to read this type can access the log. The auditd_t domain can write to it; the syslogd_t domain may be able to read it depending on the forwarding configuration. Non-audit processes cannot read or write to it without an explicit policy rule, which is the SELinux contribution to the "protect logs from modification" requirement.
| SP 800-92 Requirement | SELinux mechanism | Implementation |
|---|---|---|
| Protect logs from unauthorized modification (Section 3.2) | File type restriction on auditd_log_t | Enforced automatically by targeted policy; only auditd_t can write to auditd_log_t. |
| Separate log storage from the system being monitored (Section 3.2) | Remote log forwarding via audisp-remote | Configure /etc/audit/audisp-remote.conf (the plugin is enabled under /etc/audit/plugins.d/ on RHEL 9); SELinux confines the remote-logging plugin in its own domain (audisp_remote_t) and governs its outbound connection. |
| Generate log entries for security-relevant events (Section 3.1) | AVC records for denials; MAC_CONFIG_CHANGE and MAC_POLICY_LOAD records | Enforced by auditd; SELinux records are generated automatically when auditd is running. |
| Define log retention requirements (Section 4.2) | Not directly controlled by SELinux | Configure max_log_file, num_logs, and max_log_file_action in /etc/audit/auditd.conf. |
14.5 NIST SP 800-190: Container Runtime Controls
NIST SP 800-190 addresses container security at a higher level of abstraction than the other frameworks. It enumerates risks in Section 3 and the matching countermeasures in Section 4; its SELinux-relevant guidance is in the countermeasures chapter (host OS countermeasures in Section 4.5, container countermeasures in Section 4.4), answering the host OS and container risks described in Sections 3.5 and 3.4. These are addressed by the configurations in Chapter 13.
| SP 800-190 Requirement | SELinux configuration |
|---|---|
| Apply MAC to container processes (Section 4.5, host OS countermeasures) | Ensure container-selinux is installed and SELinux is enforcing. Containers automatically run in container_t. |
| Isolate container instances from each other (Section 4.4, container countermeasures) | Use MCS categories via the :Z flag on volume mounts. Podman assigns unique categories automatically. |
| Restrict privileged container use (Section 4.4, container countermeasures) | Avoid --privileged (which assigns spc_t). Use targeted security options instead: --security-opt label=type:container_t. |
| Protect host from container processes (Section 4.5, host OS countermeasures) | The container_t domain cannot access host file types. Use :Z not :z for private data volumes. |
14.6 Where the Standards Conflict
Two conflicts between the referenced standards are worth noting explicitly so you can make an informed decision for your environment.
Targeted vs. MLS: Here the frameworks agree more than folklore suggests. The CIS benchmark requires the targeted policy (1.3.1.3), and so does the published DISA STIG: RHEL-09-431015 checks for SELINUXTYPE=targeted, so a system running the MLS policy takes that finding as written. A genuine MLS mandate comes from program-level security requirements for multi-level classified processing, outside both documents; a system under such a mandate reconciles the conflict with the STIG through its authorizing official rather than by assuming the STIG itself demands MLS. For DoD systems the STIG governs; the CIS benchmark is the appropriate baseline for non-DoD environments, and where both apply, the federal document takes precedence.
setroubleshoot on development vs. production: The CIS benchmark (Section 1.3.1.8) requires removing setroubleshoot from production servers. The DISA STIG does not explicitly prohibit it but does require minimizing installed packages generally. If you use setroubleshoot during policy development (which is appropriate), remove it before the system is promoted to production. Both standards agree on the destination; they differ only in whether the prohibition is explicit.
14.7 Verifying SELinux Compliance with OpenSCAP
The compliance tables in Sections 14.1 and 14.2 tell you what each standard requires; they say nothing about how a formal assessment actually verifies it. In practice, DISA STIG assessments on RHEL-family systems are conducted with SCAP (Security Content Automation Protocol) tooling: a scanner evaluates machine-readable profile content against the running system and returns a pass/fail result for each control. OpenSCAP is the open-source implementation available in the AlmaLinux repositories; the SCAP Security Guide (SSG) supplies the profile content, including the SELinux rules that correspond to the controls in this chapter.
# dnf install -y openscap-scanner scap-security-guideAfter installation the AlmaLinux 9 SSG data stream lives at /usr/share/xml/scap/ssg/content/ssg-almalinux9-ds.xml. Validate it before running any scan so you catch a corrupted or outdated package before trusting results:
# oscap ds sds-validate /usr/share/xml/scap/ssg/content/ssg-almalinux9-ds.xml \
&& echo "valid" || echo "invalid"
validTwo profiles are relevant to this guide. The DISA STIG profile checks the STIG findings from Section 14.2. The CIS Level 2 Server profile checks the benchmark controls from Section 14.1, including the package removal requirements (setroubleshoot, mcstrans) that the STIG profile does not separately test. List all available profiles and confirm both are present with oscap info:
# oscap info /usr/share/xml/scap/ssg/content/ssg-almalinux9-ds.xml \
| grep -E 'profile_stig$|profile_cis$'
Id: xccdf_org.ssgproject.content_profile_stig
Id: xccdf_org.ssgproject.content_profile_cisRun the STIG scan. The --fetch-remote-resources flag is required by the AlmaLinux SSG because the data stream references OVAL definitions hosted at security.almalinux.org for CVE checks; the scanner will fail on those entries without it. On systems without outbound internet access, pre-download the OVAL file (https://security.almalinux.org/oval/org.almalinux.alsa-9.xml.bz2) to the expected local path before scanning; consult the AlmaLinux OpenSCAP Guide (see Appendix E, OPENSCAP-AL9) for the exact procedure.
# oscap xccdf eval \
--profile xccdf_org.ssgproject.content_profile_stig \
--fetch-remote-resources \
--results /tmp/stig-results.xml \
--report /tmp/stig-report.html \
/usr/share/xml/scap/ssg/content/ssg-almalinux9-ds.xmlThe scanner prints each rule title and result to the terminal as it runs. On a system correctly configured following this guide, the SELinux-relevant lines will read pass. Open /tmp/stig-report.html in a browser for the full annotated report; search the page for "SELinux" to jump to the relevant findings. Table 14.6 maps the SCAP rule identifiers to the controls from Tables 14.1 and 14.2 so you can cross-reference a specific pass/fail against the requirement that drives it.
| Rule short name | Title in oscap output | CIS 1.3.1.x | DISA STIG finding |
|---|---|---|---|
selinux_state | Ensure SELinux State is Enforcing | 1.3.1.5 (L2) | RHEL-09-431010 (CAT I) |
selinux_policytype | Configure SELinux Policy | 1.3.1.3 (L1) | RHEL-09-431015 (CAT II) |
selinux_confinement_of_daemons | Ensure No Daemons are Unconfined by SELinux | 1.3.1.6 (L2) | SSG rule (no stable STIG ID) |
selinux_not_disabled | Ensure SELinux is Not Disabled | 1.3.1.4 (L1) | n/a |
package_mcstrans_removed | Uninstall mcstrans Package | 1.3.1.7 (L1) | n/a (CIS profile only) |
package_setroubleshoot_removed | Uninstall setroubleshoot Package | 1.3.1.8 (L1) | n/a (CIS profile only) |
To evaluate the CIS controls, run the same command with the CIS profile ID instead:
# oscap xccdf eval \
--profile xccdf_org.ssgproject.content_profile_cis \
--fetch-remote-resources \
--results /tmp/cis-results.xml \
--report /tmp/cis-report.html \
/usr/share/xml/scap/ssg/content/ssg-almalinux9-ds.xmlSCAP (Security Content Automation Protocol) is a suite of open standards maintained by NIST for automating vulnerability management and security measurement. SCAP content for RHEL-family systems is maintained by the ComplianceAsCode project, which publishes the SCAP Security Guide. The AlmaLinux Foundation maintains an AlmaLinux-specific fork of that content. The rule identifiers in Table 14.6 are drawn from the ComplianceAsCode SSG project; the rule sources live under linux_os/guide/system/selinux/ in that repository.ComplianceAsCode SCAP Security Guide: https://github.com/ComplianceAsCode/content. AlmaLinux OpenSCAP Guide: https://wiki.almalinux.org/documentation/openscap-guide-for-9.html. The AlmaLinux SSG STIG profile is community-maintained and labeled [DRAFT]; it is not formally DISA-validated for AlmaLinux. For a DoD-regulated assessment, use the official DISA content for the platform, the CloudLinux AlmaLinux OS 9 STIG published at https://public.cyber.mil/stigs/ (see Section 14.2), and adapt the scanning procedure accordingly.
The commands above run the full STIG or CIS profile, which checks hundreds of controls beyond SELinux: cryptographic policy, auditing configuration, account settings, network parameters, and more. Interpreting the non-SELinux findings, running SCAP-generated Ansible remediation playbooks, and building a continuous compliance workflow across a fleet are outside the scope of this guide. A comprehensive treatment of SCAP and OpenSCAP as a general RHEL hardening toolchain is a topic for a companion volume. This section covers only what is needed to verify that the SELinux configuration built by following this guide passes the controls in Tables 14.1 and 14.2.
Capstone
The capstone chapter assembles every layer of the guide into a single end-to-end build. Each step is labeled with the chapter that explains it. A verification table at the end confirms every control is in the correct state.
Chapter 15Building a Hardened AlmaLinux 9 Web Server
Starting from a minimal AlmaLinux 9 installation, this chapter builds a production-hardened web server: SELinux enforcing with the targeted policy, httpd confined and serving TLS with correct security headers, SSH on a documented non-standard port, and a Podman container with MCS isolation running alongside the host service.
Every step is mapped to the chapter that explains it and the standard that requires or recommends it.
15.1 Starting State Assumptions
This capstone assumes a fresh minimal AlmaLinux 9 install with network access to the AlmaLinux repositories. The system has one non-root user with sudo access. No web server is installed yet. SELinux is enforcing (the default after installation).
15.2 Phase 1: Verify and Lock the SELinux Baseline
Implements: Chapter 1, Chapter 3 / Required by: CIS 1.3.1.2–1.3.1.5, DISA RHEL-09-431010 (enforcing) and RHEL-09-431015 (targeted policy), AlmaLinux OS 9 STIG ALMA-09-041930 (enforcing and kernel arguments), NIST SP 800-123 Section 4.3
# 1. Verify the current state
# sestatus
# cat /etc/selinux/config # confirm SELINUX=enforcing, SELINUXTYPE=targeted
# 2. Verify no bootloader parameters disable SELinux
# grep -E 'selinux=0|enforcing=0' /etc/default/grub && echo FAIL || echo PASS
# 2b. AlmaLinux OS 9 STIG (ALMA-09-041930): assert SELinux on the kernel command line
# grubby --args="selinux=1 enforcing=1" --update-kernel=ALL # takes effect at next reboot
# grubby --info=ALL | grep -E 'selinux=1.*enforcing=1' && echo PASS
# 3. Install the policy development tools (for later steps)
# dnf install -y setools-console policycoreutils-python-utils \
selinux-policy-devel checkpolicy
# 4. Confirm no unconfined services exist on this minimal system
# ps -eZ | grep unconfined_service_t # should return nothing15.3 Phase 2: Install and Confine httpd
Implements: Chapter 4, Chapter 5, Chapter 11 / Required by: CIS 1.3.1.6 (confine all services), NIST SP 800-123 Section 4.3
# dnf install -y httpd mod_ssl
# Create the portal directory structure
# mkdir -p /srv/grimoire/{html,logs,uploads}
# echo '<h1>Grimoire Portal</h1>' > /srv/grimoire/html/index.html
# chown -R apache:apache /srv/grimoire
# Set persistent SELinux file contexts
# semanage fcontext -a -t httpd_sys_content_t '/srv/grimoire/html(/.*)?'
# semanage fcontext -a -t httpd_log_t '/srv/grimoire/logs(/.*)?'
# semanage fcontext -a -t httpd_sys_rw_content_t '/srv/grimoire/uploads(/.*)?'
# restorecon -Rv /srv/grimoire/
# Verify labels
# ls -lZ /srv/grimoire/html/index.html # must be httpd_sys_content_t
# ls -lZ /srv/grimoire/logs/ # must be httpd_log_t15.4 Phase 3: Generate and Label the TLS Certificate
Implements: Chapter 11 / Aligned with: Mozilla Server Side TLS (Intermediate profile minimum)
# Generate a self-signed cert (replace with a CA-signed cert in production)
# openssl req -x509 -nodes -days 365 -newkey rsa:4096 \
-keyout /etc/pki/tls/private/grimoire.key \
-out /etc/pki/tls/certs/grimoire.crt \
-subj '/CN=grimoire.lab' \
-addext 'subjectAltName=DNS:grimoire.lab'
# Verify and correct labels (should be cert_t)
# ls -lZ /etc/pki/tls/certs/grimoire.crt /etc/pki/tls/private/grimoire.key
# restorecon -v /etc/pki/tls/certs/grimoire.crt /etc/pki/tls/private/grimoire.key15.5 Phase 4: Configure the Hardened Virtual Host
Implements: Chapter 11 / Aligned with: Mozilla Server Side TLS (Intermediate), OWASP Secure Headers Project
# /etc/httpd/conf.d/grimoire.conf
<VirtualHost *:80>
ServerName grimoire.lab
Redirect permanent / https://grimoire.lab/
</VirtualHost>
<VirtualHost *:443>
ServerName grimoire.lab
DocumentRoot /srv/grimoire/html
ErrorLog /srv/grimoire/logs/error.log
CustomLog /srv/grimoire/logs/access.log combined
SSLEngine on
SSLCertificateFile /etc/pki/tls/certs/grimoire.crt
SSLCertificateKeyFile /etc/pki/tls/private/grimoire.key
SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305
SSLHonorCipherOrder off
SSLSessionTickets off
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains"
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "DENY"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Content-Security-Policy "default-src 'self'"
<Directory /srv/grimoire/html>
Options -Indexes -FollowSymLinks
Require all granted
</Directory>
</VirtualHost># systemctl enable --now httpd
# firewall-cmd --add-service=http --add-service=https --permanent
# firewall-cmd --reload
# ausearch -m avc -ts recent # confirm zero denials15.6 Phase 5: Configure SSH on a Non-Standard Port
Implements: Chapter 12 / Port context management per the targeted policy
# Add port 2222 to ssh_port_t BEFORE changing sshd_config
# semanage port -a -t ssh_port_t -p tcp 2222
# Edit sshd_config
# sed -i 's/#Port 22/Port 2222/' /etc/ssh/sshd_config
# Open the new port in firewalld
# firewall-cmd --add-port=2222/tcp --permanent && firewall-cmd --reload
# systemctl restart sshd
# ausearch -m avc -c sshd -ts recent # confirm no denials15.7 Phase 6: Deploy a Confined Container
Implements: Chapter 13 / Required by: NIST SP 800-190 Section 4 countermeasures (host OS 4.5, container 4.4)
# dnf install -y podman container-selinux
# Run a confined container with a private (:Z) volume mount to demonstrate MCS isolation
# mkdir /srv/container-data
# echo 'MCS-isolated store data' > /srv/container-data/info.txt
# podman run -d --name grimoire-store \
-v /srv/container-data:/app/data:Z \
alpine sleep 3600
# Verify the MCS category and label on the volume
# ls -lZ /srv/container-data/
# podman inspect grimoire-store --format '{{.ProcessLabel}} {{.MountLabel}}'
# Verify the container runs in container_t, not spc_t
# ps -eZ | grep 'container_t'15.8 Phase 7: Remove Development Tools and Finalize
Required by: CIS 1.3.1.8 (remove setroubleshoot), CIS 1.3.1.7 (remove mcstrans)
# dnf remove -y setroubleshoot setroubleshoot-server mcstrans
# dnf remove -y checkpolicy selinux-policy-devel # if not needed in production
# rpm -q setroubleshoot mcstrans && echo FAIL || echo PASS15.9 Verification Table
Run through this table as the final step. Every check should show the expected value. Any deviation is either a configuration error or a finding.
| Control | Verification command | Expected output | Framework |
|---|---|---|---|
| SELinux enabled and enforcing | getenforce | Enforcing | CIS 1.3.1.5, DISA RHEL-09-431010 / ALMA-09-041930 |
| Targeted policy configured | grep SELINUXTYPE /etc/selinux/config | SELINUXTYPE=targeted | CIS 1.3.1.3, DISA RHEL-09-431015 |
| No bootloader SELinux disable | grep -c 'selinux=0\|enforcing=0' /etc/default/grub | 0 | CIS 1.3.1.2 |
| Kernel args assert SELinux | grubby --info=ALL | grep -c 'selinux=1 enforcing=1' | one match per installed kernel | DISA ALMA-09-041930 |
| No unconfined services | ps -eZ | grep -c unconfined_service_t | 0 | CIS 1.3.1.6, DISA SSG selinux_confinement_of_daemons |
| setroubleshoot removed | rpm -q setroubleshoot 2>&1 | package setroubleshoot is not installed | CIS 1.3.1.8 |
| mcstrans removed | rpm -q mcstrans 2>&1 | package mcstrans is not installed | CIS 1.3.1.7 |
| Portal content labeled correctly | ls -lZ /srv/grimoire/html/index.html | grep -c httpd_sys_content_t | 1 | NIST SP 800-123 Section 4.3 |
| No AVC denials in audit log | ausearch -m avc -ts today 2>&1 | grep -c 'avc:' | 0 (a clean system prints <no matches>, which the grep does not count) | All frameworks (clean log indicates correct configuration) |
| TLS certificate label correct | ls -lZ /etc/pki/tls/certs/grimoire.crt | grep -c cert_t | 1 | NIST SP 800-123, Mozilla TLS |
| Portal serves over HTTPS | curl -ks -o /dev/null -w '%{http_code}' https://localhost/ | 200 | All frameworks (service-up gate; a 403 here means the <Directory> grant or a content label is wrong, not a header problem) |
| Security headers present | curl -k -s -I https://localhost/ | grep -c 'Strict-Transport' | 1 | OWASP Secure Headers Project |
| SSH port in ssh_port_t | semanage port -l | grep -c 'ssh_port_t.*2222' | 1 | NIST SP 800-123 Section 4.2 |
| Container in container_t | ps -eZ | grep -c 'container_t' | 1 or more | NIST SP 800-190 Section 4.5 |
| auditd running | systemctl is-active auditd | active | NIST SP 800-92 Section 3.2 |
Appendices
Appendix A · Annotated Configuration Templates
A.1 /etc/selinux/config
# /etc/selinux/config
# SELinux configuration for a production AlmaLinux 9 server.
# SELINUX: enforcing = enforce policy; permissive = log only; disabled = off (not recommended).
# Changing SELINUXTYPE requires a reboot and relabel if switching between targeted and mls.
SELINUX=enforcing
# SELINUXTYPE: targeted = confine specific services (recommended); mls = multi-level security.
SELINUXTYPE=targetedA.2 /etc/audit/auditd.conf (relevant settings)
# /etc/audit/auditd.conf - key settings for a NIST SP 800-92 compliant configuration
log_file = /var/log/audit/audit.log
# max_log_file: size in MB before rotation. Set per your retention requirements.
max_log_file = 100
# num_logs: how many rotated logs to keep on disk.
num_logs = 10
# max_log_file_action: what to do when the log fills. ROTATE is safest; SUSPEND stops auditd.
max_log_file_action = ROTATE
# space_left_action: what to do when disk space is low. EMAIL notifies; SUSPEND stops logging.
space_left = 100
space_left_action = EMAIL
admin_space_left = 50
admin_space_left_action = HALT
# disk_full_action: HALT ensures the system stops rather than continuing without audit records.
disk_full_action = HALTA.3 Custom Module Template (myapp.te)
# myapp.te - template for a new confined daemon.
# Substitute "myapp" with your application name throughout.
# Build with: make -f /usr/share/selinux/devel/Makefile
# Load with: semodule -X 400 -i myapp.pp
policy_module(myapp, 1.0.0)
# --- Types ---
type myapp_t; # process domain
type myapp_exec_t; # entrypoint binary type
type myapp_etc_t; # configuration files
type myapp_log_t; # log files
type myapp_var_run_t; # PID file and runtime state
# --- Attributes (assign to standard attribute groups) ---
# init_daemon_domain sets up the domain, entrypoint, and init transition for a
# systemd-started daemon. Add application_domain() as well only if the binary is
# also meant to be launched interactively by an admin.
init_daemon_domain(myapp_t, myapp_exec_t)
files_config_file(myapp_etc_t)
logging_log_file(myapp_log_t)
files_pid_file(myapp_var_run_t)
# --- Allow rules ---
allow myapp_t myapp_etc_t:file { read open getattr };
allow myapp_t myapp_etc_t:dir { read getattr open search };
allow myapp_t myapp_log_t:file { create write append open getattr };
allow myapp_t myapp_log_t:dir { search getattr write add_name };
allow myapp_t myapp_var_run_t:file { create write open getattr unlink };
allow myapp_t myapp_var_run_t:dir { search getattr write add_name remove_name };A.4 Custom Module File Context Template (myapp.fc)
# myapp.fc - file context specifications for myapp.
# Path patterns use extended regular expression syntax.
# gen_context() wraps the context string for portability.
/usr/sbin/myapp -- gen_context(system_u:object_r:myapp_exec_t,s0)
/etc/myapp(/.*)? gen_context(system_u:object_r:myapp_etc_t,s0)
/var/log/myapp(/.*)? gen_context(system_u:object_r:myapp_log_t,s0)
/run/myapp(/.*)? gen_context(system_u:object_r:myapp_var_run_t,s0)
/run/myapp\.pid -- gen_context(system_u:object_r:myapp_var_run_t,s0)Appendix B · Deployment Checklist
Use this checklist before promoting a system to production. Check each item and record the output of the verification command.
| Item | Verification command | Pass condition | Pass? |
|---|---|---|---|
| SELinux enabled | sestatus | grep 'SELinux status' | enabled | |
| Mode: enforcing | getenforce | Enforcing | |
| Config file: enforcing | grep '^SELINUX=' /etc/selinux/config | SELINUX=enforcing | |
| Policy: targeted | grep '^SELINUXTYPE=' /etc/selinux/config | SELINUXTYPE=targeted | |
| No bootloader disable params | grep -E 'selinux=0|enforcing=0' /etc/default/grub | No output | |
| No unconfined services | ps -eZ | grep unconfined_service_t | No output | |
| setroubleshoot removed | rpm -q setroubleshoot 2>&1 | grep 'not installed' | not installed | |
| mcstrans removed | rpm -q mcstrans 2>&1 | grep 'not installed' | not installed | |
| Zero AVC denials (today) | ausearch -m avc -ts today 2>&1 | grep -c 'avc:' | 0 (clean systems print <no matches>) | |
| All web content labeled | find /srv -name '*.html' ! -context '*httpd_sys_content_t*' | No output | |
| Log directories labeled | ls -ldZ /srv/grimoire/logs | grep httpd_log_t | Output contains httpd_log_t | |
| TLS certificates labeled cert_t | ls -lZ /etc/pki/tls/certs/*.crt | grep cert_t | Output present | |
| Custom ports registered | semanage port -l | grep -E 'ssh_port_t|http_port_t' | Non-standard ports appear | |
| auditd active | systemctl is-active auditd | active | |
| Custom modules loaded | semodule -l | grep grimoire | Modules listed (if you loaded the Lab 5 or Caddy modules; a capstone-only build legitimately lists none) | |
| Container-selinux installed (if containers used) | rpm -q container-selinux | Package version shown | |
| No privileged containers running | podman ps --format '{{.Names}}' | xargs -I{} podman inspect {} --format '{{.HostConfig.Privileged}}' 2>/dev/null | grep true | No output |
Appendix C · Standards Crosswalk Master Table
These tables map SELinux configuration areas to the standards that require or address them. Use them to identify which frameworks impose obligations for a given configuration item. Table C.1 covers the compliance frameworks; Table C.2 covers the two web-server hardening standards. The DISA column lists RHEL 9 STIG identifiers, with the dedicated AlmaLinux OS 9 STIG's ALMA-09 counterparts shown where this guide has verified them; an AlmaLinux assessment is measured against the ALMA-09 identifiers, whose severities sometimes differ (see Section 14.2).
| Configuration area | CIS 1.3.1.x | DISA RHEL-09 / ALMA-09 | NIST 800-123 | NIST 800-92 | NIST 800-190 |
|---|---|---|---|---|---|
| SELinux installed | 1.3.1.1 | (implied by 431010) | Sec. 4.2 | N/A | N/A |
| Enforcing mode | 1.3.1.4, 1.3.1.5 | 431010 / ALMA 041930 (CAT II there) | Sec. 4.2 | N/A | Sec. 4.5 |
| Targeted policy | 1.3.1.3 | 431015 | Sec. 4.2 | N/A | N/A |
| No bootloader disable | 1.3.1.2 | (RHEL: no separate STIG ID; ALMA 041930 also requires selinux=1 enforcing=1 present) | N/A | N/A | N/A |
| No unconfined services | 1.3.1.6 | SSG selinux_confinement_of_daemons | Sec. 4.2 | N/A | N/A |
| setroubleshoot absent | 1.3.1.8 | (implied by min. software) | N/A | N/A | N/A |
| mcstrans absent | 1.3.1.7 | (implied by min. software) | N/A | N/A | N/A |
| File context correctness | N/A | 431020 / ALMA 008380 (faillock tally dir; context-type example) | Sec. 4.2 | N/A | N/A |
| Port context management | N/A | N/A | Sec. 4.2 | N/A | N/A |
| Audit log protection | N/A | N/A | N/A | Sec. 3.2 | N/A |
| Audit log retention | N/A | N/A | N/A | Sec. 4.2 | N/A |
| Container MAC policy | N/A | N/A | N/A | N/A | Sec. 4.5 |
| MCS container isolation | N/A | N/A | N/A | N/A | Sec. 4.4 |
| No privileged containers | N/A | N/A | N/A | N/A | Sec. 4.4 |
| Configuration area | Mozilla TLS | OWASP Headers |
|---|---|---|
| TLS certificate and key labels | cert_t for keys (see the caution in Section 11.2) | N/A |
| TLS 1.2+ only | Intermediate profile | N/A |
| HSTS header present | Required | HSTS required |
| Security response headers | N/A | X-Content-Type-Options, X-Frame-Options, CSP, Referrer-Policy |
Appendix D · Glossary
- Allow rule
- The fundamental policy statement. Grants a specific process type permission to perform specific operations against specific object types in a specific class. The absence of an allow rule is an implicit deny.
- AVC (Access Vector Cache)
- The kernel-side cache that memoizes access decisions from the security server. Prevents the policy being evaluated from scratch on every system call. Invalidated when policy is reloaded.
- Boolean
- A named conditional switch in the policy. Toggling a boolean enables or disables a pre-defined set of allow rules without requiring a custom module or a full policy reload.
- CIL (Common Intermediate Language)
- The modern intermediate language that userspace (libsemanage/secilc) compiles into the binary policy the kernel loads. It is how the module store keeps modules on disk, and it is also usable as a source format, loaded directly with
semodule -i. - Context (security context, label)
- The four-field identity string assigned to every subject and object:
user:role:type:level. The combination of subject context, object context, object class, and requested permission is what the security server evaluates for every access. - DAC (Discretionary Access Control)
- The traditional Unix permission model. Access decisions are at the discretion of the resource owner; root is exempt. Contrast with MAC.
- Domain
- The type assigned to a running process. Every process operates within a domain; domain transitions occur when a process executes a new binary with a defined transition rule.
- Domain transition
- The mechanism by which a process changes its domain type when it executes a new binary. Requires three permissions to hold together: the source domain must be able to execute the entrypoint binary (file:execute on the executable's type); the target domain must declare that binary as an entry point (file:entrypoint on the same type); and the source domain must have the transition permission to the target (process:transition). A type_transition rule then makes the transition happen automatically on exec; without one, the transition is still possible but only when the caller requests it explicitly (see Section 2.4).
- dontaudit
- A policy statement that suppresses the audit record for a specific denied access. Used for known-safe denials that would otherwise produce excessive log noise.
- Enforcing mode
- The operational SELinux mode. Denials block the access and generate audit records. The only mode that provides security containment.
- FLASK
- Flux Advanced Security Kernel. The underlying architecture of SELinux, designed by the NSA, the University of Utah, and Secure Computing Corporation. Separates the policy decision (security server) from the enforcement point (LSM hooks in the kernel).
- MAC (Mandatory Access Control)
- An access control model where access decisions are enforced by system policy, not by the discretion of individual users or resource owners. Root cannot override MAC policy. SELinux implements MAC through type enforcement.
- MCS (Multi-Category Security)
- A subset of MLS that uses categories (not sensitivity levels) to distinguish between instances of the same type. Used primarily for container isolation: two containers in
container_tcan be isolated from each other by assigning them different MCS category pairs. - MLS (Multi-Level Security)
- A SELinux policy variant that enforces a strict information-flow lattice using sensitivity levels and categories. Required for DoD systems handling classified information at multiple levels. More restrictive than the targeted policy.
- Module
- The unit of policy extension. A compiled binary loaded into the policy store with
semodule -i. Modules can add types, rules, and file context specifications to the active policy without replacing it. - neverallow
- A compile-time assertion in the policy language. States that no allow rule matching this pattern may exist in the compiled policy. Enforced when the policy is compiled, so the shipped base policy is neverallow-clean. The re-check at module-load time is off by default on a stock AlmaLinux 9 (
expand-check=0in semanage.conf), so a custom module can violate a base-policy neverallow unless you enable it; see Section 9.4. - Object class
- A category of kernel resource (file, dir, tcp_socket, process, capability, etc.). Each class has a specific set of permissions. The combination of class and permission specifies exactly which operation the subject attempted.
- Permissive mode
- A SELinux mode where denials are logged but not enforced. Useful for policy development and troubleshooting. Provides no security containment. A domain can be individually placed in permissive mode with
semanage permissive -a. - Policy store
- For the targeted policy, the active compiled binary policy and contexts live under
/etc/selinux/targeted/, while the module store (the individual modulessemoduleinstalls, by priority) lives under/var/lib/selinux/targeted/. Managed bysemoduleandsemanage. - Reference Policy
- The open-source policy project from which the targeted policy shipped with AlmaLinux 9 is derived. Provides a library of types, attributes, macros, and interfaces used by policy module authors.
- restorecon
- The command that applies the file context database to existing files. Run after adding entries with
semanage fcontext, after a relabeling event, or after moving files to fix mislabeling. - Role
- The second field in a security context. Determines which domains a process may run in. Part of Role-Based Access Control (RBAC) within SELinux. In the targeted policy, roles are coarse (system_r for system processes, unconfined_r for interactive users).
- semanage
- The primary tool for persistent policy customization: adding file context entries, port entries, booleans, users, and login mappings without writing a module.
- Type
- The third field in a security context, and the primary element of type enforcement. Every process has a type (its domain) and every object has a type. Policy rules are written in terms of types.
- Type enforcement (TE)
- SELinux's primary access control mechanism. All access decisions are made by evaluating allow rules against the source type, target type, object class, and permission of the requested operation.
- unconfined_t
- A domain in the targeted policy that is subject only to DAC controls; SELinux does not meaningfully restrict it. Interactive users run in this domain by default in the targeted policy. Processes in
unconfined_tshould not be confused with processes with no SELinux context.
Appendix E · References
All references below are primary or authoritative sources. Version numbers are cited where stable; for living documents (Mozilla TLS, OWASP) the URL points to the current version.
| Identifier | Document | URL / Location |
|---|---|---|
| NIST SP 800-123 | NIST Special Publication 800-123, Guide to General Server Security, Scarfone, K., Jansen, W., and Tracy, M., National Institute of Standards and Technology, 2008. | https://doi.org/10.6028/NIST.SP.800-123 |
| NIST SP 800-92 | NIST Special Publication 800-92, Guide to Computer Security Log Management, Kent, K. and Souppaya, M., National Institute of Standards and Technology, 2006. | https://doi.org/10.6028/NIST.SP.800-92 |
| NIST SP 800-190 | NIST Special Publication 800-190, Application Container Security Guide, Souppaya, M., Morello, J., and Scarfone, K., National Institute of Standards and Technology, 2017. | https://doi.org/10.6028/NIST.SP.800-190 |
| CIS-AL9 | CIS AlmaLinux OS 9 Benchmark, Center for Internet Security. Current version; check https://www.cisecurity.org/benchmark/almalinuxos_linux for the version number before use. | https://www.cisecurity.org/benchmark/almalinuxos_linux |
| DISA-RHEL9 | DISA Security Technical Implementation Guide for Red Hat Enterprise Linux 9, Defense Information Systems Agency. Published quarterly; always use the current version. | https://public.cyber.mil/stigs/downloads/ |
| DISA-ALMA9 | DISA Security Technical Implementation Guide for CloudLinux AlmaLinux OS 9, Defense Information Systems Agency. First published December 2024 and updated quarterly; the governing STIG for AlmaLinux OS 9 systems, listed in the NIST National Checklist Program. Identifiers use the ALMA-09 prefix, and severities occasionally differ from the RHEL 9 STIG (see Section 14.2). | https://public.cyber.mil/stigs/downloads/ |
| MOZ-TLS | Mozilla Server Side TLS, Security Engineering team, Mozilla Foundation. Living document; check the current version before implementing. | https://wiki.mozilla.org/Security/Server_Side_TLS |
| OWASP-SH | OWASP Secure Headers Project, Open Web Application Security Project. Living document. | https://owasp.org/www-project-secure-headers/ |
| SELINUX-REF | SELinux Reference Policy Project. The upstream ancestor of the RHEL-family policy and the home of the interface and macro documentation used in Part III. | https://github.com/SELinuxProject/refpolicy |
| SELINUX-POLICY-RH | fedora-selinux/selinux-policy. The source repository from which the selinux-policy packages shipped by AlmaLinux 9 are built (the c9s branch tracks the RHEL 9 family); the authoritative record of what the shipped targeted policy contains. | https://github.com/fedora-selinux/selinux-policy |
| SELINUX-WIKI | SELinux Project documentation wiki. Primary documentation for the SELinux userspace tools and policy language. | https://selinuxproject.org/page/Main_Page |
| CONTAINER-SEL | container-selinux: SELinux policies for containers. Upstream source for container type definitions used by Podman and CRI-O on AlmaLinux 9. | https://github.com/containers/container-selinux |
| ALMA9-DOCS | AlmaLinux OS 9 Documentation. AlmaLinux Wiki, AlmaLinux OS Foundation. | https://wiki.almalinux.org/ |
| RH-SEL-GUIDE | Using SELinux, Red Hat Enterprise Linux 9 Security Hardening guide. The authoritative Red Hat documentation for SELinux on the RHEL 9 platform (applies to AlmaLinux 9 without modification). | https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/9/html/using_selinux/ |
| OPENSCAP-AL9 | AlmaLinux 9 OpenSCAP Guide. AlmaLinux Wiki, AlmaLinux OS Foundation. Primary documentation for running OpenSCAP scans on AlmaLinux 9, including data stream validation, profile scanning, and OVAL-based vulnerability checks. | https://wiki.almalinux.org/documentation/openscap-guide-for-9.html |
| SSG-CAC | SCAP Security Guide, ComplianceAsCode project. The upstream source for the SELinux XCCDF rule content shipped in AlmaLinux 9's scap-security-guide package. Rule identifiers, titles, and remediation scripts are maintained here. | https://github.com/ComplianceAsCode/content |
Errata and Updates
This guide is corrected continuously, and you are part of how that happens. If you find an error, a claim that no longer matches its primary source, a command that does not behave as printed, or anything that has simply gone stale, report it to [email protected]. Name the section, and where you can, the authority that settles it; that is exactly how the book is verified in the first place, and a good report can go straight into the next revision.
The current, corrected version always lives at https://gregvogt.net/grimoire/. Each edition was correct as of the revision date printed on its cover, and claims nothing beyond it: standards move, packages update, and the page in front of you ages from the day it ships. When a detail matters, check it against the latest revision there, and against the primary source it cites, before you rely on it.
How to Cite This Guide
Because this is a living document, cite the revision you used and where you found it, so that a reader can retrieve the same text you saw. The revision is printed on the cover.
Vogt, Greg. Enforcing, Confining & Hardening with SELinux. The Programmer’s Grimoire. Revision v1.5 · June 2026. https://gregvogt.net/grimoire/selinux/
For LaTeX and reference managers:
@misc{grimoire-selinux,
author = {Vogt, Greg},
title = {Enforcing, Confining \& Hardening with SELinux},
series = {The Programmer's Grimoire},
edition = {Revision v1.5 · June 2026},
year = {2026},
url = {https://gregvogt.net/grimoire/selinux/}
}License and Reuse
The Programmer’s Grimoire is published free of charge and licensed to you under a Creative Commons Attribution-NonCommercial 4.0 International License (CC BY-NC 4.0). You are free to read, copy, share, and adapt or translate it, in any medium or format, for any non-commercial purpose, on one condition: give appropriate credit to the author, link to the license, and indicate whether you changed anything. You may not use the material for commercial purposes. The full terms are at https://creativecommons.org/licenses/by-nc/4.0/.
The intent is plain. The knowledge is meant to be free for anyone to read, copy, and translate, and the non-commercial term is what keeps it that way, so that no one else fences it off or resells it. A paid edition, where one exists, comes from the author and exists only to support the work; the knowledge itself is not the thing being sold.
Trademark and brand. The name The Programmer’s Grimoire, the series wordmark, and the look and branding of these guides are trademarks of Greg Vogt and are not part of the content license above. Reusing the licensed text, including in a translation, grants no right to the Grimoire name or brand. You may not present your version as an official Grimoire, use the name or wordmark to label, endorse, or promote a derivative or third-party work, or otherwise imply that the author stands behind it. Credit the original by name, which is the attribution the license requires, but publish your version under your own title.
Colophon
Each guide is a single HTML document with an external stylesheet and a small progressive-enhancement script, and no inline style or script at all, so it satisfies a strict Content-Security-Policy. Three formats are built from that one source: the PDF with WeasyPrint, the EPUB with EbookLib (parsed with BeautifulSoup), and the Kindle AZW3 with Calibre’s ebook-convert. What you read on screen, on paper, and on an e-reader is the same text rendered three ways.
The reading text is set in Georgia, with the bundled Literata as the press fallback; display headings, numerals, and labels are set in Cinzel, code and the interface in JetBrains Mono (with a bundled fallback face for full glyph coverage), and the Grimoire wordmark in UnifrakturCook. On screen the reader can switch the prose to Atkinson Hyperlegible or OpenDyslexic, scale the type, adjust line spacing, and toggle dark mode; the print and e-reader builds stay in the typeset faces. The bundled fonts are under the SIL Open Font License.
How it was made is described in the notes at the front, and is the point as much as the prose. First drafts are generated by an AI (Claude, made by Anthropic) and then verified, line by line, against primary sources by a human before anything ships. Every factual claim is tracked in a per-volume claims ledger and re-checked against the living standards on each revision, which is why a guide carries a revision date, and why that date is load-bearing.
