| |

LFCA 104 🐧 System Hardening Basics

System hardening is the process of reducing a system’s attack surface by removing unnecessary software, disabling unused services, configuring secure defaults, and applying restrictive access controls. It is the practical application of security principles — least privilege, defense in depth, and minimization — to a running Linux system. A freshly installed Linux distribution ships with defaults chosen for broad compatibility, not for security. Hardening narrows those defaults to what a specific system actually needs.

The discipline matters because most compromises exploit something that did not need to exist. An open port for a service nobody uses. A default account with a well-known password. A compiler left on a production server. A world-writable directory in a web root. Each unnecessary component is a potential entry point. Hardening removes them before an attacker can find them. The Center for Internet Security (CIS) Benchmarks and the DISA STIGs provide detailed hardening guidance for major Linux distributions, and they are the reference standards against which hardened systems are measured.

This chapter covers the hardening methodology, secure installation practices, package minimization, service and port reduction, account and authentication hardening, filesystem protections, kernel parameter tuning, logging, and the tools used to verify and maintain a hardened state.

Key point: Hardening reduces attack surface by removing what is not needed and restricting what remains. It is an ongoing process, not a one-time task, and CIS Benchmarks provide the reference standard for measuring compliance.


Why system hardening exists

The default configuration problem. Linux distributions enable services and features that many users do not need, because the distribution must work for a wide range of use cases. A desktop-focused distribution may enable a print service, Bluetooth, and a display manager. A server-focused distribution may enable a web server or database. On a system that does not need these, every enabled service is an unnecessary attack surface.

The attack surface problem. Attack surface is the sum of all entry points an attacker can use to interact with a system: open ports, running services, installed packages, user accounts, setuid binaries, and writable files. Reducing attack surface is the most reliable way to reduce risk because it eliminates vulnerabilities rather than mitigating them. A service that is not running cannot be exploited.

The compliance problem. Multiple regulatory and contractual frameworks require evidence of system hardening. PCI DSS requires configuration standards for system components. HIPAA requires protection against unauthorized access. ISO 27001 requires secure configuration baselines. CIS Benchmarks and DISA STIGs provide the prescriptive controls that auditors look for. A system that has not been hardened rarely passes a compliance audit.

The consistency problem. In an organization with dozens or hundreds of servers, inconsistency is a security risk. A server provisioned by one administrator may have different settings than a server provisioned by another. Hardening baselines, encoded as configuration management code, ensure every system meets the same standard. When a new vulnerability requires a configuration change, the baseline is updated once and applied everywhere.

The time-to-exploit problem. Automated scanning tools find vulnerable systems within hours of a service being exposed to the internet. A default installation with SSH password authentication enabled and a weak root password can be compromised within minutes. Hardening reduces the window of exposure by closing the most commonly exploited paths before the system goes into production.


a. Hardening methodology and secure installation

Hardening begins before the operating system is installed, with decisions about what to install. A minimal installation — base system plus only the packages required for the intended role — starts with a smaller attack surface than a full installation with every package group selected.

The methodology follows a consistent pattern. First, inventory what the system needs to do: which services it must run, which users must access it, which network connections it must accept and initiate. Second, remove everything that does not serve those functions. Third, configure what remains with the most restrictive settings that still allow it to function. Fourth, verify the configuration against a known baseline. Fifth, monitor for drift and re-apply as needed.

During installation, choices that reduce attack surface include selecting a minimal package set, enabling disk encryption for systems that may be physically accessible, setting a strong root password and creating an administrative user instead of using root directly, and enabling SELinux or AppArmor from the start. On cloud instances, using a vendor-hardened image or applying a hardening baseline immediately after provisioning reduces the window of vulnerability.

A critical practice is to snapshot or back up the system before hardening begins. Misconfigurations can render a system inaccessible, and a snapshot allows quick recovery without a full reinstall.

b. Package minimization and update management

Every installed package is code that runs on the system and may contain vulnerabilities. Removing packages that are not needed reduces the number of potential vulnerability paths. The package manager provides the tools: apt and dnf on Debian-based and Red Hat-based systems respectively.

Removing unnecessary packages begins with identifying what is installed and why. On a production server, tools like compilers, development headers, and debugging utilities are rarely needed and can be removed. Services like telnet, rsh, and ftp transmit credentials in plaintext and should not be installed. Print services, Bluetooth, and desktop environment packages on servers are unnecessary.

Keeping the remaining packages updated is the other half of package management. Unpatched software is one of the most common initial access vectors. Automatic updates, or at minimum a regular update schedule, ensure that security patches are applied promptly. On Debian and Ubuntu, unattended-upgrades can install security updates automatically. On Red Hat-based systems, dnf-automatic provides similar functionality.

Package integrity matters as well. Using only official repositories, verifying GPG signatures on packages, and avoiding third-party repositories unless necessary all reduce the risk of installing compromised software.

c. Service and port reduction

Running services are the most direct attack surface on a system. Each listening service is a potential entry point. The hardening process identifies every running service, determines whether it is needed, and disables what is not.

Listing running services uses systemctl list-units --type=service and ss -tlnp for listening ports. Each service and each open port should be justified. If a service is not required for the system’s role, it is disabled with systemctl disable --now <service>. If a service is required but should not be reachable from the network, it can be bound to localhost only, or blocked at the firewall.

The firewall is a complementary control. Even if a service is running, the firewall can prevent external access. A default-deny firewall policy that allows only required ports is the standard. On systems using firewalld, the --add-service and --remove-service commands manage access. On systems using iptables or nftables directly, rules are written to permit only specific traffic.

Disabling IPv6 entirely is sometimes recommended, but it is better to configure it correctly than to disable it, because some applications depend on IPv6 and disabling it can cause subtle failures. If IPv6 is not used, it should be disabled in the kernel parameters, not by removing the capability.

d. Account and authentication hardening

User accounts are the primary path for legitimate access, and therefore the primary target for attackers. Hardening accounts begins with removing unnecessary ones. Default accounts created by the distribution or by packages should be removed or locked if they are not needed. The userdel command removes an account; usermod -L locks a password without removing the account; passwd -l does the same.

Password policy is enforced through PAM (Pluggable Authentication Modules) and the login.defs file. Settings include minimum password length, complexity requirements, password expiration, and account lockout after failed attempts. The pam_pwquality module enforces complexity and length. The pam_faillock module locks accounts after a specified number of failed login attempts.

SSH is the most commonly exposed service on Linux servers and requires specific hardening. Key-based authentication should replace password authentication. The PermitRootLogin setting should be no so that root cannot log in directly. PasswordAuthentication should be no once keys are deployed. MaxAuthTries limits brute-force attempts. AllowUsers or AllowGroups restricts which accounts can log in. The SSH configuration lives in /etc/ssh/sshd_config and is validated with sshd -t before restarting the service.

Multi-factor authentication for SSH, using TOTP or hardware keys, adds a second factor that defeats credential theft. The pam_google_authenticator module provides TOTP support.

e. Filesystem protections and permissions

Filesystem hardening focuses on preventing unauthorized modification and limiting the impact of a compromise. The principle is that files should be owned by the appropriate user, have the minimum permissions required, and reside on filesystems with appropriate mount options.

Critical files and directories have expected permissions. /etc/passwd is readable by all but writable only by root. /etc/shadow is readable only by root. /boot is readable but not writable except by root. Home directories should not be world-readable or world-writable. The hardening process audits these and corrects deviations.

Mount options provide additional protection. The nodev option prevents interpretation of device files on a filesystem, nosuid prevents setuid binaries from taking effect, and noexec prevents execution of binaries. Applying these options to filesystems like /tmp, /var/tmp, and /dev/shm limits what an attacker who gains write access to those directories can do. The /etc/fstab file configures mount options.

File integrity monitoring detects unauthorized changes to critical files. Tools like AIDE (Advanced Intrusion Detection Environment) create a baseline of file hashes and attributes, then compare the current state against the baseline. When a system binary changes unexpectedly, AIDE reports it.

f. Kernel parameters and network hardening

The Linux kernel exposes many tunable parameters through sysctl. Some have security implications. The CIS Benchmarks specify settings for network stack behavior, memory protection, and process restrictions.

Network-related settings include disabling IP forwarding unless the system is a router, disabling source routing, ignoring ICMP redirects, and enabling TCP SYN cookies to mitigate SYN flood attacks. These settings are configured in /etc/sysctl.d/ files and applied with sysctl --system.

Memory and process protections include enabling ASLR (Address Space Layout Randomization), restricting access to kernel logs and pointers, and preventing users from creating core dumps that might contain sensitive data. The kernel.randomize_va_space parameter controls ASLR, and kernel.dmesg_restrict limits access to kernel messages.

The sysctl settings are numerous, and the CIS Benchmarks provide the specific values for each distribution. Applying them systematically, preferably through a configuration management tool, ensures consistency.

g. Logging, auditing, and verification

Hardening is incomplete without visibility into what the system is doing. rsyslog or journald collects system logs. auditd records system calls and file access for security-relevant events. Together they provide the data needed to detect and investigate incidents.

Logs should be sent to a remote logging server so that an attacker who compromises the local system cannot erase the evidence of their activity. The rsyslog configuration supports remote forwarding. journald can also forward to a remote host.

Verification is the final step of hardening. Tools like Lynis audit a system against a set of hardening guidelines and report findings. OpenSCAP evaluates a system against a SCAP profile, such as the CIS Benchmark or a DISA STIG profile, and produces a compliance report. These tools identify gaps that manual review might miss.

Maintaining the hardened state requires periodic re-verification. Configuration drift happens as administrators make changes, packages are installed, and services are enabled. A scheduled scan with Lynis or OpenSCAP detects drift and triggers remediation.


Complete Example Session

# ============================================
# PART 1: MINIMIZE INSTALLED PACKAGES
# ============================================
# List installed packages and remove unnecessary ones.

dpkg --list | wc -l
sudo apt remove --purge telnet rsh-client ftp
sudo apt autoremove --purge
# ============================================
# PART 2: LIST RUNNING SERVICES
# ============================================
# Identify services and listening ports.

systemctl list-units --type=service --state=running
sudo ss -tlnp
# ============================================
# PART 3: DISABLE UNNECESSARY SERVICES
# ============================================
# Stop and disable services that are not needed.

sudo systemctl disable --now cups
sudo systemctl disable --now avahi-daemon
# ============================================
# PART 4: CONFIGURE THE FIREWALL
# ============================================
# Default deny, allow only required ports.

sudo firewall-cmd --permanent --remove-service=dhcpv6-client
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --reload
# ============================================
# PART 5: HARDEN SSH
# ============================================
# Key-based auth, no root login, no passwords.

sudo tee /etc/ssh/sshd_config.d/99-hardening.conf << 'EOF'
PermitRootLogin no
PasswordAuthentication no
MaxAuthTries 3
AllowGroups ssh-users
EOF
sudo sshd -t
sudo systemctl reload sshd
# ============================================
# PART 6: ENFORCE PASSWORD POLICY
# ============================================
# Minimum length, complexity, expiration.

sudo apt install libpam-pwquality
sudo tee /etc/security/pwquality.conf << 'EOF'
minlen = 14
dcredit = -1
ucredit = -1
ocredit = -1
lcredit = -1
EOF
# ============================================
# PART 7: APPLY FILESYSTEM MOUNT OPTIONS
# ============================================
# Add nodev, nosuid, noexec to /tmp.

sudo tee -a /etc/fstab << 'EOF'
tmpfs /tmp tmpfs defaults,nodev,nosuid,noexec 0 0
EOF
sudo mount -o remount /tmp
# ============================================
# PART 8: APPLY KERNEL HARDENING
# ============================================
# Network and memory protections.

sudo tee /etc/sysctl.d/99-hardening.conf << 'EOF'
net.ipv4.ip_forward = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.tcp_syncookies = 1
kernel.randomize_va_space = 2
kernel.dmesg_restrict = 1
EOF
sudo sysctl --system
# ============================================
# PART 9: AUDIT FOR WORLD-WRITABLE FILES
# ============================================
# These are potential modification paths.

find / -type f -perm -0002 -not -path "/proc/*" 2>/dev/null
# ============================================
# PART 10: VERIFY WITH LYNIS
# ============================================
# Audit the system and review findings.

sudo apt install lynis
sudo lynis audit system
# Review /var/log/lynis.log and /var/log/lynis-report.dat

These ten parts cover the practical application of hardening: package minimization, service reduction, firewall configuration, SSH hardening, password policy, filesystem mount options, kernel parameters, world-writable file auditing, and verification with Lynis. Each step reduces attack surface, and the verification step confirms that the changes took effect.


Quick Reference

Hardening Categories

CategoryActions
PackagesRemove unnecessary; update regularly
ServicesDisable unused; bind to localhost; firewall
AccountsRemove defaults; strong passwords; lockout
SSHKey auth; no root login; restrict users
FilesystemMinimum permissions; nodev/nosuid/noexec
Kernelsysctl network and memory protections
LoggingRemote forwarding; auditd
VerificationLynis, OpenSCAP

Key Configuration Files

FilePurpose
/etc/ssh/sshd_configSSH daemon configuration
/etc/sysctl.d/*.confKernel parameters
/etc/security/pwquality.confPassword complexity
/etc/fstabMount options
/etc/security/limits.confResource limits
/etc/audit/auditd.confAudit daemon configuration

Essential Hardening Commands

CommandPurpose
ss -tlnpList listening ports
systemctl disable --nowDisable a service
firewall-cmd --permanentConfigure firewall persistently
sshd -tValidate SSH configuration
sysctl --systemApply kernel parameters
find / -perm -0002Find world-writable files
lynis audit systemAudit hardening state

CIS Benchmark Control Families

ControlFocus
1Initial setup (filesystem, updates, users)
2Services (server and client)
3Network configuration
4Logging and auditing
5Access, authentication, authorization
6System maintenance

Best Practices

✅ Do This:

sudo apt remove telnet rsh-client                 # Remove insecure tools
sudo systemctl disable --now cups                 # Disable unused services
# /etc/ssh/sshd_config.d/99-hardening.conf
PermitRootLogin no                                # No direct root SSH
PasswordAuthentication no                         # Key-based auth only
tmpfs /tmp tmpfs defaults,nodev,nosuid,noexec    # Restrict /tmp
sudo lynis audit system                           # Verify hardening

❌ Don’t Do This:

systemctl disable --now firewalld                 # ❌ Disabling firewall
PermitRootLogin yes                               # ❌ Root SSH allowed
chmod 777 /var/www                                # ❌ World-writable
mount -o remount,exec /tmp                        # ❌ Allows execution in /tmp
# No remote logging                               # ❌ Logs lost on compromise

Common Pitfalls

PitfallWhy It HappensFix
Locked out after SSH hardeningPasswordAuthentication no before keys deployedTest keys in a separate session first
Service breaks after hardeningRequired service disabledReview dependencies before disabling
Application fails after mount optionsnoexec on a directory holding executablesApply noexec only to data directories
Kernel parameter causes network issueip_forward = 0 on a routerApply only to non-routing systems
Firewall blocks legitimate trafficRule missingUse firewall-cmd --add-service for required services
Hardening revertsConfiguration driftUse configuration management; re-verify

Real-World Examples

1. Remove Telnet and rsh

sudo apt remove --purge telnet rsh-client

2. Disable Print Service on Server

sudo systemctl disable --now cups
sudo systemctl mask cups

3. SSH Key-Only Authentication

# /etc/ssh/sshd_config.d/99-hardening.conf
PasswordAuthentication no
PubkeyAuthentication yes
PermitRootLogin no

4. Firewall Default Deny

sudo firewall-cmd --set-default-zone=drop
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --reload

5. Restrict /tmp

tmpfs /tmp tmpfs defaults,nodev,nosuid,noexec 0 0

6. Enable TCP SYN Cookies

echo "net.ipv4.tcp_syncookies = 1" | sudo tee /etc/sysctl.d/99-syn.conf
sudo sysctl --system

7. Enable Auditd

sudo apt install auditd
sudo systemctl enable --now auditd

8. Remote Log Forwarding

# /etc/rsyslog.d/50-remote.conf
*.* @@logserver.example.com:514

9. Lynis Audit

sudo lynis audit system
grep "Hardening index" /var/log/lynis.log

10. AIDE Baseline

sudo apt install aide
sudo aideinit
sudo mv /var/lib/aide/aide.db.new /var/lib/aide/aide.db

Visual

Hardening Layers

┌──────────────────────────────────────────────────────────────┐
│  HARDENING AT EVERY LAYER                                    │
│                                                              │
│  ┌────────────────────────────────────────────────────────┐  │
│  │  PACKAGE LAYER                                         │  │
│  │  Remove unnecessary; update regularly                  │  │
│  └────────────────────────────────────────────────────────┘  │
│                          │                                   │
│                          ▼                                   │
│  ┌────────────────────────────────────────────────────────┐  │
│  │  SERVICE LAYER                                         │  │
│  │  Disable unused; bind to localhost                     │  │
│  └────────────────────────────────────────────────────────┘  │
│                          │                                   │
│                          ▼                                   │
│  ┌────────────────────────────────────────────────────────┐  │
│  │  NETWORK LAYER                                         │  │
│  │  Default-deny firewall; minimal open ports             │  │
│  └────────────────────────────────────────────────────────┘  │
│                          │                                   │
│                          ▼                                   │
│  ┌────────────────────────────────────────────────────────┐  │
│  │  ACCOUNT LAYER                                         │  │
│  │  Remove defaults; strong passwords; key auth           │  │
│  └────────────────────────────────────────────────────────┘  │
│                          │                                   │
│                          ▼                                   │
│  ┌────────────────────────────────────────────────────────┐  │
│  │  FILESYSTEM LAYER                                      │  │
│  │  Minimum permissions; restrictive mount options        │  │
│  └────────────────────────────────────────────────────────┘  │
│                          │                                   │
│                          ▼                                   │
│  ┌────────────────────────────────────────────────────────┐  │
│  │  KERNEL LAYER                                          │  │
│  │  sysctl network and memory protections                 │  │
│  └────────────────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────────────┘

Attack Surface Reduction

┌──────────────────────────────────────────────────────────────┐
│  DEFAULT INSTALL vs HARDENED SYSTEM                          │
│                                                              │
│  DEFAULT:                                                    │
│  ┌────────────────────────────────────────────────────────┐  │
│  │  Open ports: 22, 80, 111, 631, 5353                    │  │
│  │  Services: sshd, cups, rpcbind, avahi                  │  │
│  │  Packages: ~1500 installed                             │  │
│  │  SSH: password auth, root login enabled                │  │
│  │  Firewall: disabled or permissive                      │  │
│  └────────────────────────────────────────────────────────┘  │
│                                                              │
│  HARDENED:                                                   │
│  ┌────────────────────────────────────────────────────────┐  │
│  │  Open ports: 22 (restricted)                           │  │
│  │  Services: sshd only                                   │  │
│  │  Packages: ~400 installed                              │  │
│  │  SSH: key auth only, root login disabled               │  │
│  │  Firewall: default deny                                │  │
│  └────────────────────────────────────────────────────────┘  │
│                                                              │
│  Fewer entry points, less code running, tighter defaults.    │
└──────────────────────────────────────────────────────────────┘

Hardening Workflow

┌──────────────────────────────────────────────────────────────┐
│  THE HARDENING PROCESS                                       │
│                                                              │
│  1. INVENTORY                                                │
│     └── What does this system need to do?                    │
│                                                              │
│  2. REMOVE                                                   │
│     └── Delete packages and services not needed              │
│                                                              │
│  3. RESTRICT                                                 │
│     └── Configure remaining components minimally             │
│                                                              │
│  4. VERIFY                                                   │
│     └── Lynis, OpenSCAP against CIS Benchmark                │
│                                                              │
│  5. MONITOR                                                  │
│     └── Detect drift; re-apply as needed                     │
│                                                              │
│  Hardening is not a one-time task.                           │
│  Systems drift; new vulnerabilities appear;                  │
│  requirements change. The cycle repeats.                     │
└──────────────────────────────────────────────────────────────┘

CIS Benchmark Coverage

┌──────────────────────────────────────────────────────────────┐
│  CIS BENCHMARK CONTROL FAMILIES                              │
│                                                              │
│  ┌────────────────────────────────────────────────────────┐  │
│  │  1. INITIAL SETUP                                      │  │
│  │  Filesystem config, updates, users, sudo               │  │
│  └────────────────────────────────────────────────────────┘  │
│                          │                                   │
│                          ▼                                   │
│  ┌────────────────────────────────────────────────────────┐  │
│  │  2. SERVICES                                           │  │
│  │  Server services, client services                      │  │
│  └────────────────────────────────────────────────────────┘  │
│                          │                                   │
│                          ▼                                   │
│  ┌────────────────────────────────────────────────────────┐  │
│  │  3. NETWORK CONFIGURATION                              │  │
│  │  Kernel parameters, firewall                           │  │
│  └────────────────────────────────────────────────────────┘  │
│                          │                                   │
│                          ▼                                   │
│  ┌────────────────────────────────────────────────────────┐  │
│  │  4. LOGGING AND AUDITING                               │  │
│  │  auditd, rsyslog, log rotation                         │  │
│  └────────────────────────────────────────────────────────┘  │
│                          │                                   │
│                          ▼                                   │
│  ┌────────────────────────────────────────────────────────┐  │
│  │  5. ACCESS, AUTH, AUTHORIZATION                        │  │
│  │  SSH, PAM, sudo                                        │  │
│  └────────────────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────────────┘

Summary

ItemValue
Hardening definitionReducing attack surface by removing and restricting
MethodologyInventory, remove, restrict, verify, monitor
Package hardeningRemove unnecessary; update regularly
Service hardeningDisable unused; firewall default-deny
SSH hardeningKey auth, no root login, restrict users
Password policyPAM pwquality; length and complexity
FilesystemMinimum permissions; nodev/nosuid/noexec
Kernelsysctl network and memory protections
LoggingRemote forwarding; auditd
VerificationLynis, OpenSCAP
Reference standardCIS Benchmarks, DISA STIGs

Key takeaways:

  • Hardening reduces attack surface. Every package removed, service disabled, and port closed eliminates a potential entry point that an attacker could exploit.
  • Start from a minimal installation. The fewer packages installed, the smaller the attack surface and the fewer vulnerabilities to manage.
  • Services are the primary attack surface. List every running service and listening port, justify each one, and disable everything that is not required.
  • SSH is the most exposed service and requires specific hardening. Key-based authentication, no root login, restricted user access, and validation with sshd -t before applying changes.
  • Account hygiene is fundamental. Remove default accounts, enforce strong passwords, lock accounts after failed attempts, and review access regularly.
  • Mount options add defense in depth. nodev, nosuid, and noexec on data directories limit what an attacker who gains write access can do.
  • Kernel parameters tune security behavior. sysctl settings control network stack behavior, memory protections, and process restrictions.
  • Verification is part of hardening. Lynis and OpenSCAP compare the system against a baseline and report gaps that manual review might miss.
  • Hardening is ongoing. Configuration drift, new vulnerabilities, and changing requirements mean the process repeats.

Remember: System hardening is the discipline of making a system do exactly what it needs to do and nothing more. It begins with a minimal installation, continues through package and service reduction, extends into account, filesystem, and kernel configuration, and is verified against a known standard. The CIS Benchmarks provide the reference for what “hardened” means on major Linux distributions, and tools like Lynis and OpenSCAP measure compliance. Hardening is not a one-time task but a cycle: inventory what the system needs, remove what it does not, restrict what remains, verify the result, and monitor for drift. Each layer of hardening reduces the attack surface, and together they make a system that is significantly more difficult to compromise than a default installation.



Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!