Apache Security: How to Secure Your Apache Server

Apache Security: How to Secure Your Apache Server. Apache HTTP server is a free and open source software for hosting web applications. Approximately 40% of all websites and web applications run on Apache. A cross platform solution that runs seamlessly on Unix and Windows operating systems. Besides, it’s also highly customizable and provides a wide range of functionalities.

Due to its popularity, Apache is also prone to numerous security threats. As such, it’s essential to implement a security approach to make it difficult to compromise. Securing Apache web server is crucial to protect your data, ensure your website remains available, and prevent unauthorized activities.

Here are Apache Security: How to Secure Your Apache Server and 15 best ways to secure your Apache server:

Apache Security: 15 Best Ways to secure Your Apache Server

1. Enable HTTPS

To improve the security of your Apache server, it’s important to utilize HTTPS. This ensures data is encrypted during transmission. Acquire an SSL certificate like Let’s Encrypt and activate the mod_ssl module in Apache. This enables the server to handle secure connections.

Subsequently, ensure that all incoming HTTP traffic is automatically redirected to HTTPS. This redirection ensures that even if users or links point to the non-secure version of your site, they are transferred to the secure version seamlessly.

Lastly, incorporate security headers to fortify the connection security. The Strict-Transport-Security (HSTS) header is especially vital, as it ensures browsers use a secure connection, thereby eliminating the risk of data being transmitted unencrypted.

2. Minimize Modules

Apache’s web server design is built on a modular architecture, meaning that it uses separate pieces or “modules” to add specific functionalities. This modular approach has both positive and negative implications. On the one hand, it allows web administrators to add an array of functionalities tailored to their specific needs. On the other, each activated module introduces its own set of vulnerabilities.

To avoid negative impact, only enable essential modules for your website’s operation. Periodically review your activated modules and deactivate those that aren’t in use. By minimizing the number of active modules, you’re effectively reducing potential entry points for attackers, making your server more secure.

3. Modify ServerTokens and Turn Off Server Signature

In Apache, ServerTokens control the information that’s presented in server generated documents, such as error messages. Basically, this feature sets the value for the server’s HTTP response header field. When the server generates error pages, for instance, it displays crucial info about the Apache version. 

Details about your Apache server version helps attackers exploit known vulnerabilities specific to your server version. Adjust ServerTokens settings to Prod, and turn off ServerSignature to ensure server generated messages don’t reveal version details.

Here is how to disable the modify ServerTokens in Apache:

  • Open the configuration file:
				
					sudo vi /etc/apache2/apache2.conf

				
			
  • Add the following lines at the bottom of the config file:
				
					ServerSignature Off
ServerTokens Prod
				
			
				
					sudo service apache2 restart
				
			

4. Restrict Directory Listings

Directory listing is a feature that allows users to view all the contents of a directory when there is no default index file i.e index.html or index.php. After the user accesses the directory, they view all files and subdirectories in it. This is a security concern as it leads to access of sensitive files or information. Therefore, it’s crucial to disable directory listing to avoid exposing files. 

Using the Options -Indexes directive in your configuration, you disable directory listing, ensuring that visitors can’t see the contents of directories. This configuration ensures sensitive files or data aren’t inadvertently exposed, and it also gives a more professional appearance to your site.

Here is how to disable directory listing in Apache:

Access the configuration file:

				
					sudo vi /etc/apache2/apache2.conf 

				
			

or

				
					sudo nano /etc/apache2/apache2.conf
				
			

Look for the <Directory> directive in the configuration file. Essentially, it looks like this:

				
					
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted


				
			

Replace Indexes with -Indexes to disable directory listings:

				
					
    Options -Indexes FollowSymLinks
    AllowOverride None
    Require all granted


				
			

Save the file and exit, and then restart the server:

				
					sudo systemctl restart apache2
				
			

After restarting, test the changes if the directory listing is successfully disabled. Visit a directory within the website that doesn’t have an index file. If the directory listing is successfully disabled, it should display a HTTP 403 Forbidden error.

5. Secure the Apache Filesystem

Next way to improve Apache Security: How to Secure Your Apache Server is to secure Filesystem. The underlying filesystem of your server acts as the engine that runs applications like Apache. Therefore, it’s essential to run applications with the right user privilege level. Running Apache as a non-root user ensures that even if there’s a security breach, the potential damage remains limited.

Set directories to 755, and files to 644. This ensures that unauthorized users can’t make modifications. Sensitive files that hold critical data, such as configuration files httpd.conf, should have extra protection. This ensures they remain inaccessible to potential intruders.

6. Limit Allowed HTTP Methods

The Apache HTTP protocol supports several request methods. Methods like GET and POST are frequently used, while other methods such as PUT, TRACE, and DELETE are rarely used but pose security threats

With the Limit and LimitExcept directives, specify which HTTP methods are allowed on your server. By disabling unnecessary ones, you reduce the server’s exposure to certain types of attacks. Here is how to disable methods in the configuration file:

  • Open the config file and find the directory directive:
				
					sudo vi /etc/apache2/apache2.conf

				
			
				
					
    
        Deny from all
    

				
			
  • Ensure you replace /var/www/html with the path to the directory you want to restrict. Once done, save the config file and restart the server. 

7. Implement ModSecurity

Secure Apache using third party modules such as ModSecurity. ModSecurity is a signature based web application firewall (WAF) for Apache. It’s a protective barrier that intercepts and inspects HTTP traffic, looking for malicious patterns or anomalies. By implementing ModSecurity, you create a robust layer of defence against various web based attacks, such as SQL injections, cross-site scripting, and more.

Here is how to implement ModSecurity in Apache:

  • Install ModSecurity on your system:
				
					sudo apt update -y
sudo apt install libapache2-mod-security2 -y

				
			

Install ModSecurity by cloning the official github repository:

https://github.com/SpiderLabs/ModSecurity

After installing ModSecurity, enable Apache 2 module:

				
					sudo a2enmod headers
				
			
  • Restart the Apache server. Then, configure the ModSecurity. First, remove the .recommended extension from the configuration file:
				
					sudo cp /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
				
			
  • In the config file, change the value of SecRuleEngine (SecRuleEngine DetectionOnly) to On:
				
					SecRuleEngine On
				
			

Restart Apache.

				
					git clone https://github.com/coreruleset/coreruleset.git
				
			
  • Navigate the directory:
				
					cd coreruleset/
				
			
  • Change the crs-setup.conf.example to crs-setup.conf:
				
					sudo mv crs-setup.conf.example /etc/modsecurity/crs-setup.conf
				
			
  • Move the rules to the modsecurity directory:
				
					sudo mv rules/ /etc/modsecurity/
				
			
  • Include the following lines in the security2.conf file:
				
					sudo nano /etc/apache2/mods-enabled/security2.conf
				
			
				
					IncludeOptional /etc/modsecurity/*.conf
Include /etc/modsecurity/rules/*.conf

				
			

Then restart Apache to implement the changes:

				
					sudo systemctl restart apache2
				
			
  • Lastly, test the ModSecurity configuration on your local machine.

8. Use Mod_Evasive to Defend Apache Server Against DoS and DDoS

Mod_evasive is an Apache module designed to secure Apache servers against malicious attacks. At its core, mod_evasive acts as a monitor that scrutinizes the incoming traffic patterns to the Apache server. By doing so, it identifies rapid successive requests from singular or multiple IP addresses. When it detects an abnormal spike in the number of requests, it blocks the IP addresses to prevent further requests.

Here is how to configure mod_evasive on Ubuntu:

  • Update your OS
				
					sudo apt update -y
				
			
  • Install Apache Web Server Utility:
				
					apt-get install apache2-utils
				
			
  • Install the mod_evasive module:
				
					apt install libapache2-mod-evasive
				
			
  • Configure mod_evasive:
				
					sudo nano /etc/apache2/mods-enabled/evasive.conf
				
			

Under the mod_evasive section, make these changes:

				
					
    DOSHashTableSize 3097
    DOSPageCount 2
    DOSSiteCount 50
    DOSPageInterval 1
    DOSSiteInterval 1
    DOSBlockingPeriod 100
    DOSEmailNotify 

				
			

DOS Parameters Explained

Here is a detail of all the above parameters:

  • DOSHashTableSize. Defines the size of the hash table.
  • DOSPageCount. Threshold for requests to the same page within the DOSPageInterval, beyond which an IP is blocked.
  • DOSSiteCount. Threshold for total requests by a client across any page within the DOSSiteInterval.
  • DOSPageInterval. Time frame (in seconds) for considering the number of page requests for blocking.
  • DOSSiteInterval. Time frame (in seconds) for considering the total number of site requests for blocking.
  • DOSBlockingPeriod. Duration (in seconds) an IP is blocked after exceeding thresholds, and is reset with each request attempt.
  • DOSEmailNotify. Sends an email notification to a specified address when an IP gets blocked.

Besides, you configure mod_evasive to perform various actions during an attack scenario. For instance, configure it to send notifications to system administrators, log the incident, or execute custom scripts to handle the situation. 

9. Protect Directories With Passwords

With Apache Security: How to Secure Your Apache Server you shall always protect directories that house sensitive data with a password. By doing so, you add a security layer that requires authentication before granting access. Leveraging .htaccess and .htpasswd files in Apache, you specify directories to be password protected. Any user attempting to access these directories is prompted to enter valid credentials before being granted access.

10. Disable Unused Services and Daemons

Servers often come with various services and daemons running by default. These services range from networking utilities to software managers and might be activated automatically. Each running service or daemon is potential vulnerability, especially if it’s network-facing. Attackers exploit unpatched, outdated, or insecure services to gain entry into a system. The risk is even higher if you are unaware of these services or do not regularly update them.

To avert these risks, it’s essential to audit running services using tools like netstat or ss. If you find any service that’s not required, disable it immediately. Reducing the number of active services improves security while also freeing up server resources to improve overall performance.

11. Harden Your PHP

Apache is part of the LAMP stack, which also includes Linux, MySQL, and PHP. The Apache HTTP server pairs with the PHP language to deliver dynamic web content. This combination forms the backbone of many websites. However, it also has security risks, as some PHP vulnerabilities directly impact Apache’s security. PHP, with its vast ecosystem, does introduce potential risks. If exploited, these vulnerabilities might compromise the very core of an Apache-driven web service

The PHP configuration file (php.ini) is vital to maintain the server’s overall integrity. High-risk functions in PHP such as exec(), shell_exec(), and eval() have the ability to directly interact with the server’s underlying system. If left unchecked, these could allow attackers to execute arbitrary commands on the Apache server. Therefore, disable these functions to minimize inside the configuration file to reduce the security risk. 

12. Use HTTP Content Security Policy (CSP)

CSP is an HTTP header that gives website administrators the ability to specify which content sources are trustworthy and, consequently, allowed to be loaded by web browsers. Configure a CSP to only allow scripts from the site’s own domain or specific external sources, while blocking all others so cross site scripting attacks are prevented from external malicious content.

Implement CSP in Apache by modifying the example.conf file. 

  • On your terminal, open the config file:
				
					vi /etc/apache2/sites-enabled/example.conf
				
			

Add the following line:

				
					Header always set Content-Security-Policy "default-src 'self'; font-src *;img-src * data:; script-src *; style-src *;"
				
			

The, restart .

13. Configure a Firewall to Prevent Unauthorized Access

Firewalls act as gatekeepers, monitoring and controlling the traffic that goes in and out of your server. Basically, firewalls, filter out malicious traffic from access your server. There are several tools, like ufw and firewalld that provide system level firewalls. This means that many malicious attempts are stopped before they negatively impact the Apache server. This proactive approach to security drastically reduces the server’s vulnerability to external threats.

14. Secure Database Access

If your Apache server communicates with databases like MySQL or PostgreSQL, you need to ensure secure database access. This includes implementing unique passwords for each database user and having strict password policies. This makes it much difficult for attackers to gain unauthorized access through brute force or credential based attacks.

Basically, limit database connections to specific IP addresses or local interfaces. This ensures only specific entities, such as the web server, accesses the database, minimizing exposure to potential threats. Also, you need to frequently review and adjust user privileges in the database. Always grant users only the necessary permissions for their roles to reduce the risk associated with compromised accounts.

15. Use Intrusion Detection Systems (IDS)

Intrusion Detection Systems (IDS) monitor server activities for malicious behavior, providing real-time alerts to admins. With the ever evolving nature of cyber threats, having an IDS in place is the difference between preventing an attack and a data breach. To secure your Apache server, use IDSs such as Snort, OSSEC, and Suricata.

Snort examines network traffic for signs of intrusion, like repeated failed login attempts. It uses a rule-based language to detect potentially malicious activity. Ideally, it combines anomaly, protocol, and signature inspection methods to help secure your server. By integrating an IDS into an Apache server, add another layer of defence. It ensures you still detect and mitigate threats that pass the initial security measures.

Thank you for reading Apache Security: How to Secure Your Apache Server. We conclude the article. Thank you.

Apache Security: How to Secure Your Apache Server Conclusion

With Apache being one of the most popular web servers globally, its essential to secure it from potential threats . From restricting directory listings and managing modules to securing the underlying filesystem, each security approach is essential. All these security methods complements the other, creating a multi faceted protection against cyber attacks. By embracing these best practices, you significantly enhance your server’s resilience and performance.

Avatar for Dennis Muvaa
Dennis Muvaa

Dennis is an expert content writer and SEO strategist in cloud technologies such as AWS, Azure, and GCP. He's also experienced in cybersecurity, big data, and AI.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x