How to Harden Linux for Maximum Security and Privacy
This comprehensive guide explains how to choose a secure Linux distribution, apply kernel hardening, configure sysctl and boot parameters, enforce mandatory access controls, sandbox applications, use hardened compilers and memory allocators, tighten root and user permissions, and adopt best‑practice privacy measures to dramatically reduce the attack surface of a Linux system.
This guide provides step‑by‑step instructions for hardening a Linux system with a focus on security and privacy, not performance or usability. All commands require root privileges and variables marked with $ should be replaced with appropriate values for your environment.
Choosing the Right Distribution
Avoid distributions that freeze packages, as they lag behind security updates.
Prefer distributions without Systemd to reduce unnecessary attack surface.
Use musl as the default C library instead of glibc for a smaller, less vulnerable code base.
Prefer LibreSSL over OpenSSL to eliminate legacy, unnecessary features.
Gentoo Linux is ideal for fine‑grained kernel configuration, but Void Linux with a Musl build is a practical compromise.
Kernel
The kernel is the most attractive target for attackers; therefore, extensive hardening is essential.
Stable vs LTS Kernels
Stable kernels contain all recent security fixes but also introduce new features that increase the attack surface. Long‑term support (LTS) kernels have fewer features and a smaller attack surface, though they may lack some recent mitigations. The recommendation is to use a recent LTS branch such as 4.19.
Sysctl Configuration
Sysctl allows runtime tuning of kernel parameters. Below are the recommended settings, grouped by purpose.
Kernel Self‑Protection
kernel.kptr_restrict=2Hides kernel pointers from unprivileged processes; set to 1 for additional restriction. kernel.dmesg_restrict=1 Prevents unprivileged users from reading the kernel log via dmesg. kernel.printk=3 3 3 3 Reduces console kernel messages during boot.
kernel.unprivileged_bpf_disabled=1
net.core.bpf_jit_harden=2Limits eBPF to privileged users and enables JIT hardening. dev.tty.ldisc_autoload=0 Prevents loading vulnerable TTY line disciplines by unprivileged users. vm.unprivileged_userfaultfd=0 Restricts the userfaultfd syscall to privileged processes. kernel.kexec_load_disabled=1 Disables the kexec system call to stop loading a new kernel from userspace. kernel.sysrq=4 Limits SysRq functionality to the safe SAK key; set to 0 to disable entirely. kernel.unprivileged_userns_clone=0 Prevents unprivileged creation of user namespaces, reducing privilege‑escalation risk. kernel.perf_event_paranoid=3 Restricts performance‑event interfaces to privileged users.
Network Hardening
net.ipv4.tcp_syncookies=1Mitigates SYN‑flood DoS attacks. net.ipv4.tcp_rfc1337=1 Drops RST packets for sockets in TIME‑WAIT, preventing certain attacks.
net.ipv4.conf.all.rp_filter=1
net.ipv4.conf.default.rp_filter=1Enables source address verification.
net.ipv4.conf.all.accept_redirects=0
net.ipv4.conf.default.accept_redirects=0
net.ipv6.conf.all.accept_redirects=0
net.ipv6.conf.default.accept_redirects=0Disables ICMP redirects to stop MITM attacks. net.ipv4.icmp_echo_ignore_all=1 Ignores all ICMP echo requests, mitigating Smurf attacks.
net.ipv4.conf.all.accept_source_route=0
net.ipv6.conf.all.accept_source_route=0Disables source routing to prevent traffic redirection attacks.
net.ipv6.conf.all.accept_ra=0
net.ipv6.conf.default.accept_ra=0Disables IPv6 router advertisements.
net.ipv4.tcp_sack=0
net.ipv4.tcp_dsack=0
net.ipv4.tcp_fack=0Disables TCP SACK extensions, which can be abused in certain exploits.
User‑Space Hardening
kernel.yama.ptrace_scope=2Restricts ptrace to processes with CAP_SYS_PTRACE; set to 3 to disable entirely.
vm.mmap_rnd_bits=32
vm.mmap_rnd_compat_bits=16Increases ASLR entropy for memory mappings.
fs.protected_symlinks=1
fs.protected_hardlinks=1Prevents creation of symlinks/hardlinks that could be used in TOCTOU attacks.
fs.protected_fifos=2
fs.protected_regular=2Blocks creation of files in world‑writable directories.
Boot Parameters
Pass hardening options to the kernel via the bootloader (GRUB, Syslinux, systemd‑boot). Example parameters:
slab_nomerge
slub_debug=FZ
init_on_alloc=1 init_on_free=1
page_alloc.shuffle=1
pti=on
vsyscall=none
debugfs=off
oops=panic
module.sig_enforce=1
lockdown=confidentiality
mce=0
quiet loglevel=0These disable slab merging, enable slab sanity checks, zero memory on allocation/free, randomize page allocator, enable kernel page‑table isolation, disable legacy vsyscalls, turn off debugfs, panic on kernel oops, enforce signed modules, enable strict lockdown mode, disable Machine Check Exception handling, and silence boot messages.
hidepid
Mount /proc with hidepid=2,gid=proc to restrict process visibility to the owning user. Add to /etc/fstab:
proc /proc proc nosuid,nodev,noexec,hidepid=2,gid=proc 0 0For systemd‑logind compatibility, create /etc/systemd/system/systemd-logind.service.d/hidepid.conf with:
[Service]
SupplementaryGroups=procReducing Kernel Attack Surface
Disable unnecessary kernel modules and features. Examples:
install dccp /bin/false
install sctp /bin/false
install rds /bin/false
install tipc /bin/false
install n‑hdlc /bin/false
install ax25 /bin/false
install netrom /bin/false
install x25 /bin/false
install rose /bin/false
install decnet /bin/false
install econet /bin/false
install af_802154 /bin/false
install ipx /bin/false
install appletalk /bin/false
install psnap /bin/false
install p8023 /bin/false
install p8022 /bin/false
install can /bin/false
install atm /bin/falseBlacklist rarely used filesystems (e.g., cramfs, jffs2, hfs, squashfs, udf) and optionally network filesystems (cifs, nfs, gfs2) if not needed.
Mandatory Access Control (MAC)
Enable either AppArmor or SELinux. AppArmor can be activated with boot parameters: apparmor=1 security=apparmor SELinux activation: selinux=1 security=selinux After enabling, create policies (e.g., aa-genprof $program) and fine‑tune them.
Sandboxing
Run untrusted applications inside a sandbox such as Bubblewrap, gVisor, or a hardened systemd service. Example systemd service snippet:
[Service]
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
ProtectSystem=strict
ProtectHome=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
ProtectKernelLogs=true
ProtectHostname=true
ProtectClock=true
ProtectProc=invisible
ProcSubset=pid
PrivateTmp=true
PrivateUsers=yes
PrivateDevices=true
MemoryDenyWriteExecute=true
NoNewPrivileges=true
LockPersonality=true
RestrictRealtime=true
RestrictSUIDSGID=true
RestrictAddressFamilies=AF_INET
RestrictNamespaces=yes
SystemCallFilter=write read openat close brk fstat lseek mmap mprotect munmap rt_sigaction rt_sigprocmask ioctl nanosleep select access execve getuid arch_prctl set_tid_address set_robust_list prlimit64 pread64 getrandom
SystemCallArchitectures=native
UMask=0077
IPAddressDeny=any
AppArmorProfile=/etc/apparmor.d/usr.bin.exampleAdjust the options per service; consult systemd.exec for details.
Hardened Memory Allocator
Install hardened_malloc and preload it globally via /etc/ld.so.preload or per‑application with LD_PRELOAD="/usr/lib/libhardened_malloc.so" $program. Recommended kernel config for it:
CONFIG_SLAB_QUARANTINE_RANDOM_LENGTH=0 CONFIG_SLAB_QUARANTINE_QUEUE_LENGTH=0 CONFIG_GUARD_SLABS_INTERVAL=8Increase vm.max_map_count to accommodate the allocator:
vm.max_map_count=524240Hardening Compiler Flags
When compiling native C/C++ programs with Clang, enable modern mitigations:
-flto -fvisibility=hidden -fsanitize=cfi # Control‑Flow Integrity
-fsanitize=shadow-call-stack # Shadow stack (ARM64 only)
-fsanitize=safe-stack # SafeStack fallback
-ftrivial-auto-var-init=zero # Zero‑initialize locals
-enable-trivial-auto-var-init-zero-knowing-it-will-be-removed-from-clangMemory‑Safe Languages
Prefer Rust, Swift, or Java for new projects, as they provide built‑in protection against buffer overflows, use‑after‑free, and other common memory bugs.
Root Account Hardening
Leave /etc/securetty empty to prevent direct root logins.
Restrict su to the wheel group via auth required pam_wheel.so use_uid.
Lock the root account with passwd -l root (ensure an alternative admin method exists).
Disable remote root SSH login: PermitRootLogin no in /etc/ssh/sshd_config.
Increase password hash rounds:
password required pam_unix.so sha512 shadow nullok rounds=65536.
Prevent Xorg from running as root: needs_root_rights = no in /etc/X11/Xwrapper.config.
Firewall
Use a restrictive iptables (or nftables) policy that drops all inbound traffic by default and only allows established connections and loopback. Example iptables snippet:
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate INVALID -j DROP
-A INPUT -p udp -m conntrack --ctstate NEW -j ACCEPT
-A INPUT -p tcp --tcp-flags FIN,SYN,RST,ACK SYN -m conntrack --ctstate NEW -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-proto-unreachable
COMMITAdjust rules to your specific needs; consult the Arch Wiki and man pages for details.
Identity & Privacy
Use generic hostnames and usernames (e.g., host, user).
Set timezone to UTC and locale/keyboard to US.
Replace /var/lib/dbus/machine-id or /etc/machine-id with a generic value.
Randomize MAC addresses partially (preserve OUI) using macchanger -e $iface and automate via systemd service.
Disable ICMP and TCP timestamps: net.ipv4.tcp_timestamps=0.
Install tirdad kernel module to randomize TCP ISNs.
Prefer secure time sync over NTP (e.g., sdwdate or a custom HTTPS‑based tool).
Mitigate key‑stroke fingerprinting with tools like KeyTrac or Kloak.
File Permissions
Restrict permissions on sensitive directories:
chmod 700 /home/$user
chmod 700 /boot /usr/src /lib/modules /usr/lib/modulesRemove unnecessary setuid/setgid bits:
find / -type f \( -perm -4000 -o -perm -2000 \) -exec chmod u-s {} \;
find / -type f \( -perm -4000 -o -perm -2000 \) -exec chmod g-s {} \;Use setcap to grant fine‑grained capabilities instead of setuid where possible.
Umask
Set a restrictive default file creation mask:
umask 0077Core Dumps
Disable core dumps via sysctl, systemd, and ulimit:
kernel.core_pattern=|/bin/false [Coredump]
Storage=none * hard core 0Also set fs.suid_dumpable=0 to prevent privileged processes from dumping.
Swap
Minimize swap usage to reduce data leakage:
vm.swappiness=1PAM Hardening
Enforce strong passwords and login delay:
password required pam_pwquality.so retry=2 minlen=16 difok=6 dcredit=-3 ucredit=-2 lcredit=-2 ocredit=-3 enforce_for_root
password required pam_unix.so use_authtok sha512 shadow
auth optional pam_faildelay.so delay=4000000Microcode Updates
Install CPU microcode packages (e.g., intel-ucode or amd-ucode) from your distribution’s repository.
IPv6 Privacy Extensions
Enable temporary IPv6 addresses:
net.ipv6.conf.all.use_tempaddr=2
net.ipv6.conf.default.use_tempaddr=2For NetworkManager add ipv6.ip6-privacy=2 to /etc/NetworkManager/NetworkManager.conf. For systemd‑networkd set IPv6PrivacyExtensions=kernel in /etc/systemd/network/ipv6-privacy.conf.
Partition & Mount Options
Separate critical directories onto distinct partitions and use restrictive mount flags:
/ / ext4 defaults 1 1
/home /home ext4 defaults,nosuid,noexec,nodev 1 2
/tmp /tmp ext4 defaults,bind,nosuid,noexec,nodev 1 2
/var /var ext4 defaults,bind,nosuid 1 2
/boot /boot ext4 defaults,nosuid,noexec,nodev 1 2Note that noexec can be bypassed with shell scripts; consider additional hardening.
Entropy
Install additional entropy sources such as haveged and jitterentropy. Load the jitterentropy kernel module early via /usr/lib/modules-load.d/jitterentropy.conf containing jitterentropy_rng.
Physical Security
Enable full‑disk encryption (e.g., LUKS via dm-crypt).
Set BIOS/UEFI passwords and disable unused boot options.
Use bootloader passwords (GRUB, Syslinux, systemd‑boot) and consider verified boot (UEFI Secure Boot + Intel Boot Guard/AMD Secure Boot).
Restrict USB device usage with USBGuard or blacklist modules ( install firewire-core /bin/false, install thunderbolt /bin/false).
Enable IOMMU ( intel_iommu=on amd_iommu=on) and early PCI bus‑master disable ( efi=disable_early_pci_dma).
Mitigate cold‑boot attacks by powering off machines completely and, if needed, using hardware‑level RAM erasure or Tails‑style memory wiping.
Best Practices
Minimize installed software to reduce attack surface.
Keep the system up‑to‑date with automated security updates.
Avoid leaking any system information, however trivial.
Follow general security and privacy recommendations (e.g., Madaidan’s guide).
References
For further reading see the Arch Linux Security wiki, Whonix documentation, NSA hardening guides, KSPP kernel settings, and the extensive list of footnoted sources included in the original article.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
