How to Harden Linux: Essential Security Settings and Best Practices
This comprehensive guide walks you through selecting a secure Linux distribution, configuring kernel and sysctl parameters, applying boot‑time hardening, managing network and firewall rules, restricting root access, enabling MAC policies, sandboxing applications, and employing advanced memory and entropy techniques to dramatically improve system privacy and resilience against attacks.
Guide Overview
This guide explains how to maximize Linux security and privacy, focusing on hardening the kernel, system services, and user environment.
Choosing a Linux Distribution
Avoid frozen package repositories.
Prefer distributions without Systemd.
Use musl as the default C library.
Prefer LibreSSL over OpenSSL.
Gentoo is recommended for a fully configurable hardened system; Void Linux with musl is a good compromise.
Kernel Hardening
The kernel is the most attractive attack target; use a stable or LTS kernel with caution.
Stable vs LTS
Stable kernels include all security fixes but have a larger attack surface; LTS kernels have fewer features and a smaller attack surface.
Sysctl Settings
sysctl -w $tunable=$valueKey sysctl hardening options include:
kernel.kptr_restrict=2 – hide kernel pointers.
kernel.dmesg_restrict=1 – restrict kernel log access.
kernel.printk=3 3 3 3 – limit console kernel messages.
kernel.unprivileged_bpf_disabled=1 and net.core.bpf_jit_harden=2 – mitigate eBPF abuse.
dev.tty.ldisc_autoload=0 – prevent loading unsafe line disciplines.
vm.unprivileged_userfaultfd=0 – restrict userfaultfd.
kernel.kexec_load_disabled=1 – disable kexec.
kernel.sysrq=4 – limit SysRq.
kernel.unprivileged_userns_clone=0 – restrict user namespaces.
kernel.perf_event_paranoid=3 – restrict performance events.
Boot Parameters
Common hardening boot 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=0Apply them via GRUB, Syslinux, or systemd‑boot as appropriate.
Kernel Self‑Protection
Enable Kernel Self‑Protection (KSPP) options.
Consider Grsecurity or Linux‑hardened patches.
Use Linux Kernel Runtime Guard (LKRG) for runtime integrity.
User Space Hardening
Hideproc and Sysfs
Mount /proc with hidepid=2,gid=proc and restrict sysfs access using tools like hide‑hardware‑info.
MAC (Mandatory Access Control)
Enable AppArmor or SELinux via boot parameters:
apparmor=1 security=apparmor selinux=1 security=selinuxCreate policies with aa-genprof for AppArmor.
Sandboxing
Use Bubblewrap, gVisor, or systemd sandbox options to isolate applications. Example systemd service sandbox:
[Service]
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
ProtectSystem=strict
ProtectHome=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
ProtectKernelLogs=true
ProtectHostname=true
ProtectClock=true
ProtectProc=invisible
PrivateTmp=true
PrivateUsers=yes
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.exampleMemory Allocator Hardening
Use hardened_malloc via LD_PRELOAD or global /etc/ld.so.preload. Adjust kernel config for slab quarantine and increase vm.max_map_count.
Memory‑Safe Languages
Prefer Rust, Swift, or Java for new code to avoid classic C/C++ memory bugs.
Root Account Protection
Empty /etc/securetty to prevent root login on consoles.
Restrict su to the wheel group.
Lock the root password: passwd -l root.
Disable remote root SSH login: PermitRootLogin no.
Increase password hash rounds in /etc/pam.d/passwd (e.g., rounds=65536).
Firewall
Basic iptables policy that drops all inbound traffic:
*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 UDP
-A INPUT -p tcp --tcp-flags FIN,SYN,RST,ACK SYN -m conntrack --ctstate NEW -j TCP
-A INPUT -p udp -j REJECT --reject-with icmp-port-unreachable
-A INPUT -p tcp -j REJECT --reject-with tcp-reset
-A INPUT -j REJECT --reject-with icmp-proto-unreachable
COMMITIdentity and Privacy
Use generic hostnames and usernames.
Set timezone to UTC and locale/keymap to US.
Replace /etc/machine-id with a generic value.
Randomize MAC addresses while preserving the OUI.
Disable IPv6 address autoconfiguration and enable privacy extensions.
Swap and Core Dumps
Set vm.swappiness=1 to minimize swapping.
Disable core dumps via kernel.core_pattern=|/bin/false, systemd /etc/systemd/coredump.conf.d/disable.conf with Storage=none, and * hard core 0 in /etc/security/limits.conf.
Prevent setuid processes from dumping memory: fs.suid_dumpable=0.
PAM Hardening
Enforce strong passwords with pam_pwquality and add delay on failed logins with pam_faildelay (e.g., delay=4000000 for 4 seconds).
Microcode Updates
Install and keep CPU microcode packages up to date to mitigate Spectre, Meltdown, and related CPU bugs.
Entropy Sources
Install haveged and jitterentropy (load jitterentropy_rng module).
Disable trust in RDRAND with random.trust_cpu=off.
Editing Files as Root
Use sudoedit instead of running editors as root. Set EDITOR=nano if desired.
Distribution‑Specific Hardening
Configure APT to use HTTPS mirrors and enable seccomp sandbox: APT::Sandbox::Seccomp "true";.
Set BIOS/UEFI passwords, disable unused boot options, and keep firmware updated.
Protect bootloaders with passwords (GRUB, Syslinux, systemd‑boot) and enable verified boot where possible.
Blacklist dangerous kernel modules (e.g., install dccp /bin/false).
Physical Security
Full‑disk encryption (excluding /boot) and verified boot.
Enable IOMMU ( intel_iommu=on amd_iommu=on) and early PCI DMA disable ( efi=disable_early_pci_dma).
Blacklist Thunderbolt and FireWire modules.
Mitigate cold‑boot attacks by allowing memory to be zeroed on shutdown and using firmware reset‑erase features.
Best Practices
Remove unnecessary software to reduce attack surface.
Keep the system updated automatically.
Avoid leaking any identifying information.
Follow general security and privacy guidelines.
Glossary
Key concepts such as Linux capabilities, SELinux/AppArmor policies, and references to further reading are provided.
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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
