
Linux Hardening
Linux system hardening techniques covering attack surface reduction, access controls, authentication, network security, and monitoring for defensive security operations.
Introduction
Linux is only as secure as its configuration. Default installations favor usability, leaving attack surface that offensive operators routinely exploit: unpatched software, weak authentication, misconfigured services, and excessive privileges.
This guide covers practical hardening techniques from a defensive perspective, addressing the common vulnerabilities that lead to initial access and privilege escalation.
Attacker Perspective
Understanding attacker methodology helps prioritize defenses. The techniques here address vulnerabilities commonly exploited during penetration tests and real-world attacks.
System Updates and Patching
Unpatched vulnerabilities remain a primary attack vector. Automate updates where possible and maintain a patch management process.
Automated Updates
# Debian/Ubuntu - Enable unattended upgrades
apt install unattended-upgrades
dpkg-reconfigure -plow unattended-upgrades
# RHEL/CentOS - Enable automatic updates
dnf install dnf-automatic
systemctl enable --now dnf-automatic.timerKernel Live Patching
For systems requiring high uptime, consider live patching solutions:
- Ubuntu Livepatch - Free for up to 3 systems
- RHEL kpatch - Included with RHEL subscription
- KernelCare - Third-party commercial solution
# Ubuntu Livepatch
snap install canonical-livepatch
canonical-livepatch enable <token>
# Check patch status
canonical-livepatch statusVulnerability Scanning
Regular scanning identifies missing patches and misconfigurations:
# OpenVAS/Greenbone - Network vulnerability scanner
# Nessus - Commercial scanner
# Lynis - Local system auditing
# Run Lynis audit
lynis audit system
# Check for known vulnerabilities
apt list --upgradable
dnf check-update --securityAttack Surface Reduction
Disable Unnecessary Services
Every running service is a potential entry point. Audit and disable services that aren't required:
# List enabled services
systemctl list-unit-files --state=enabled
# Disable unnecessary services
systemctl disable --now cups.service
systemctl disable --now avahi-daemon.service
systemctl disable --now bluetooth.service
# Common services to evaluate:
# - cups (printing)
# - avahi-daemon (mDNS)
# - rpcbind (NFS)
# - telnet (insecure)
# - ftp (use sftp instead)Remove Unnecessary Packages
# Debian/Ubuntu - Remove unused packages
apt autoremove
apt purge <package>
# RHEL/CentOS
dnf autoremove
dnf remove <package>
# Identify packages by purpose
dpkg -l | grep -E "telnet|ftp|rsh"Restrict Compiler Access
Compilers on production systems enable attackers to build exploits locally:
# Restrict gcc to root only
chmod 700 /usr/bin/gcc
chmod 700 /usr/bin/g++
chmod 700 /usr/bin/make
# Or remove entirely on production systems
apt remove build-essentialAccess Control
User Account Hardening
# Lock unused system accounts
passwd -l <username>
# Set password expiration
chage -M 90 <username> # Maximum 90 days
chage -m 7 <username> # Minimum 7 days between changes
chage -W 14 <username> # Warn 14 days before expiration
# View password aging
chage -l <username>
# Disable empty passwords
sed -i 's/nullok//g' /etc/pam.d/common-authSudo Configuration
Misconfigured sudo is a common privilege escalation vector. Apply least privilege:
# /etc/sudoers - Use visudo to edit
# BAD - Overly permissive
user ALL=(ALL) NOPASSWD: ALL
# GOOD - Specific commands only
user ALL=(root) /usr/bin/systemctl restart nginx
user ALL=(root) /usr/bin/journalctl -u nginx
# Require password for sudo
Defaults timestamp_timeout=5
Defaults passwd_tries=3
# Log all sudo commands
Defaults logfile="/var/log/sudo.log"
Defaults log_input, log_outputReview dangerous sudo configurations:
# Check for NOPASSWD entries
grep -r "NOPASSWD" /etc/sudoers /etc/sudoers.d/
# Check for ALL permissions
grep -r "ALL=(ALL)" /etc/sudoers /etc/sudoers.d/Mandatory Access Control
SELinux and AppArmor provide kernel-level access controls beyond traditional Unix permissions.
SELinux (RHEL/CentOS/Fedora):
# Check SELinux status
getenforce
sestatus
# Enable SELinux (if disabled)
# Edit /etc/selinux/config
SELINUX=enforcing
# Troubleshoot denials
ausearch -m AVC -ts recent
sealert -a /var/log/audit/audit.logAppArmor (Debian/Ubuntu):
# Check AppArmor status
aa-status
# Enable profile
aa-enforce /etc/apparmor.d/usr.sbin.nginx
# Troubleshoot denials
dmesg | grep apparmorAuthentication Hardening
SSH Configuration
SSH is the primary remote access method and frequent attack target:
# /etc/ssh/sshd_config
# Disable root login
PermitRootLogin no
# Disable password authentication (use keys)
PasswordAuthentication no
PubkeyAuthentication yes
# Limit users who can SSH
AllowUsers admin deployer
# Or use groups
AllowGroups sshusers
# Disable empty passwords
PermitEmptyPasswords no
# Use strong ciphers and MACs
Ciphers [email protected],[email protected]
MACs [email protected],[email protected]
# Limit authentication attempts
MaxAuthTries 3
# Set idle timeout
ClientAliveInterval 300
ClientAliveCountMax 2
# Apply changes
systemctl restart sshdSSH Key Management
# Generate strong keys (Ed25519 preferred)
ssh-keygen -t ed25519 -C "user@host"
# Set restrictive permissions
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chmod 600 ~/.ssh/id_ed25519
# Restrict authorized_keys options
# ~/.ssh/authorized_keys
from="192.168.1.0/24",no-agent-forwarding,no-port-forwarding ssh-ed25519 AAAA...Multi-Factor Authentication
# Install Google Authenticator PAM module
apt install libpam-google-authenticator
# Configure for user
google-authenticator
# Enable in PAM
# /etc/pam.d/sshd
auth required pam_google_authenticator.so
# /etc/ssh/sshd_config
ChallengeResponseAuthentication yes
AuthenticationMethods publickey,keyboard-interactivePassword Policy
# Install password quality module
apt install libpam-pwquality
# /etc/security/pwquality.conf
minlen = 14
dcredit = -1 # Require digit
ucredit = -1 # Require uppercase
lcredit = -1 # Require lowercase
ocredit = -1 # Require special character
maxrepeat = 3 # Max consecutive identical characters
# Account lockout - /etc/pam.d/common-auth
auth required pam_faillock.so preauth silent deny=5 unlock_time=900
auth required pam_faillock.so authfail deny=5 unlock_time=900Network Security
Firewall Configuration
Use host-based firewalls to limit exposure:
iptables:
# Default deny incoming
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# Allow established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow loopback
iptables -A INPUT -i lo -j ACCEPT
# Allow SSH from specific network
iptables -A INPUT -p tcp --dport 22 -s 10.0.0.0/8 -j ACCEPT
# Save rules
iptables-save > /etc/iptables/rules.v4firewalld:
# Set default zone
firewall-cmd --set-default-zone=drop
# Allow SSH from specific source
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.0.0.0/8" port port="22" protocol="tcp" accept'
# Reload
firewall-cmd --reloadDisable IPv6 (If Not Used)
# /etc/sysctl.conf
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
# Apply
sysctl -pNetwork Hardening
# /etc/sysctl.conf
# Disable IP forwarding (unless router/gateway)
net.ipv4.ip_forward = 0
# Ignore ICMP redirects
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
# Ignore source-routed packets
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
# Enable SYN cookies (DoS protection)
net.ipv4.tcp_syncookies = 1
# Log martian packets
net.ipv4.conf.all.log_martians = 1
# Apply
sysctl -pFile System Security
Mount Options
# /etc/fstab - Add security options
# /tmp - noexec prevents running executables
tmpfs /tmp tmpfs defaults,noexec,nosuid,nodev 0 0
# /var/tmp
tmpfs /var/tmp tmpfs defaults,noexec,nosuid,nodev 0 0
# /home - nosuid prevents setuid
/dev/sda2 /home ext4 defaults,nosuid,nodev 0 2SUID/SGID Audit
SUID binaries are common privilege escalation targets:
# Find all SUID files
find / -perm -4000 -type f 2>/dev/null
# Find all SGID files
find / -perm -2000 -type f 2>/dev/null
# Remove unnecessary SUID
chmod u-s /usr/bin/unnecessary-binary
# Essential SUID binaries (don't remove):
# /usr/bin/sudo, /usr/bin/passwd, /usr/bin/suWorld-Writable Files
# Find world-writable files
find / -perm -002 -type f 2>/dev/null
# Find world-writable directories (excluding /tmp)
find / -perm -002 -type d ! -path "/tmp/*" ! -path "/var/tmp/*" 2>/dev/null
# Fix permissions
chmod o-w /path/to/fileMonitoring and Detection
Audit Logging
# Install auditd
apt install auditd
# /etc/audit/rules.d/audit.rules
# Log sudo usage
-w /etc/sudoers -p wa -k sudoers
-w /etc/sudoers.d/ -p wa -k sudoers
# Log passwd changes
-w /etc/passwd -p wa -k passwd_changes
-w /etc/shadow -p wa -k shadow_changes
# Log SSH config changes
-w /etc/ssh/sshd_config -p wa -k sshd_config
# Log privilege escalation attempts
-a always,exit -F arch=b64 -S execve -C uid!=euid -F euid=0 -k privilege_escalation
# Apply rules
augenrules --loadIntrusion Detection
# AIDE - File integrity monitoring
apt install aide
aideinit
aide --check
# OSSEC/Wazuh - Host-based IDS
# Provides log analysis, file integrity, rootkit detectionLog Management
# Centralize logs with rsyslog
# /etc/rsyslog.conf
*.* @@logserver.example.com:514
# Retain logs
# /etc/logrotate.d/rsyslog
rotate 90
compressSecurity Benchmarks
Apply established security baselines:
- CIS Benchmarks - Industry-standard hardening guides
- STIG - DoD Security Technical Implementation Guides
- Lynis - Automated security auditing
# Run Lynis for compliance check
lynis audit system --pentest
# Review hardening index score
# Target: 80+ for production systemsQuick Reference: Hardening Checklist
- Enable automatic security updates
- Disable unnecessary services
- Configure sudo with least privilege
- Disable SSH root login and password authentication
- Enable SELinux/AppArmor
- Configure host firewall (default deny)
- Set secure mount options (/tmp noexec)
- Audit SUID binaries
- Enable audit logging
- Implement password policy
- Deploy file integrity monitoring
Related Resources
- Sudo Misconfigurations - Common sudo security issues
- Capabilities - Linux capability abuse
- Privileged Groups - Group membership escalation
- Cron Job Abuse - Scheduled task exploitation
References
MITRE ATT&CK Techniques (Defensive Context)
- T1548 - Abuse Elevation Control Mechanism - Sudo/SUID abuse
- T1068 - Exploitation for Privilege Escalation - Kernel exploits
- T1070 - Indicator Removal - Log tampering
- T1078 - Valid Accounts - Credential abuse
- T1021.004 - Remote Services: SSH - SSH attacks
Common Weakness Enumeration
- CWE-250 - Execution with Unnecessary Privileges - Least privilege violations
- CWE-269 - Improper Privilege Management - Access control issues
- CWE-732 - Incorrect Permission Assignment - File permissions
Official Documentation
Last updated on
Linux Cron Job Abuse for Privilege Escalation and Persistence
Comprehensive guide to exploiting cron job misconfigurations for privilege escalation and persistence, covering detection methods, exploitation techniques, and hardening strategies.
Linux Kernel Exploits
Guide to identifying and exploiting Linux kernel vulnerabilities for privilege escalation, including enumeration techniques, common exploits, and safety considerations.