LINUX SYSTEM HARDENING: PAM, POSIX ACLs, SELINUX & APPARMOR

Architect enterprise-grade operating system security for B.Tech Computer Science & IT: Pluggable Authentication Modules (PAM) stack control flags and configuration flows, POSIX Access Control Lists (getfacl/setfacl), Linux Security Modules (LSM) kernel hooks, Security-Enhanced Linux (SELinux) Type Enforcement, contexts, booleans, AVC denial triage, and AppArmor profile engineering.

🐧 Kernel Mediations, Defense-in-Depth & Mandatory Access Enforcement

In traditional UNIX and Linux systems, the default security posture relies on Discretionary Access Control (DAC) centered on the all-powerful root user (UID 0). Under pure DAC, if a daemon process running as root or a service account (such as nginx or httpd) is compromised via remote code execution, the attacker inherits the full permissions of that process, often allowing complete compromise of the underlying operating system. Linux System Hardening replaces this vulnerable paradigm with deep, multi-layered defensive controls. At the user authentication boundary, Pluggable Authentication Modules (PAM) enforce modular password complexity, rate-limiting, and multi-factor policies. At the file system layer, POSIX Access Control Lists (ACLs) extend standard read-write-execute bits to individual users and groups. Crucially, the Linux Security Modules (LSM) framework integrates Mandatory Access Control (MAC) directly into the kernel through SELinux (Security-Enhanced Linux) and AppArmor, confining compromised daemons to strict operational boundaries regardless of root privileges.

1. Linux Kernel Hardening Architecture & LSM Hook Topography
Architectural schematic illustrating how Linux mediates system calls. Traces execution from user-space through standard DAC checks into the Linux Security Modules (LSM) hook infrastructure powering SELinux and AppArmor.
Linux Security Modules (LSM) System Call Mediation Topography
LINUX KERNEL SECURITY MEDIATION PIPELINE:

[USER-SPACE PROCESS: e.g., Apache / NGINX / Daemon]
                    β”‚
                    β–Ό (Issues System Call: open(), execve(), socket(), read())
═══════════════════════════════════════════════════════════════════════════════
[LINUX KERNEL SPACE]
                    β”‚
                    β–Ό
     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
     β”‚ TRADITIONAL DAC CHECKS       β”‚ ──► [Checks POSIX Owner, Group, Other bits & ACLs]
     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                    β”‚
                    β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β–Ό (DAC Check Passed)       β–Ό (DAC Check Fails)
     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
     β”‚ LINUX SECURITY MODULES (LSM) β”‚   β”‚ EACCES: Permission Denied (Early) β”‚
     β”‚ KERNEL HOOKS                 β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                    β”‚
                    β–Ό (Queries Active Mandatory Access Engine)
     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
     β”‚ ACTIVE MAC ENGINE (SELinux / AppArmor)                 β”‚
     β”‚ β€’ Evaluates Subject Context vs. Object Context Labels  β”‚
     β”‚ β€’ Queries Access Vector Cache (AVC) for quick decision β”‚
     β”‚ β€’ If AVC Miss: Evaluates Security Policy Database      β”‚
     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                    β”‚
                    β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β–Ό (Policy Matched: ALLOW)  β–Ό (Policy Violation: DENY)
     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
     β”‚ EXECUTE HARDWARE INSTRUCTION β”‚   β”‚ AUDIT DENIAL LOGGED & KERNEL      β”‚
     β”‚ Access granted to Inode,     β”‚   β”‚ BLOCKS ACCESS IMMEDIATELY         β”‚
     β”‚ Socket buffer, or Memory     β”‚   β”‚ (AVC denial in /var/log/audit/...)β”‚
     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Architectural Standard: LSM hooks are restrictive, not permissive. A system call must pass traditional DAC checks FIRST. If DAC allows the action, the LSM hook evaluates the Mandatory Access Control (SELinux/AppArmor) policy. If either check fails, the operation is denied.
Real-Time Example 1: Pluggable Authentication Modules (PAM) Stack Architecture
Analysis of the Linux PAM architecture (RFC 86.0 / Linux-PAM). Explains module management groups (auth, account, password, session), control flags (required, requisite, sufficient, optional), and building a secure configuration for /etc/pam.d/common-auth.
PAM Management Groups & Control Flag Evaluation Logic
THE PAM CONFIGURATION MATRIX:

Syntax: module_type  control_flag  module_path  [module_arguments]

1. THE FOUR PAM MANAGEMENT GROUPS:
β€’ auth     : Authenticates identity (checks passwords, biometric keys, TOTP tokens).
β€’ account  : Validates account status (checks expiration, login hour limits, disabled status).
β€’ password : Enforces password updates, complexity requirements, and history restrictions.
β€’ session  : Configures and tears down the user environment (mounts directories, limits, umask).

2. CONTROL FLAG EVALUATION RULES:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ CONTROL FLAG β”‚ PROCESSING LOGIC ON FAILURE / SUCCESS                                  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ required     β”‚ Must succeed. If it fails, failure is recorded, but REMAINING modules  β”‚
β”‚              β”‚ in the stack are still executed to prevent timing side-channel leaks.  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ requisite    β”‚ Must succeed. If it fails, execution TERMINATES IMMEDIATELY, returning β”‚
β”‚              β”‚ failure to the calling program without running subsequent modules.     β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ sufficient   β”‚ If it succeeds (and no prior 'required' failed), execution TERMINATES  β”‚
β”‚              β”‚ IMMEDIATELY with SUCCESS! If it fails, the failure is ignored.         β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ optional     β”‚ Result is ignored unless it is the only module defined in the stack.   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

HARDENED PAM SPECIFICATION (/etc/pam.d/system-auth snippet):
# Enforce 3-failed-attempts lockout for 15 minutes via pam_faillock
auth        required      pam_env.so
auth        required      pam_faillock.so preauth audit silent deny=3 unlock_time=900
auth        sufficient    pam_unix.so nullok try_first_pass
auth        [default=die] pam_faillock.so authfail audit deny=3 unlock_time=900
auth        required      pam_deny.so

# Enforce strong password complexity via pam_pwquality
password    requisite     pam_pwquality.so retry=3 minlen=14 dcredit=-1 ucredit=-1 ocredit=-1 lcredit=-1
password    sufficient    pam_unix.so sha512 shadow try_first_pass use_authtok remember=5
Security Invariant: Using 'required' instead of 'requisite' for password validation prevents timing attacks. Attackers cannot determine whether a username exists or whether a specific authentication stage passed based on server response latency.
Real-Time Example 2: POSIX Extended Access Control Lists (getfacl & setfacl)
Overcoming traditional standard 9-bit UNIX permission limits using POSIX.1e Extended ACLs. Demonstrates getfacl, granting fine-grained user and group access via setfacl, configuring the ACL mask, and defining inherited default directory ACLs.
Bash (POSIX Extended ACL Configuration & Mask Management)
#!/usr/bin/env bash
# ==============================================================================
# SCRIPT: posix_acl_hardening.sh
# Demonstrates granular file access delegation beyond standard ugo/rwx bits
# ==============================================================================
set -e

DIR="/var/secure_projects"
mkdir -p "$DIR"
chmod 750 "$DIR"

# 1. Inspect baseline permissions (Standard DAC)
echo "[*] Baseline directory permissions:"
ls -ld "$DIR"

# 2. Grant explicit Read & Execute permission to auditor user 'rohan'
# Without changing directory ownership or adding rohan to the primary group!
setfacl -m u:rohan:rx "$DIR"

# 3. Grant full access to development group 'devsecops'
setfacl -m g:devsecops:rwx "$DIR"

# 4. Define DEFAULT ACLs on the directory
# Guarantees that any new file created inside inherits these permissions automatically!
setfacl -d -m u:rohan:rx "$DIR"
setfacl -d -m g:devsecops:rwx "$DIR"

# 5. Restrict maximum effective permissions using the ACL MASK
# Even if devsecops has 'rwx', a mask of 'r-x' blocks write access!
setfacl -m m::rx "$DIR"

# 6. Verify active Access Control List entries
echo -e "\n[*] Active POSIX ACL Inode Metadata (getfacl):"
getfacl "$DIR"
Terminal Output: [*] Baseline directory permissions: drwxr-x--- 2 root root 4096 Nov 04 10:20 /var/secure_projects [*] Active POSIX ACL Inode Metadata (getfacl): # file: var/secure_projects # owner: root # group: root user::rwx user:rohan:r-x group::r-x group:devsecops:rwx #effective:r-x mask::r-x other::--- default:user::rwx default:user:rohan:r-x default:group::r-x default:group:devsecops:rwx default:mask::rwx default:other::--- Notice: An extra '+' symbol appears in 'ls -l' (drwxr-x---+), indicating active extended POSIX ACLs.
Real-Time Example 3: SELinux Architecture: Contexts, Type Enforcement & MLS Labels
Deep dive into Security-Enhanced Linux (SELinux) label mechanics. Deconstructs the 5-part security context (user:role:type:sensitivity:category), explains Type Enforcement (TE), and demonstrates inspecting contexts on processes and files.
SELinux Security Context Anatomy & Type Enforcement Model
THE FIVE-PART SELINUX SECURITY CONTEXT ANATOMY:

Format: user_u : role_r : type_t : level [s0-s15:c0.c1023]
        β””β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         User     Role     Type        Multi-Level (MLS/MCS)

1. USER (e.g., system_u, unconfined_u):
   β€’ Binds a Linux account to a set of authorized SELinux roles.
   β€’ Unrelated to standard Linux UID/usernames.

2. ROLE (e.g., system_r, object_r, secadm_r):
   β€’ RBAC implementation within SELinux. Files always have role 'object_r'.
   β€’ Processes transition between roles based on policy definitions.

3. TYPE (THE CORE OF TYPE ENFORCEMENT - e.g., httpd_t, httpd_sys_content_t):
   β€’ Defines the operational sandbox domain.
   β€’ For processes, this is called a Domain (e.g., httpd_t).
   β€’ For files and ports, this is called a Type (e.g., httpd_sys_content_t, http_port_t).

4. LEVEL (MLS / MCS - Multi-Category Security - e.g., s0:c0,c100):
   β€’ Enforces Bell-LaPadula multi-level confidentiality and container isolation (Docker/K8s sVirt).

HOW TYPE ENFORCEMENT MEDIATES REAL TRANSACTIONS:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ PROCESS DOMAIN: httpd_t (Apache Web Server)                                                   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                               β”‚
            β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
            β–Ό (Permitted Access)                  β–Ό (Blocked Access)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ OBJECT: httpd_sys_content_t  β”‚        β”‚ OBJECT: shadow_t             β”‚
β”‚ /var/www/html/index.html     β”‚        β”‚ /etc/shadow                  β”‚
β”‚ Rule: allow httpd_t          β”‚        β”‚ No allow rule exists!        β”‚
β”‚   httpd_sys_content_t : file β”‚        β”‚ Access BLOCKED at kernel,    β”‚
β”‚   { read open getattr };     β”‚        β”‚ EVEN IF APACHE RUNS AS ROOT! β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Type Enforcement Invariant: Under SELinux, process privileges depend on the process context (httpd_t), not UID 0. Even if an attacker achieves a root shell inside the web server, the kernel blocks the process from reading /etc/shadow or pivoting across the internal network because no allow rule exists between httpd_t and shadow_t.
Real-Time Example 4: Operating SELinux: Enforcing, Permissive, Booleans & semanage
Managing SELinux in production environments. Demonstrates switching modes (getenforce, setenforce), viewing and setting SELinux Booleans (getsebool, setsebool), and modifying file label definitions permanently with semanage fcontext and restorecon.
Bash (Production SELinux Administration & Context Relabeling)
#!/usr/bin/env bash
# ==============================================================================
# SCRIPT: selinux_operations.sh
# Production commands for administering SELinux policy states and labels
# ==============================================================================

# 1. Check current SELinux execution mode
echo "[*] Current SELinux Status:"
sestatus

# Modes:
# Enforcing  : Policies actively enforced; violations blocked and logged.
# Permissive : Policies evaluated; violations logged, but NOT blocked (Audit mode).
# Disabled   : Kernel module disabled; zero protection or tracking.

# Temporarily switch to Permissive for troubleshooting (without reboot)
sudo setenforce 0
# Switch back to Enforcing
sudo setenforce 1

# 2. Managing Policy Booleans (Tunable switches inside binary policies)
# Example: Allow NGINX/Apache to establish outbound database connections
echo "[*] Setting SELinux Booleans..."
getsebool httpd_can_network_connect_db
sudo setsebool -P httpd_can_network_connect_db on # -P makes change persistent across reboots

# 3. Labeling custom web directory paths (e.g., custom web root at /srv/website)
# WARNING: 'chcon' is temporary! It gets wiped on relabel or filesystem restore.
# ALWAYS use 'semanage fcontext' for permanent configuration:
sudo semanage fcontext -a -t httpd_sys_content_t "/srv/website(/.*)?"

# 4. Apply the defined policy context to the actual disk directory
sudo restorecon -Rv /srv/website

# 5. Allow web server to listen on a non-standard port (e.g., port 8089)
sudo semanage port -a -t http_port_t -p tcp 8089
Configuration Telemetry: SELinux status: enabled SELinuxfs mount: /sys/fs/selinux SELinux root directory: /etc/selinux Loaded policy name: targeted Current mode: enforcing Mode from config file: enforcing Policy MLS status: enabled Policy deny_unknown status: allowed Memory protection checking: actual (secure) Max kernel policy version: 33 Relabeling /srv/website from default_t to httpd_sys_content_t... done.
Real-Time Example 5: Triage and Resolution of SELinux AVC Denials (audit2why & audit2allow)
Troubleshooting SELinux Access Vector Cache (AVC) denial events. Uses ausearch to isolate audit entries, audit2why to diagnose root causes, and audit2allow to generate custom Type Enforcement policy modules.
Audit Logs & AVC Denial Triage Workflow
# ==============================================================================
# SELINUX AUDIT LOG ANALYSIS & DENIAL TRIAGE PIPELINE
# Log path: /var/log/audit/audit.log
# ==============================================================================

# Step 1: Query audit log for recent AVC (Access Vector Cache) denials
sudo ausearch -m avc -ts recent

# RAW AVC DENIAL EXAMPLE IN /var/log/audit/audit.log:
# type=AVC msg=audit(1793741200.104:481): avc:  denied  { name_connect } for  pid=4912
# comm="nginx" dest=3306 scontext=system_u:system_r:httpd_t:s0
# tcontext=system_u:object_r:mysqld_port_t:s0 tclass=tcp_socket permissive=0

# Step 2: Use audit2why to receive human-readable explanations of why the access was denied
sudo ausearch -m avc -ts recent | audit2why

# SAMPLE audit2why OUTPUT:
# Was caused by:
#   The boolean httpd_can_network_connect_db was inactive.
#   Description:
#   Allow httpd to can network connect db
#   Allow access by executing:
#   # setsebool -P httpd_can_network_connect_db 1

# Step 3: If NO boolean exists, generate a custom Type Enforcement (TE) policy module
# WARNING: Review the generated .te file before compiling to avoid granting excessive privileges!
sudo ausearch -m avc -c nginx | audit2allow -M custom_nginx_db

# Generated file: custom_nginx_db.te
# module custom_nginx_db 1.0;
# require {
#     type httpd_t;
#     type mysqld_port_t;
#     class tcp_socket name_connect;
# }
# allow httpd_t mysqld_port_t:tcp_socket name_connect;

# Step 4: Install the compiled policy module into the running kernel
sudo semodule -i custom_nginx_db.pp
echo "[βœ”] Custom SELinux policy module successfully installed."
Triage Diagnostic Report: AVC denial analyzed: Process 'nginx' (httpd_t) was blocked from connecting to TCP port 3306 (mysqld_port_t). Remediation Path A (Preferred): Activate existing boolean 'httpd_can_network_connect_db'. Remediation Path B (Custom services): Author and compile custom Type Enforcement module via audit2allow -M.
Real-Time Example 6: AppArmor Architecture: Path-Based Confinement & Profiles
Analysis of AppArmor (Application Armor), the default MAC system on Ubuntu and Debian. Contrasts its path-based approach with SELinux's label-based Type Enforcement, detailing profile states (enforce, complain) and profile structure.
AppArmor Profile Specification (/etc/apparmor.d/usr.sbin.nginx)
# ==============================================================================
# APPARMOR PROFILE SPECIFICATION: /etc/apparmor.d/usr.sbin.nginx
# Path-based confinement: Explicitly binds permissions to absolute filesystem paths
# ==============================================================================

#include <tunables/global>

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

    # Capability grants: Drop all capabilities except designated operations
    capability net_bind_service,
    capability setuid,
    capability setgid,

    # File access modes:
    # r = read | w = write | x = execute | m = memory map exec | k = lock | l = link
    /usr/sbin/nginx mr,

    # Static web content: Read-only access
    /var/www/html/** r,
    /srv/web/public/** r,

    # Configuration files: Read-only access
    /etc/nginx/** r,
    /etc/nginx/nginx.conf r,

    # Log directories: Append and write access
    /var/log/nginx/* w,
    /var/log/nginx/*.log a,

    # Runtime and PID sockets
    /run/nginx.pid rw,
    /run/nginx.sock rw,

    # Deny access to sensitive files explicitly (Deny rules override Allow rules!)
    deny /etc/shadow r,
    deny /etc/ssh/** r,
    deny /home/** rwklx,
}

# ------------------------------------------------------------------------------
# APPARMOR MANAGEMENT COMMANDS
# ------------------------------------------------------------------------------
# View status of loaded profiles
# $ sudo aa-status

# Put profile in Complain mode (Logs violations without blocking - equivalent to Permissive)
# $ sudo aa-complain /usr/sbin/nginx

# Put profile in Enforce mode (Actively blocks unauthorized actions)
# $ sudo aa-enforce /usr/sbin/nginx

# Automatically generate profile from logged actions using audit profiler
# $ sudo aa-genprof /usr/sbin/nginx
AppArmor vs. SELinux Comparison: 1. Path-based vs. Label-based: AppArmor binds rules to file path strings (/var/www/**); SELinux binds rules to extended inode attributes (httpd_sys_content_t) regardless of file location. 2. Learning Curve: AppArmor profiles are human-readable text files authored in minutes; SELinux requires mastering complex type lattices, booleans, and policy compilation.
Real-Time Example 7: Python Audit Script: Automated System Hardening Baseline Auditor
Building an automated system security audit script in Python. Inspects active SELinux/AppArmor enforcement states, identifies world-writable directories, flags SUID/SGID binaries, and verifies password hashing algorithms.
Python (Automated Linux Hardening Baseline Audit Script)
import os
import subprocess
from typing import List, Dict

class LinuxSecurityAuditor:
    @staticmethod
    def audit_mac_framework() -> dict:
        """Inspects active kernel MAC framework (SELinux or AppArmor)."""
        mac_info = {"selinux": "DISABLED", "apparmor": "DISABLED"}

        # Check SELinux
        if os.path.exists("/sys/fs/selinux/enforce"):
            try:
                out = subprocess.check_output(["getenforce"], text=True).strip()
                mac_info["selinux"] = out
            except Exception:
                mac_info["selinux"] = "ERROR"

        # Check AppArmor
        if os.path.exists("/sys/kernel/security/apparmor"):
            try:
                out = subprocess.check_output(["aa-status", "--enabled"], text=True)
                mac_info["apparmor"] = "ENABLED"
            except Exception:
                mac_info["apparmor"] = "PRESENT_NOT_ENFORCING"

        return mac_info

    @staticmethod
    def find_dangerous_suid_binaries() -> List[str]:
        """Scans standard binary directories for SUID bit (Perms: 0o4000)."""
        suid_binaries = []
        target_dirs = ["/bin", "/sbin", "/usr/bin", "/usr/sbin"]

        for d in target_dirs:
            if not os.path.exists(d):
                continue
            for root, _, files in os.walk(d):
                for f in files:
                    full_path = os.path.join(root, f)
                    try:
                        stat_res = os.stat(full_path, follow_symlinks=False)
                        # Check SUID bit
                        if stat_res.st_mode & 0o4000:
                            suid_binaries.append(full_path)
                    except (PermissionError, FileNotFoundError):
                        continue
        return suid_binaries

    @staticmethod
    def check_password_hashing_algorithm() -> str:
        """Inspects /etc/login.defs or /etc/shadow for modern hashing algorithms."""
        try:
            with open("/etc/login.defs", "r") as f:
                for line in f:
                    if line.strip().startswith("ENCRYPT_METHOD"):
                        return line.strip()
        except FileNotFoundError:
            pass
        return "UNKNOWN"

if __name__ == "__main__":
    auditor = LinuxSecurityAuditor()

    print("==========================================================================")
    print("           LINUX SYSTEM HARDENING BASELINE AUDIT REPORT")
    print("==========================================================================")
    
    mac_status = auditor.audit_mac_framework()
    print(f"[*] MAC Subsystems   : SELinux: {mac_status['selinux']} | AppArmor: {mac_status['apparmor']}")

    hash_algo = auditor.check_password_hashing_algorithm()
    print(f"[*] Password Hashing : {hash_algo} (Baseline requires SHA512 or YESCRYPT)")

    suid_list = auditor.find_dangerous_suid_binaries()
    print(f"[*] SUID Binaries    : {len(suid_list)} found across binary search paths.")
    for b in suid_list[:5]:
        print(f"    β€’ {b}")
    if len(suid_list) > 5:
        print(f"    β€’ ... and {len(suid_list) - 5} more.")
Audit Script Telemetry: ========================================================================== LINUX SYSTEM HARDENING BASELINE AUDIT REPORT ========================================================================== [*] MAC Subsystems : SELinux: Enforcing | AppArmor: DISABLED [*] Password Hashing : ENCRYPT_METHOD YESCRYPT (Baseline requires SHA512 or YESCRYPT) [*] SUID Binaries : 24 found across binary search paths. β€’ /usr/bin/passwd β€’ /usr/bin/sudo β€’ /usr/bin/chfn β€’ /usr/bin/newgrp β€’ /usr/bin/gpasswd β€’ ... and 19 more. Audit Complete: Baseline confirms SELinux is Enforcing and modern yescrypt password hashing is active.
Real-Time Example 8: Debugging Hardening Anti-Patterns & Administration Triage
Troubleshooting common Linux hardening mistakes: running chmod -R 777 to solve permission denials, setting SELINUX=disabled permanently, leaving dangerous SUID binaries active, and permissive sudoers wildcards.
Linux Hardening Anti-Patterns & Diagnostic Triage
LINUX SYSTEM HARDENING DEFECTS & ARCHITECTURAL CORRECTIONS:

// ==============================================================================
// PITFALL 1: RUNNING "chmod -R 777" TO RESOLVE WEB SERVER ERRORS
// DEFECT: Web developer encounters "HTTP 403 Forbidden" and runs:
// $ sudo chmod -R 777 /var/www/html
// CATASTROPHE: Every local user and compromised process can now modify or overwrite
// website files, inject web shells, and alter scripts!
// CAUSE: The error was almost certainly an SELinux label mismatch (e.g., default_t).
// CORRECTION: Keep permissions restricted (directories 755, files 644) and fix the
// SELinux context properly:
// $ sudo restorecon -Rv /var/www/html
// ==============================================================================

// ==============================================================================
// PITFALL 2: DISABLING SELINUX IN /etc/selinux/config INSTEAD OF FIXING POLICIES
// DEFECT: Administrator sets SELINUX=disabled to bypass a denial.
// CONSEQUENCE:
// 1. All filesystem Mandatory Access Control protections are permanently lost.
// 2. Newly created files lose SELinux extended attributes.
// 3. Re-enabling SELinux later requires a slow, hours-long full-system relabel:
//    $ sudo touch /.autorelabel && sudo reboot
// CORRECTION: Switch to Permissive mode for troubleshooting (setenforce 0), identify
// the missing boolean using audit2why, and re-enable Enforcing mode!
// ==============================================================================

// ==============================================================================
// PITFALL 3: OVER-PERMISSIVE SUDOERS CONFIGURATION (NOPASSWD + WILDCARDS)
// DEFECT: dev ALL=(ALL) NOPASSWD: /usr/bin/find, /usr/bin/vim
// EXPLOIT: Both 'find' and 'vim' support direct shell escapes!
// An attacker runs: $ sudo find . -exec /bin/sh \; -quit
// Result: Instant root shell with zero password required!
// CORRECTION: Follow the Principle of Least Privilege: Never grant sudo access to
// compilers, editors, pagers (less/more), or search tools with shell execution capabilities.
// ==============================================================================
Triage Summary: - chmod 777 Anti-pattern: Reverted to 755/644 permissions; resolved 403 errors by applying httpd_sys_content_t. - SELinux Disabled Pitfall: Avoided disabling SELinux; used targeted booleans to grant required access. - Sudo Shell Escapes: Removed interactive binaries (find, vim, less) from sudoers rules.
Real-Time Example 9: Linux System Hardening Specification Reference Matrix
A comprehensive reference summary pairing hardening components, configuration files, operational commands, and security objectives for B.Tech engineering students.
Linux Hardening & MAC Specification Reference Matrix
LINUX HARDENING & MAC SPECIFICATION MATRIX:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ SUBSYSTEM / COMPONENT   β”‚ CONFIGURATION PATH           β”‚ CONTROL SCOPE    β”‚ PRIMARY SECURITY OBJECTIVE    β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ PAM Authentication      β”‚ /etc/pam.d/                  β”‚ User Space / Authβ”‚ Multi-factor auth, account    β”‚
β”‚                         β”‚ (system-auth, common-auth)   β”‚ Boundary         β”‚ lockouts, password complexity β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ POSIX Extended ACLs     β”‚ setfacl / getfacl commands   β”‚ File System Layerβ”‚ Granular user/group access    β”‚
β”‚                         β”‚ (File inode metadata)        β”‚ (DAC Extension)  β”‚ beyond standard 9-bit masks   β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Linux Security Modules  β”‚ /sys/kernel/security/        β”‚ Linux Kernel     β”‚ Framework providing hooks for β”‚
β”‚ (LSM Framework)         β”‚ Kernel compile flags         β”‚ System Calls     β”‚ Mandatory Access Control (MAC)β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ SELinux Type Enforcementβ”‚ /etc/selinux/config          β”‚ Kernel / Inode   β”‚ Confines processes to strict  β”‚
β”‚ (Red Hat, CentOS, Fedoraβ”‚ /etc/selinux/targeted/       β”‚ Extended Labels  β”‚ domains (e.g., httpd_t)       β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ SELinux Booleans        β”‚ getsebool / setsebool -P     β”‚ Dynamic Kernel   β”‚ Tunable policy toggles withoutβ”‚
β”‚                         β”‚                              β”‚ Policy Flags     β”‚ recompiling rule matrices     β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ SELinux Audit Analysis  β”‚ ausearch -m avc              β”‚ Audit Logging    β”‚ Investigates Access Vector    β”‚
β”‚                         β”‚ audit2why / audit2allow      β”‚ & Forensics      β”‚ Cache (AVC) denial events     β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ AppArmor Profiles       β”‚ /etc/apparmor.d/             β”‚ Path-Based       β”‚ Process confinement bound to  β”‚
β”‚ (Ubuntu, Debian, SUSE)  β”‚ aa-enforce / aa-complain     β”‚ Kernel Sandbox   β”‚ file path hierarchies         β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ SUID/SGID Hardening     β”‚ chmod u-s <binary>           β”‚ Privilege Escal- β”‚ Strips root execution flags   β”‚
β”‚                         β”‚ find / -perm /4000           β”‚ ation Boundary   β”‚ from unneeded system binaries β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ TOP 5 LINUX HARDENING PRINCIPLES:                                                                         β”‚
β”‚ 1. Never disable SELinux/AppArmor: Fix label contexts and adjust booleans instead of disabling MAC.       β”‚
β”‚ 2. Enforce the Principle of Least Privilege: Run daemons as dedicated unprivileged system users.          β”‚
β”‚ 3. Restrict SUID/SGID Binaries: Audit and remove the SUID bit from binaries that do not require it.       β”‚
β”‚ 4. Harden PAM Stacks: Enforce account lockouts after repeated failed attempts to stop brute-forcing.      β”‚
β”‚ 5. Audit Regularly: Inspect /var/log/audit/audit.log to catch privilege escalation attempts early.        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Academic & Professional Standard: Linux security requires defense-in-depth across the entire operating system stack. Combining PAM authentication constraints, POSIX file ACLs, and kernel-level Mandatory Access Control (SELinux/AppArmor) ensures that even if an attacker achieves remote code execution, they remain confined within an isolated sandbox and cannot compromise the underlying host.