← Back to all projects

SELINUX DEEP DIVE LEARNING PROJECTS

Learn SELinux: From Zero to Mandatory Access Control Master

Goal: Deeply understand SELinux (Security-Enhanced Linux)—what mandatory access control truly means, how the kernel enforces security policies, why labels and types are the foundation of modern Linux security, and how to write custom policies that protect real-world systems from compromise. You’ll move from “just disable SELinux” to confidently securing production servers, containers, and custom applications.


Why SELinux Matters

In 2000, the National Security Agency (NSA) released SELinux to the open-source community—the result of decades of research into mandatory access control systems. This wasn’t charity; it was recognition that the traditional Unix permission model (owner/group/other) was fundamentally inadequate for modern security threats.

The Problem SELinux Solves

Traditional Unix permissions answer one question: “Does this user have permission to access this file?”

But this model fails catastrophically when:

  • A web server process is compromised—it can access ANY file the www-data user can read
  • A daemon runs as root—a single vulnerability gives attackers complete system control
  • Applications share the same user—one compromised app can attack others
Traditional DAC (Discretionary Access Control):
┌─────────────────────────────────────────────────────────────┐
│                      ROOT USER                               │
│  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────┐        │
│  │ Apache  │  │ MySQL   │  │ SSH     │  │ Cron    │        │
│  └────┬────┘  └────┬────┘  └────┬────┘  └────┬────┘        │
│       │            │            │            │              │
│       └────────────┴────────────┴────────────┘              │
│                         │                                    │
│                    FULL ACCESS                               │
│                         │                                    │
│    ┌────────────────────┴────────────────────┐              │
│    │         ENTIRE FILESYSTEM               │              │
│    │  /etc/shadow  /home/*  /var/lib/mysql   │              │
│    └─────────────────────────────────────────┘              │
└─────────────────────────────────────────────────────────────┘

If Apache is compromised → Attacker has ROOT access to EVERYTHING

SELinux asks a different question: “Is THIS process allowed to perform THIS action on THIS object?”

SELinux MAC (Mandatory Access Control):
┌─────────────────────────────────────────────────────────────┐
│                    SELINUX POLICY                            │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐         │
│  │httpd_t      │  │mysqld_t     │  │sshd_t       │         │
│  │(Apache)     │  │(MySQL)      │  │(SSH)        │         │
│  └──────┬──────┘  └──────┬──────┘  └──────┬──────┘         │
│         │                │                │                 │
│         ▼                ▼                ▼                 │
│  ┌──────────────┐ ┌──────────────┐ ┌──────────────┐        │
│  │httpd_sys_    │ │mysqld_db_t   │ │sshd_key_t    │        │
│  │content_t     │ │              │ │              │        │
│  │/var/www/html │ │/var/lib/mysql│ │/etc/ssh/*    │        │
│  └──────────────┘ └──────────────┘ └──────────────┘        │
│                                                             │
│  Apache CANNOT read MySQL data or SSH keys                  │
│  MySQL CANNOT read web content or SSH keys                  │
│  Even if running as same Unix user!                         │
└─────────────────────────────────────────────────────────────┘

Real-World Impact

CVE-2019-5736 (Container Escape): A vulnerability in runc allowed malicious containers to overwrite the host runc binary and escape containment. SELinux blocked this attack—even with the vulnerability present, the container process couldn’t write to the host binary due to type enforcement.

Statistics:

  • Over 20 years of kernel-level security enforcement
  • Default on RHEL, CentOS, Fedora, and Android
  • Protects millions of production servers worldwide
  • Required for government and military compliance (Common Criteria, LSPP)

Why Developers Disable SELinux (And Why That’s Wrong)

The infamous advice “just run setenforce 0” exists because:

  1. Lack of understanding: Developers don’t know how to read denial messages
  2. Poor error messages: “Permission denied” doesn’t tell you SELinux blocked it
  3. Complex policy language: Writing custom policies seems impossible
  4. Time pressure: “It works with SELinux off” becomes the permanent solution

After completing these projects, you’ll be the person who fixes SELinux problems instead of disabling security.


The SELinux Architecture

How SELinux Integrates with the Kernel

┌─────────────────────────────────────────────────────────────────────┐
│                         USER SPACE                                   │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────────────┐    │
│  │ Process  │  │ Process  │  │ Process  │  │ Policy Tools     │    │
│  │ (httpd)  │  │ (mysqld) │  │ (sshd)   │  │ semanage, audit  │    │
│  └────┬─────┘  └────┬─────┘  └────┬─────┘  └────────┬─────────┘    │
│       │             │             │                  │              │
├───────┴─────────────┴─────────────┴──────────────────┴──────────────┤
│                      SYSTEM CALL INTERFACE                           │
├─────────────────────────────────────────────────────────────────────┤
│                         KERNEL SPACE                                 │
│                                                                      │
│  ┌────────────────────────────────────────────────────────────┐     │
│  │              Linux Security Modules (LSM)                   │     │
│  │  ┌─────────────────────────────────────────────────────┐   │     │
│  │  │                  SELinux Hooks                       │   │     │
│  │  │   open()  ──► security_file_open()  ──► ALLOW/DENY  │   │     │
│  │  │   exec()  ──► security_bprm_check() ──► ALLOW/DENY  │   │     │
│  │  │   connect()──► security_socket_connect()──►ALLOW/DENY│   │     │
│  │  └─────────────────────────┬───────────────────────────┘   │     │
│  └────────────────────────────┼───────────────────────────────┘     │
│                               │                                      │
│  ┌────────────────────────────▼───────────────────────────────┐     │
│  │                   SELinux Security Server                   │     │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐ │     │
│  │  │ Policy      │  │ Access      │  │ Security Context    │ │     │
│  │  │ Database    │  │ Vector      │  │ Management          │ │     │
│  │  │ (compiled)  │  │ Cache (AVC) │  │ (SID mapping)       │ │     │
│  │  └─────────────┘  └─────────────┘  └─────────────────────┘ │     │
│  └────────────────────────────────────────────────────────────┘     │
└─────────────────────────────────────────────────────────────────────┘

The Security Context (Label)

Every process, file, port, and object in SELinux has a security context (also called a label):

Format: user:role:type:level

Example: system_u:system_r:httpd_t:s0
         ────────  ────────  ──────  ──
            │         │        │     │
            │         │        │     └── MLS/MCS Level (s0 = lowest sensitivity)
            │         │        │
            │         │        └── TYPE (most important for Type Enforcement)
            │         │
            │         └── ROLE (constrains which types a user can transition to)
            │
            └── USER (SELinux user, NOT Unix user)

Viewing contexts:

# File contexts
$ ls -Z /var/www/html/index.html
system_u:object_r:httpd_sys_content_t:s0 /var/www/html/index.html

# Process contexts
$ ps -eZ | grep httpd
system_u:system_r:httpd_t:s0     1234 ?   00:00:01 httpd

# Your current context
$ id -Z
unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

Type Enforcement: The Core of SELinux

Type Enforcement (TE) is what makes SELinux powerful. It defines rules like:

allow httpd_t httpd_sys_content_t:file { read open getattr };
│      │       │                  │      │
│      │       │                  │      └── Permissions granted
│      │       │                  │
│      │       │                  └── Object class (file, dir, socket, etc.)
│      │       │
│      │       └── TARGET type (what can be accessed)
│      │
│      └── SOURCE type (the process type)
│
└── Rule type (allow, dontaudit, auditallow, neverallow)
Type Enforcement Decision Flow:
┌─────────────────────────────────────────────────────────────┐
│  Process: httpd (type: httpd_t)                             │
│           │                                                  │
│           │ wants to read /var/www/html/index.html          │
│           ▼                                                  │
│  ┌────────────────────────────────────────┐                 │
│  │ 1. Get file's security context          │                 │
│  │    → httpd_sys_content_t                │                 │
│  └───────────────────┬────────────────────┘                 │
│                      ▼                                       │
│  ┌────────────────────────────────────────┐                 │
│  │ 2. Check AVC (Access Vector Cache)      │                 │
│  │    Cache hit? → Return cached decision  │                 │
│  └───────────────────┬────────────────────┘                 │
│                      │ Cache miss                            │
│                      ▼                                       │
│  ┌────────────────────────────────────────┐                 │
│  │ 3. Query Security Server               │                 │
│  │    Source: httpd_t                      │                 │
│  │    Target: httpd_sys_content_t          │                 │
│  │    Class:  file                         │                 │
│  │    Perms:  read                         │                 │
│  └───────────────────┬────────────────────┘                 │
│                      ▼                                       │
│  ┌────────────────────────────────────────┐                 │
│  │ 4. Policy lookup: FOUND allow rule     │                 │
│  └───────────────────┬────────────────────┘                 │
│                      ▼                                       │
│            ┌─────────────────┐                               │
│            │    ALLOWED      │                               │
│            └─────────────────┘                               │
└─────────────────────────────────────────────────────────────┘

Domain Transitions

When a process executes a program, SELinux can change its type:

Domain Transition:
┌──────────────────────────────────────────────────────────────────┐
│  init_t process                                                   │
│      │                                                            │
│      │ execve("/usr/sbin/httpd")                                  │
│      ▼                                                            │
│  ┌────────────────────────────────────────────┐                  │
│  │ SELinux checks:                             │                  │
│  │                                             │                  │
│  │ 1. type_transition init_t httpd_exec_t :   │                  │
│  │    process httpd_t;                         │                  │
│  │                                             │                  │
│  │ 2. allow init_t httpd_exec_t : file        │                  │
│  │    { execute };                             │                  │
│  │                                             │                  │
│  │ 3. allow init_t httpd_t : process          │                  │
│  │    { transition };                          │                  │
│  │                                             │                  │
│  │ 4. allow httpd_t httpd_exec_t : file       │                  │
│  │    { entrypoint };                          │                  │
│  └────────────────────────────────────────────┘                  │
│      │                                                            │
│      ▼                                                            │
│  httpd_t process (confined!)                                      │
└──────────────────────────────────────────────────────────────────┘

MLS/MCS: Sensitivity and Categories

Multi-Level Security (MLS):
┌─────────────────────────────────────────────────────────────┐
│  Sensitivity Levels (Hierarchical):                         │
│                                                              │
│      s3 ─── Top Secret                                      │
│      s2 ─── Secret                                          │
│      s1 ─── Confidential                                    │
│      s0 ─── Unclassified                                    │
│                                                              │
│  Bell-LaPadula Model:                                       │
│  • No Read Up:   s1 CANNOT read s2/s3                       │
│  • No Write Down: s3 CANNOT write to s0                     │
└─────────────────────────────────────────────────────────────┘

Multi-Category Security (MCS):
┌─────────────────────────────────────────────────────────────┐
│  Categories (Non-Hierarchical): c0-c1023                    │
│                                                              │
│  Container Isolation via MCS:                               │
│  Container A: s0:c123,c456                                  │
│  Container B: s0:c789,c012                                  │
│  → Containers cannot access each other's files!             │
└─────────────────────────────────────────────────────────────┘

SELinux Modes

┌─────────────────────────────────────────────────────────────────┐
│  ENFORCING: Policy enforced, violations BLOCKED and logged     │
│  PERMISSIVE: Policy NOT enforced, violations LOGGED only       │
│  DISABLED: SELinux completely off (requires reboot to change)  │
│                                                                  │
│  Per-Domain Permissive: semanage permissive -a httpd_t          │
│  → Only httpd_t is permissive, rest stays enforcing             │
└─────────────────────────────────────────────────────────────────┘

Concept Summary Table

Concept Cluster What You Need to Internalize
DAC vs MAC DAC is user-centric; MAC is policy-centric. MAC cannot be overridden by object owner.
Security Contexts Every object has a label: user:role:type:level. TYPE is most critical.
Type Enforcement Rules define what source types can do to target types.
Domain Transitions Processes change type when executing files.
Booleans On/off switches for policy features. getsebool -a, setsebool -P.
File Contexts Path-to-label mappings. semanage fcontext and restorecon.
AVC Denials Audit log messages showing what SELinux blocked.
Policy Modules Self-contained packages (.pp) from .te/.fc/.if source.
MLS/MCS Sensitivity levels (s0-s15) and categories (c0-c1023).

Deep Dive Reading by Concept

SELinux Fundamentals

Concept Book & Chapter
DAC vs MAC Philosophy “SELinux System Administration, 3rd Ed” by Sven Vermeulen — Ch. 1
Security Context Format “SELinux by Example” by Frank Mayer et al. — Ch. 2
LSM Architecture “The Linux Programming Interface” by Michael Kerrisk — Ch. 39

Type Enforcement & Policy

Concept Book & Chapter
Type Enforcement Rules “SELinux by Example” by Mayer et al. — Ch. 4
Domain Transitions “SELinux by Example” by Mayer et al. — Ch. 5
Writing Policy Modules “SELinux System Administration” by Vermeulen — Ch. 6

Troubleshooting & Advanced

Concept Book & Chapter
Reading AVC Denials “SELinux System Administration” by Vermeulen — Ch. 4
MLS/MCS Security “SELinux by Example” by Mayer et al. — Ch. 6
Container Security “Podman in Action” by Dan Walsh — Ch. 8

Project List

Projects are ordered from fundamental understanding to advanced implementations.


Project 1: SELinux Context Explorer & Visualizer

  • File: SELINUX_DEEP_DIVE_LEARNING_PROJECTS.md
  • Main Programming Language: Python
  • Alternative Programming Languages: Bash, Go, Rust
  • Coolness Level: Level 3: Genuinely Clever
  • Business Potential: 1. The “Resume Gold”
  • Difficulty: Level 1: Beginner
  • Knowledge Area: SELinux Fundamentals / Security Contexts
  • Software or Tool: SELinux userspace tools
  • Main Book: “SELinux System Administration, 3rd Edition” by Sven Vermeulen

What you’ll build: A CLI tool that explores and visualizes security contexts across your system—showing processes, files, ports with their labels, creating reports showing the security landscape.

Why it teaches SELinux: Before securing anything, you must SEE what’s labeled and how. This forces you to understand that everything has a context and what each field means.

Core challenges you’ll face:

  • Parsing security contexts → understanding user:role:type:level format
  • Querying multiple object types → files, processes, ports all have contexts
  • Detecting unlabeled or misconfigured objects → common SELinux problems

Key Concepts:

  • Security Context Format: “SELinux by Example” Ch. 2 - Frank Mayer
  • File Labeling: “SELinux System Administration” Ch. 5 - Sven Vermeulen

Difficulty: Beginner | Time estimate: Weekend Prerequisites: Basic Python, RHEL/Fedora/CentOS VM with SELinux enabled

Real World Outcome

$ ./selinux-explorer --summary

╔═══════════════════════════════════════════════════════════════════╗
║                    SELinux Context Explorer v1.0                   ║
║ System Status: ENFORCING    Policy: targeted                      ║
╚═══════════════════════════════════════════════════════════════════╝

┌─ PROCESS DOMAINS (Top 10) ────────────────────────────────────────┐
│ Domain          │ Count │ Example                                 │
│ unconfined_t    │   127 │ /usr/bin/bash                          │
│ httpd_t         │     8 │ /usr/sbin/httpd                        │
│ sshd_t          │     3 │ /usr/sbin/sshd                         │
└───────────────────────────────────────────────────────────────────┘

⚠️  WARNINGS:
• 3 files with unlabeled_t in /var/www/html/upload/
  Run: restorecon -Rv /var/www/html/upload/

The Core Question You’re Answering

“What security contexts exist on my system, and what do they mean?”

Interview Questions They’ll Ask

  1. “What is a security context and what are its components?”
  2. “How would you find all files with a specific SELinux type?”
  3. “A process is running as unconfined_t—what does that mean?”

Implementation Hints

  1. System Status Module: Query getenforce, sestatus
  2. Process Scanner: Read /proc/[pid]/attr/current or parse ps -eZ
  3. File Scanner: Use os.getxattr(path, 'security.selinux') or ls -Z
  4. Port Scanner: Parse semanage port -l output
  5. Anomaly Detector: Flag unlabeled_t, default_t, wrong types

Project 2: AVC Denial Analyzer & Auto-Fixer

  • File: SELINUX_DEEP_DIVE_LEARNING_PROJECTS.md
  • Main Programming Language: Python
  • Alternative Programming Languages: Go, Rust, Bash
  • Coolness Level: Level 4: Hardcore Tech Flex
  • Business Potential: 2. The “Micro-SaaS / Pro Tool”
  • Difficulty: Level 2: Intermediate
  • Knowledge Area: SELinux Troubleshooting / Audit Logs
  • Software or Tool: audit, setroubleshoot, audit2allow
  • Main Book: “SELinux System Administration, 3rd Edition” by Sven Vermeulen

What you’ll build: An intelligent tool that monitors audit logs in real-time, parses AVC denial messages, explains them in plain English, and suggests fixes—from boolean changes to custom policy modules.

Why it teaches SELinux: The #1 reason people disable SELinux is they can’t understand denial messages. By parsing and explaining every field, you’ll internalize what denials mean.

Core challenges you’ll face:

  • Parsing AVC messages → understanding audit log format
  • Determining fix strategies → booleans vs labels vs policy
  • Generating policy modules → audit2allow and .te files
  • Avoiding insecure fixes → understanding least privilege

Difficulty: Intermediate | Time estimate: 1-2 weeks Prerequisites: Project 1 completed, understanding of security contexts

Real World Outcome

$ sudo ./avc-analyzer --watch

🔴 AVC Denial Detected at 14:32:45
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Raw: avc: denied { read } for pid=5678 comm="httpd" name="config.ini"
     scontext=system_u:system_r:httpd_t:s0
     tcontext=system_u:object_r:user_home_t:s0 tclass=file

📋 EXPLANATION:
Apache (httpd_t) tried to READ "config.ini" but was DENIED because:
• The file is labeled user_home_t (user's home directory type)
• No policy rule allows httpd_t to read user_home_t files

🔧 FIXES (in order of preference):
1. ✅ BEST: Move file to /var/www/html/ and run restorecon
2. ⚠️  ALT: semanage fcontext -a -t httpd_sys_content_t '/path'
3. ❌ AVOID: Enable httpd_read_user_content boolean (too broad!)

The Core Question You’re Answering

“When SELinux blocks something, HOW do I fix it correctly?”

Interview Questions They’ll Ask

  1. “Walk me through troubleshooting an SELinux denial.”
  2. “What’s the difference between audit2allow and audit2why?”
  3. “When should you use a boolean vs create custom policy?”

Implementation Hints

  1. Log Monitor: Tail /var/log/audit/audit.log
  2. AVC Parser: Regex for avc:\s+denied\s+\{([^}]+)\}.*scontext=([^\s]+).*tcontext=([^\s]+)
  3. Fix Recommender: Check booleans first, then relabel, then policy
  4. Plain English Generator: Template-based explanation

Project 3: Custom Application Policy Module Builder

  • File: SELINUX_DEEP_DIVE_LEARNING_PROJECTS.md
  • Main Programming Language: SELinux Policy Language (m4/CIL)
  • Alternative Programming Languages: Python (for tooling), Bash
  • Coolness Level: Level 4: Hardcore Tech Flex
  • Business Potential: 3. The “Service & Support” Model
  • Difficulty: Level 3: Advanced
  • Knowledge Area: SELinux Policy Development
  • Software or Tool: semodule, checkmodule, sepolgen
  • Main Book: “SELinux by Example” by Frank Mayer et al.

What you’ll build: A complete SELinux policy module for a custom daemon—including type definitions, domain transitions, file contexts, network access rules, using reference policy interfaces.

Why it teaches SELinux: Writing policy is the deepest level of understanding. You’ll learn m4 macros, reference policy conventions, and how to confine applications properly.

Core challenges you’ll face:

  • Defining new types → understanding type hierarchies and attributes
  • Creating domain transitions → how processes become confined
  • Using reference policy interfaces → the modular policy approach
  • Handling network and IPC → object classes beyond files

Difficulty: Advanced | Time estimate: 2-3 weeks Prerequisites: Projects 1-2 completed, understanding of AVC messages

Real World Outcome

$ ls -la myapp_selinux/
-rw-r--r-- myapp.fc     # File contexts
-rw-r--r-- myapp.if     # Interfaces
-rw-r--r-- myapp.te     # Type enforcement

$ cat myapp.te
policy_module(myapp, 1.0.0)

type myapp_t;
type myapp_exec_t;
type myapp_conf_t;
type myapp_log_t;

init_daemon_domain(myapp_t, myapp_exec_t)

allow myapp_t myapp_conf_t:file read_file_perms;
logging_log_filetrans(myapp_t, myapp_log_t, file)
corenet_tcp_bind_generic_port(myapp_t)

$ sudo semodule -i myapp.pp
$ ps -eZ | grep myapp
system_u:system_r:myapp_t:s0     12345 ?   00:00:01 myapp

The Core Question You’re Answering

“How do I properly confine a custom application?”

Interview Questions They’ll Ask

  1. “Walk me through the structure of an SELinux policy module.”
  2. “What’s the difference between a type and an attribute?”
  3. “Why use reference policy interfaces instead of raw allow rules?”

Implementation Hints

  1. Analyze app: lsof -p <pid>, strace -f to see what it accesses
  2. Create skeleton: sepolicy generate --init /usr/sbin/myapp
  3. File Contexts (.fc): Map paths to types with regex
  4. Type Enforcement (.te): Use interfaces, not raw allow rules
  5. Test workflow: Set permissive, exercise app, collect denials, add rules

Project 4: SELinux Boolean Manager with Web Dashboard

  • File: SELINUX_DEEP_DIVE_LEARNING_PROJECTS.md
  • Main Programming Language: Python (Flask/FastAPI)
  • Alternative Programming Languages: Go, Rust, Node.js
  • Coolness Level: Level 3: Genuinely Clever
  • Business Potential: 2. The “Micro-SaaS / Pro Tool”
  • Difficulty: Level 2: Intermediate
  • Knowledge Area: SELinux Booleans / Web Development
  • Software or Tool: getsebool, setsebool, semanage
  • Main Book: “SELinux System Administration” by Sven Vermeulen

What you’ll build: A web-based dashboard that displays all SELinux booleans with descriptions, current states, and allows toggling them with audit logging and rollback capability.

Why it teaches SELinux: Booleans are the admin-friendly knobs of SELinux policy. Building this forces you to understand what each boolean controls, how they modify policy behavior at runtime, and the security implications of each setting.

Core challenges you’ll face:

  • Enumerating all booleans with descriptions → maps to understanding policy flexibility
  • Parsing semanage boolean output → maps to the boolean subsystem
  • Implementing safe toggle with audit trail → maps to accountability in security
  • Grouping booleans by function → maps to understanding policy domains

Key Concepts:

  • SELinux Booleans: SELinux Cookbook Ch. 4 - Sven Vermeulen
  • Runtime Policy Modification: SELinux System Administration Ch. 5
  • Boolean Impact Analysis: RHEL SELinux Guide, Booleans section

Difficulty: Intermediate | Time estimate: 1-2 weeks Prerequisites: Basic Python web development, Projects 1-2 recommended

Real World Outcome

┌─────────────────────────────────────────────────────────────┐
│  SELinux Boolean Manager          [Search: ______] [Refresh]│
├─────────────────────────────────────────────────────────────┤
│ Category: httpd_* (Web Server)                    [Expand]  │
├─────────────────────────────────────────────────────────────┤
│ ☑ httpd_can_network_connect                         [ON ]   │
│   Allow HTTPD scripts to make network connections           │
│   Changed: 2024-01-15 by admin | [Rollback] [History]       │
│                                                             │
│ ☐ httpd_can_network_connect_db                      [OFF]   │
│   Allow HTTPD to connect to database ports                  │
│   Default: off | Last changed: Never                        │
│                                                             │
│ ☑ httpd_enable_cgi                                  [ON ]   │
│   Allow HTTPD to execute CGI scripts                        │
│   Changed: 2024-01-10 by admin | [Rollback] [History]       │
├─────────────────────────────────────────────────────────────┤
│ Category: container_* (Podman/Docker)             [Expand]  │
├─────────────────────────────────────────────────────────────┤
│ ☐ container_use_devices                             [OFF]   │
│   Allow containers to use host devices                      │
│   ⚠️ Security Warning: Reduces container isolation          │
└─────────────────────────────────────────────────────────────┘

$ curl localhost:5000/api/booleans/httpd_can_network_connect
{
  "name": "httpd_can_network_connect",
  "current": true,
  "default": false,
  "description": "Allow HTTPD scripts and modules to connect to the network",
  "last_changed": "2024-01-15T10:30:00Z",
  "changed_by": "admin"
}

The Core Question You’re Answering

“What runtime flexibility does SELinux provide, and how do I safely use it?”

Booleans are the bridge between strict policy and operational reality. Understanding them teaches you that SELinux isn’t all-or-nothing.

Concepts You Must Understand First

  1. Boolean Mechanics
    • How do booleans modify compiled policy at runtime?
    • What’s the difference between persistent and non-persistent changes?
    • How do conditional policy rules work?
  2. Security Implications
    • Why are some booleans off by default?
    • What attack vectors does each boolean potentially enable?

Interview Questions They’ll Ask

  1. “How do SELinux booleans work internally?”
  2. “Give an example of when you’d enable a boolean vs writing custom policy.”
  3. “How would you audit boolean changes in production?”
  4. “What’s the security tradeoff of httpd_can_network_connect?”

Implementation Hints

  1. Enumerate booleans: getsebool -a, semanage boolean -l
  2. Get descriptions: Parse /usr/share/selinux/devel/policy.xml or use seinfo
  3. Persistent toggle: setsebool -P vs runtime-only setsebool
  4. Track changes: Log to SQLite with timestamp, user, old/new value
  5. Safety: Implement confirmation for dangerous booleans, batch rollback

Project 5: Container SELinux Sandbox Lab

  • File: SELINUX_DEEP_DIVE_LEARNING_PROJECTS.md
  • Main Programming Language: Bash/Python
  • Alternative Programming Languages: Go, Rust
  • Coolness Level: Level 4: Hardcore Tech Flex
  • Business Potential: 3. The “Service & Support” Model
  • Difficulty: Level 3: Advanced
  • Knowledge Area: Container Security / SELinux Integration
  • Software or Tool: Podman, Docker, udica, container-selinux
  • Main Book: “Container Security” by Liz Rice

What you’ll build: A lab environment demonstrating container SELinux confinement, including breaking out of containers without SELinux, showing protection with SELinux, and generating custom container policies with udica.

Why it teaches SELinux: Containers are the modern frontier of SELinux. This project shows why namespace isolation alone isn’t enough and how SELinux provides defense in depth. You’ll see real container escapes fail against SELinux.

Core challenges you’ll face:

  • Understanding container_t and svirt_lxc_net_t → maps to container type enforcement
  • Demonstrating protection against breakout attempts → maps to MAC vs namespaces
  • Using udica to generate custom policies → maps to automated policy generation
  • MCS separation between containers → maps to multi-category security

Key Concepts:

  • Container SELinux Types: container-selinux documentation
  • MCS Isolation: RHEL Container Security Guide
  • udica Tool: Fedora Magazine “Custom SELinux Policies for Containers”
  • Container Escapes: Container Security Ch. 9 - Liz Rice

Difficulty: Advanced | Time estimate: 2-3 weeks Prerequisites: Podman/Docker experience, Projects 1-3 completed

Real World Outcome

# Lab 1: See SELinux container types
$ podman run --rm fedora cat /proc/self/attr/current
system_u:system_r:container_t:s0:c123,c456

# Lab 2: Attempt host filesystem access (blocked by SELinux)
$ podman run --rm -v /etc:/host-etc:ro fedora cat /host-etc/shadow
cat: /host-etc/shadow: Permission denied

$ ausearch -m avc -ts recent
type=AVC msg=audit(1705123456.789:1234): avc:  denied  { read }
  for pid=12345 comm="cat" name="shadow"
  scontext=system_u:system_r:container_t:s0:c123,c456
  tcontext=system_u:object_r:shadow_t:s0
  tclass=file permissive=0

# Lab 3: MCS isolation between containers
$ podman run -d --name db redis
$ podman run -d --name web nginx

$ ps -eZ | grep -E "(redis|nginx)"
system_u:system_r:container_t:s0:c100,c200  redis-server
system_u:system_r:container_t:s0:c300,c400  nginx

# Different MCS categories = can't access each other's data!

# Lab 4: Generate custom policy with udica
$ podman inspect myapp | udica myapp_container
Policy myapp_container created!

$ cat myapp_container.cil
(block myapp_container
  (type process)
  (roletype system_r process)
  (typeattributeset container_domain (process))
  (allow process container_file_t (file (read open getattr)))
  ...
)

$ semodule -i myapp_container.cil
$ podman run --security-opt label=type:myapp_container.process myapp

The Core Question You’re Answering

“Why isn’t container namespace isolation enough?”

Namespaces hide resources; SELinux prevents access. This project shows the difference viscerally.

Concepts You Must Understand First

  1. Container Isolation Layers
    • How do namespaces provide isolation?
    • What can bypass namespace isolation?
    • Where does SELinux fit in defense-in-depth?
  2. Container SELinux Labels
    • What is container_t vs container_runtime_t?
    • How does MCS provide container-to-container isolation?
    • What is the svirt system?

Interview Questions They’ll Ask

  1. “Explain how SELinux protects containers beyond namespaces.”
  2. “What is MCS and how does it isolate containers from each other?”
  3. “How would you generate a custom SELinux policy for a container?”
  4. “What container escapes does SELinux prevent?”
  5. “What’s the difference between running with –privileged and SELinux disabled?”

Implementation Hints

  1. Setup lab VMs: Fedora/RHEL with SELinux enforcing, Podman installed
  2. Create attack scenarios: Host file read, /proc exploitation, device access
  3. Compare DAC vs MAC: Show what works with SELinux permissive vs enforcing
  4. udica workflow: Inspect running container, generate policy, apply, test
  5. Document each failure: Show AVC denial, explain what SELinux blocked

Project 6: File Context Integrity Checker

  • File: SELINUX_DEEP_DIVE_LEARNING_PROJECTS.md
  • Main Programming Language: Python
  • Alternative Programming Languages: Rust, Go, Bash
  • Coolness Level: Level 3: Genuinely Clever
  • Business Potential: 3. The “Service & Support” Model
  • Difficulty: Level 2: Intermediate
  • Knowledge Area: SELinux File Contexts / Security Auditing
  • Software or Tool: restorecon, fixfiles, matchpathcon
  • Main Book: “SELinux System Administration” by Sven Vermeulen

What you’ll build: A tool that scans filesystems for mislabeled files (files whose current context doesn’t match what policy dictates), reports violations, and can fix them. Integrates with system monitoring for drift detection.

Why it teaches SELinux: File context mismatches are the #1 source of SELinux denials. Understanding why labels drift (file moves, backups, manual creation) and how to fix them is essential ops knowledge.

Core challenges you’ll face:

  • Understanding file context specifications → maps to the .fc file format
  • Comparing actual vs expected contexts → maps to matchpathcon logic
  • Handling special cases (symlinks, /tmp, user home) → maps to context inheritance
  • Efficient filesystem scanning → maps to performance at scale

Key Concepts:

  • File Context Files: SELinux Notebook - File Contexts section
  • restorecon internals: libselinux documentation
  • Context Inheritance: SELinux System Administration Ch. 3
  • Extended Attributes: Understanding xattrs and security.selinux

Difficulty: Intermediate | Time estimate: 1-2 weeks Prerequisites: Project 1 completed, understanding of file contexts

Real World Outcome

$ ./selinux-context-checker --path /var/www --report

SELinux File Context Integrity Report
=====================================
Scanned: /var/www
Files checked: 1,247
Mislabeled: 23
Unlabeled: 2

MISLABELED FILES:
┌────────────────────────────────────────────────────────────────────────┐
│ Path                        │ Current          │ Expected             │
├────────────────────────────────────────────────────────────────────────┤
│ /var/www/uploads/doc.pdf    │ user_home_t      │ httpd_sys_rw_content │
│ /var/www/config/app.conf    │ default_t        │ httpd_sys_content_t  │
│ /var/www/cgi-bin/script.sh  │ httpd_sys_content│ httpd_sys_script_exe │
└────────────────────────────────────────────────────────────────────────┘

RISK ASSESSMENT:
- HIGH: /var/www/cgi-bin/script.sh - CGI script won't execute (wrong type)
- MEDIUM: /var/www/config/app.conf - App may fail to read config
- LOW: /var/www/uploads/doc.pdf - Read access may be denied

$ ./selinux-context-checker --path /var/www --fix --dry-run
Would restore context for 23 files:
  restorecon -v /var/www/uploads/doc.pdf
  restorecon -v /var/www/config/app.conf
  ...

$ ./selinux-context-checker --path /var/www --fix
Restored context for 23 files.
All files now match expected SELinux context.

The Core Question You’re Answering

“Why does my file have the wrong SELinux context, and how do I fix it?”

Context drift is inevitable. Backups, file moves, manual creation—all can result in wrong labels. This project makes you an expert at detection and remediation.

Concepts You Must Understand First

  1. File Context Mechanism
    • How does SELinux assign contexts to new files?
    • What’s the file context specification format (regex, type, range)?
    • When is restorecon necessary?
  2. Context Sources
    • Where are file context definitions stored?
    • What’s the order of precedence for matching?

Interview Questions They’ll Ask

  1. “A web app can’t read its config file. How do you diagnose if it’s an SELinux labeling issue?”
  2. “What’s the difference between chcon and restorecon?”
  3. “Why might a file have a different context than policy specifies?”
  4. “How would you ensure file contexts stay correct after a backup restore?”

Implementation Hints

  1. Get expected context: matchpathcon /path/to/file
  2. Get actual context: ls -Z or getfattr -n security.selinux
  3. Compare and report: Build diff logic, handle edge cases
  4. Use selinux Python bindings: import selinux; selinux.matchpathcon(path, mode)
  5. Consider performance: Use parallel processing for large filesystems

Project 7: Network Port Security Auditor

  • File: SELINUX_DEEP_DIVE_LEARNING_PROJECTS.md
  • Main Programming Language: Python
  • Alternative Programming Languages: Go, Rust, Bash
  • Coolness Level: Level 3: Genuinely Clever
  • Business Potential: 3. The “Service & Support” Model
  • Difficulty: Level 2: Intermediate
  • Knowledge Area: SELinux Network Controls / Port Types
  • Software or Tool: semanage port, netstat/ss, seinfo
  • Main Book: “SELinux System Administration” by Sven Vermeulen

What you’ll build: A security tool that audits which processes can bind to which ports according to SELinux policy, identifies non-standard port bindings, and generates reports on network attack surface reduction.

Why it teaches SELinux: Network access control is a critical SELinux feature. This project shows how SELinux prevents processes from binding to unauthorized ports—stopping backdoors even if DAC permissions allow it.

Core challenges you’ll face:

  • Understanding port types (http_port_t, ssh_port_t, etc.) → maps to network object classes
  • Querying which domains can bind to which ports → maps to allow rules for network
  • Detecting non-standard port usage → maps to security auditing
  • Generating attack surface reports → maps to security posture assessment

Key Concepts:

  • SELinux Port Types: SELinux Notebook - Network Statements section
  • Network Object Classes: SELinux System Administration Ch. 7
  • Port Labeling: semanage port documentation
  • Network Policy Analysis: sesearch for network permissions

Difficulty: Intermediate | Time estimate: 1-2 weeks Prerequisites: Basic networking knowledge, Project 1 completed

Real World Outcome

$ ./selinux-port-auditor --full-scan

SELinux Network Port Security Audit
====================================

LISTENING SERVICES & PORT AUTHORIZATION:
┌─────────────────────────────────────────────────────────────────────────────┐
│ Process        │ Port  │ Domain        │ Port Type     │ Status            │
├─────────────────────────────────────────────────────────────────────────────┤
│ sshd           │ 22    │ sshd_t        │ ssh_port_t    │ ✓ Authorized      │
│ nginx          │ 80    │ httpd_t       │ http_port_t   │ ✓ Authorized      │
│ nginx          │ 443   │ httpd_t       │ http_port_t   │ ✓ Authorized      │
│ postgres       │ 5432  │ postgresql_t  │ postgresql_port│ ✓ Authorized     │
│ custom_app     │ 9999  │ init_t        │ unreserved_t  │ ⚠ Non-standard    │
│ mystery_proc   │ 4444  │ unconfined_t  │ unreserved_t  │ ⛔ ALERT: Review! │
└─────────────────────────────────────────────────────────────────────────────┘

POTENTIAL SECURITY ISSUES:
1. mystery_proc (PID 12345) running as unconfined_t on port 4444
   - Risk: Unconfined processes bypass SELinux controls
   - Action: Investigate process, consider creating confined domain

2. custom_app binding to non-standard port 9999
   - Risk: No specific SELinux port type defined
   - Action: Create port type or use `semanage port -a -t myapp_port_t -p tcp 9999`

RECOMMENDATIONS:
- 2 processes should be investigated
- Run `semanage port -l | grep 4444` to check port authorization

$ ./selinux-port-auditor --domain httpd_t --ports
Ports httpd_t can bind to:
  TCP: 80, 443, 8080, 8443, 8008 (http_port_t)
  TCP: 8009 (http_port_t)  # AJP connector

The Core Question You’re Answering

“How does SELinux control network access beyond traditional firewalls?”

Firewalls control external access; SELinux controls what processes can do internally. A compromised httpd can’t suddenly start listening on port 4444.

Concepts You Must Understand First

  1. Network Object Classes
    • What object classes exist for networking (tcp_socket, udp_socket)?
    • What permissions apply (bind, connect, listen, accept)?
    • How do port types restrict binding?
  2. Port Type System
    • How are ports assigned types?
    • What happens when a process tries to bind to an unauthorized port?

Interview Questions They’ll Ask

  1. “How does SELinux complement iptables/firewalld?”
  2. “A service needs to listen on a non-standard port. How do you configure SELinux?”
  3. “What’s the difference between allowing a network connection via firewall vs SELinux?”
  4. “How would you detect if a process is binding to unauthorized ports?”

Implementation Hints

  1. Get listening ports: ss -tlnp or netstat -tlnp
  2. Get port types: semanage port -l
  3. Get process context: ps -eZ mapped to PID from netstat
  4. Query policy: sesearch --allow -s httpd_t -c tcp_socket -p name_bind
  5. Cross-reference: Match process domain to allowed port types

Project 8: SELinux Policy Diff Tool

  • File: SELINUX_DEEP_DIVE_LEARNING_PROJECTS.md
  • Main Programming Language: Python
  • Alternative Programming Languages: Rust, Go
  • Coolness Level: Level 4: Hardcore Tech Flex
  • Business Potential: 3. The “Service & Support” Model
  • Difficulty: Level 3: Advanced
  • Knowledge Area: SELinux Policy Analysis / Change Management
  • Software or Tool: seinfo, sediff, apol
  • Main Book: “SELinux by Example” by Frank Mayer

What you’ll build: A tool that compares two SELinux policy versions (or a policy before/after module installation) and reports exactly what changed: new types, modified rules, removed permissions.

Why it teaches SELinux: Understanding policy changes is crucial for security auditing and change management. This project forces you to understand policy structure at a deep level—types, attributes, rules, and their relationships.

Core challenges you’ll face:

  • Parsing policy binaries or source → maps to policy compilation and structure
  • Identifying meaningful vs cosmetic changes → maps to understanding policy semantics
  • Handling large rule sets efficiently → maps to policy optimization
  • Presenting diffs clearly → maps to security communication

Key Concepts:

  • Policy Binary Format: SELinux by Example - Policy Internals
  • sediff Tool: SETools documentation
  • Policy Modules: SELinux Notebook - Modular Policy section
  • Rule Analysis: seinfo and sesearch internals

Difficulty: Advanced | Time estimate: 2-3 weeks Prerequisites: Projects 1-3 completed, understanding of policy modules

Real World Outcome

$ ./selinux-policy-diff policy.31 policy.32

SELinux Policy Comparison Report
================================
Base: policy.31 (2024-01-01)
Target: policy.32 (2024-01-15)

SUMMARY:
┌─────────────────────────────────────────┐
│ Category          │ Added  │ Removed   │
├─────────────────────────────────────────┤
│ Types             │ +3     │ -0        │
│ Attributes        │ +1     │ -0        │
│ Allow Rules       │ +47    │ -2        │
│ Type Transitions  │ +5     │ -0        │
│ Booleans          │ +2     │ -0        │
└─────────────────────────────────────────┘

NEW TYPES:
  + myapp_t          (domain attribute)
  + myapp_exec_t     (file attribute)
  + myapp_log_t      (file attribute)

NEW ALLOW RULES (security-relevant):
  + allow myapp_t self:tcp_socket { create connect };
  + allow myapp_t http_port_t:tcp_socket name_connect;
  + allow myapp_t myapp_log_t:file { create write append };

REMOVED RULES:
  - allow httpd_t tmp_t:file write;   # GOOD: Reduced permissions
  - allow ftpd_t user_home_t:dir search;

NEW BOOLEANS:
  + myapp_can_network (default: off)
  + myapp_use_nfs (default: off)

SECURITY ASSESSMENT:
  ✓ No new unconfined permissions
  ✓ No new write access to sensitive types
  ⚠ New network access for myapp_t - verify intended

$ ./selinux-policy-diff --module myapp.pp --show-rules

The Core Question You’re Answering

“What exactly changed in the SELinux policy, and is it safe?”

Policy changes can introduce security holes. This project makes you an expert at auditing policy modifications.

Concepts You Must Understand First

  1. Policy Structure
    • What components make up a compiled policy?
    • How are types, attributes, and rules organized?
    • What’s the difference between source and binary policy?
  2. Rule Semantics
    • When are two rules semantically equivalent?
    • How do attributes affect rule expansion?

Interview Questions They’ll Ask

  1. “How would you audit SELinux policy changes before deploying to production?”
  2. “What’s the difference between seinfo and sesearch?”
  3. “How do you determine if a policy change reduces security?”
  4. “Explain how type attributes affect policy analysis.”

Implementation Hints

  1. Extract policy info: seinfo -t, seinfo -a, sesearch --allow
  2. Use SETools Python bindings: setools library
  3. Handle attributes: Expand to actual types for comparison
  4. Categorize changes: Types, rules, constraints, booleans
  5. Security scoring: Flag changes that add access to sensitive types

Project 9: Ansible SELinux Hardening Role

  • File: SELINUX_DEEP_DIVE_LEARNING_PROJECTS.md
  • Main Programming Language: YAML (Ansible)
  • Alternative Programming Languages: Puppet, Chef, SaltStack
  • Coolness Level: Level 3: Genuinely Clever
  • Business Potential: 3. The “Service & Support” Model
  • Difficulty: Level 2: Intermediate
  • Knowledge Area: SELinux Automation / Configuration Management
  • Software or Tool: Ansible, ansible-selinux modules
  • Main Book: “Ansible for DevOps” by Jeff Geerling

What you’ll build: A comprehensive Ansible role that configures SELinux across a fleet of servers: enforcing mode, proper booleans for services, custom file contexts, and port definitions.

Why it teaches SELinux: Automating SELinux teaches you every configuration touchpoint systematically. You’ll codify best practices into repeatable infrastructure, learning what’s configurable and why.

Core challenges you’ll face:

  • Idempotent SELinux configuration → maps to state management
  • Handling different distro defaults → maps to policy variations
  • Testing SELinux changes safely → maps to operational safety
  • Role-based configuration (web, db, app) → maps to policy by function

Key Concepts:

  • Ansible SELinux Modules: Ansible documentation (selinux, seboolean, sefcontext)
  • Configuration Management: Ansible for DevOps - Jeff Geerling
  • SELinux State Machine: Enforcing vs Permissive transitions
  • Fleet Management: CIS Benchmarks SELinux sections

Difficulty: Intermediate | Time estimate: 1-2 weeks Prerequisites: Basic Ansible knowledge, Projects 1-2 completed

Real World Outcome

# roles/selinux_hardening/tasks/main.yml
---
- name: Ensure SELinux is enforcing
  ansible.posix.selinux:
    policy: targeted
    state: enforcing
  register: selinux_state

- name: Configure web server booleans
  ansible.posix.seboolean:
    name: "{{ item.name }}"
    state: "{{ item.state }}"
    persistent: true
  loop:
    - { name: httpd_can_network_connect, state: true }
    - { name: httpd_can_network_connect_db, state: true }
    - { name: httpd_execmem, state: false }
  when: "'webservers' in group_names"

- name: Set custom file contexts
  community.general.sefcontext:
    target: '/opt/myapp(/.*)?'
    setype: httpd_sys_content_t
    state: present
  notify: Restore SELinux contexts
$ ansible-playbook -i inventory site.yml --tags selinux

PLAY [Configure SELinux Hardening] **************

TASK [selinux_hardening : Ensure SELinux is enforcing] ***
changed: [web1.example.com]
changed: [web2.example.com]
ok: [db1.example.com]  # Already enforcing

TASK [selinux_hardening : Configure web server booleans] ***
changed: [web1.example.com] => httpd_can_network_connect: off -> on
changed: [web1.example.com] => httpd_can_network_connect_db: off -> on
ok: [web2.example.com]  # Already configured

TASK [selinux_hardening : Set custom file contexts] ***
changed: [web1.example.com]

RUNNING HANDLER [Restore SELinux contexts] ***
changed: [web1.example.com]

PLAY RECAP *************************************
web1.example.com   : ok=4    changed=3
web2.example.com   : ok=4    changed=0
db1.example.com    : ok=2    changed=0

The Core Question You’re Answering

“How do I manage SELinux at scale without manual intervention?”

One server is easy. A thousand servers require automation. This project teaches configuration management for MAC.

Concepts You Must Understand First

  1. Ansible SELinux Modules
    • What does each module manage (selinux, seboolean, sefcontext, seport)?
    • What’s the difference between sefcontext and selogin?
  2. State Management
    • How do you handle transitioning from disabled to enforcing?
    • What requires a reboot?

Interview Questions They’ll Ask

  1. “How would you enable SELinux across 500 servers that currently have it disabled?”
  2. “What’s the safe way to transition from permissive to enforcing in production?”
  3. “How do you test SELinux configuration changes before production deployment?”
  4. “What should happen if an SELinux change fails on one server?”

Implementation Hints

  1. Structure: Use role with variables for different server roles
  2. Check mode: Test with --check before applying
  3. Molecule testing: Use Molecule to test role in containers
  4. Handlers: Use handlers to run restorecon only when needed
  5. Facts gathering: Create custom facts for SELinux state reporting

Project 10: MLS/MCS Classification Demo System

  • File: SELINUX_DEEP_DIVE_LEARNING_PROJECTS.md
  • Main Programming Language: Python/C
  • Alternative Programming Languages: Go, Rust
  • Coolness Level: Level 4: Hardcore Tech Flex
  • Business Potential: 4. The “Open Core” Infrastructure
  • Difficulty: Level 4: Expert
  • Knowledge Area: Multi-Level Security / Government Classification
  • Software or Tool: SELinux MLS policy, polyinstantiation
  • Main Book: “SELinux by Example” by Frank Mayer

What you’ll build: A demonstration system implementing true Multi-Level Security with sensitivity labels (Unclassified → Top Secret), showing how data can flow up but not down, polyinstantiated directories, and cross-level communication via trusted channels.

Why it teaches SELinux: MLS is the most sophisticated SELinux feature, implementing the Bell-LaPadula model. This is where SELinux came from (NSA requirements). Understanding MLS gives you insight into the theoretical foundations of mandatory access control.

Core challenges you’ll face:

  • Understanding sensitivity and category labels → maps to the MLS/MCS range
  • Implementing Bell-LaPadula (No Read Up, No Write Down) → maps to information flow control
  • Setting up polyinstantiated directories → maps to level-based isolation
  • Creating trusted subjects for cross-level operations → maps to privilege management

Key Concepts:

  • Bell-LaPadula Model: SELinux by Example Ch. 8
  • MLS Policy: SELinux Notebook - MLS sections
  • Sensitivity Levels: s0-s15 in SELinux
  • Category Sets: c0-c1023 for compartmentalization

Difficulty: Expert | Time estimate: 3-4 weeks Prerequisites: Projects 1-5 completed, understanding of security models

Real World Outcome

# Setup: Users at different clearance levels
$ id alice
uid=1001(alice) context=user_u:user_r:user_t:s0-s2:c0.c15
# Alice has clearance up to SECRET (s2)

$ id bob
uid=1002(bob) context=user_u:user_r:user_t:s0-s3:c0.c31
# Bob has clearance up to TOP SECRET (s3)

# Classification Demo
$ su - alice
$ echo "Unclassified Report" > /mls/s0/report.txt
$ echo "Secret Analysis" > /mls/s2/analysis.txt
$ echo "Top Secret Intel" > /mls/s3/intel.txt
bash: /mls/s3/intel.txt: Permission denied
# Alice cannot write to TOP SECRET (above her clearance)

$ cat /mls/s2/analysis.txt
Secret Analysis
# Alice can read at her level

$ cat /mls/s3/intel.txt
cat: Permission denied
# Alice cannot read TOP SECRET (No Read Up)

# As Bob (TOP SECRET clearance)
$ su - bob
$ cat /mls/s3/intel.txt
Top Secret Intel
# Bob can read TOP SECRET

$ echo "Bob's notes" >> /mls/s0/report.txt
bash: Permission denied
# Bob cannot write to UNCLASSIFIED (No Write Down - prevents leaks!)

# Polyinstantiated directories
$ ls -Z /tmp
# Each user sees different /tmp based on their level
# Alice's /tmp is isolated from Bob's /tmp

# Audit log showing MLS enforcement
$ ausearch -m AVC | grep mls
type=AVC msg=audit(...): avc:  denied  { write } for
  scontext=user_u:user_r:user_t:s3
  tcontext=system_u:object_r:mls_file_t:s0
  mls_constraint: write up denied

The Core Question You’re Answering

“How can a system prevent information from flowing to unauthorized recipients, even from privileged users?”

MLS enforces information flow control. Even root cannot violate classification rules. This is the ultimate expression of MAC.

Concepts You Must Understand First

  1. Bell-LaPadula Model
    • What is “No Read Up, No Write Down”?
    • Why does “No Write Down” prevent data leakage?
    • What are “trusted subjects” and when are they needed?
  2. MLS/MCS Labels
    • What’s the format of an MLS range (s0-s3:c0.c255)?
    • How do sensitivity levels differ from categories?
    • What is dominance in MLS context?
  3. Polyinstantiation
    • What are polyinstantiated directories?
    • Why would /tmp need to be polyinstantiated?
    • How does pam_namespace work?

Interview Questions They’ll Ask

  1. “Explain the Bell-LaPadula model and how SELinux implements it.”
  2. “What’s the difference between MLS sensitivity levels and MCS categories?”
  3. “Why might a government system need ‘No Write Down’ enforcement?”
  4. “What is polyinstantiation and when is it used?”
  5. “How would you implement cross-classification data transfer securely?”

Implementation Hints

  1. Use MLS policy: Install selinux-policy-mls or build custom
  2. Create level hierarchy: s0 (unclass) → s1 (conf) → s2 (secret) → s3 (ts)
  3. Setup users: semanage login -a -s user_u -r s0-s2 alice
  4. Polyinstantiation: Configure /etc/security/namespace.conf
  5. Test flows: Create files at each level, verify access control

Project 11: SELinux Kernel Module Inspector

  • File: SELINUX_DEEP_DIVE_LEARNING_PROJECTS.md
  • Main Programming Language: C
  • Alternative Programming Languages: Rust (with kernel bindings)
  • Coolness Level: Level 5: Pure Magic
  • Business Potential: 1. The “Resume Gold”
  • Difficulty: Level 5: Master
  • Knowledge Area: Linux Kernel / LSM Framework
  • Software or Tool: Linux kernel source, debugfs, ftrace
  • Main Book: “Linux Kernel Development” by Robert Love

What you’ll build: A kernel module or tracing tool that inspects SELinux internals at runtime: watching LSM hooks fire, examining the AVC cache contents, tracing policy decisions, and visualizing the security server’s decision process.

Why it teaches SELinux: This is as deep as it gets. You’ll understand SELinux at the kernel level—how LSM hooks intercept system calls, how the security server makes decisions, and how the AVC caches those decisions. This knowledge is rare and valuable.

Core challenges you’ll face:

  • Understanding the LSM framework → maps to kernel security architecture
  • Tracing SELinux hook invocations → maps to where access control happens
  • Inspecting AVC cache entries → maps to performance optimization
  • Understanding the security server → maps to policy enforcement engine

Key Concepts:

  • LSM Framework: Linux kernel documentation, security/
  • SELinux AVC: security/selinux/avc.c in kernel source
  • Security Server: security/selinux/ss/ in kernel source
  • Kernel Tracing: ftrace, bpftrace, kprobes

Difficulty: Master | Time estimate: 1-2 months Prerequisites: All previous projects, C programming, kernel development basics

Real World Outcome

# Using the inspector module/tool
$ sudo insmod selinux_inspector.ko
$ dmesg | tail

selinux_inspector: Loaded, monitoring LSM hooks

# Trigger some activity
$ curl http://localhost/

$ cat /sys/kernel/debug/selinux_inspector/recent_decisions
┌────────────────────────────────────────────────────────────────────────────┐
│ Timestamp       │ Hook            │ Subject      │ Object       │ Decision │
├────────────────────────────────────────────────────────────────────────────┤
│ 1705123456.001  │ file_open       │ httpd_t      │ http_port_t  │ ALLOW    │
│ 1705123456.002  │ socket_connect  │ httpd_t      │ http_port_t  │ ALLOW    │
│ 1705123456.003  │ file_read       │ httpd_t      │ httpd_sys_c  │ ALLOW    │
│ 1705123456.004  │ file_write      │ httpd_t      │ shadow_t     │ DENY     │
└────────────────────────────────────────────────────────────────────────────┘

$ cat /sys/kernel/debug/selinux_inspector/avc_stats
AVC Cache Statistics:
  Entries: 1,247 / 512 (slots)
  Lookups: 45,678
  Hits: 44,890 (98.3%)
  Misses: 788
  Allocations: 1,247
  Reclaims: 102

Hot entries (most frequently accessed):
  1. httpd_t -> httpd_sys_content_t:file:read    (12,456 hits)
  2. init_t -> init_t:process:transition         (8,234 hits)
  3. sshd_t -> sshd_t:tcp_socket:accept         (5,123 hits)

$ cat /sys/kernel/debug/selinux_inspector/hook_frequency
LSM Hook Invocation Frequency (last 60s):
  file_permission:    45,678
  inode_permission:   34,567
  socket_create:       1,234
  task_alloc:            567
  bprm_check_security:   234

The Core Question You’re Answering

“What actually happens inside the kernel when SELinux makes an access decision?”

This project lifts the veil on SELinux internals. You’ll see the machinery that makes MAC work at the lowest level.

Concepts You Must Understand First

  1. Linux Security Modules (LSM)
    • What is the LSM framework and why was it created?
    • How do security modules register hooks?
    • What’s the relationship between LSM and SELinux?
  2. SELinux Kernel Components
    • What is the Security Server?
    • How does the AVC cache work?
    • What triggers cache invalidation?
  3. Kernel Development Basics
    • How do you build and load kernel modules?
    • What is debugfs and how do you use it?
    • How do ftrace and kprobes work?

Interview Questions They’ll Ask

  1. “Explain the Linux Security Module framework at a high level.”
  2. “How does SELinux’s AVC cache improve performance?”
  3. “What happens when SELinux policy is reloaded?”
  4. “At what point in a system call does SELinux make access decisions?”
  5. “How would you trace SELinux decisions in production?”

Implementation Hints

  1. Study kernel source: Read security/selinux/ directory
  2. Start with ftrace: Use existing tracepoints before writing code
  3. Use bpftrace: bpftrace -e 'kprobe:selinux_file_permission { ... }'
  4. debugfs interface: Create /sys/kernel/debug/mymodule/ entries
  5. Safety first: Test in VM, have serial console for recovery

Final Project: Enterprise SELinux Security Platform

  • File: SELINUX_DEEP_DIVE_LEARNING_PROJECTS.md
  • Main Programming Language: Python/Go
  • Alternative Programming Languages: Rust
  • Coolness Level: Level 5: Pure Magic
  • Business Potential: 4. The “Open Core” Infrastructure
  • Difficulty: Level 4: Expert
  • Knowledge Area: Enterprise Security / Full-Stack SELinux
  • Software or Tool: All previous project tools combined
  • Main Book: All previous books combined

What you’ll build: A comprehensive platform that combines all previous projects: centralized SELinux monitoring across a fleet, real-time AVC analysis with auto-remediation suggestions, policy change auditing, compliance reporting, and anomaly detection.

Why it teaches SELinux: This is the capstone project that demonstrates mastery. You’ll integrate everything you’ve learned into a production-grade system that could be deployed in an enterprise environment.

Core challenges you’ll face:

  • Aggregating SELinux data from multiple hosts → maps to distributed systems
  • Real-time AVC analysis at scale → maps to stream processing
  • Policy compliance checking → maps to security standards
  • Intelligent remediation suggestions → maps to expert system design

Key Concepts:

  • All concepts from previous projects combined
  • Distributed Logging: ELK stack, Loki, or similar
  • Time-Series Analysis: For anomaly detection
  • Compliance Frameworks: CIS, STIG, PCI-DSS SELinux requirements

Difficulty: Expert | Time estimate: 2-3 months Prerequisites: All 11 projects completed

Real World Outcome

┌─────────────────────────────────────────────────────────────────────────────┐
│ SELinux Enterprise Security Platform                    [Dashboard] [Alerts]│
├─────────────────────────────────────────────────────────────────────────────┤
│ Fleet Overview: 127 hosts monitored                                         │
│                                                                             │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐                │
│ │   Enforcing     │ │   Permissive    │ │   Disabled      │                │
│ │      121        │ │       4         │ │       2         │                │
│ │     95.3%       │ │      3.1%       │ │      1.6%       │                │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘                │
│                                                                             │
│ AVC Denials (Last 24h)                    Policy Changes (Last 7d)         │
│ ┌─────────────────────────────┐          ┌─────────────────────────────┐   │
│ │ ████████████ 1,247          │          │ Modules installed: 3        │   │
│ │ ██████ 623                  │          │ Booleans changed: 12        │   │
│ │ ███ 312                     │          │ File contexts added: 47     │   │
│ │ 0    500   1000   1500      │          │ Port definitions: 5         │   │
│ └─────────────────────────────┘          └─────────────────────────────┘   │
│                                                                             │
│ ⚠️ ALERTS                                                                   │
│ ├─ CRITICAL: Host web-prod-03 switched to Permissive (15 min ago)          │
│ ├─ HIGH: 47 new AVC denials for custom_app_t in last hour                  │
│ └─ MEDIUM: Boolean httpd_execmem enabled on 3 web servers                   │
│                                                                             │
│ 🔧 AUTO-REMEDIATION SUGGESTIONS                                             │
│ ├─ web-prod-03: Missing file context for /opt/app/logs → Run restorecon    │
│ ├─ db-prod-01: mysqld_t needs connect to custom port → Add port type       │
│ └─ app-prod-02: Consider creating policy module for repeated denials       │
│                                                                             │
│ 📋 COMPLIANCE STATUS                                                        │
│ ├─ CIS Benchmark: 94% compliant (7 findings)                               │
│ ├─ STIG: 89% compliant (15 findings)                                       │
│ └─ Custom Policy: 100% compliant                                           │
└─────────────────────────────────────────────────────────────────────────────┘

$ selinux-platform-cli analyze --host web-prod-03
Analyzing SELinux state for web-prod-03...

Current Mode: Permissive (WARNING: Should be Enforcing)
Policy Version: 31
Last Policy Change: 2024-01-15 10:30:00

Recent AVC Denials Analysis:
┌────────────────────────────────────────────────────────────────────────────┐
│ Pattern                         │ Count │ Recommendation                   │
├────────────────────────────────────────────────────────────────────────────┤
│ httpd_t -> app_data_t (read)    │ 156   │ Add file context for /opt/app    │
│ httpd_t -> port 9000 (connect)  │ 47    │ semanage port -a -t http_port_t  │
│ httpd_t -> tmp_t (write)        │ 12    │ Check httpd_tmp_exec boolean     │
└────────────────────────────────────────────────────────────────────────────┘

Generated Policy Module:
  selinux-platform-cli generate-policy --host web-prod-03 > web_prod_03_custom.te

The Core Question You’re Answering

“How do I operationalize SELinux security across an entire organization?”

Individual server security is the start. Enterprise security means visibility, automation, and compliance at scale.

Concepts You Must Understand First

  1. All Previous Concepts - This is the integration project
  2. Distributed Systems
    • How do you aggregate logs from many hosts?
    • How do you handle network partitions?
  3. Security Operations
    • What makes an alert actionable?
    • How do you balance security with operability?

Interview Questions They’ll Ask

  1. “How would you design an SELinux monitoring system for 1000+ servers?”
  2. “What metrics would you track for SELinux health?”
  3. “How do you handle false positives in security alerting?”
  4. “Describe your approach to SELinux compliance automation.”
  5. “How would you detect SELinux bypass attempts?”

Implementation Hints

  1. Agent-based collection: Deploy lightweight agent on each host
  2. Central aggregation: Use message queue (Kafka, NATS) for reliability
  3. Stream processing: Analyze AVC denials in real-time
  4. Pattern detection: Use ML or rule-based for anomaly detection
  5. API-first design: REST API for all operations, web UI as consumer

Project Comparison Table

Project Difficulty Time Depth of Understanding Fun Factor Language
1. Context Explorer Beginner Weekend ★★★☆☆ ★★★★☆ Python
2. AVC Analyzer Intermediate 1-2 weeks ★★★★☆ ★★★★★ Python
3. Policy Module Builder Advanced 2-3 weeks ★★★★★ ★★★☆☆ C/M4
4. Boolean Manager Intermediate 1-2 weeks ★★★☆☆ ★★★★☆ Python
5. Container Sandbox Lab Advanced 2-3 weeks ★★★★☆ ★★★★★ Bash
6. File Context Checker Intermediate 1-2 weeks ★★★☆☆ ★★★☆☆ Python
7. Port Security Auditor Intermediate 1-2 weeks ★★★☆☆ ★★★★☆ Python
8. Policy Diff Tool Advanced 2-3 weeks ★★★★★ ★★★☆☆ Python
9. Ansible Hardening Role Intermediate 1-2 weeks ★★★☆☆ ★★★★☆ YAML
10. MLS/MCS Demo System Expert 3-4 weeks ★★★★★ ★★★★★ Python/C
11. Kernel Inspector Master 1-2 months ★★★★★ ★★★★★ C
Final: Enterprise Platform Expert 2-3 months ★★★★★ ★★★★★ Python/Go

Recommendation

For Beginners (New to SELinux)

Start with Project 1: Context Explorer to build foundational understanding of security contexts. Then move to Project 2: AVC Analyzer to understand how SELinux makes decisions and why things get denied. These two projects will give you 80% of the practical knowledge needed for daily SELinux work.

Recommended path: 1 → 2 → 4 → 6

For Intermediate (Know basics, want depth)

If you can already read contexts and understand basic AVC messages, start with Project 3: Policy Module Builder. Writing your own policy module is the turning point where SELinux transforms from “that annoying security thing” to “a powerful tool I control.”

Recommended path: 2 → 3 → 5 → 7 → 8

For Advanced (Want to master SELinux)

If you’ve written policy modules and understand Type Enforcement, tackle Project 10: MLS/MCS Demo to understand the theoretical foundations, then Project 11: Kernel Inspector to see how it all works at the kernel level.

Recommended path: 8 → 10 → 11 → Final

For DevOps/SRE (Focus on operations)

Start with Project 2: AVC Analyzer for troubleshooting skills, then Project 9: Ansible Hardening Role for automation, then Project 5: Container Lab for modern infrastructure.

Recommended path: 2 → 6 → 9 → 5 → Final


Summary

This learning path covers SELinux from fundamental concepts to kernel internals through 12 hands-on projects. Here’s the complete list:

# Project Name Main Language Difficulty Time Estimate
1 SELinux Context Explorer & Visualizer Python Beginner Weekend
2 AVC Denial Analyzer & Auto-Fixer Python Intermediate 1-2 weeks
3 Custom Application Policy Module Builder C/M4 Advanced 2-3 weeks
4 SELinux Boolean Manager with Web Dashboard Python (Flask) Intermediate 1-2 weeks
5 Container SELinux Sandbox Lab Bash/Python Advanced 2-3 weeks
6 File Context Integrity Checker Python Intermediate 1-2 weeks
7 Network Port Security Auditor Python Intermediate 1-2 weeks
8 SELinux Policy Diff Tool Python Advanced 2-3 weeks
9 Ansible SELinux Hardening Role YAML (Ansible) Intermediate 1-2 weeks
10 MLS/MCS Classification Demo System Python/C Expert 3-4 weeks
11 SELinux Kernel Module Inspector C Master 1-2 months
Final Enterprise SELinux Security Platform Python/Go Expert 2-3 months

For beginners: Start with projects #1, #2, #4, #6 For intermediate: Jump to projects #2, #3, #5, #7, #8 For advanced: Focus on projects #8, #10, #11, Final

Expected Outcomes

After completing these projects, you will:

  • Understand the WHY: Know why SELinux exists, its NSA origins, and why MAC matters beyond DAC
  • Read any context: Parse user:role:type:level fluently and understand what each component means
  • Debug any denial: Analyze AVC messages, use audit2why, and fix problems systematically
  • Write custom policy: Create policy modules for any application, using reference policy interfaces
  • Automate SELinux: Deploy and manage SELinux across fleets using Ansible or similar tools
  • Secure containers: Understand how SELinux provides defense-in-depth beyond namespaces
  • Understand MLS/MCS: Know the Bell-LaPadula model and how SELinux implements classification
  • Trace kernel internals: Understand LSM hooks, the AVC cache, and the security server
  • Ace interviews: Answer any SELinux question from basic to advanced with confidence

You’ll have built 12 working projects that demonstrate deep understanding of SELinux from first principles to production deployment.


Key Resources

Essential Books

  1. “SELinux System Administration” by Sven Vermeulen - Best practical guide
  2. “SELinux by Example” by Frank Mayer et al. - Deepest theoretical coverage
  3. “SELinux Notebook” (The SELinux Project) - Comprehensive free reference
  4. “Container Security” by Liz Rice - For container SELinux integration

Online Resources

  • SELinux Project Wiki: https://selinuxproject.org/
  • Red Hat SELinux Guide: RHEL documentation
  • Fedora SELinux User Guide: Excellent practical reference
  • Dan Walsh’s Blog: Insights from the SELinux maintainer

Tools to Master

  • ausearch, audit2why, audit2allow - AVC analysis
  • seinfo, sesearch - Policy querying
  • semanage - Configuration management
  • sepolicy - Policy generation and analysis
  • restorecon, chcon - Context management
  • sealert - GUI troubleshooting (setroubleshoot)