Skip to main content
Linux Hardening: Kernel Sysctl, AppArmor & SELinux
Lesson 12 of 17

Linux Hardening: Kernel Sysctl, AppArmor & SELinux

Tune kernel sysctl security parameters and enforce Mandatory Access Control with AppArmor profiles and SELinux contexts without breaking legitimate services.

Advanced 28 min Cloud & DevSecOps

Learning objectives

  • Configure and persist kernel memory, filesystem, and network hardening parameters with sysctl
  • Distinguish Discretionary Access Control (DAC) from Mandatory Access Control (MAC)
  • Inspect, test in complain mode, and enforce path-based AppArmor profiles
  • Diagnose SELinux AVC denials with ausearch and fix file or port labels persistently using semanage and restorecon

Recommended first: Linux Fundamentals Recap: ACLs, PAM & SSH HardeningLinux Processes, systemd Sandboxing & auditd Logs

#Why this matters

Discretionary Access Control (DAC) permissions, POSIX ACLs, and systemd service sandboxing go a long way, yet they leave two major gaps. First, default kernel settings often prioritise compatibility over security, exposing kernel pointers, allowing cross-process ptrace, or accepting spoofed network packets. Second, if an attacker exploits a flaw inside a process running as root or holding broad DAC access, standard ownership checks will not stop it.

Kernel tuning through sysctl hardens the operating system's global defaults, while Mandatory Access Control (MAC) via AppArmor or SELinux confines every program to the exact files, sockets, and capabilities its policy allows.

#Hardening kernel defaults with sysctl

The Linux kernel exposes tunable variables under /proc/sys/. Changes made with sysctl -w apply immediately in memory and vanish on reboot; persistent settings belong in /etc/sysctl.d/*.conf and are reloaded with sysctl --system. Files in /etc/sysctl.d/ are processed in lexical order and override vendor defaults in /usr/lib/sysctl.d/, so using a high prefix such as 99-hardening.conf ensures your security settings win.

Parameter Recommended value Security benefit
kernel.randomize_va_space 2 Enables full ASLR for stack, heap, and libraries
kernel.kptr_restrict 2 Hides kernel symbol addresses in /proc/kallsyms
kernel.dmesg_restrict 1 Restricts reading kernel dmesg logs to CAP_SYSLOG
kernel.yama.ptrace_scope 1 Limits ptrace debugging to direct child processes
fs.protected_symlinks 1 Blocks following untrusted symlinks in sticky directories
fs.protected_hardlinks 1 Prevents unprivileged hardlinks to files you cannot read/write
fs.suid_dumpable 0 Disables core dumps for SUID or privilege-changing programs
net.ipv4.conf.all.rp_filter 1 Drops packets whose source IP fails reverse-path routing checks
net.ipv4.conf.all.accept_redirects 0 Ignores ICMP redirect messages that could alter routing
net.ipv4.tcp_syncookies 1 Mitigates TCP SYN flood exhaustion

Save the hardening directives in /etc/sysctl.d/99-hardening.conf:

ini
kernel.kptr_restrict = 2
kernel.dmesg_restrict = 1
kernel.yama.ptrace_scope = 1
fs.protected_symlinks = 1
fs.protected_hardlinks = 1
fs.suid_dumpable = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0

Reload all drop-in files and verify that the updated kernel values are active:

Applying and verifying a persistent sysctl drop-in
$ sudo sysctl --system | tail -n 4
* Applying /etc/sysctl.d/99-hardening.conf ...
kernel.kptr_restrict = 2
kernel.dmesg_restrict = 1
$ sysctl kernel.kptr_restrict kernel.yama.ptrace_scope
kernel.kptr_restrict = 2
kernel.yama.ptrace_scope = 1

Setting kernel.yama.ptrace_scope = 1 prevents one compromised user process from attaching a debugger to another process owned by the same user (for example, dumping secrets from an SSH agent), while value 2 restricts ptrace strictly to CAP_SYS_PTRACE. Note one important operational nuance: if a host acts as a router, VPN gateway, or container node, setting net.ipv4.ip_forward = 0 breaks forwarding, and strict rp_filter = 1 can drop legitimate packets on hosts with asymmetric multi-homed routes (use 2 for loose mode only when needed). Always match network sysctl parameters to the host's role.

#From DAC to Mandatory Access Control

Under DAC, file owners decide permissions and root bypasses almost every check. Under MAC, Linux Security Modules (LSMs) intercept kernel system calls after DAC passes and enforce an independent system-wide policy:

  1. 4User ProcessAttempts open("/etc/shadow", O_RDONLY)
  2. 3DAC CheckChecks UID, GID, mode, and POSIX ACLs
  3. 2LSM Hook (MAC)AppArmor path profile or SELinux label policy
  4. 1Kernel VFSAllows or returns EACCES (-13)

Most distributions enable one primary LSM by default: Debian, Ubuntu, and SUSE ship AppArmor, while RHEL, Fedora, and Rocky Linux ship SELinux. Both protect against zero-day application bugs and lateral movement, but they identify resources differently.

#Confining programs with AppArmor

AppArmor attaches policies to executable file paths stored under /etc/apparmor.d/. Each profile runs in one of two active modes:

  • enforce: violations are blocked and logged.
  • complain: violations are permitted and logged (apparmor="ALLOWED"), making it safe to profile an unfamiliar service before switching to enforce.
Inspecting AppArmor status and toggling modes
$ sudo aa-status | head -n 10
apparmor module is loaded.
42 profiles are loaded.
40 profiles are in enforce mode.
   /usr/sbin/chronyd
   /usr/sbin/tcpdump
2 profiles are in complain mode.
   /usr/local/bin/ingest-agent
$ sudo aa-enforce /etc/apparmor.d/usr.local.bin.ingest-agent

A minimal AppArmor profile defines includes, network families, and explicit path permissions (r read, w write, m mmap executable, ix inherit profile on exec):

text
#include <tunables/global>

profile /usr/local/bin/ingest-agent {
  #include <abstractions/base>

  network inet stream,
  network inet6 stream,

  /usr/local/bin/ingest-agent mr,
  /etc/ingest/config.yml r,
  /var/lib/ingest/** rw,
  deny /etc/shadow r,
}

Because AppArmor evaluates paths, moving or hard-linking a binary to an unprofiled path outside the profile's scope leaves it unconfined unless covered by a wildcard or parent profile. Use aa-logprof to review ALLOWED entries generated during complain mode and refine rules interactively before running aa-enforce.

#Understanding SELinux labels and contexts

SELinux uses Type Enforcement on security labels stored in extended filesystem attributes (xattr) and kernel process structures. Every subject and object carries a four-part context user:role:type:level:

Viewing process and file SELinux contexts
$ ps -eZ | grep httpd
system_u:system_r:httpd_t:s0     1842 ?        00:00:01 httpd
$ ls -Z /var/www/html/index.html
system_u:object_r:httpd_sys_content_t:s0 /var/www/html/index.html

Policy rules dictate which domain (httpd_t) may perform actions on which object type (httpd_sys_content_t) or port type (http_port_t). SELinux operates in Enforcing, Permissive (logs denials without blocking), or Disabled mode (getenforce prints the current state; /etc/selinux/config sets the boot default).

When SELinux blocks an action, the kernel logs an Access Vector Cache (AVC) denial. Using ausearch from the previous lesson, an administrator can pinpoint the exact mismatch instead of disabling SELinux:

Diagnosing an AVC denial and fixing the label persistently
$ sudo ausearch -m AVC -ts recent -i
type=AVC msg=audit(11/18/2026 16:05:11.104:918) : avc:  denied  { read } for  pid=1842 comm=httpd name=report.html dev="sda1" ino=262145 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:user_home_t:s0 tclass=file permissive=0
$ sudo semanage fcontext -a -t httpd_sys_content_t "/srv/web(/.*)?"
$ sudo restorecon -Rv /srv/web

Why did that fail originally? Someone moved report.html from a home directory (user_home_t) into /srv/web, and mv preserves source labels instead of inheriting the destination directory's context. Running semanage fcontext registers the rule in policy, and restorecon applies it permanently.

If a service legitimately binds a non-standard port (such as 8081 for an internal web app) or needs outbound network connections, adjust the policy cleanly with semanage port -a -t http_port_t -p tcp 8081 or setsebool -P httpd_can_network_connect on (-P persists across reboots).

#Common mistakes

  • Disabling SELinux or AppArmor instead of reading logs: running setenforce 0 permanently or unloading AppArmor removes host-wide containment. Always inspect ausearch -m AVC or AppArmor DENIED logs first, and use Permissive or complain mode only while tuning.
  • Using chcon instead of semanage fcontext + restorecon: chcon changes a file's label temporarily until the next filesystem relabel or restorecon run overwrites it.
  • Forgetting mv vs cp label behaviour on SELinux: mv preserves existing security contexts, whereas cp creates a new destination file that inherits the target directory's default context.
  • Copying generic sysctl templates blindly: enabling net.ipv4.ip_forward = 0 or strict rp_filter = 1 without checking whether the machine runs containers, VPN tunnels, or asymmetric routing can silently drop traffic.

#Summary

  • sysctl hardens kernel memory, filesystem links, and network defaults via persistent /etc/sysctl.d/*.conf drop-ins applied with sysctl --system.
  • Mandatory Access Control enforces policy in kernel space after DAC checks pass, limiting even compromised privileged services.
  • AppArmor confines executables by filesystem path and supports complain mode for safe rule development with aa-logprof before switching to aa-enforce.
  • SELinux enforces Type Enforcement labels (user:role:type:level); diagnose denials with ausearch -m AVC and apply durable fixes using semanage fcontext, restorecon, semanage port, and setsebool -P.

Knowledge check

Sign in to take the test, complete lessons and save your progress. Log in

Practice: test your knowledge