π§ 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.
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/...)β
ββββββββββββββββββββββββββββββββ βββββββββββββββββββββββββββββββββββββ
auth, account, password, session), control flags (required, requisite, sufficient, optional), and building a secure configuration for /etc/pam.d/common-auth.
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
getfacl, granting fine-grained user and group access via setfacl, configuring the ACL mask, and defining inherited default directory ACLs.
#!/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"
user:role:type:sensitivity:category), explains Type Enforcement (TE), and demonstrates inspecting contexts on processes and files.
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! β
ββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββ
getenforce, setenforce), viewing and setting SELinux Booleans (getsebool, setsebool), and modifying file label definitions permanently with semanage fcontext and restorecon.
#!/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
ausearch to isolate audit entries, audit2why to diagnose root causes, and audit2allow to generate custom Type Enforcement policy modules.
# ==============================================================================
# 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."
enforce, complain) and profile structure.
# ==============================================================================
# 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
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.")
chmod -R 777 to solve permission denials, setting SELINUX=disabled permanently, leaving dangerous SUID binaries active, and permissive sudoers wildcards.
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.
// ==============================================================================
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. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ