Table of Contents
- Understanding Linux Web Server Hardening
- Pre-Hardening Preparation
- Operating System (OS) Hardening
- Web Server-Specific Hardening
- Network Security Hardening
- User and Access Control Hardening
- File System and Permission Hardening
- Security Monitoring and Logging
- Advanced Hardening Techniques
- Conclusion
- References
1. Understanding Linux Web Server Hardening
Server hardening is a proactive approach to security that involves:
- Reducing the attack surface: Disabling unused services, ports, and software.
- Enforcing least privilege: Restricting user and process permissions to the minimum required.
- Patching vulnerabilities: Regularly updating software to fix known flaws.
- Securing configurations: Hardening default settings (e.g., hiding version info, disabling weak protocols).
A “layered” approach is critical—no single technique guarantees security, but combining multiple strategies creates a robust defense.
2. Pre-Hardening Preparation
Before diving into hardening, lay the groundwork to avoid misconfiguration or data loss:
2.1 Inventory and Documentation
- Document your stack: Note the OS version (e.g., Ubuntu 22.04, CentOS Stream 9), web server (Apache, Nginx), and dependencies (PHP, MySQL).
- Map services and ports: Identify running services (e.g.,
ss -tulpn) and open ports (e.g.,netstat -tulpn) to prioritize hardening.
2.2 Back Up Critical Data
- Create encrypted, offsite backups of configurations (e.g.,
/etc/apache2/,/etc/nginx/), databases, and web content. Test restoration regularly to ensure backups are valid.
2.3 Test in a Staging Environment
- Apply hardening steps to a staging server first to avoid breaking production. Use tools like
vagrantor Docker to replicate your production environment.
3. Operating System (OS) Hardening
The OS is the foundation of your server—securing it minimizes low-level vulnerabilities.
3.1 Update the System
Outdated software is a top attack vector. Automate security updates:
- Debian/Ubuntu:
sudo apt update && sudo apt upgrade -y sudo apt install unattended-upgrades sudo dpkg-reconfigure -plow unattended-upgrades # Enable auto-updates - RHEL/CentOS:
sudo dnf update -y sudo dnf install dnf-automatic sudo systemctl enable --now dnf-automatic.timer
3.2 Remove Unnecessary Software
Uninstall unused packages to reduce bloat and vulnerabilities:
# List installed packages
sudo apt list --installed # Debian/Ubuntu
sudo dnf list installed # RHEL/CentOS
# Purge unused packages (e.g., telnet, ftp)
sudo apt purge telnet ftp -y
sudo dnf remove telnet ftp -y
3.3 Disable Unused Services
Stop and disable services not critical to your web server (e.g., cups, bluetooth):
# List running services
sudo systemctl list-unit-files --type=service --state=enabled
# Disable a service (e.g., cups)
sudo systemctl stop cups
sudo systemctl disable cups
3.4 Kernel Hardening
Harden the Linux kernel using sysctl to mitigate network and memory exploits. Edit /etc/sysctl.conf or create a custom file in /etc/sysctl.d/:
# /etc/sysctl.d/hardening.conf
net.ipv4.tcp_syncookies = 1 # Mitigate SYN floods
net.ipv4.icmp_echo_ignore_all = 1 # Block ICMP (ping) requests
net.ipv4.conf.all.rp_filter = 1 # Enable reverse path filtering
net.ipv4.conf.all.forwarding = 0 # Disable IP forwarding (if not a router)
fs.protected_hardlinks = 1 # Prevent hardlink attacks
fs.protected_symlinks = 1 # Prevent symlink attacks
kernel.randomize_va_space = 2 # Enable ASLR (Address Space Layout Randomization)
Apply changes: sudo sysctl -p /etc/sysctl.d/hardening.conf.
3.5 Secure Boot and GRUB
- UEFI Secure Boot: Enable in BIOS/UEFI to prevent unsigned kernels or malware from loading during boot.
- GRUB Password: Protect the bootloader to block unauthorized kernel modifications:
sudo grub-mkpasswd-pbkdf2 # Generate a hashed password sudo nano /etc/grub.d/40_custom # Add: set superusers="admin" password_pbkdf2 admin <hashed_password> sudo update-grub
3.6 File System Security
Use fstab to enforce secure mount options (e.g., noexec, nosuid on temporary directories):
# /etc/fstab (example entries)
tmpfs /tmp tmpfs defaults,noexec,nosuid,size=1G 0 0
tmpfs /var/tmp tmpfs defaults,noexec,nosuid,size=512M 0 0
/dev/sda1 / ext4 defaults,nodev 0 1 # nodev: No device files on /
4. Web Server-Specific Hardening
Web servers (Apache, Nginx) are the frontline—harden them to block web-based attacks.
4.1 Apache Hardening
4.1.1 Hide Version Information
Attackers use version info to exploit known vulnerabilities. Edit /etc/apache2/conf-available/security.conf:
ServerTokens Prod # Only show "Apache" (no version)
ServerSignature Off # Disable server signature in error pages
Enable the config: sudo a2enconf security && sudo systemctl restart apache2.
4.1.2 Disable Directory Listing
Prevent users from browsing file directories. In /etc/apache2/apache2.conf or .htaccess:
<Directory /var/www/html>
Options -Indexes # Disable directory listing
</Directory>
4.1.3 Enable ModSecurity (WAF)
ModSecurity is an open-source Web Application Firewall (WAF) that blocks SQLi, XSS, and more:
sudo apt install libapache2-mod-security2 -y
sudo cp /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
sudo sed -i 's/SecRuleEngine DetectionOnly/SecRuleEngine On/' /etc/modsecurity/modsecurity.conf
sudo systemctl restart apache2
4.1.4 Secure HTTP Headers
Use mod_headers to enforce security headers (e.g., HSTS, CSP). Edit /etc/apache2/conf-available/security.conf:
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" # HSTS
Header set Content-Security-Policy "default-src 'self'; script-src 'self'" # CSP
Header set X-Content-Type-Options "nosniff" # Block MIME sniffing
Header set X-Frame-Options "DENY" # Prevent clickjacking
4.2 Nginx Hardening
4.2.1 Hide Version Information
Edit /etc/nginx/nginx.conf and add server_tokens off; in the http block:
http {
server_tokens off; # Remove version from responses
...
}
4.2.2 Rate Limiting
Prevent DDoS or brute-force attacks with limit_req:
http {
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s; # 10 requests/second
server {
location / {
limit_req zone=mylimit burst=20 nodelay; # Allow 20 bursts
}
}
}
4.2.3 Secure Headers
Add headers to /etc/nginx/nginx.conf or your site’s config:
server {
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header Content-Security-Policy "default-src 'self'";
add_header X-Content-Type-Options "nosniff";
add_header X-Frame-Options "DENY";
}
4.2.4 Enable ModSecurity for Nginx
Integrate ModSecurity with Nginx using the modsecurity-nginx connector:
sudo apt install libmodsecurity3 nginx-module-modsecurity -y
Edit /etc/nginx/nginx.conf to load the module:
load_module modules/ngx_http_modsecurity_module.so;
http {
modsecurity on;
modsecurity_rules_file /etc/modsecurity/main.conf;
}
5. Network Security Hardening
Secure network access to block unauthorized traffic and mitigate attacks.
5.1 Configure a Firewall
Use ufw (Uncomplicated Firewall) or iptables to allow only essential ports (e.g., 80/TCP, 443/TCP for HTTP/HTTPS, 22/TCP for SSH):
# UFW setup
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp # SSH (restrict later!)
sudo ufw allow 80/tcp # HTTP
sudo ufw allow 443/tcp # HTTPS
sudo ufw enable
sudo ufw status
5.2 Harden SSH Access
SSH is a common entry point—lock it down:
- Disable password authentication: Use SSH keys instead. Edit
/etc/ssh/sshd_config:PasswordAuthentication no PubkeyAuthentication yes - Restrict SSH users: Allow only specific users (e.g.,
webadmin):AllowUsers [email protected]/24 # Restrict to local subnet - Change SSH port: Reduce brute-force attempts by using a non-default port (e.g., 2222):
Port 2222 - Enable 2FA: Use
google-authenticatorfor two-factor authentication:
Editsudo apt install libpam-google-authenticator -y google-authenticator # Follow prompts to generate QR code/etc/pam.d/sshd:auth required pam_google_authenticator.so
5.3 Block DDoS Attacks
- Rate limiting: Use
iptablesto limit connections per IP:sudo iptables -A INPUT -p tcp --dport 80 -m connlimit --connlimit-above 10 -j DROP - Cloud protection: Use Cloudflare or Akamai to absorb DDoS traffic before it reaches your server.
6. User and Access Control Hardening
Limit user privileges to prevent privilege escalation attacks.
6.1 Minimize User Accounts
Delete or disable unused accounts (e.g., guest, old admin accounts):
sudo userdel -r olduser # Delete user and home directory
sudo passwd -l olduser # Lock account if deletion isn't possible
6.2 Enforce Strong Passwords
Use pam_cracklib to enforce password complexity (length, special chars):
- Debian/Ubuntu: Edit
/etc/pam.d/common-password:password required pam_cracklib.so minlen=12 ucredit=-1 lcredit=-1 dcredit=-1 ocredit=-1 - RHEL/CentOS: Edit
/etc/pam.d/system-auth:password required pam_pwquality.so minlen=12 ucredit=-1 lcredit=-1 dcredit=-1 ocredit=-1
6.3 Restrict Sudo Access
Use visudo to grant sudo privileges only to essential users, with least privilege:
sudo visudo
Add:
webadmin ALL=(ALL) /usr/bin/systemctl restart apache2, /usr/bin/apt update # Restrict commands
7. File System and Permission Hardening
Incorrect permissions allow attackers to modify critical files—enforce strict controls.
7.1 Set Proper File Permissions
- Web files: Owned by a non-root user (e.g.,
www-data), with read-only access for the web server:sudo chown -R www-data:www-data /var/www/html sudo find /var/www/html -type d -exec chmod 755 {} \; # Directories: rwxr-xr-x sudo find /var/www/html -type f -exec chmod 644 {} \; # Files: rw-r--r-- - Critical system files: Make
/etc/passwd,/etc/shadow, and/etc/sudoersimmutable withchattr:sudo chattr +i /etc/passwd /etc/shadow /etc/sudoers
7.2 Audit for World-Writable Files
World-writable files (permissions 777) are high-risk. Find and fix them:
sudo find / -perm -007 -type f -exec ls -l {} \; # List world-writable files
sudo chmod o-w /path/to/file # Remove world-write access
8. Security Monitoring and Logging
Detect breaches early with robust monitoring and logging.
8.1 Centralize Logs
Aggregate logs (e.g., Apache/Nginx access logs, auth logs) with tools like the ELK Stack (Elasticsearch, Logstash, Kibana) or Graylog for easier analysis.
8.2 Enable File Integrity Monitoring (FIM)
Tools like AIDE (Advanced Intrusion Detection Environment) alert on unauthorized file changes:
sudo apt install aide -y
sudo aideinit # Generate initial database
sudo cp /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz
sudo aide --check # Run manual check (schedule with cron)
8.3 Use Fail2ban
Block brute-force attacks by banning IPs with too many failed login attempts:
sudo apt install fail2ban -y
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
Edit /etc/fail2ban/jail.local to enable SSH protection:
[sshd]
enabled = true
port = 2222 # Match your SSH port
maxretry = 3
bantime = 86400 # Ban for 24 hours
9. Advanced Hardening Techniques
For high-security environments, add these layers:
9.1 Web Application Firewall (WAF)
Beyond ModSecurity, use cloud WAFs like Cloudflare WAF or AWS WAF to block OWASP Top 10 attacks (injection, broken auth, etc.).
9.2 Container Security (if using Docker)
- Run containers as non-root users.
- Use read-only file systems:
FROM nginx USER nginx VOLUME ["/tmp", "/var/run"] # Writable only for necessary dirs - Limit container capabilities with
--cap-drop=ALL.
9.3 Encrypt Data in Transit and at Rest
- In transit: Use Let’s Encrypt for free SSL/TLS certificates:
sudo apt install certbot python3-certbot-apache -y sudo certbot --apache -d example.com - At rest: Encrypt disks with LUKS (Linux Unified Key Setup) during OS installation.
10. Conclusion
Linux web server hardening is an ongoing process, not a one-time task. By combining OS hardening, network controls, strict permissions, and monitoring, you create a resilient defense against attacks. Regularly audit your server, patch vulnerabilities, and stay updated on emerging threats (e.g., via the CVE Database) to maintain security over time.