#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:
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 = 0Reload all drop-in files and verify that the updated kernel values are active:
$ 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 = 1Setting 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:
- 4User ProcessAttempts open("/etc/shadow", O_RDONLY)
- 3DAC CheckChecks UID, GID, mode, and POSIX ACLs
- 2LSM Hook (MAC)AppArmor path profile or SELinux label policy
- 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.
$ 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-agentA minimal AppArmor profile defines includes, network families, and explicit path permissions (r read, w write, m mmap executable, ix inherit profile on exec):
#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:
$ 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.htmlPolicy 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:
$ 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/webWhy 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 0permanently or unloading AppArmor removes host-wide containment. Always inspectausearch -m AVCor AppArmorDENIEDlogs first, and usePermissiveorcomplainmode only while tuning. - Using
chconinstead ofsemanage fcontext+restorecon:chconchanges a file's label temporarily until the next filesystem relabel orrestoreconrun overwrites it. - Forgetting
mvvscplabel behaviour on SELinux:mvpreserves existing security contexts, whereascpcreates a new destination file that inherits the target directory's default context. - Copying generic
sysctltemplates blindly: enablingnet.ipv4.ip_forward = 0or strictrp_filter = 1without checking whether the machine runs containers, VPN tunnels, or asymmetric routing can silently drop traffic.
#Summary
sysctlhardens kernel memory, filesystem links, and network defaults via persistent/etc/sysctl.d/*.confdrop-ins applied withsysctl --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
complainmode for safe rule development withaa-logprofbefore switching toaa-enforce. - SELinux enforces Type Enforcement labels (
user:role:type:level); diagnose denials withausearch -m AVCand apply durable fixes usingsemanage fcontext,restorecon,semanage port, andsetsebool -P.