Linux

Apache Web Server Security Hardening

Apache Web Server Security Hardening

In this tutorial, we will show you how enhance Apache Web Server security hardening strategy with our expert tips and configurations. Apache HTTP Server remains one of the most widely deployed web servers worldwide, powering millions of websites across the internet. This popularity makes it a prime target for cybercriminals seeking to exploit vulnerabilities. Properly securing your Apache installation is not just good practice—it’s essential for protecting your data, maintaining service availability, and preserving your organization’s reputation.

Table of Contents

Understanding Apache Security Fundamentals

Security hardening is a systematic process of reducing your server’s attack surface by implementing configuration changes, security controls, and best practices. According to research by Positive Technologies, 52% of scanned web applications contain high-risk vulnerabilities. These vulnerabilities often stem from default configurations that reveal sensitive information or fail to implement basic security measures.

The Defense-in-Depth Approach

Effective Apache security requires multiple protective layers rather than relying on a single security measure. This includes operating system hardening, network security controls, proper Apache configuration, and application-level security mechanisms. If one security control fails, others remain in place to mitigate potential damage.

Common Apache Attack Vectors

Before implementing security measures, it’s important to understand how attackers typically target Apache servers:

  • Distributed Denial of Service (DDoS) attacks
  • Cross-Site Scripting (XSS) vulnerabilities
  • SQL injection attacks
  • Directory traversal attacks
  • Information disclosure through server headers
  • Man-in-the-middle attacks

Keeping Your Apache Server Updated

Maintaining the latest Apache version is your first line of defense against security vulnerabilities. New releases frequently contain patches for security issues that could otherwise be exploited.

Checking Your Current Version

To verify your current Apache version, use the following command:

httpd -v

or

apache2 -v

depending on your distribution.

Update Procedures By Distribution

For Debian/Ubuntu systems:

sudo apt update
sudo apt upgrade apache2

For CentOS/RHEL systems:

sudo yum update httpd

Automating Security Updates

Consider implementing automatic updates using cron jobs or your distribution’s unattended-upgrade features:

# Example cron job for automatic updates
0 3 * * * /usr/bin/apt update && /usr/bin/apt -y upgrade apache2

Always test updates in a staging environment before applying them to production servers to prevent service disruptions.

Basic Apache Configuration Hardening

Hide Apache Version and OS Information

Default Apache installations reveal detailed server information in HTTP headers, which attackers can use during reconnaissance. Modify your configuration to hide these details:

ServerTokens Prod
ServerSignature Off

This limits the Server response header to simply “Apache” instead of showing detailed version information.

For even more security, you can use ModSecurity to completely customize your server banner:

SecServerSignature MyCustomServer

Disable Directory Listings

Automatic directory listings can expose sensitive files not linked from your website. Disable this feature by adding the following to your configuration:

Options -Indexes

This simple change prevents attackers from discovering unlinked files that might contain sensitive information.

Disable Server Side Includes (SSI)

Server Side Includes can be exploited for remote code execution. Unless you specifically need this feature, disable it:

Options -Includes

This helps prevent SSI attacks that could allow script injection or remote code execution.

Set Proper File Permissions

Implement strict file permissions for Apache configuration files and web content:

  • Configuration files: 640 or more restrictive
  • Document root: 750 for directories, 640 for files
  • Log files: 640 or more restrictive

These permission settings ensure that only authorized users can read or modify critical files.

Disable Unnecessary Modules

Review and disable any Apache modules that aren’t required for your specific use case:

# List all enabled modules
apache2ctl -M

# Disable unnecessary modules
a2dismod status info autoindex

By reducing the number of active modules, you decrease the potential attack surface of your server.

Implementing Secure Communication

Enable HTTPS with SSL/TLS

HTTPS is essential for protecting data in transit. Configure Apache to use HTTPS by obtaining and implementing an SSL/TLS certificate:

  1. Obtain an SSL certificate (from a trusted CA or using Let’s Encrypt)
  2. Install the certificate on your server
  3. Configure Apache to use the certificate
<VirtualHost *:443>
    ServerName example.com
    SSLEngine on
    SSLCertificateFile /path/to/certificate.crt
    SSLCertificateKeyFile /path/to/private.key
    SSLCertificateChainFile /path/to/chain.crt
</VirtualHost>

Configure Modern TLS Settings

Disable outdated protocols and ciphers, allowing only secure TLS versions:

SSLProtocol TLSv1.2
SSLCipherSuite HIGH:MEDIUM:!SSLv3:!kRSA:!RC4:!3DES

These settings ensure that your server only uses strong encryption protocols and cipher suites.

Implement HTTP Strict Transport Security (HSTS)

HSTS prevents downgrade attacks by instructing browsers to only use HTTPS:

<IfModule mod_headers.c>
    Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
</IfModule>

The max-age parameter (set to two years in this example) tells browsers to access your site only via HTTPS for that duration.

Redirect HTTP to HTTPS

Force all visitors to use the secure version of your website:

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / https://example.com/
</VirtualHost>

This configuration ensures that even if users access your site via HTTP, they’ll be automatically redirected to the secure HTTPS version.

Access Control and Authentication

IP-Based Restrictions

Limit access to sensitive areas by IP address:

<Directory "/var/www/html/admin">
    Require ip 192.168.1.100
</Directory>

This configuration only allows access from the specified IP address, adding an additional layer of protection for administrative areas.

Protect Server Information Directories

Restrict access to server information directories like `/server-status` and `/server-info`:

<Location "/server-status">
    Require host localhost
</Location>

These directories can reveal sensitive information about your server configuration and should be accessible only to administrators.

Directory-Level Security

Configure security settings for specific directories with sensitive content:

<Directory "/var/www/html/sensitive_directory">
    Require all denied
</Directory>

This completely blocks access to the specified directory for all users.

Implement Authentication

Use password protection for sensitive areas using .htaccess and .htpasswd files:

<Directory "/var/www/html/protected">
    AuthType Basic
    AuthName "Restricted Area"
    AuthUserFile /etc/apache2/.htpasswd
    Require valid-user
</Directory>

To create a password file:

htpasswd -c /etc/apache2/.htpasswd username

This prompts you to set a password for the specified username, creating a secure authentication mechanism.

Mitigating Common Attacks

Preventing DDoS Attacks

Implement protection against Distributed Denial of Service attacks by configuring HTTP limits:

KeepAliveTimeout 5
MaxRequestWorkers 150
LimitRequestBody 102400
TimeOut 30

These settings help your server handle legitimate traffic while mitigating the impact of DDoS attempts.

ModEvasive for DDoS Protection

Install and configure mod_evasive to provide advanced DDoS protection:

<IfModule mod_evasive20.c>
    DOSHashTableSize 3097
    DOSPageCount 2
    DOSSiteCount 50
    DOSPageInterval 1
    DOSSiteInterval 1
    DOSBlockingPeriod 60
</IfModule>

This module detects and blocks potential DDoS attacks by monitoring request patterns.

Preventing XSS Attacks

Configure the X-XSS-Protection header to enable browser protection against cross-site scripting:

Header set X-XSS-Protection "1; mode=block"

This header helps prevent XSS attacks by enabling the protection mechanisms built into modern browsers.

Disable TRACE Method

The TRACE HTTP method can be exploited for cross-site tracing attacks. Disable it in your configuration:

TraceEnable off

This simple directive prevents potential information disclosure and cross-site tracing vulnerabilities.

Implementing ModSecurity Web Application Firewall

ModSecurity functions as a web application firewall (WAF) that monitors HTTP traffic and blocks malicious requests, providing an essential layer of protection for your web applications.

Installing ModSecurity

For Debian/Ubuntu:

sudo apt install libapache2-mod-security2

For CentOS/RHEL:

sudo yum install mod_security

Basic Configuration

Load the ModSecurity modules in your Apache configuration:

LoadModule unique_id_module modules/mod_unique_id.so
LoadModule security2_module modules/mod_security2.so

Implementing OWASP Core Rule Set

The OWASP ModSecurity Core Rule Set (CRS) provides pre-configured rules to protect against common web application attacks:

<IfModule security2_module>
    Include conf/crs/modsecurity_crs_10_setup.conf
    Include conf/crs/base_rules/*.conf
</IfModule>

This implementation provides protection against XSS, SQL injection, and other common attacks out of the box.

Custom ModSecurity Rules

Create custom rules for your specific environment. For example, to block SQL injection attempts:

SecRule ARGS "@contains SELECT" "id:1000,deny,status:403,msg:'SQL Injection Attempt'"

Testing ModSecurity

You can test your ModSecurity implementation by attempting to access a URL with a potential attack pattern:

http://yourdomain.com/?param=<script>alert('XSS')</script>

If ModSecurity is properly configured, this request should be blocked, and the attempt should be logged in the ModSecurity audit log.

Security Headers Implementation

Properly configured HTTP headers provide an additional layer of security for your web applications. Here are the essential security headers to implement:

X-Content-Type-Options

Prevent MIME-type sniffing attacks:

Header set X-Content-Type-Options "nosniff"

This header prevents browsers from interpreting files as a different MIME type than what is declared.

X-Frame-Options

Protect against clickjacking attacks:

Header set X-Frame-Options "SAMEORIGIN"

This header controls how your site can be framed, preventing it from being embedded in frames on other sites.

Content-Security-Policy

Implement a content security policy to mitigate XSS risks:

Header set Content-Security-Policy "default-src 'self'"

This powerful header allows you to specify which content sources are trusted, helping to prevent various types of attacks.

Referrer-Policy

Control how much referrer information is included with requests:

Header set Referrer-Policy "strict-origin-when-cross-origin"

This header helps protect user privacy by controlling the amount of information sent in the Referrer header.

Feature-Policy/Permissions-Policy

Limit which browser features can be used on your site:

Header set Permissions-Policy "geolocation=(), microphone=(), camera=()"

This relatively new header allows you to control which browser features and APIs can be used by your site and embedded content.

Regular Security Auditing and Monitoring

Enable Comprehensive Logging

Configure Apache to maintain detailed logs of all activities:

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

Consider increasing log verbosity for security-critical areas to capture more detailed information.

Log Analysis Tools

Implement log analysis tools to help identify potential security incidents:

  • Logwatch for basic log summarization
  • GoAccess for real-time log analysis
  • ELK Stack (Elasticsearch, Logstash, Kibana) for advanced log management

Security Scanning Tools

Regularly scan your Apache server for vulnerabilities:

  • Nikto for web server scanning
  • OpenVAS for comprehensive vulnerability assessment
  • Lynis for system hardening audits

Intrusion Detection

Consider implementing an intrusion detection system (IDS) such as OSSEC or Wazuh to monitor for suspicious activities and alert administrators to potential security incidents.

Schedule Regular Security Audits

Establish a regular schedule for security audits to ensure all hardening measures remain effective and to identify any new vulnerabilities that may have emerged.

Troubleshooting Common Security Issues

Dealing with False Positives in ModSecurity

ModSecurity may occasionally block legitimate requests. To address this:

  1. Check the ModSecurity audit log to identify the rule that triggered the block
  2. Create a custom rule to exclude specific legitimate patterns that are being flagged
  3. Consider adjusting the paranoia level in the CRS configuration

Resolving SSL/TLS Configuration Issues

If you encounter SSL/TLS configuration problems:

  1. Use the SSL Labs Server Test to identify specific issues
  2. Verify certificate validity and chain of trust
  3. Ensure proper file permissions on certificate files
  4. Check for cipher compatibility with your intended audience

Fixing Permission-Related Problems

If you experience permission-related issues after hardening:

  1. Verify that Apache can read all necessary files
  2. Check that log directories are writable by the Apache user
  3. Ensure that the main configuration files have appropriate permissions

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button