How to Optimise and Harden Apache

How to Optimise and Harden Apache

What Do I Need?

  • A Dedicated or VPS Linux Server
  • CentOS/Ubuntu

What is Apache?

Apache is an open-source web server solution, developed and maintained by the Apache Software Foundation and a super active community, that runs over 60% of all the web servers in the world.

  1. Keep Up to Date
  1. The most important thing to prevent damage, make sure the webserver is up to date because the apache community is working hard to prevent security issues and releasing new versions based on security fixes and new features.
yum update httpd

  1. Hide Apache Version
  1. It seems that the default Apache configuration will expose the Apache version and operating system type. Exposing version means you’re helping hackers to speed the reconnaissance process.

How to Optimise and Harden Apache

  1. To hide this information from browsers, you’ll need to make some changes in Apache’s main configuration file. Open configuration file, /etc/httpd/conf/httpd.conf with an editor and search for ‘ServerSignature’, it’s by default ‘On’. We need to ‘Off’ these server signatures and the second line “ServerTokens Prod” tells Apache to return only Apache as a product in the server response header on every page request. It suppresses the operating system, major and minor version info.
vi /etc/httpd/conf/httpd.conf

serverSignature Off

serverTokens Prod

  1. Save the file and restart the Apache service to reflect these changes:
systemctl restart httpd

How to Optimise and Harden Apache

  1. Disable Directory Listing
  1. By default, Apache lists all the content of the Document root directory in the absence of an index file. Disable directory listing in a browser so the visitor doesn’t see what all file and folders you have under root or subdirectory. If this is enabled, then a bad actor can easily view any file, analyze it, and obtain sensitive information about an application of your Apache server.
  2. You could turn off directory listing by using Options directive in the configuration file for a specific directory.
vi /etc/httpd/conf/httpd.conf

Options -Indexes

How to Optimise and Harden Apache

  1. Disable Etag
  1. ETags are made out of three components: the INode, MTime, and Size. Enabling Etag helps remote attackers to obtain sensitive information like inode number, multipart MIME boundary, and child process through Etag header. Disabling Etag is required to fix PCI compliance.
  2. Open /etc/httpd/conf/httpd.conf and add the following directive, save the file, and restart the Apache service to reflect these changes.
vi /etc/httpd/conf/httpd.conf

FileETag None

systemctl restart httpd

  1. Disable Unnecessary Modules
  1. Please note that by default, Apache comes with lots of unnecessary installed modules, so it’s recommended to disable all those modules that aren’t in use. You can list all the compiled modules of the web server, using the following command;
grep LoadModule /etc/httpd/conf.modules.d/00-base.conf

How to Optimise and Harden Apache

  1. To disable the particular module, you can insert “#” at the beginning of that line and restart the service.

How to Optimise and Harden Apache

  1. Run Apache as Separate User and Group
  1. With a default installation, Apache runs as nobody or daemon. For security reasons, it’s recommended to run Apache its own user account which will help us to track the particular user activity when we’re facing some load issues on the server.
groupadd apache

useradd -d /var/www/ -g apache -s /bin/nologin apache

  1. Modify Apache user and group on Apache config file
vi /etc/httpd/conf/httpd.conf

User apache

Group apache

How to Optimise and Harden Apache

  1. Ensure that Files Outside the Webroot are not Served
  1. We need to restrict the user’s access to the root directory and we can allow the user to access appropriate Directory blocks. Secure the root directory by setting the following in the configuration file /etc/httpd/conf/httpd.conf.
[Apache 2.2]

Options None

Order deny,allow

Deny from all

[Apache 2.4]

Require all denied

  1. Options None – Set this to None, which won’t enable any optional extra features.
  2. Order deny, allow – This is the order in which the ‘Deny’ and ‘Allow’ directives should be processed. This processes the “deny” first and ‘allow’ next.
  3. Deny from all – This denies requests from everybody to the root directory. There’s no Allow directive for the root directory. So, nobody can access it.
  1. Turn off Support for Unused .htaccess Files
  1. Using .htaccess file inside a specific subdirectory under the home directory, or anywhere outside of it, users can overwrite the default apache directives. It’s not recommended to allow users to use the .htaccess file and override Apache directives. To do this, set ‘AllowOverride None’ in the root directory.
AllowOverride None

  1. Don’t Allow Apache to Follow Symbolic Links
  1. You can disable FollowSymLinks with the Options directive from the httpd.conf configuration file and may also disable this for a particular directory only.
Options -FollowSymLinks

  1. Disable other Options
  1. Following are the available values for Options directive:
  1. Options All – All options are enabled (except MultiViews). If you don’t specify Options directive, this is the default value.
  2. Options ExecCGI – Execute CGI scripts (uses mod_cgi)
  3. Options FollowSymLinks – If you have symbolic links in this directory, it will be followed.
  4. Options Includes – Allow server side includes (uses mod_include)
  5. Options IncludesNOEXEC – Allow server side includes without the ability to execute a command or cgi.
  6. Options Indexes – Disable directory listing
  7. Options MultiViews – Allow content negotiated multiviews (uses mod_negotiation)
  8. Options SymLinksIfOwnerMatch – Similar to FollowSymLinks. But the server will only follow symbolic links for which the target file or directory is owned by the same user id as the link.
  1. We can turn off server side includes (mod_include) and CGI execution if not needed. For that we need to modify the main configuration file /etc/httpd/conf/httpd.conf.
Options -Includes

Options -ExecCGI

  1. Limit HTTP Request Body, Field & Size
  1. Apache has several directives that allow you to limit the size of a request, LimitRequestBody can also be useful for mitigating the effects of a denial of service attack. You can limit the size of the requests by using the Apache directive LimitRequestBody in combination with the Directory tag. This directive is set to unlimited by default. You can set the value in bytes from 0 (unlimited) to 2147483647 (2GB) that are allowed in a request body. You can set this limit according to your site needs. Add the following line:
LimitRequestBody 204800

  1. Save the file and restart Apache.
  2. Please note that the directives LimitRequestBody, LimitRequestFields, LimitRequestFieldSize, LimitRequestLine, and LimitXMLRequestBody should be carefully configured to limit resource consumption triggered by client input.
  1. Install/Enable mod_security
  1. Mod-Security is an open-source web Application Firewall. It includes different functionalities like filtering, server identity masking, and null byte attack prevention. Real-time traffic monitoring is also allowed through this module. One of the biggest strengths of ModSecurity is virtual patching. You’re protected against application vulnerabilities for which you’re not yet able to patch. With ModSecurity, you can protect and harden your website against unwanted malicious traffic and reduce the size of the possible attack vector. You can do the following with mod_security:
  1. Simple filtering
  2. Regular Expression based filtering
  3. URL Encoding Validation
  4. Unicode Encoding Validation
  5. Auditing
  6. Null byte attack prevention
  7. Upload memory limits
  8. Server identity masking
  9. Built-in Chroot support
  1. Install mod_security
yum install mod_security

/etc/init.d/httpd restart

  1. When the installation is complete, you will find the configuration file tools in /etc/httpd/conf.d.

How to Optimise and Harden Apache

  1. Protect DDoS Attacks and Hardening
  1. Although complete protection against a DDoS attack isn’t at all possible with the below methods, you can still survive against small bandwidth attacks. Protecting your server from large and huge DDoS attacks is beyond the scope of Apache and any web server for that matter. This is primarily because web servers aren’t made to solve that problem, and cannot go beyond a certain extent to protect themselves against such attacks. Here are some directives that can help you to get control over it.
  1. Timeout: We can set RequestReadTimeout for the client. If the client fails to send headers or body within the configured time, a 408 REQUEST TIMEOUT error is sent. The default value is 300secs.
  2. KeepAlive=on: Keep more than one request per connection.
  3. KeepAliveTimeout: Number of seconds to wait for the next request from the same client on the same connection. The default value is 5 secs.
  4. MaxKeepAliveRequests: The maximum number of requests to allow during a persistent connection. Set to 0 to allow an unlimited amount. The default value is 100.
  5. MaxRequestWorkers: It allows the server to handle the maximum number of simultaneous connections without running out of resources. The default value is 250.
  6. LimitRequestFields: This directive allows the server administrator to modify the limit on the number of request header fields allowed in an HTTP request. The default value is 100.
  7. LimitRequestFieldSize: This directive allows the server administrator to set the limit on the allowed size of an HTTP request header field. The default value is 8190 bytes.

How to Optimise and Harden Apache

  1. Secure with SSL Certificates
  1. SSL is an additional layer of security you’re adding to web applications. Suppose you have a website in which people log in by proving their credentials or you have an eCommerce website where people provides their bank details or debit/credit card details to purchase products, by default, your web server sends these details in plain-text format but when you use SSL certificates to your websites, Apache sends all this information in encrypted text. However, default SSL configuration leads to certain vulnerabilities and you should consider tweaking those configurations.
  2. SSL Key

Please note, the higher the key length you have, the more complex it becomes to break SSL keys. The majority of giant Web Companies use 2048 bit keys.

  1. Disable SSLv2, SSLv3

SSL 2.0 & 3.0, reportedly suffers from several cryptographic flaws. So please use the following;

SSLProtocol -ALL +TLSv1

  1. Disable Null and Weak Ciphers

SSL Cipher is an encryption algorithm that’s used as a key between two computers over the internet. Data encryption is the process of converting plain text into secret ciphered codes. It’s based on your web server SSL Cipher configuration that the data encryption will take place. Allow only strong ciphers so you close all the doors that try to handshake on lower cipher suites.

SSLCipherSuite ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM

How to Optimise and Harden Apache

  1. Enable Apache Logging
  1. Apache logging provides detailed information about client requests made on your web server, hence enabling such logging will prove useful when investigating the cause of particular issues.
  2. Apache stores two kinds of logs Error log and Access log.
  1. Apache Error Log

Contains information about errors that the webserver encountered when processing requests. The location of the error log is set using the ErrorLog directive. If you’re encountering any issues with Apache, you should first take a look at this file using cat, grep, or any other UNIX/Linux text utilities. Default error log file location is /var/log/httpd/error_log.

vi /etc/httpd/conf/httpd.conf

ServerName example.com

ServerAdmin webmaster@example.com

DocumentRoot /var/www/example.com

ErrorLog /var/www/example.com/logs/error.log
  1. Apache Access Log

The server access log records all requests processed by the server. The location and content of the access_log are controlled by the CustomLog directive. Default apache access log file location is /var/log/httpd/access_log.

vi /etc/httpd/conf/httpd.conf

ServerName example.com

ServerAdmin

webmaster@example.com

DocumentRoot /var/www/example.com

CustomLog /var/www/example.com/logs/access.log

Next Steps

Reboot your server and enjoy the knowledge that you’ve now successfully optimized and hardened your web server.

Conclusion

Personally, I’d recommend next researching appropriate encryption for your server to protect usernames, passwords, and webspaces. My suggestions are PureKit by Virgil Security. PureKit is an open-source security framework meant for enabling post-compromise protection for stored data and features. Open-source, peer-reviewed, and regularly updated, it’s definitely the way to go. Go Virgil!

How To Set up a VSFTPD Server on a CentOS 7 VPS or Dedicated Server

Brief Description FTP is usually insecure exposing clear-text passwords, userna
2 min read
Avi Ilinsky
Avi Ilinsky
Hosting Expert

How To Set up a VSFTPD Server on an Ubuntu 16.04 VPS or Dedicated Server

Brief Description FTP data is usually insecure since information (usernames, pa
2 min read
Eliran Ouzan
Eliran Ouzan
Web Designer & Hosting Expert

How to use phpMyAdmin to develop a website (without MySQL experience)

Brief description A web developer who is not well versed into coding websites f
2 min read
Idan Cohen
Idan Cohen
Marketing Expert

How to Install MySQL on a Windows Web Server Running Apache

This tutorial will show you how to install the MySQL database on a Windows serve
3 min read
Michael Levanduski
Michael Levanduski
Expert Hosting Writer & Tester
HostAdvice.com provides professional web hosting reviews fully independent of any other entity. Our reviews are unbiased, honest, and apply the same evaluation standards to all those reviewed. While monetary compensation is received from a few of the companies listed on this site, compensation of services and products have no influence on the direction or conclusions of our reviews. Nor does the compensation influence our rankings for certain host companies. This compensation covers account purchasing costs, testing costs and royalties paid to reviewers.
Click to go to the top of the page
Go To Top