dotlinux guide

How to Secure Apache on a Linux Server: A Comprehensive Guide

Apache HTTP Server is one of the most widely used web servers globally, powering millions of websites. However, its popularity makes it a prime target for attackers. Securing Apache is critical to protect against threats like data breaches, DDoS attacks, cross-site scripting (XSS), and server hijacking. This blog provides a step-by-step guide to hardening Apache on a Linux server, covering fundamental concepts, practical configuration steps, common practices, and industry best practices. By the end, you’ll have the knowledge to fortify your Apache setup against common vulnerabilities.

Table of Contents

Prerequisites

Before starting, ensure you have:

  • A Linux server (Ubuntu/Debian or RHEL/CentOS) with Apache installed.
  • Root or sudo access to the server.
  • Basic familiarity with Linux command-line and Apache configuration files.

Fundamental Concepts

Apache Architecture Overview

Apache uses a modular architecture, where core functionality is extended via modules (e.g., mod_ssl for HTTPS, mod_rewrite for URL rewriting). Key configuration files include:

  • Debian/Ubuntu: /etc/apache2/apache2.conf (main config), /etc/apache2/sites-available/ (virtual hosts).
  • RHEL/CentOS: /etc/httpd/conf/httpd.conf (main config), /etc/httpd/conf.d/ (additional configs).

Security Layers for Apache

Securing Apache involves multiple layers:

  • Network: Firewalls to restrict port access.
  • OS: File permissions and user privileges.
  • Application: Apache configuration (e.g., hiding version info, access controls).
  • Data: Encryption (HTTPS) and WAF rules to block attacks.

Step-by-Step Security Implementation

1. Update Apache and Dependencies

Outdated software is a primary attack vector. Always keep Apache and its dependencies updated:

Debian/Ubuntu:

sudo apt update && sudo apt upgrade apache2 -y

RHEL/CentOS:

sudo yum update httpd -y

2. Minimize Apache Footprint: Disable Unused Modules

Apache loads many modules by default. Disable unused modules to reduce attack surface:

List Enabled Modules

Debian/Ubuntu:

apache2ctl -M  # Lists loaded modules

RHEL/CentOS:

httpd -M

Disable Modules (Example: mod_autoindex, mod_info)

Debian/Ubuntu: Use a2dismod (disable) and a2enmod (enable):

sudo a2dismod autoindex  # Disables directory listing module
sudo a2dismod info       # Disables server info module
sudo systemctl restart apache2

RHEL/CentOS: Edit /etc/httpd/conf/httpd.conf and comment out unused modules:

# LoadModule autoindex_module modules/mod_autoindex.so
# LoadModule info_module modules/mod_info.so

Restart Apache:

sudo systemctl restart httpd

3. Secure Configuration Files

Apache configuration files must be protected from unauthorized edits.

Set Strict Permissions

Ensure config files are owned by root and readable only by the Apache user:

# For Debian/Ubuntu (Apache user: www-data)
sudo chmod 640 /etc/apache2/apache2.conf
sudo chown root:www-data /etc/apache2/apache2.conf

# For RHEL/CentOS (Apache user: apache)
sudo chmod 640 /etc/httpd/conf/httpd.conf
sudo chown root:apache /etc/httpd/conf/httpd.conf

Hide Apache Version and OS Info

By default, Apache exposes its version and OS (e.g., Apache/2.4.52 (Ubuntu)). Hide this with:

Edit the main config file (apache2.conf or httpd.conf) and add:

ServerTokens Prod       # Returns "Apache" instead of version/OS
ServerSignature Off     # Disables server signature in error pages

Test the Change:

curl -I http://your-server-ip  # Should show "Server: Apache"

4. Restrict Access Control

Control who can access your server’s directories and resources.

Limit Access with Directory Directives

Use <Directory> blocks in Apache config to restrict access. For example, deny all access to /var/www/html except from trusted IPs:

<Directory /var/www/html>
    Require all denied                # Deny by default
    Require ip 192.168.1.0/24         # Allow specific IP range
    Require ip 10.0.0.10              # Allow single IP
</Directory>

Disable .htaccess (When Possible)

.htaccess files allow per-directory configuration but can be exploited if writable. Prefer main config over .htaccess by setting AllowOverride None:

<Directory /var/www/html>
    AllowOverride None  # Disables .htaccess processing
</Directory>

5. Enforce HTTPS with Let’s Encrypt

HTTPS encrypts data in transit. Use Let’s Encrypt for free SSL/TLS certificates:

Install Certbot (Let’s Encrypt Client)

Debian/Ubuntu:

sudo apt install certbot python3-certbot-apache -y

RHEL/CentOS:

sudo yum install certbot python3-certbot-apache -y

Obtain and Install Certificate

sudo certbot --apache -d example.com -d www.example.com

Certbot auto-configures Apache to use HTTPS and redirect HTTP to HTTPS.

Verify Auto-Renewal

Let’s Encrypt certificates expire in 90 days. Ensure auto-renewal:

sudo certbot renew --dry-run  # Tests renewal process

Common Security Practices

Firewall Hardening

Only allow HTTP (80) and HTTPS (443) ports. Block all others:

Debian/Ubuntu (UFW):

sudo ufw allow 'Apache Full'  # Allows 80/tcp and 443/tcp
sudo ufw enable               # Enables firewall

RHEL/CentOS (Firewalld):

sudo firewall-cmd --add-service=http --permanent
sudo firewall-cmd --add-service=https --permanent
sudo firewall-cmd --reload

Disable Directory Listing

Prevent Apache from displaying file lists when no index.html exists:

Add Options -Indexes to <Directory> blocks:

<Directory /var/www/html>
    Options -Indexes  # Disables directory listing
</Directory>

Prevent .htaccess Overrides

As mentioned earlier, set AllowOverride None to disable .htaccess and enforce security via main config.

Best Practices

Deploy ModSecurity WAF

ModSecurity is a Web Application Firewall (WAF) that blocks common attacks (SQLi, XSS).

Install ModSecurity

Debian/Ubuntu:

sudo apt install libapache2-mod-security2 -y
sudo cp /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf

RHEL/CentOS:

sudo yum install mod_security -y

Enable and Configure

Edit modsecurity.conf and set:

SecRuleEngine On  # Enable WAF

Load OWASP Core Rule Set (CRS) for pre-built attack rules:

sudo git clone https://github.com/coreruleset/coreruleset.git /etc/modsecurity/crs
sudo ln -s /etc/modsecurity/crs/crs-setup.conf.example /etc/modsecurity/crs/crs-setup.conf

Update Apache config to include CRS:

Include /etc/modsecurity/crs/crs-setup.conf
Include /etc/modsecurity/crs/rules/*.conf

Restart Apache:

sudo systemctl restart apache2  # or httpd

Implement HTTP Security Headers

Headers mitigate attacks like XSS and clickjacking. Add these to your Apache config (e.g., in a <VirtualHost> block):

Header set X-Content-Type-Options "nosniff"
Header set X-Frame-Options "DENY"  # Prevents clickjacking
Header set X-XSS-Protection "1; mode=block"
Header set Content-Security-Policy "default-src 'self'"  # Restrict resource loading
Header set Strict-Transport-Security "max-age=31536000; includeSubDomains"  # Enforce HTTPS

Test Headers:

curl -I https://example.com  # Should show headers in response

Rate Limiting to Mitigate DDoS

Use mod_ratelimit to limit requests per client and prevent DDoS:

Enable mod_ratelimit (Debian/Ubuntu: sudo a2enmod ratelimit; RHEL/CentOS: uncomment LoadModule ratelimit_module).

Add to Apache config:

<IfModule mod_ratelimit.c>
    <Location />
        SetOutputFilter RATE_LIMIT
        SetEnv rate-limit 100  # 100 requests per minute
        RateLimitRequestBody 102400  # Limit request body to 100KB
    </Location>
</IfModule>

Monitor and Audit Logs

Apache logs (access/error) are critical for detecting attacks.

Enable Logging

Ensure logging is enabled in your config:

ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

Rotate Logs with Logrotate

Prevent log files from consuming disk space. Apache uses logrotate by default (config: /etc/logrotate.d/apache2 or /etc/logrotate.d/httpd).

Regular Backups

Back up Apache configs and website data:

sudo tar -czf /backup/apache_backup_$(date +%F).tar.gz /etc/apache2 /var/www/html

Conclusion

Securing Apache requires a layered approach: updating software, minimizing the attack surface, enforcing HTTPS, restricting access, and monitoring for threats. By following this guide—disabling unused modules, hiding version info, using ModSecurity, and implementing security headers—you’ll significantly reduce risk. Remember, security is ongoing: regularly audit configs, update rules, and monitor logs to stay ahead of new threats.

References