# SELinux

> Source: Courseiva IT Certification Glossary — https://courseiva.com/glossary/selinux

## Quick definition

SELinux is a security system built into Linux that controls which programs can access which files and resources on your computer. It works by assigning labels to everything and using rules to decide what is allowed. If a program tries to do something not explicitly permitted, SELinux blocks it. This helps prevent malware or misconfigured software from causing harm.

## Simple meaning

Imagine you live in a large apartment building with many rooms, each room belonging to different people or purposes. You have a strict building manager who carries a master list of every room key and every rule about who can enter which room. This manager does not let anyone enter a room unless the rules explicitly say that person is allowed. This is exactly how SELinux works on a Linux system.

In a regular Linux system without SELinux, if a user or program has permission to access something, they can typically do whatever they want with it, as long as the basic file permissions allow it. This is like having a normal key to a room and being allowed to go in, rearrange furniture, or even break things. SELinux changes this by adding an extra layer of rules. Even if you have the key (traditional permissions), the building manager (SELinux) checks a separate set of rules to see if your specific action is allowed. If the rules say you can only look at the furniture, but not touch it, SELinux will block you from moving anything.

SELinux assigns every file, process, port, and device a security label, called a context. The rules, known as policies, define which contexts can interact with which other contexts. When a program tries to open a file, SELinux checks the program’s context against the file’s context and the policy. If the action is not explicitly permitted, it is denied. This happens automatically in the background, without the user needing to intervene. By default, many Linux distributions like Red Hat Enterprise Linux, Fedora, and CentOS come with SELinux enabled and enforcing a strict policy out of the box. This means that even if you accidentally run a malicious script, SELinux can often prevent it from accessing critical system files because the script’s context does not have permission on those files.

In everyday terms, think of your computer as having a security guard for every program. The guard checks the program’s ID badge (context) and a rulebook (policy) before allowing it to do anything. If the program tries to read a password file, the guard stops it unless the rulebook specifically says that type of program is allowed to read password files. This is why SELinux is so effective at mitigating the damage from vulnerabilities in software like web servers or file-sharing services. It confines the damage to only what the policy allows, even if the attacker gains control of the program.

## Technical definition

SELinux (Security-Enhanced Linux) is a Linux kernel security module that provides a mechanism for supporting access control security policies, including mandatory access controls (MAC). The U.S. National Security Agency (NSA) originally designed SELinux as a series of patches to the Linux kernel using the Linux Security Modules (LSM) framework. It was integrated into the mainstream Linux kernel in version 2.6, and has since become a standard security feature in enterprise Linux distributions.

SELinux implements mandatory access control by labeling every object (files, directories, network sockets, inter-process communication channels) and every subject (processes, users) with a security context. Each security context consists of three components: user, role, and type. The type is the primary component used for enforcing the default targeted policy. For example, a web server process might have the context “system_u:system_r:httpd_t” where “httpd_t” is the type. A file in the web root might be labeled “system_u:object_r:httpd_sys_content_t”. The policy contains rules that define which types can access which types and in what ways (read, write, execute, create, etc.).

The SELinux policy is composed of rules that are loaded into the kernel at boot time. These rules can be in one of two modes: enforcing or permissive. In enforcing mode, SELinux denies actions that violate the policy and logs them. In permissive mode, it logs violations but does not deny actions. There is also a disabled mode where SELinux is turned off entirely. Administrators typically run in enforcing mode on production systems and may temporarily switch to permissive mode for troubleshooting.

SELinux uses a concept called “type enforcement” (TE), which is the primary mechanism. Every object is assigned a type, and the policy defines allowed interactions between types. For example, a rule might state that a process with type “httpd_t” can read files with type “httpd_sys_content_t” but cannot write to files with type “shadow_t” (the shadow password file). SELinux supports Role-Based Access Control (RBAC) and Multi-Level Security (MLS), which are used for more strict environments like military or intelligence systems.

Real IT implementations commonly use SELinux to protect critical services such as Apache HTTPD, Nginx, MySQL, PostgreSQL, Samba, and SSH. When a new service is installed, SELinux requires that the service’s files be properly labeled with the correct context. Tools like “semanage” and “restorecon” help manage contexts. Auditing and log analysis are done via “ausearch” and “sealert” for troubleshooting denials. A typical workflow for a sysadmin is to check “/var/log/audit/audit.log” for “AVC” (Access Vector Cache) denials when something fails, then either create a local policy module or change file contexts to resolve the issue.

In exam contexts, understanding that SELinux provides a supplementary layer of security on top of traditional discretionary access control (DAC) is critical. It does not replace file permissions; rather, it enforces additional rules. A process must pass both DAC and MAC checks to access a resource. This two-layer model is foundational for many security-related exam questions.

## Real-life example

Think of a high-security office building where employees have ID badges. The building has a main entrance security guard who checks badges, which is like standard Linux file permissions. But inside, there are special rooms: a server room, a HR records room, and a finance vault. Each room has a color-coded access system. Your badge may let you into the building, but the room doors only open if your badge has the correct color for that specific room. This is exactly how SELinux works.

Inside each room, the rules are even stricter. In the HR room, you can look at files but not print them. In the finance vault, you can only deposit files, not take them out. The building’s security system (SELinux) has a master policy that dictates these rules. If you try to enter the server room with a badge that says “HR staff” but not “IT staff,” the door simply will not open, no matter how many times you swipe. The security guard at the main entrance cannot override this; the room door has its own lock that only accepts the correct color.

Now, imagine a scenario where a cleaning person finds an unattended laptop in the finance vault. Even though the cleaning person has a valid building badge, the laptop’s screen lock prevents access because the cleaning person’s credentials are not authorized. In SELinux terms, even if a process has root privileges (the highest building access), the SELinux policy blocks actions that are not explicitly permitted by type enforcement. This is why a compromised web server cannot simply read your password file, because the web server’s type (“httpd_t”) is not allowed to access the “shadow_t” file type.

The everyday analogy is a well-staffed museum with different galleries. Each gallery has its own security guard who checks not just your ticket (basic permissions) but also your visitor category (context). A student visitor may be allowed in the general gallery but not the restoration lab. Even if the student sneaks into the lab, the guard there will stop them because the student’s visitor type does not match the lab’s required type. SELinux acts exactly like those gallery guards, checking each interaction against a predefined rulebook and blocking anything that is not explicitly allowed.

## Why it matters

SELinux matters because it dramatically reduces the attack surface of a Linux system. In real-world IT environments, vulnerabilities are constantly discovered in services like web servers, database servers, and file sharing protocols. Without SELinux, an attacker who exploits a bug in Apache or Nginx can often gain full control of the system, because the web server process typically runs under a limited user but can still access many system files if the basic file permissions allow it. SELinux confines the web server process to only what it strictly needs to do. Even if the attacker gains control of the web server process, they cannot read shadow password files, launch a shell, or write to system directories outside the web root.

For system administrators, SELinux simplifies compliance with security frameworks like PCI DSS, HIPAA, and FedRAMP. These standards require that access to data be restricted based on the principle of least privilege. SELinux provides a built-in, kernel-level mechanism to enforce that principle without requiring custom scripting or third-party tools. With SELinux, administrators can confidently deploy services knowing that the kernel itself will prevent many types of privilege escalation attacks.

Another reason SELinux matters is its role in modern containerization and virtualization. Docker containers, for instance, can run with SELinux labels that restrict what host files the container can access. This adds a layer of security beyond standard namespace isolation. In cloud environments, SELinux helps ensure that multi-tenant systems are better isolated, reducing the risk of one tenant affecting another. Even in desktop environments, SELinux protects against malicious scripts that might try to access personal documents or browser passwords.

For IT professionals, knowing SELinux is often a job requirement for Linux administration roles, particularly in enterprise environments that use Red Hat or CentOS. CompTIA Linux+ includes SELinux concepts, and Red Hat Certified Engineer (RHCE) exams heavily test SELinux configuration and troubleshooting. Without understanding SELinux, a sysadmin may find themselves unable to install or configure common services, as SELinux denials can appear as mysterious permission errors. Understanding SELinux separates a junior administrator from a senior one who can confidently troubleshoot and configure security policies.

## Why it matters in exams

SELinux is a core objective in several major IT certification exams. In the CompTIA Linux+ (XK0-005) exam, SELinux appears under Domain 3 (Security). Candidates must understand the difference between enforcing and permissive modes, how to check SELinux status with commands like “getenforce” and “sestatus”, and how to manage file contexts using “chcon”, “restorecon”, and “semanage”. Typical questions present a scenario where a service fails to start or a file cannot be accessed, and the candidate must identify that SELinux is blocking the action, then determine whether to change the file context, create a custom policy module, or temporarily set permissive mode for troubleshooting.

For the Red Hat Certified System Administrator (RHCSA) and Red Hat Certified Engineer (RHCE) exams, SELinux is a heavy focus. The RHCSA exam objectives explicitly include troubleshooting SELinux issues, changing file contexts, setting booleans, and managing SELinux modes. The RHCE exam requires automation of SELinux configurations using Ansible modules like “selinux”, “seboolean”, and “sefcontext”. A common exam task is to configure a web server to serve content from a non-default directory and correctly label the directory with “httpd_sys_content_t”. Candidates who fail to apply the correct SELinux context will lose points because the service will be inaccessible.

The SUSE Linux Enterprise Server 15 (SUSE) certification also covers SELinux, though SUSE historically used AppArmor more prominently. However, newer versions of SUSE support SELinux as an alternative, and exam questions may ask about the differences. The Linux Professional Institute (LPI) exams, such as LPIC-2 (202-450), include SELinux in the security section, focusing on policy management and auditing.

In these exams, SELinux questions often come in three flavors: command-line scenario, best-practice selection, and troubleshooting. Command-line questions ask for the correct command to set a mode, change a context, or view a boolean. Best-practice questions ask which mode a production server should run in (enforcing) and why. Troubleshooting questions describe an error log (often an AVC denial) and ask the candidate to identify the root cause or the steps to resolve it. A deep understanding of the audit log format, the “ausearch” command, and the “sealert” graphical tool is beneficial.

Exam takers should be familiar with the SELinux man pages and the standard locations of logs. They should practice installing a service, breaking its SELinux context, and fixing it. Knowing how to search for booleans using “getsebool -a” and set them with “setsebool -P” is also frequently tested. Ultimately, exam questions aim to ensure that candidates can maintain a secure system using SELinux without disabling it entirely, which is a sign of good security hygiene.

## How it appears in exam questions

SELinux appears in certification exams primarily through scenario-based questions, command recall questions, and configuration troubleshooting. One common pattern is the “service not starting” scenario. The question describes a fresh installation of a service like Apache or MySQL, but the service fails to start. The logs show “Permission denied” but the file permissions are correct. The question asks what the likely cause is, with options including incorrect file permissions, missing SELinux context, firewall rules, or SELinux mode. The correct answer is usually that the SELinux file context is incorrect or the SELinux boolean is not enabled.

Another frequent pattern involves a user trying to access a custom directory through a web server. The administrator has set up the DocumentRoot to a path like “/var/www/html/custom”, but users get a 403 Forbidden error. The question presents log entries with “avc: denied” messages. The candidate must identify that the file context for “/var/www/html/custom” is not set to “httpd_sys_content_t”. The solution involves using “semanage fcontext” to add a mapping and then running “restorecon” to apply it.

Configuration questions often ask about SELinux booleans. For example, a question might ask: “You want to allow Apache to connect to a remote database using a network socket. What SELinux boolean must be enabled?” The answer is “httpd_can_network_connect_db”. Another variation: “Which boolean allows Apache to use NFS-mounted directories?” Answer: “httpd_use_nfs”. These questions test the candidate’s ability to recall specific booleans relevant to common services.

Troubleshooting questions often present audit log snippets. A candidate may see: “type=AVC msg=audit(123456.789:123): avc: denied { read } for pid=1234 comm=”httpd” path=”/var/www/html/index.html” dev=”sda1” ino=5678 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:default_t:s0 tclass=file”. The candidate must interpret this as the httpd process being denied read access to a file with the wrong context (default_t instead of httpd_sys_content_t). The fix is to restore the correct context.

Finally, command recall questions test specific tools: “Which command sets SELinux to permissive mode until reboot?” (Answer: “setenforce 0”). “Which command shows the current SELinux mode?” (Answer: “getenforce”). “Which command lists all SELinux booleans?” (Answer: “getsebool -a”). These are straightforward but require memorization of command names and syntax.

## Example scenario

Scenario: You are a junior Linux administrator at a medium-sized company. The company has a web application running on a CentOS server using the Apache HTTPD web server. The developers have created a new web application that needs to store user-uploaded images in a directory at /opt/webapp/uploads. The Apache process must be able to read and write files in this directory. You have set the Linux file permissions so that the “apache” user owns the directory and permissions are 755. You restart the Apache service, and the application seems to work for a few minutes, but then the uploads fail. Users get an error message saying “Unable to save file.”

You check the Apache error log at /var/log/httpd/error_log and see the message: “(13)Permission denied: /opt/webapp/uploads/image.jpg”. You check standard Linux file permissions again; they are correct. The Apache user has write permission. So why is Apache still being denied?

The answer is SELinux. By default, Apache processes run with the SELinux type “httpd_t”. Files created in “/opt/webapp/uploads” have a default type of “default_t” because the /opt directory is not labeled for web content. SELinux sees the “httpd_t” process trying to write to a file with type “default_t”, and the policy does not allow that. So SELinux denies the write, even though standard file permissions allow it.

To fix this, you need to change the SELinux context of the “/opt/webapp/uploads” directory to “httpd_sys_content_t” (for read-only) or “httpd_sys_rw_content_t” (for read-write). You run: “semanage fcontext -a -t httpd_sys_rw_content_t '/opt/webapp/uploads(/.*)?'” to add the mapping, then “restorecon -Rv /opt/webapp/” to apply it. After this, the uploads work. This scenario perfectly illustrates how SELinux interacts with real-world file access problems and why it is essential to remember that standard permissions are not the only gatekeeper.

## Common mistakes

- **Mistake:** Assuming that disabling SELinux is a good troubleshooting step.
  - Why it is wrong: Disabling SELinux removes the security layer entirely, leaving the system vulnerable to exploits. It should only be done temporarily for testing and never in production. Many exam questions test the correct approach: use permissive mode instead of fully disabling.
  - Fix: Switch to permissive mode with setenforce 0 for testing, and then fix the underlying policy rather than disabling SELinux permanently.
- **Mistake:** Confusing SELinux file contexts with standard Linux permissions (chmod/chown).
  - Why it is wrong: SELinux uses security contexts (user:role:type) separate from file ownership and mode bits. Even if a file is owned by root and has 777 permissions, SELinux can still deny access if the context is wrong. Learners often forget this and only check chmod.
  - Fix: Always check SELinux contexts using ls -Z when troubleshooting access issues after verifying standard permissions.
- **Mistake:** Thinking that changing a file context with chcon is permanent.
  - Why it is wrong: chcon changes the context immediately, but the change is not persistent across filesystem relabelings (like with restorecon). For permanent changes, semanage fcontext should be used to create a mapping in the policy.
  - Fix: Use semanage fcontext to add a context mapping, then run restorecon to apply it. This ensures the context persists even after a full system relabel.
- **Mistake:** Believing that SELinux only affects security and does not impact application functionality.
  - Why it is wrong: SELinux directly impacts whether applications can function if they need to access resources that are not allowed by policy. Misconfigured SELinux can cause services to fail silently or produce cryptic errors. Many learners overlook SELinux causing application problems.
  - Fix: When an application fails with permission errors despite correct standard permissions, always check the SELinux audit log (/var/log/audit/audit.log) for AVC denials.
- **Mistake:** Assuming that setting SELinux to permissive mode is a replacement for correct policy configuration.
  - Why it is wrong: Permissive mode only logs denials; it does not enforce them. While helpful for troubleshooting, leaving a system in permissive mode weakens security because the kernel will still log violations but not stop them. Production systems should remain in enforcing mode.
  - Fix: Use permissive mode only to identify denied actions, then create proper policies or change contexts to allow legitimate actions while keeping the system in enforcing mode.

## Exam trap

{"trap":"A question shows an error with “Permission denied” and asks “What is the most likely cause?” A distractor option says “The file permissions are set to 644 and the owner is root.” Another says “SELinux is in enforcing mode.”","why_learners_choose_it":"Learners see “SELinux enforcing” and immediately think that is the problem. They forget that SELinux by itself does not cause denials unless the context or policy is wrong. The simple presence of enforcing mode is not a problem-it is the expected state. The trap is that the option is worded as if SELinux being enforcing is inherently bad.","how_to_avoid_it":"Understand that SELinux enforcing mode is the default secure state for enterprise systems. The real cause of a denial is a mismatch between the subject's context and the object's context. Look for an option describing a file context issue or a missing boolean. If the question says “SELinux is enforcing” alone, it is a distractor; enforcing is not a bug."}

## Commonly confused with

- **SELinux vs AppArmor:** AppArmor is another Linux security module that also implements mandatory access control, but it uses path-based profiles instead of security labels (contexts) assigned to each object. AppArmor profiles are easier to write and manage for beginners, but SELinux provides more granular control and is more widely used in Red Hat-based distributions. AppArmor is default on Ubuntu and SUSE, while SELinux is default on Red Hat, Fedora, and CentOS. (Example: If you have a web server on Ubuntu, AppArmor might have a profile that says “Apache can read files under /var/www/”. On Red Hat, SELinux would say “Apache (httpd_t) can read files with type httpd_sys_content_t”. Both achieve similar security but through different mechanisms.)
- **SELinux vs Discretionary Access Control (DAC):** DAC is the standard Linux permission model using file ownership, groups, and mode bits (chmod). SELinux is a mandatory access control (MAC) system that overrides DAC. A process must pass both checks before accessing a resource. Learners often confuse the two because both involve access decisions, but DAC is based on user identity and ownership, while SELinux is based on security labels and policies. (Example: In a DAC system, if you own a file with 755 permissions, you can delete it. In SELinux, even if you own the file and have 755 permissions, SELinux can still block deletion if the policy says your process type cannot delete that file type.)
- **SELinux vs Linux Capabilities:** Linux capabilities break down root privileges into smaller units, such as CAP_NET_BIND_SERVICE (ability to bind to a low port). SELinux works alongside capabilities; they are not the same thing. Capabilities refine what a process can do within the kernel, while SELinux refines access to files, ports, and other resources. A process could have all capabilities but still be blocked by SELinux if its context is wrong. (Example: A web server process can have the capability to bind to port 80 without being root, but SELinux will still prevent it from reading files labeled with the wrong context. Both mechanisms are used together for defense in depth.)
- **SELinux vs Firewall (iptables/nftables):** A firewall controls network traffic, allowing or blocking packets based on IP addresses, ports, and protocols. SELinux controls local access to resources like files, directories, and network sockets after a process is already running on the system. They operate at different layers: firewall is network-facing, SELinux is host-based. (Example: A firewall might allow HTTP traffic to port 80, but SELinux will still block Apache from reading a file if the file has the wrong context. Both need to be correctly configured for a service to work.)

## Step-by-step breakdown

1. **Determine SELinux Mode and Status** — Before any troubleshooting, use “getenforce” to see if SELinux is enforcing, permissive, or disabled. Use “sestatus” for more detailed info including the loaded policy name. This step reveals whether SELinux is even active and in which mode.
2. **Identify the Service and Its SELinux Context** — Every running process has an SELinux context shown in the output of “ps -eZ” or “ps auxZ”. For example, the Apache process typically runs as “system_u:system_r:httpd_t:s0”. Knowing the subject’s type (httpd_t) is crucial to understanding which rules apply.
3. **Check the SELinux Context of the Resource** — Use “ls -Z” on the file or directory in question. The output shows the security context. For example, a file in the web root should have “unconfined_u:object_r:httpd_sys_content_t:s0”. If it shows “default_t” or “var_t”, that indicates the wrong context for a web server.
4. **Examine the Audit Log for AVC Denials** — When a denial occurs, SELinux writes an AVC (Access Vector Cache) entry to /var/log/audit/audit.log. Use “ausearch -m avc -ts recent” to filter recent denials. The log tells you exactly what was denied, the source context, the target context, and the operation (read, write, etc.).
5. **Apply the Correct File Context or Boolean** — If the file context is wrong, use “semanage fcontext” to add a persistent mapping and then “restorecon” to apply it. If the issue is that a service needs a capability that is blocked by a boolean (like httpd_can_network_connect), use “setsebool -P” to enable the boolean permanently.
6. **Test and Verify the Fix** — After applying changes, restart the service and attempt the action again. Check the audit log again to ensure no new denials appear. Run “sealert -l *” to view any GUI alerts of resolved issues. If the fix works, ensure the system remains in enforcing mode.

## Practical mini-lesson

SELinux is not a set-it-and-forget-it tool. In practice, administrators must actively manage contexts, booleans, and policies to ensure that services run smoothly without compromising security. The most common task an IT professional will face is troubleshooting an SELinux denial when installing a new application or changing a directory.

First, understand that SELinux contexts are inherited from the parent directory when a file is created. Files in /var/www/html inherit the “httpd_sys_content_t” type because /var/www/html is labeled with that type. If you create a custom directory outside of the standard locations, the new directory will get the default type of its parent (e.g., /opt gets “usr_t” or “default_t”). This is why copying files to a custom directory often leads to denials.

To manage this, use “semanage fcontext -l” to list all current file context mappings. Then add a new mapping for your directory using: “semanage fcontext -a -t httpd_sys_content_t '/custom/path(/.*)?'”. The regular expression pattern ensures that all files and subdirectories under that path are included. Then run “restorecon -Rv /custom/path” to apply the changes.

Booleans are another essential component. They are on/off switches that allow specific behaviors without writing custom policies. For example, if you want to allow Apache to send emails via a local mail server, you must enable the boolean “httpd_can_sendmail”. Use “getsebool -a | grep httpd” to list all booleans related to Apache. To enable one permanently, run: “setsebool -P httpd_can_sendmail on”. The -P flag makes the change persistent across reboots.

What can go wrong? The most common pitfall is over-permissive configurations. For instance, a beginner might set the entire filesystem to a permissive type or enable every boolean to avoid errors. This defeats the purpose of SELinux. The correct approach is to grant the minimum required permissions and only for the specific directories or services needed.

Another common issue is forgetting to apply contexts after moving or copying files. If you copy a file from /tmp to your web root with “cp”, the file retains its original context (likely “default_t”). You must use “cp -Z” to preserve the target directory’s context, or run “restorecon” after the copy. Using “mv” generally preserves the target directory’s context, but it is safer to always run restorecon after moving files.

In professional environments, SELinux is often integrated with configuration management tools like Ansible, Puppet, or Chef. For example, an Ansible playbook can set SELinux booleans, file contexts, and even compile and load custom policy modules. This ensures that security configurations are consistent across hundreds of servers. Understanding SELinux from the command line is the foundation, but automation awareness is what makes a senior engineer.

Finally, remember that SELinux is not the enemy. Many new administrators see it as a hindrance because it blocks things. In reality, it is a robust security layer that, when properly configured, allows you to run potentially vulnerable services with confidence. The goal is not to disable SELinux, but to understand it well enough to make it work for you.

## Commands

```

```


```

```


```

```


```

```


```

```


```

```


```

```


```

```


```

```


```

```


```

```


```

```


```

```


```

```


```

```


```

```


## Troubleshooting clues

- **undefined** — symptom: undefined. undefined
- **undefined** — symptom: undefined. undefined
- **undefined** — symptom: undefined. undefined
- **undefined** — symptom: undefined. undefined
- **undefined** — symptom: undefined. undefined
- **undefined** — symptom: undefined. undefined

## Memory tip

Remember “S-E-Linux is S-E-Ldom the Enemy”, when a service fails with permission errors, check SELinux before blaming file permissions or configurations.

---

Practice questions and the full interactive page: https://courseiva.com/glossary/selinux
